Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 SQL Select query from XML

Author  Topic 

atlzonlyplayer
Starting Member

1 Post

Posted - 2010-11-16 : 01:52:50
Hi guys, I am trying to figure out how to write a select sql query for the xml data below. I cannot get the query to give me exactly whats displayed. Any help would be appreciated. The tables look like this

Orders, Products, and, Order Details which has the foreign key of OrderId and ProductId from the Products and Orders table.

<Orders>
<PurchaseOrder>
<OrderID>10248</OrderID>
<OrderDate>1996-07-04T00:00:00</OrderDate>
<OrderDetails>
<Item ProductID="11" UnitPrice="14.0000" Quantity="12" />
<Item ProductID="42" UnitPrice="9.8000" Quantity="10" />
<Item ProductID="72" UnitPrice="34.8000" Quantity="5" />
</OrderDetails>
</PurchaseOrder>
<PurchaseOrder>
<OrderID>10249</OrderID>
<OrderDate>1996-07-05T00:00:00</OrderDate>
<OrderDetails>
<Item ProductID="14" UnitPrice="18.6000" Quantity="9" />
<Item ProductID="51" UnitPrice="42.4000" Quantity="40" />
</OrderDetails>
</PurchaseOrder>
</Orders>

Sachin.Nand

2937 Posts

Posted - 2010-11-16 : 08:29:07
Try this.You can do it for the other columns in the xml

declare @x xml='<Orders>
<PurchaseOrder>
<OrderID>10248</OrderID>
<OrderDate>1996-07-04T00:00:00</OrderDate>
<OrderDetails>
<Item ProductID="11" UnitPrice="14.0000" Quantity="12" />
<Item ProductID="42" UnitPrice="9.8000" Quantity="10" />
<Item ProductID="72" UnitPrice="34.8000" Quantity="5" />
</OrderDetails>
</PurchaseOrder>
<PurchaseOrder>
<OrderID>10249</OrderID>
<OrderDate>1996-07-05T00:00:00</OrderDate>
<OrderDetails>
<Item ProductID="14" UnitPrice="18.6000" Quantity="9" >tes </Item>
<Item ProductID="51" UnitPrice="42.4000" Quantity="40" />
</OrderDetails>
</PurchaseOrder>
</Orders>'

select x.i.value('../../OrderID[1]','varchar(40)'),
x.i.value('../../OrderDate[1]','varchar(40)'),
x.i.value('@ProductID','varchar(40)')
from @x.nodes('Orders/PurchaseOrder/OrderDetails/Item')x(i)


PBUH

Go to Top of Page
   

- Advertisement -