So I have the below that will allow me to get xml from one record in the Products table.
However, I need to to be able to get the XML from ALL records in the Products table, along with its ProductId.
I’m confused on how to start this.
DECLARE @MyXML XML
SET @MyXML =
(SELECT ProductsXML
FROM Products
WHERE ProductId= 1)
SELECT
a.b.value('@upccode','int') as UPC,
a.b.value('@dateadded','date') as DateAdded
FROM
@MyXML.nodes('xml/Product/UPC')a(b);
I’m using SQL Server 2008.
Test Data:
ProductId: 1
ProductsXML:
<xml>
<Product>
<UPC upccode="1237" dateadded="10/9/2012"/>
<UPC upccode="1236" dateadded="10/8/2012"/>
<UPC upccode="1235" dateadded="10/7/2012"/>
<UPC upccode="1234" dateadded="10/6/2012"/>
</Product>
</xml>
ProductId: 2
ProductsXML:
<xml>
<Product>
<UPC upccode="9876" dateadded="9/9/2012"/>
<UPC upccode="9877" dateadded="9/8/2012"/>
<UPC upccode="0998" dateadded="9/7/2012"/>
<UPC upccode="7877" dateadded="9/6/2012"/>
</Product>
</xml>
The Result I’m looking for is something like this:
ProductId UPC DateAdded
--------- --- ---------
1 1237 10/9/2012
1 1236 10/8/2012
....
2 9876 9/9/2012
2 9877 9/8/2012
Right now I can get the above but ONLY by specifying one PoductId at a time. I want to be able to run all of the `Products’ without specifying each entry.
I guess you are looking for something like this.
There is no need to have a XML variable in there. Query the
Productstable directly and useCROSS APPLYagainstProductsXMLfield to shred your XML.