我即将完成一项查询,该查询旨在向通过特定软件处理订单时提交错误的人发送每日电子邮件更新。数据是从CTE中的表中提取的。如果我将@ExcelOutput变量设置为以下内容,则运行查询并发送电子邮件:
SET @ExcelOutput = ('SELECT [Rep Name], [Temp Rep Number], [Error Code], [Account Number], [Report Date] FROM ##TempEmailTest')
但是,如果我添加一个where子句,我需要添加该子句以使逻辑正常工作,该查询将引发以下错误:
Msg 22050,Level 16,State 1,Line 7 无法初始化sqlcmd库,错误号为-2147467259。
SET @ExcelOutput = ('SELECT [Rep Name], [Temp Rep Number], [Error Code], [Account Number], [Report Date] FROM ##TempEmailTest WHERE [Temp Rep Number] >= @Loop')
以下是完整查询:
IF OBJECT_ID('tempdb..##TempEmailTest') IS NOT NULL
BEGIN
DROP TABLE ##TempEmailTest
END
USE MyDataBase
GO
WITH CTE AS
(SELECT
a.[Temp Rep Number],
a.[Rep Name],
a.[Error Code],
a.[Account Number],
a.[Report Date],
a.[Test Email]
FROM
(SELECT
DENSE_RANK() OVER(ORDER BY org.[Rep Name]) AS [Temp Rep Number],
org.[Rep Name],
tab.[Error Code],
tab.[Account Number],
tab.[Report Date],
'test@test.com' AS [Test Email]
FROM tbl_mytable org
INNER JOIN tbl_mytable1 tab ON org.[Rep Name] = tab.[Rep Name]
WHERE tab.[Total Errors] <> 0
AND tab.[Report Date] = CONVERT(VARCHAR(8),GETDATE(),1)) AS a)
SELECT
[Temp Rep Number],
[Rep Name],
[Error Code],
[Account Number],
[Report Date],
[Test Email]
INTO ##TempEmailTest
FROM CTE
DECLARE @Loop int
SET @Loop = 1
DECLARE @LoopEnd int
SET @LoopEnd = (SELECT MAX([Temp Rep Number]) AS [Temp Row Number] FROM ##TempEmailTest)
WHILE @Loop <= @LoopEnd
BEGIN
DECLARE @TempRepNumber int
DECLARE @RepName nvarchar(MAX)
DECLARE @RepEmail nvarchar(MAX)
DECLARE @AccountNumber varchar(MAX)
DECLARE @ErrorCode varchar(Max)
DECLARE @ExcelOutput varchar(2048)
SELECT
@TempRepNumber = [Temp Rep Number],
@RepName = [Rep Name],
@Accountnumber = [Account Number],
@ErrorCode = [Error Code]
FROM ##TempEmailTest
WHERE @Loop = [Temp Rep Number]
SET @RepEmail = (SELECT
Email.[Test Email]
FROM
(SELECT
ROW_NUMBER() OVER(ORDER BY [Test Email]) AS [Email Row],
[Test Email]
FROM ##TempEmailTest
WHERE [Temp Rep Number] = @Loop) AS Email
WHERE Email.[Email Row] = 1)
SET @ExcelOutput = ('SELECT [Rep Name], [Temp Rep Number], [Error Code], [Account Number], [Report Date] FROM ##TempEmailTest WHERE [Temp Rep Number] = @Loop')
exec msdb.dbo.sp_send_dbmail
@profile_name = 'test_profile',
@recipients = @RepEmail,
@from_address = 'Test@test1.com',
@subject = 'test',
@body = 'test',
@query = @ExcelOutput,
@attach_query_result_as_file = 1,
@query_attachment_filename = 'test.csv',
@query_result_separator=',', --enforce csv
@query_result_no_padding=1, --trim
@query_result_width=32767 --stop wordwrap
SET @Loop = @Loop + 1
END
答案 0 :(得分:0)
试试这个https://www.sqlservercentral.com/Forums/Topic723716-338-1.aspx
SET @ExcelOutput = 'SET NOCOUNT ON SELECT [Rep Name], [Temp Rep Number], [Error Code], [Account Number], [Report Date] FROM ##TempEmailTest WHERE [Temp Rep Number] >' + cast(@Loop as varchar(3))