create table #test_email_recipients (id int identity, email_address varchar(100), company varchar(100))
insert #test_email_recipients (email_address,company) values ('email_1','EE')
insert #test_email_recipients (email_address,company) values ('email_2','EE')
insert #test_email_recipients (email_address,company) values ('email_3','BB')
-- if you want to acually run it, need to change your profile_name accordingly... ie change MY_MAIL_PROFILE to whatever is your real profile, and change the above e-mail addresses to something real, and remove the comments from below...
declare @sql varchar(max)
select @sql = isnull(@sql,'') + 'exec msdb.dbo.sp_send_dbmail @profile_name=''MY_MAIL_PROFILE'',@recipients='''+
(select email_address + ';' from #test_email_recipients e where c.company = e.company for xml path('')) +
''',@subject=''Email Listings for '+company+''',@body = ''Dear Staff member of '+company+
','+replicate(char(13)+char(10),2)+'You Belong to Company '+company+replicate(char(13)+char(10),2)+
'Cheers,'+char(13)+char(10)+'Mark Wills'';'+char(13)+char(10)
from #test_email_recipients c group by company
print @sql
--exec (@sql) -- currerntly less than 500 characters
drop table #test_email_recipients
|