Tuesday, July 22, 2008

Using XML to Pivot

Here is a simple example that shows how to use XML to pivot data.

--Create Temp Table and Insert some sample data
DECLARE @Table TABLE (tst VARCHAR(10))
INSERT INTO @Table VALUES(1)
INSERT INTO @Table VALUES(2)
INSERT INTO @Table VALUES(3)
INSERT INTO @Table VALUES(4)

--Select the original data set
SELECT * FROM @Table

--Now pivot the data using XML
SELECT STUFF(( SELECT ',' + tst
FROM @Table
FOR XML PATH('')
),
1, 1, '')


0 comments: