SQL Server: update to match and replace only exact words

梦想与她 提交于 2019-12-02 12:01:46

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!