我有一个使用命令数据透视表构建的表。 我正在编写一个程序(C#),它将sql查询的结果插入到excel文件中。 我使用库ClosedXML.Excel,System.Data.SqlClient;。 我在插入值数据透视表(1,1)时遇到问题,其余值插入到excel文件中。 数据类型错误:1、1。 在程序中,我使用以下数据类型。
switch (dr.GetDataTypeName(j))
{
case "Varchar2":
string s = dr.GetString(j);
if (s.Substring(0, 1) == "=")
s = " " + s;
ws.Cell(row, j + 1).Value = s;
break;
case "decimal":
ws.Cell(row, j + 1).Value = dr.GetDecimal(j);
break;
case "datetime":
ws.Cell(row, j + 1).Value = dr.GetDateTime(j);
break;
case "int":
ws.Cell(row, j + 1).Value = dr.GetInt32(j);
break;
case "varchar":
ws.Cell(row, j + 1).Value = dr.GetString(j);
break;
default:
break;
}
mssql查询
DECLARE @employeeA NVARCHAR (MAX) SET @employeeA = 'Bob'
DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + CONVERT(NVARCHAR, [date_A], 106) + ']',
'[' + CONVERT(NVARCHAR, [date_A], 106) + ']')
FROM (SELECT DISTINCT [date_A] FROM [dbo].[#TABLE_1]) PV
ORDER BY [date_A]
DECLARE @queryD NVARCHAR(MAX)
SET @queryD = '
SELECT * into [dbo].[##RESULT] FROM (
select
Qty as numrow
,groups
,employee
,date_A
,''test1'' as NAMEROW
from [dbo].[#TABLE_1]
) x
PIVOT
(
sum([numrow])
FOR [date_A] IN (' + @cols + ')
) p
where employee = '''+@employeeA+'''
'
EXEC(@queryD)
select * from [dbo].[##RESULT]
结果查询:
groups employee NAMEROW 07.11.2018 08.11.2018
group1 Bob test1 1 1