开发者

Sql Server XQuery transform xml in select clause

开发者 https://www.devze.com 2023-02-14 19:23 出处:网络
Is there some way to transform/project XML from an XML columnin the select clause of an Sql Server query?

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>
  &开发者_C百科lt;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.


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')
0

精彩评论

暂无评论...
验证码 换一张
取 消