Question

I have a SQL Server 2005 query that generates a large result set (up to several gigabytes):

SELECT * FROM Product FOR XML PATH('Product')

Running the query generates a single row containing a document with many product elements:

Row 1:
<Product>
  <Name>Product One</Name>
  <Price>10.00</Price>
</Product>
<Product>
  <Name>Product Two</Name>
  <Price>20.00</Price>
</Product>
...

I would like to change the query so that instead of a result set with one row containing a single document with multiple product elements, it returns multiple rows each with a single document consisting of a sing Product element:

Row 1:
<Product>
  <Name>Product One</Name>
  <Price>10.00</Price>
</Product>

Row 2:
<Product>
  <Name>Product Two</Name>
  <Price>20.00</Price>
</Product>

In the end, I would like to consume this query from C# with an IDataReader without either SQL Server or my application having the entire result set loaded in to memory. Are there any changes I could make to the SQL to enable this scenario?

Was it helpful?

Solution

I think you want something like this.(you can run below query on AdventureWorks)

SELECT ProductID
      ,( SELECT * FROM Production.Product AS b WHERE a.ProductID= b.ProductID FOR XML PATH('Name') ) AS RowXML
FROM  Production.Product AS a

OTHER TIPS

I Think This will give you good result,

SELECT top 3 Productid,Name, XmlColumn from Production.Product a cross apply ( select  top 1  a.* from Production.Product b FOR XML PATH('test')) as outputdata(XmlColumn)

If you know the column names, I'd rather avoid the nested select to the table

SELECT ProductID,(SELECT Name, Price FOR XML RAW('Product'),ELEMENTS) AS RowXML
FROM  Production.Product AS a

if PRICE and NAME are in one table Product

SELECT * FROM Product FOR XML AUTO, ELEMENTS

or, if not, you can create a view vw_Product which will return only 2 columns that you want and then write

SELECT * FROM vw_Product as Product FOR XML AUTO, ELEMENTS

you can use XmlReader to read from the results of this query row by row, to avoid loading big XML document in memory. See http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executexmlreader.aspx

in your query you used PATH('Product'), an this is why it produced a single node with all products.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top