在sp_send_dbmail中使用@recipients中的select

时间:2015-02-04 10:20:48

标签: sql sql-server sql-server-2008 sp-send-dbmail

我在过程中使用sp_send_dbmail。我在不同国家执行了4次。

exec pr_drop_out_addresses @country='NO'
exec pr_drop_out_addresses @country='SE'
exec pr_drop_out_addresses @country='FI'
exec pr_drop_out_addresses @country='DK'

对于每个执行官,我想将邮件发送到设置og收据。每个国家都有所不同。我尝试使用声明@recipients解决它,但我的引号出现问题。代码是这样的。有什么建议如何绕过这个问题?

declare @country varchar (10)
set @country='SE'


declare @recipients nvarchar(500)='''' +select CASE when @country='NO' then 'xxxx@xxx' when @country='SE' then 'yyy@xxxx' END+'''';                                 
declare @subject nvarchar(255) = 'Adresser fra ' + @country;
declare @query_attachment_filename nvarchar(255) = 'Adresser_for_'+@country +'_'+convert(varchar(10),getdate(),121) +'.csv';
EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'VNPSQL email',
    @recipients = @recipients,
    @query = 'SELECT * FROM NSGstatistikk_dev.dbo.test',
    @subject = @subject,
    @attach_query_result_as_file=1,
    @query_attachment_filename = @query_attachment_filename,
    @query_result_separator = ';',
    @query_result_no_padding = 1;

1 个答案:

答案 0 :(得分:0)

您使用的语法不正确: 使用:

SELECT @recipients ='''' + CASE when @country='NO' then 'xxxx@xxx' when @country='SE' then 'yyy@xxxx' END+'''';

另外,根本不需要引号:

SELECT @recipients = CASE when @country='NO' then 'xxxx@xxx' when @country='SE' then 'yyy@xxxx' END;