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
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.