5

我想知道如何使用 xquery 更新 SQL Server 2005 中 XML 节点的部分文本

在下面的例子中,我想用“excellent”替换“very”这个词

    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

任何帮助,将不胜感激

4

1 回答 1

2

由于您要替换的这个词不是 XML 标记的内容 - 而只是该内容的一部分 - 您可能只想查看基于文本的替换选项。

如果你有这样的东西,它会起作用:

declare @xml as xml

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

然后,您可以进入 XML 并用其他内容替换 的内容<rating>....</rating>

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
于 2011-05-03T12:31:46.830 回答