SQL Server: update to match and replace only exact words

前端 未结 1 1480
青春惊慌失措
青春惊慌失措 2021-01-26 17:50

I want to match an exact word and replace it with another word.

Here is the SQL Server query that I am using:

UPDATE BODYCONTENT 
SET BODY = CAST(REPLACE         


        
1条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-26 18:14

    I am getting the impression that all the different versions of test are within the same row value, which is why you are stating that the suggested like 'test' is not working.

    Based on this, the below is rather ugly but functional per your requirements:

    declare @t table(s ntext);
    insert into @t values('Test testtest Test1 Test TEST');
    
    select s as Original
            ,ltrim(rtrim(replace(
                                replace(
                                        replace(N' ' + cast(s as nvarchar(max)) + N' '  -- Add a single space before and after value,
                                                ,' ','<>'                               -- then replace all spaces with any two characters.
                                                )
                                        ,'>test<','>prod<'      -- Use these two characters to identify single instances of 'test'
                                        )
                                ,'<>',' '       -- Then replace the delimiting characters with spaces and trim the value.
                                )
                        )
                ) as Updated
    from @t;
    

    Output:

    +-------------------------------+-------------------------------+
    |           Original            |            Updated            |
    +-------------------------------+-------------------------------+
    | Test testtest Test1 Test TEST | prod testtest Test1 prod prod |
    +-------------------------------+-------------------------------+
    

    The use of <> in place of spaces is due to SQL Server's default behaviour to ignore trailing spaces in string comparisons. These can be any two characters, but I find these to be aesthetically pleasing.

    0 讨论(0)
提交回复
热议问题