开发者

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 u开发者_如何学Csing 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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜