我想知道如何使用xquery
更新SQL Server 2005中XML节点的部分文本在以下示例中,我想将“very”替换为“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
任何帮助将不胜感激
答案 0 :(得分: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