一尘不染

将列值作为属性添加到xml字段

sql

我想将属性值添加到查询中的xml字段中。我的例子如下

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,quantity int)
insert into @table1
select 1,3

select ??? 
from @table t
inner join @table1 t1
on t.bookid = t1.bookid

我希望我的最终结果看起来像这样

<book title="you are not alone" author="Esther" quantity="3">
  <EDITIONS>
    <edition year="2012"/>
    <edition year="2013"/>
  </EDITIONS>
</book>

阅读 160

收藏
2021-03-08

共1个答案

一尘不染

如果需要选择数据,则可以使用xquery:

select
    t.xmlCol.query('
         element book {
             for $i in book/@* return $i,
             attribute quantity {sql:column("t1.quantity")},
             for $i in book/* return $i
         }
    ')
from @table t
    inner join @table1 t1 on t.bookid = t1.bookid

[sql fiddle demo](http://sqlfiddle.com/#!3/d41d8/21875)

甚至更简单:

select
    t.xmlCol.query('
         element book {
             book/@*,
             attribute quantity {sql:column("t1.quantity")},
             book/*
         }
    ')
from @table t
    inner join @table1 t1 on t.bookid = t1.bookid

[sql fiddle demo](http://sqlfiddle.com/#!3/d41d8/21883)

2021-03-08