存储过程中执行SQL语句,如果查询结果集不为空,则将发送Mail告诉结果
这是我新建的存储过程,请大家帮忙看下,IF判断语句是不是哪里写的有问题,在编译完成后,调用存储过程,不管SQL语句查询结果集是否为空,都发出了Mail,只要结果集不为空,才发出Mail就行。
USE [LTDB]
GO
/****** Object: StoredProcedure [dbo].[sp2_SendMail] Script Date: 02/17/2012 08:32:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp2_SendMail]
@recipients VARCHAR(MAX) = NULL,
@subject NVARCHAR(255) = NULL,
@body NVARCHAR(MAX) = NULL,
@query NVARCHAR(MAX) = NULL,
@MailFrom sysname = 'rick@SERVMS.COM',
@attach_query_result_as_file BIT = 0,
@query_attachment_filename NVARCHAR(260) = NULL,
@query_result_header BIT = 1
As
set @query = 'select Username from ltdb..bd_user a left join ifdb..employee b on a.username=b.emplid where a.username not in("CAR","Jeck") and b.emplid is null'
begin
if @query <>''
exec msdb..sp_send_dbmail
@profile_name = 'rick@SERVMS.COM' --寄件人
,@recipients = 'rick@SERVMS.COM' --收件人
,@subject = 'Check' --主题
,@body = 'These accounts were not in the employee list. Please see the detail information in the attachment.' --正文
,@query = @query --要执行的查询
,@attach_query_result_as_file = 1
end
------解决方案--------------------
if @query <>''你自己看看你这个@query是什么东西。。它怎么可能为空。。
------解决方案--------------------你可以判断查询结果有多少个,根据个数判断
------解决方案--------------------发送邮件这样的SQL函数都用到了,获得SQL返回记录数量这样的事情还不知道吗?
theforever_csdn_sqlNums:='select count(*) from l表名 where 其它条件'
--执行sql语句,返回结果赋值给rowsCount
execute immediate theforever_csdn_sqlNums into RowsCount;
再判断RowsCount就可以了。