Replace whole word using ms sql server “replace”

后端 未结 3 1174
借酒劲吻你
借酒劲吻你 2021-01-19 04:28
declare @str varchar(50)=\'GoodLuck Markand\'
declare @replacedString varchar(50)
set @replacedString = replace(@str,\'Good\',\'Better\')
print @replacedString
         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-19 04:53

    Try This: (Works as Expected)

    declare @str varchar(500)
    set @str = 'Good Good Good Good Good Good Good Good Luck Good GoodLuck MarkAndGood GoodMarkAnd MarkAndGood Good'
    declare @replacedString varchar(500)
    SET @replacedString = replace(@str,' Good ',' Better ')
    
    SET @replacedString = replace(@replacedString,' Good ',' Better ')
    
    SET @replacedString = CASE WHEN CHARINDEX('Good ', @replacedString) = 1 THEN 
                            STUFF(@replacedString, 1, Len('Good'), 'Better')
                          ELSE @replacedString END
    
    SELECT CASE WHEN CHARINDEX(REVERSE(' Good'), REVERSE(@replacedString)) = 1 THEN 
                                 Reverse(STUFF(Reverse(@replacedString), CHARINDEX(Reverse(' Good'), 
                                 Reverse(@replacedString)), Len(' Good'), Reverse(' Better')))
                          ELSE @replacedString END AS A
    

    Input:

    Good Good Luck Good GoodLuck Good

    Result:

    Better Better Luck Better GoodLuck Better

提交回复
热议问题