Subquery returned more than 1 value

2019-02-20 20:13发布

I need to set up a job in SQL Server 2008 to run at the first of the month sending an email to our customers. However, I do not know how to loop through the results of the subquery.

Resulting in this error message:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Here's the relevant code:

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

2条回答
再贱就再见
2楼-- · 2019-02-20 20:39

the problem is @recipients = @MailRecipients. It is expecting a string (an email address) and you are giving it a recordSet.

查看更多
爷的心禁止访问
3楼-- · 2019-02-20 20:40

The error is here where you have many rows trying to be assigned to a single variable

SET @Recipients =(SELECT DISTINCT a.EMail
     FROM   a
    --approximately 600 email addresses 

You'd need to change it to a separated list thus

SET @Recipients = STUFF(
           (select DISTINCT ';' + CAST(a.EMail AS varchar(max))
           FROM a FOR XML PATH ('')
           )
          ,1,1, '') 

Note: @Recipients will need to be varchar(max)

查看更多
登录 后发表回答