SQL Server中Dynamic Pivot的电子邮件结果

时间:2015-12-22 19:56:48

标签: sql sql-server sql-server-2012 pivot

*****EDIT*****

The problem resulted from using a temp table. Therefore this post was marked as a duplicate.

我编写了一个动态选择Pivot列的查询。当我像EXEC sp_executesql @DynamicPivotQuery

那样执行它时,查询工作正常

动态支点看起来像这样(它有效):

DECLARE @DynamicPivotQuery AS nvarchar(MAX)
DECLARE @PivotColumnNames AS nvarchar(MAX)
DECLARE @PivotSelectColumnNames AS nvarchar(MAX)

SELECT @PivotColumnNames = UPPER(ISNULL(@PivotColumnNames + ',','') 
                           + QUOTENAME(CSR)) FROM (SELECT DISTINCT CSR FROM #stats) AS CSRs
SELECT @PivotSelectColumnNames = 
                                 UPPER(ISNULL(@PivotSelectColumnNames + ',','')
                                 + 'ISNULL(' + QUOTENAME(CSR) + ', 0) AS '
                                 + QUOTENAME(CSR))
FROM (SELECT DISTINCT CSR FROM #stats) AS CSRs

SET @DynamicPivotQuery = 
N'SELECT Category, ' + @PivotSelectColumnNames + '
FROM #stats 
PIVOT (
    MAX([COUNT])
    FOR CSR IN (' + @PivotColumnNames + ')) as PivotTable'

我想将这些结果通过电子邮件发送给SQL Server代理作业。

当我执行下面的sp_send_dbmail时,它会抛出一个错误:

EXEC msdb.dbo.sp_send_dbmail
@profile_name='donotreply'
,@recipients ='****@****.com'
,@query= @DynamicPivotQuery
,@subject= 'Weekly Stats for New Sales, Winbacks, and TPV by Reps'
,@attach_query_result_as_file=1
,@query_attachment_filename='Customer Service Report.csv'
,@query_result_separator=',' --enforce csv
,@query_result_no_padding=1 --trim
,@query_result_width=32767  --stop wordwrap

这是它抛出的错误:

Msg 22050, Level 16, State 1, Line 0
Error formatting query, probably invalid parameters
Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 517
Query execution failed: Msg 208, Level 16, State 1, Server CV-SQL2012\CVOSSQL, Line 1
Invalid object name '#stats'.

我尝试使用更简单的查询来代替@DynamicPivotQuery执行电子邮件SP并且它有效。

感谢您阅读

1 个答案:

答案 0 :(得分:1)

您需要在创建临时表的相同动态上下文中执行sendmail

或者切换到全局临时表或永久表。