Click here to Skip to main content
15,893,668 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello All,

I am generating a pivot table,I also want to show the Grand Total field at the end
So I want to generate a table dynamically but I will not know in advance as to how
many columns it would have.Only I know in advance is the datatype is numeric(18,2).
Now can anyone help me to resolve this .

SQL
ALTER proc [dbo].[GetPivotData] @measure nvarchar(200),@Week NVARCHAR(100),@country nvarchar(100)
as 
begin

DECLARE @SQL  NVARCHAR(max)
DECLARE @OpID nvarchar(100)
DECLARE @cols NVARCHAR(2000)
DECLARE @QUERY NVARCHAR(4000)

Create Table #TempTbl(Week BIGINT,Measure numeric(18,2),Operator nvarchar(100))

DECLARE @getOperators CURSOR
SET @getOperators = CURSOR FOR Select distinct(Operator)from Data 
OPEN @getOperators
FETCH NEXT
FROM @getOperators INTO @OpID
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @SQL='SELECT TOP (8) ISNULL(Week,0) AS Week,'+@measure+' ,Operator='''+@OpID+''' FROM Data WHERE (Country ='''+@country+''') AND (Operator = '''+ @OPID +''')
 AND ( Week <'''+@Week+''') ORDER BY Week DESC'
Insert #TempTbl EXEC(@SQL)
FETCH NEXT
FROM @getOperators INTO @OpID
END
CLOSE @getOperators
DEALLOCATE @getOperators


SELECT  @cols = STUFF(( SELECT distinct '],['+Operator FROM  #TempTbl order by '],['+Operator FOR XML PATH('') ),1,2,'') + ']'
SET @QUERY='Select Week,'+@cols+' from(Select * from #TempTbl) as mytbl
pivot(sum(Measure)for Operator in ('+@cols+'))as PVTTBL Order by Week DESC'
EXEC(@QUERY)

END 

-- exec [getPivotData] '[TPDOC VOLUME]','201048','Australia'
Posted
Updated 24-Oct-11 3:24am
v2
Comments
m@dhu 24-Oct-11 9:25am    
Added code block.

1 solution

When running a query, you probably know number of columns that will be returned. If that is the case, you can return additional output parameter that will be equal to number of columns.

Otherwise, you may found information in this link
How To Retrieve Column Schema by Using the DataReader[^] helpful.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900