替换除第一次出现之外的SQL列中字符串中出现的所有子字符串

时间:2017-05-23 02:15:48

标签: sql sql-server

我在列文本中有一个字符串,如下所示:

Test:HJ,BHS,Test:FG,SKL,Test:KL,PDC  

(依此类推......此字符串没有固定长度)

每次测试出现时都会跟着两个字母,三个字母(这是字符串的模式)

现在我想用Test替换此字符串,只显示一次,如下所示:

Test:HJ,BHS,:FG,SKL,:KL,PDC

1 个答案:

答案 0 :(得分:2)

您可以像这样使用replace

DECLARE @Text varchar(500) = 'Test:HJ,BHS,Test:FG,SKL,Test:KL,PDC  ( and so on ...there is no fixed length of this string )'

SELECT Replace(@Text, ',' + LEFT(@Text,charindex(':', @Text)), ',:')

返回

Test:HJ,BHS,:FG,SKL,:KL,PDC  ( and so on ...there is no fixed length of this string )