我有一个向客户发送生日电子邮件的代码,查询工作正常,但是SQL Mail服务器始终向所有客户发送生日电子邮件,即使他没有生日
use Insurance
go
select
Customer.CustomerID
,Customer.FirstName
,Customer.LastName
,Customer.Birthday
,Customer.Email
from Customer
where Customer.CustomerID = Customer.CustomerID and
DAY([Birthday]) = DAY(GETDATE())
AND MONTH([Birthday]) = MONTH(GETDATE())
declare @Receipientlist nvarchar(4000)
set @Receipientlist =
STUFF((select ';' + Email FROM dbo.Customer FOR XML PATH('')),1,1,'')
EXEC msdb.dbo.sp_send_dbmail @profile_name='test',
@recipients=@Receipientlist,
@subject='Insurance',
@body='Happy Birthday.
Today is your Birthday.'
答案 0 :(得分:1)
您在批次顶部的查询与您执行manifest
的语句无关。如果只想通过电子邮件发送客户生日的信息,则需要在创建收件人的语句中进行过滤(并且不需要上一个语句):
msdb.dbo.sp_send_dbmail
我还改变了使用DECLARE @RecipientList nvarchar(4000);
--I removed the CustomerID = CustomerID clause, as it'll always equal itself,
--apart from when it's value is NULL (and I doubt it'll ever be NULL)
SET @RecipientList = STUFF((SELECT N';' + Email
FROM dbo.Customer
WHERE DAY([Birthday]) = DAY(GETDATE())
AND MONTH([Birthday]) = MONTH(GETDATE())
FOR XML PATH(N''),TYPE).value('.','nvarchar(4000)'), 1, 1,N'');
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'test',
@recipients = @RecipientList,
@subject = 'Insurance',
@body = 'Happy Birthday.
Today is your Birthday.';
和TYPE
子句从子查询返回值的方式。电子邮件地址可以包含一些特殊字符,这些特殊字符将在不使用value
的情况下被转义(例如,TYPE
将变为&
)。 (我还纠正了&
的拼写。)