问题
I would like to add an attribute value to an xml field in a query. my example is below
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
I want my final result to look like this
<book title="you are not alone" author="Esther" quantity="3">
<EDITIONS>
<edition year="2012"/>
<edition year="2013"/>
</EDITIONS>
</book>
回答1:
IF you need select data, you can use 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
or even 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
回答2:
If you can use a token in the body of the XML you could use a replace() to replace the token with the quantity value.
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
Otherwise you could use the xml.modify function like so:
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
It does not look like you can use the xml.modify in a select statement so you may need to use a loop to loop the vales in table and table1 and write the results to another table for final output.
来源:https://stackoverflow.com/questions/19138953/add-column-value-to-an-xml-field-as-an-attribute