TamarGranor
Programmer
SQL Server 2008 R2
I'm trying to understand the FOR XML PATH('') and how it's used when you want to combine multiple values from a column into a single record. To experiment, I'm using the AdventureWorks database.
My simple example is to get a list of orders with a comma-separated (or semi-colon separated) list of the items in that order. I'm modeling my code after what I found here:
[URL unfurl="true"]http://www.mssqltips.com/sqlservertip/2914/rolling-up-multiple-rows-into-a-single-row-and-column-for-sql-server-data/[/url]
Specifically, at this point, I'm up to what is titled "Example 1". But something's not working.
When I use this code:
I get the error:
Msg 8120, Level 16, State 1, Line 4
Column 'Purchasing.PurchaseOrderDetail.ProductID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Not surprisingly, if I remove the GROUP BY, I get one row per product.
I know there are other ways to solve this particular problem, but I'm trying to understand this approach. What am I missing?
Tamar
I'm trying to understand the FOR XML PATH('') and how it's used when you want to combine multiple values from a column into a single record. To experiment, I'm using the AdventureWorks database.
My simple example is to get a list of orders with a comma-separated (or semi-colon separated) list of the items in that order. I'm modeling my code after what I found here:
[URL unfurl="true"]http://www.mssqltips.com/sqlservertip/2914/rolling-up-multiple-rows-into-a-single-row-and-column-for-sql-server-data/[/url]
Specifically, at this point, I'm up to what is titled "Example 1". But something's not working.
When I use this code:
Code:
SELECT PurchaseOrderID,
(SELECT ';' + Name
FROM Production.Product
WHERE Purchasing.PurchaseOrderDetail.ProductID = Production.Product.ProductID
FOR XML PATH('')) OrderProducts
FROM Purchasing.PurchaseOrderDetail
GROUP BY PurchaseOrderID
ORDER BY 1
I get the error:
Msg 8120, Level 16, State 1, Line 4
Column 'Purchasing.PurchaseOrderDetail.ProductID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Not surprisingly, if I remove the GROUP BY, I get one row per product.
I know there are other ways to solve this particular problem, but I'm trying to understand this approach. What am I missing?
Tamar