Skip to content
Advertisement

SQL – Replace characters in a SQL string

I would like to know how to replace all characters between 2 dashes (-) and replace the dashes as well. It should be in a single select statement, not a loop. The text between the dashes can be variable length and any character. The characters before and after the dashes can also be variable length.

        141911001-200-20     = 14191100120  // Replaced -200-
        141911001-10-50      = 14191100150  // Replaced -10-
        141911001-50-10      = 14191100110  // Replaced -50-
        141911001-aaaa-85    = 14191100185  // Replaced --aaaa--
        11111111111-bbbbb-4444 = 111111111114444 //Replace-bbbbb-

Advertisement

Answer

You can do it by using CHARINDEX, SUBSTRING and LEN

CREATE TABLE #TEMP
(
  test_value VARCHAR(20)
)

INSERT INTO #TEMP
VALUES ('141911001-200-20')
,('141911001-10-50')
, ('141911001-50-10')
,('141911001-aaaa-85')

SELECT SUBSTRING(test_value, CHARINDEX('-', test_value), LEN(test_value)) AS subFirstDash -- Substring starts on the first dash (-) index
 , CHARINDEX('-', SUBSTRING(test_value, CHARINDEX('-', test_value) + 1, LEN(test_value))) AS lastDashIndex -- Last dash(-) index from the previous substring
 , SUBSTRING(SUBSTRING(test_value, CHARINDEX('-', test_value) + 1, LEN(test_value)), 0, CHARINDEX('-', SUBSTRING(test_value, CHARINDEX('-', test_value) + 1, LEN(test_value)))) AS btwDashes -- Value between dashes (-)
 , REPLACE(test_value, '-' + SUBSTRING(SUBSTRING(test_value, CHARINDEX('-', test_value) + 1, LEN(test_value)), 0, CHARINDEX('-', SUBSTRING(test_value, CHARINDEX('-', test_value) + 1, LEN(test_value)))) + '-', '') AS new_value -- Value between dashes (-) replaced 
 , test_value AS original_value
FROM #TEMP

DROP TABLE #TEMP

Check this fiddle

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement