Wednesday, 28 May 2014

Transpose Datatable value from Sql server query using PIVOT Store Procedure


//***************Conditions from server side

CREATE Procedure [TransposeTable]        
    @conditionCol nvarchar(max)          
as        
Begin        
Declare @cols nvarchar(max)        
DECLARE @query AS NVARCHAR(MAX);                
SELECT @query ='SELECT * FROM(SELECT [Columns],  [Columnsid]        
FROM TransposeTable        
) AS source        
PIVOT        
(    MAX(ColumnsID)        
   FOR Columns IN( ' + @conditionCol + ' )' +        
' ) as pvt'        
execute(@query);        
End

//***************Conditions with Inner Query


CREATE Procedure [TransposeTable]                
as        
Begin        
Declare @cols nvarchar(max)        
DECLARE @query AS NVARCHAR(MAX);        
select @cols = STUFF((SELECT  distinct  ',' + QUOTENAME([Columns])  from [TransposeTable]        
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')        
SELECT @query ='SELECT  * FROM(SELECT [Columns],  [Columnsid]        
FROM TransposeTable        
) AS source        
PIVOT        
(    MAX([Columnsid])        
   FOR [Columns] IN( ' + @cols + ' )' +        
' ) as pvt'        
execute(@query);        
End



No comments:

Post a Comment

How to highlight selected text in notepad++

  –> To highlight a block of code in Notepad++, please do the following steps step-1  :- Select the required text. step-2  :- Right click...