我想添加一个带有表列值的节点。我的例子在下面
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
答案 0 :(得分:3)
无法在查询中向现有XML添加元素。但是,您可以使用XML本身重新创建XML,并添加所需的新元素或属性。
Roman Pekar在his answer中向您提出了一个您可以使用的技巧,如果您了解他的所作所为,您应该能够在这里适应这个答案。
您需要创建一个新的根元素book
,添加现有元素簿中的属性,添加book中的子元素,最后使用sql:column
添加新元素以提取值。
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
答案 1 :(得分:2)
一种解决方案是将modify
method与insert XML DML statement一起使用:
declare @TableWXmlCol table (bookid int,xmlCol xml)
insert into @TableWXmlCol
select 1,
'<book title="you are not alone" author="Esther">
<EDITIONS>
<edition year="2012"/>
<edition year="2013"/>
</EDITIONS>
</book>'
declare @TableWSeller table(bookid int,seller varchar(5))
insert into @TableWSeller
select 1,'xyz'
UPDATE a
SET xmlCol.modify('insert <seller>{sql:column("b.seller")}</seller> into (/book)[1]')
FROM @TableWXmlCol a
INNER JOIN @TableWSeller b ON a.bookid = b.bookid;
SELECT *
FROM @TableWXmlCol;
输出:
/*
bookid xmlCol
------ ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 <book title="you are not alone" author="Esther"><EDITIONS><edition year="2012" /><edition year="2013" /></EDITIONS><seller>xyz</seller></book>
*/