EXEC msdb.dbo.sp_send_dbmail 忽略查询
EXEC msdb.dbo.sp_send_dbmail ignored Query
我有一个代码可以向客户发送生日电子邮件,查询工作正常,但是 SQL 邮件服务器总是向所有客户发送生日电子邮件,即使他没有生日
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.'
您在批处理顶部的查询与执行 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
,这些字符将被转义(例如 &
将变为 &
)。 (我也更正了 @RecipientList
的拼写。)
我有一个代码可以向客户发送生日电子邮件,查询工作正常,但是 SQL 邮件服务器总是向所有客户发送生日电子邮件,即使他没有生日
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.'
您在批处理顶部的查询与执行 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
,这些字符将被转义(例如 &
将变为 &
)。 (我也更正了 @RecipientList
的拼写。)