Thursday, October 14, 2010

Pivot In SQL SERVER

Hi Frendz..

HERE is Final Table #Example & it's Pivot.. 


declare @columnheader varchar(max)

Select @columnheader = COALESCE(@columnheader + ',isnull([' + cast(@FieldName as varchar) + '],0)','isnull([' + cast(@FieldName as varchar)+ '],0)')
FROM #Example

 DECLARE @query VARCHAR(max)
SET @query = 'SELECT * into fianltable FROM #Example
PIVOT
 (
 SUM(Col1)  
 FOR [MergeValue]  IN (' + @columnheader + ')
 )
 AS p order by ' + @columnheader + ''

EXECUTE(@query)


select * from fianltable
drop table fianltable

No comments: