TSQL: One Row Per Element With FOR XML

*爱你&永不变心* 提交于 2019-12-04 23:58:15

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

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 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.

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!