How to export dynamic SQL Server pivot table to excel
NickName:Rinus Ask DateTime:2015-04-22T16:58:19

How to export dynamic SQL Server pivot table to excel

I'm working on a webapp that displays data from a Microsoft SQL Server dynamic pivot table.

Normally I'd try and figure out a way to do the dynamic pivot in c#, but in this case the pivot has to be a SQL Server stored procedure because other apps also need access to the pivot table.

Here's the SQL:

DECLARE @DynamicPivot AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

SELECT 
    @ColumnName = ISNULL(@ColumnName + ',', '') 
                  + QUOTENAME(xml_tag_name)
FROM 
    (SELECT DISTINCT xml_tag_name FROM DataEntries) AS TagValues

SET @DynamicPivot =
N'SELECT DISTINCT capture_id, ' + @ColumnName + '
FROM DataEntries
PIVOT(MAX(xml_tag_value) 
FOR xml_tag_name IN (' + @ColumnName + ')) AS PVTTable'

EXEC sp_executesql @DynamicPivot

All the articles I've gone through deal with normal export to Excel or static pivots. eg: Export Table from SQL Server to Excel 2007 using C#.

How do I go about exporting this dynamic pivot to Excel?

Copyright Notice:Content Author:「Rinus」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/29792506/how-to-export-dynamic-sql-server-pivot-table-to-excel

More about “How to export dynamic SQL Server pivot table to excel” related questions