我想添加一个具有表列中的值的节点。我的例子如下
declare @table table (bookid int,xmlCol xml)
insert into @table
select 1,
'<book title="you are not alone" author="Esther">
<EDITIONS>
<edition year="2012"/>
<edition year="2013"/>
</EDITIONS>
</book>'
declare @table1 table(bookid int,seller varchar(5))
insert into @table1
select 1,'xyz'
select ???
from @table t
inner join @table1 t1
on t.bookid = t1.bookid
我希望我的最终结果是这样的
<book title="you are not alone" author="Esther">
<EDITIONS>
<edition year="2012"/>
<edition year="2013"/>
</EDITIONS>
<seller> XYZ</seller>
</book>
我不想更新,我认为它可以在 xquery 中完成,但我找不到任何如何执行此操作的示例。不久前我有一个关于添加属性的类似问题,并对 Roman Pekar 的回答感到满意。 add column value to an xml field as an attribute
最佳答案
无法将元素添加到查询中的现有 XML。不过,您可以使用 XML 本身重新创建 XML,并添加所需的新元素或属性。
Roman Pekar 出现在 his answer对于您的另一个问题,您可以使用一种技巧,如果您了解他的作用,您应该能够调整该答案以适合您。
您需要创建一个新的根元素book
,添加现有元素book中的属性,添加book中的子元素,最后使用sql:column
添加新元素code> 提取值。
select T.xmlCol.query('element book {
book/@*, (:Add attributes from root node:)
book/*, (:Add sub nodes from root node:)
element seller (:Add the new element:)
{sql:column("T1.seller")} (:Get the value for the new node:)
}')
from @table as T
inner join @table1 as T1
on T.bookid = T1.bookid
关于sql-server - 在选择查询中向 xml 列添加节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20886999/