How to replace part of XML node in SQL Server 2005

I would like to know how I can update part of XML node text 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

+5
source share
1 answer

Since this is the word you want to replace, it is not the content of the XML tag, but only part of that content - you might just want to check for text-based replacement options.

This will work if you have something like this:

declare @xml as xml

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

You can then turn to XML and replace the content <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

, , , <info> :

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
+2

All Articles