Skip to content

Find a string inside a string and update in SQL Server

I have a table like this :

create table Fbank (id int, COCODE nvarchar(max))

insert into Fbank 
values (1, '<row xml:space="preserve" id="174580000041250.040002">
  <c4>BAL MIGRATED</c4>

I need to replace the string inside the tag c24 tag..

Excepted output: I need to replace the letter ‘G’ to be replaced with ‘T’ like this inside c24 tag – HT0010001 and all the rest should be same unchanged…

What I tired:

declare @searchText varchar(20) = (

update Fbank 
set cocode = STUFF(@searchText, CHARINDEX('<c24>', COCODE), 1, 'T')



If the code always begins with ‘H’, then I imagine it’s easier to just have ‘<c24>H’ be part of the string to replace, but then add it back again:

update Fbank 
set    COCODE = replace(cocode, '<c24>HG', '<c24>HT');

If it doesn’t, then I’d say you’re on the right track with charindex and substring. But use patindex instead, and update fbank directly, don’t put the search term into any variable. If you’re trying to split up your logic into parts, consider cross apply:

update      fb 
set         cocode = stuff(cocode, ix, 1, 'T')
from        Fbank fb
cross apply (select ix = patindex('%<c24>%', cocode) + 6) ap
where       substring(cocode, ix, 1) = 'G'
User contributions licensed under: CC BY-SA
1 People found this is helpful