1 loops subquery sql-server-2008
我需要在 SQL Server 2008 中设置一个作业,以便在每个月的第一天向我们的客户发送电子邮件。但是,我不知道如何遍历子查询的结果。
导致此错误消息:
子查询返回了 1 个以上的值。当子查询跟随 =、!=、<、<=、>、>= 或当子查询用作表达式时,这是不允许的。
这是相关的代码:
SET @Recipients =(SELECT DISTINCT a.EMail
FROM a
--approximately 600 email addresses
SET @MailSubject = 'Customer News'
SET @MailRecipients = @Recipients
SET @MailMessage = 'Dear customer, Attached is your customer news letter.'
SET @FileName = N'E:file\to\be\attached.doc'
EXEC msdb.dbo.sp_send_dbmail @recipients = @MailRecipients,
@body = @MailMessage,
@blind_copy_recipients='misj@mikl.org',
@subject = @MailSubject,
@file_attachments = @FileName
Run Code Online (Sandbox Code Playgroud)
错误在这里,您有许多行试图分配给单个变量
SET @Recipients =(SELECT DISTINCT a.EMail
FROM a
--approximately 600 email addresses
Run Code Online (Sandbox Code Playgroud)
您需要将其更改为单独的列表,因此
SET @Recipients = STUFF(
(select DISTINCT ';' + CAST(a.EMail AS varchar(max))
FROM a FOR XML PATH ('')
)
,1,1, '')
Run Code Online (Sandbox Code Playgroud)
注意:@Recipients 需要是 varchar(max)