Friday, July 15, 2016
SQL Query - Get multiple row results in one column with XML and STUFF()
Today I want to show you, how you can put the results of an SQL query into one column.
First I create a temporarily table for our data and fill some data in it:
CREATE TABLE #table (product nvarchar(255))
INSERT INTO #table
SELECT 'product-1' as product
UNION
SELECT 'product-2' as product
UNION
SELECT 'product-3' as product
UNION
SELECT 'product-4' as product
Now we have our base table for our query. Here are the results of this table
Query:
select * from #table
Results:
product
product-1
product-2
product-3
product-4
Now we can see, we have 4 rows with our example products. Maybe we have a requirement to put all products in one row. This can be done by using the STUFF function and XML.
Here is the code:
select STUFF((SELECT distinct ',' + t.product
from #table t (nolock)
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'') as allProducts
Now the result of this query is this:
allProducts
product-1,product-2,product-3,product-4
Hope you enjoyed this lesson.
Labels:
Code Snippet,
SQL Server 2008,
SQL Server 2014 Express,
STUFF,
Transact SQL,
XML
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment