sp_send_dbmail预定作业仅执行IF结果<> 0

时间:2014-05-13 08:21:07

标签: sql sql-server-2008 scheduled-tasks sp-send-dbmail

我有以下预定工作 -

Execute as login = 'sa'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQL Mail Profile',
@recipients = 'Tania.Mofflin@fuelfix.com.au',
@subject = 'Wennsoft Service Management - Unposted Costs',
@body = 'Unposted Costs from Closed POs:
        ',
@execute_query_database = 'FPLL',
@query = 'Select A.Service_Call_ID as "Service Call", A.Reference_TRX_Number as "Reference Number", A.WS_Committed_Cost as "Committed Cost"
            from SV000810 A LEFT JOIN POP10110 B on A.Reference_TRX_Number = B.PONUMBER and A.SEQNUMBR = B.ORD
            where A.WS_Committed_Cost <> 0 and B.QTYUNCMTBASE = 0'

哪个工作正常,但我想包含一个IF语句,只有在没有结果的情况下才会执行。

三江源

1 个答案:

答案 0 :(得分:0)

这是一个老问题,但...... 由于你正在使用的工作步骤只是T-SQL,你可以这样做:

IF exists(Select *
        from SV000810 A LEFT JOIN POP10110 B on A.Reference_TRX_Number = B.PONUMBER and 
        A.SEQNUMBR = B.ORD where A.WS_Committed_Cost <> 0 and B.QTYUNCMTBASE = 0)
BEGIN
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQL Mail Profile',
@recipients = 'Tania.Mofflin@fuelfix.com.au',
@subject = 'Wennsoft Service Management - Unposted Costs',
@body = 'Unposted Costs from Closed POs:
        ',
@execute_query_database = 'FPLL',
@query = 'Select A.Service_Call_ID as "Service Call", A.Reference_TRX_Number as 
    "Reference Number", A.WS_Committed_Cost as "Committed Cost"
        from SV000810 A LEFT JOIN POP10110 B on A.Reference_TRX_Number = B.PONUMBER and 
        A.SEQNUMBR = B.ORD
        where A.WS_Committed_Cost <> 0 and B.QTYUNCMTBASE = 0'
END

请注意查询在此处运行两次,因此效果不佳。您可以将查询结果转储到临时表中,然后使用临时表执行EXISTS()和电子邮件,或者如果您愿意,可以使用表变量。以上只是您尝试的最快捷途径。