Reputation: 23214
Is there some way to transform/project XML from an XML column in the select clause of an Sql Server query?
Lets say we have a table with Id:Guid , Data:XML .
And lets say we have the following data in the "Data" column:
<Order>
<Details>
<Detail>
<Quantity>10</Quantity>
<ItemPrice>20</Quantity>
</Detail>
<Detail>
<Quantity>10</Quantity>
<ItemPrice>20</Quantity>
</Detail>
</Details>
</Order>
is there any way to project this (using a select + xquery) into , say for example:
<Order>
<Details>
<Detail>
<LineTotal>200</LineTotal>
</Detail>
<Detail>
<LineTotal>200</LineTotal>
</Detail>
</Details>
</Order>
I'm not interested in how this can be done in memory of my app, I want a server side transform in the select clause in the sql query.
Upvotes: 1
Views: 1536
Reputation: 107696
Produces exactly the output you want, but SQL Server XML is quite limited. In this example, you really need to know exactly how to (re)produce the entire tree - with the variation "hand coded".
declare @tbl table (id uniqueidentifier, data xml)
insert @tbl select newid(), '
<Order>
<Details>
<Detail>
<Quantity>10</Quantity>
<ItemPrice>20</ItemPrice>
</Detail>
<Detail>
<Quantity>10</Quantity>
<ItemPrice>20</ItemPrice>
</Detail>
</Details>
</Order>'
select ((
select d.d.value('(Quantity)[1]','int') * d.d.value('(ItemPrice)[1]','int') [LineTotal]
from ds.ds.nodes('Detail') d(d)
for xml path('Detail'), type)) Details
from @tbl t
cross apply data.nodes('Order/Details') ds(ds)
for xml path('Order')
Upvotes: 5