2013-10-02 26 views
2

我想將屬性值添加到查詢中的xml字段。我的例子如下將列值添加到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> 

回答

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

甚至simplier:

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

如果你可以使用令牌在XML的身體,你可以使用替代()來代替令牌與數量值。

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中的值,並將結果寫入另一個表以進行最終輸出。

+0

第一個解決方案的工作原理,但有另一種方法來解決這個問題嗎?我最好不要改變表中的xml結構 – user829982