Generate dynamic columns using a single variable for PIVOT

I came across this very handy way of dynamically formatting and converting tables rows into columns for a PIVOT statement. No CURSOR or CTE is required, just a single variable.

Run the example against a SQL 2012 instance and you will get the idea.

DECLARE @cols AS NVARCHAR(MAX)
--===============================================================
-- BUILD THE IN STRING LIST - NEAT TRICK
--===============================================================
BEGIN
	SELECT @cols =	ISNULL(@cols + ', [', '[') 
			+ CAST([subsystem] as NVARCHAR(100))+ ']'
	  FROM [msdb].[dbo].[syssubsystems]
END

SELECT @cols

This works in SQL Server 2000, 2005, 2008, 2012.

, ,

No comments yet.

Leave a Reply