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を使用できるようには見えないため、ループを使用してテーブルとテーブル1の値をループし、最終出力のために結果を別のテーブルに書き込む必要がある場合があります。

于 2013-10-02T15:44:30.003 に答える