Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a part of XML node in SQL Server 2005

I would like to know how I can update a part of the text of an XML node in SQL Server 2005 using xquery

In the following example I would like to replace the word "very" with "excellent"

    declare @xml as xml
    set @xml = '<root><info>well hello this is a very good example</info></root>'
    declare @replacement as varchar(50)
    set @replacement = 'excellent'
    declare @search as varchar(50)
    set @search = 'very'

    set @xml.modify('replace value of (/root/info/text())[1]
                     with replace((/root/info/text())[1],sql:variable("@search"),sql:variable("@replacement"))'
        )
    select @xml

Any help would be appreciated

like image 940
Peter Avatar asked Nov 04 '22 22:11

Peter


1 Answers

Since this word you want to replace isn't the contents of a XML tag - but only part of that content - you might just want to check out text-based replacement options.

It would work if you had something like this:

declare @xml as xml

set @xml = '<root><info>well hello this is a <rating>very good</rating> example</info></root>'

Then, you could reach into the XML and replace the contents of <rating>....</rating> with something else:

declare @replacement as varchar(50)
set @replacement = 'excellent'

set 
    @xml.modify('replace value of (/root/info/rating/text())[1]
                 with sql:variable("@replacement")')

select @xml

But as it stands now, you probably have to grab the textual contents of the <info> and do a textual replace on that:

DECLARE @xml as XML
SET @xml = '<root><info>well hello this is a very good example</info></root>'

DECLARE @newcontent VARCHAR(1000)
SELECT @newcontent = @xml.value('(/root/info/text())[1]', 'VARCHAR(1000)')

-- replace "very" with "excellent"    
SELECT @newcontent = REPLACE(@newcontent, 'very', 'excellent')

SET 
@xml.modify('replace value of (/root/info/text())[1]
                 with sql:variable("@newcontent")')

SELECT @xml
like image 146
marc_s Avatar answered Nov 09 '22 12:11

marc_s