如何在T-SQL中按递增顺序替换重复的字符串?

时间:2016-03-09 04:50:40

标签: sql-server tsql

我有一个单行表:

Id | Description
---------------
 1   #Hello#, Its 5 am. #Hello#, Its 9 am. #Hello# its 12 pm.

我想用递增的顺序替换这些重复的字符串#Hello#。我需要像

这样的输出
Id | Description
---------------
 1   #Hello#, Its 5 am. #Hello1#, Its 9 am. #Hello2# its 12 pm

1 个答案:

答案 0 :(得分:1)

试试这个,

DECLARE @V_STR      NVARCHAR(1000)  =   (SELECT [Description] FROM [Table1])
        ,@V_COUNT   INT =   0
        ,@V_TMP     NVARCHAR(100)   =   '#Hello#'
WHILE ((CHARINDEX(@V_TMP,@V_STR)) > 0)
BEGIN
    SELECT @V_STR = STUFF(@V_STR,(CHARINDEX(@V_TMP,@V_STR)),LEN(@V_TMP),'#Hello'+CAST(@V_COUNT AS NVARCHAR)+'#')
    SET @V_COUNT += 1
END
SELECT @V_STR