Search code examples
sql-servert-sqlsubstring

Remove second appearence of a substring from string in SQL Server


I need to remove the second appearance of a substring from the main string, IF both substrings are next to each other. e.g.:

Jhon\Jhon\Jane\Mary\Bob needs to end Jhon\Jane\Mary\Bob

but Mary\Jane\Mary\Bob has to remain unchanged.

Can anyone can come out with a performant way to do this?

'\' is the separator of different names, so it can be use as limit of the substring to replace.

EDIT: this is to be run on a SELECT statement, so it should be a one line solution, I can't use variables. Also, if the names are repetaed anywhere else, I have to let them there. Only remove one occurrence if both the first and the second names are the same.


Solution

  • I decided to go for string manipulation. I thought it'd take longer to execute the query, but testing it in... ejem... production environment... ejem... I found out that it did not (much to my surprise). It ain't pretty, I know, but it's easy to mantain...

    Here is a simplified version of my final query:

    SELECT SOQ.PracticeId,
           CASE WHEN LEFT(SOQ.myString, SOQ.SlashPos) = SUBSTRING(SOQ.myString, SOQ.SlashPos + 1, LEN(LEFT(SOQ.myString, SOQ.SlashPos)))
                THEN RIGHT(SOQ.myString, LEN(SOQ.myString) - SOQ.SlashPos)
                ELSE SOQ.myString
           END as myString
      FROM (SELECT OQ.AllFields, OQ.myString, CHARINDEX('\', OQ.myString, 0) as SlashPos
              FROM MyOriginalQuery OQ) SOQ