0

我正在开发一个显示来自 Microsoft SQL Server 动态数据透视表的数据的 web 应用程序。

通常我会尝试找出一种在 c# 中进行动态数据透视的方法,但在这种情况下,数据透视必须是 SQL Server 存储过程,因为其他应用程序也需要访问数据透视表。

这是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

我读过的所有文章都涉及正常导出到 Excel 或静态数据透视表。例如:使用 C# 将表从 SQL Server 导出到 Excel 2007

如何将此动态数据透视表导出到 Excel?

4

1 回答 1

0

这是给你的一个例子。

它创建到全局临时表的动态数据透视表,然后将其导出到 Excel。如果您发现导出部分有问题 - 请告诉我。

CREATE TABLE Table1 (ColId INT,ColName VARCHAR(10))
INSERT INTO Table1 VALUES(1, 'Country')
INSERT INTO Table1 VALUES(2, 'Month')
INSERT INTO Table1 VALUES(3, 'Day')

CREATE TABLE Table2 (tID INT,ColID INT,Txt VARCHAR(10))

INSERT INTO Table2 VALUES (1,1, 'US')
INSERT INTO Table2 VALUES (1,2, 'July')
INSERT INTO Table2 VALUES (1,3, '4')
INSERT INTO Table2 VALUES (2,1, 'US')
INSERT INTO Table2 VALUES (2,2, 'Sep')
INSERT INTO Table2 VALUES (2,3, '11')
INSERT INTO Table2 VALUES (3,1, 'US')
INSERT INTO Table2 VALUES (3,2, 'Dec')
INSERT INTO Table2 VALUES (3,3, '25')


DECLARE @cols NVARCHAR(2000);
SELECT  @cols = COALESCE(@cols + ',[' + colName + ']', '[' + colName + ']')
FROM    Table1
ORDER BY colName;
IF OBJECT_ID('tempdb..##t1') IS NOT NULL
    BEGIN
        DROP TABLE ##t1;
    END;

DECLARE @query NVARCHAR(4000);
SET @query = N'SELECT tID, ' + @cols + ' into ##t1
FROM
(SELECT  t2.tID
      , t1.ColName
      , t2.Txt
FROM    Table1 AS t1
        JOIN Table2 AS t2 ON t1.ColId = t2.ColID) p
PIVOT
(
MAX([Txt])
FOR ColName IN
( ' + @cols + ' )
) AS pvt
ORDER BY tID;';


EXECUTE(@query);

SELECT  *
FROM    ##t1;


DECLARE @sql VARCHAR(MAX);
DECLARE @FileName VARCHAR(MAX) = 'C:\Test.xls';
SET @sql = 'INSERT INTO OPENROWSET(''Microsoft.ACE.OLEDB.12.0'',''Excel 12.0;Database='
    + @FileName + ''',''SELECT * FROM [Sheet1$]'') SELECT * FROM ##T1';
EXECUTE(@sql);
于 2015-04-22T19:45:06.043 回答