Wednesday, January 5, 2011

Stored Procedure to Create Dynamic PIVOT in SQL

We can create dynamic PIVOT in SQL. Check the below example

CREATE PROCEDURE [dbo].[Trainings]

-- Add the parameters for the stored procedure here

AS
BEGIN

SET NOCOUNT ON;
DECLARE @Columns varchar(8000)
DECLARE @SQL varchar(8000)

--Create PIVOT table fields list in ('', '') format

SET @Columns = substring((select ',['+Training_Name+']' from View_Training group by Training_Name for xml path('')),2,8000)

--PIVOT table query

SET @SQL = 'SELECT * FROM
(Select * from View_Training) CrossTraning
PIVOT
(max(Status) for Training_Name in ('+@Columns+')) pivottable'

EXEC(@sql)
END

No comments:

Post a Comment