更改xml列中标记的值

时间:2011-10-13 09:45:37

标签: sql xml tsql

我有一些代码将新的xml标记与现有项的值一起添加到表MyTable中的XML MyColumn列。

UPDATE MyTable SET MyColumn.modify('insert element newItem {/ RootElement / ExistingItem / node()}之后(/ RootElement / ExistingItem)[1]')

我想要做的是编辑以xpath表达式表示的值。 假设我在ExistingItem元素中具有“Test”的值。 我希望在我的NewItem元素中有“测试其他东西”。

我该怎么办?

1 个答案:

答案 0 :(得分:1)

有些麻烦的解决方案,万一更简单的问题不会出现:

--sample data
declare @t table
(
    col xml
)

insert into @t select '<RootElement><ExistingItem>Test</ExistingItem></RootElement>'

--solution
--read existing element into a variable
declare @str varchar(50)
select @str = 'something ' + cast(t.c.query('data(.)') as varchar) + ' else'
from @t cross apply col.nodes('(/RootElement/ExistingItem)[1]') t(c)
--insert new element with the value of the variable
update @t set col.modify('insert element NewItem {sql:variable("@str")} after (/RootElement/ExistingItem)[1]')
select * from @t