3

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

2 回答 2

4

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

于 2013-10-02T18:46:19.810 回答
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,因此您可能需要使用循环来循环 table 和 table1 中的值并将结果写入另一个表以进行最终输出。

于 2013-10-02T15:44:30.003 回答