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

时间:2013-10-02 14:09:22

标签: sql sql-server xml sql-server-2008-r2 sqlxml

我想在查询中的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>

2 个答案:

答案 0 :(得分:3)

如果您需要选择数据,可以使用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

甚至更简单:

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

答案 1 :(得分:1)

如果您可以在XML正文中使用令牌,则可以使用replace()将该令牌替换为数量值。

declare @table table (bookid int,xmlCol NVARCHAR(MAX))
insert into @table
select 1,
'<book title="you are not alone" author="Esther" {quantity}>
  <EDITIONS>
    <edition year="2012"/>
    <edition year="2013"/>
  </EDITIONS>
</book>'

declare @table1 table(bookid int,quantity int)
insert into @table1
select 1,3 

select 
   CAST(REPLACE(t.xmlCol, '{quantity}', 'quantity="' + CAST(t1.quantity AS NVARCHAR(50)) + '"') AS XML) AS xmlCol
from @table t
inner join @table1 t1
on t.bookid = t1.bookid

否则你可以像这样使用xml.modify函数:

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 

DECLARE 
     @myDoc XML
    ,@Qty INT

SET @myDoc = (SELECT xmlCol FROM @table WHERE bookid = 1)
SET @Qty = (SELECT quantity FROM @table1 WHERE bookid = 1)

SET @myDoc.modify('           
insert attribute quantity {sql:variable("@Qty") }           
into   (/book) [1] ') 
SELECT @myDoc

看起来您不能在select语句中使用xml.modify,因此您可能需要使用循环来循环表和table1中的值,并将结果写入另一个表以进行最终输出。