I am using a sp_send_dbmail in a procedure. I execute it 4 times with different countries.
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'
For each exec I would like to send the mail to set og receipients. They are different for each country. I try to solve it with a declare @recipients, but I get problems with the quotes. The code is like this. Any suggestions how to bypass the problem?
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;
You are using incorrect syntax: Use:
SELECT @recipients ='''' + CASE when @country='NO' then 'xxxx@xxx' when @country='SE' then 'yyy@xxxx' END+'''';
also, quotes are not required at all:
SELECT @recipients = CASE when @country='NO' then 'xxxx@xxx' when @country='SE' then 'yyy@xxxx' END;