我创建了一个查询,以我需要的方式提取信息和电子邮件,以便呈现给我们的客户。如何将其转换为由查询(查询A)提供的存储过程?我需要它为每个唯一的cmp_code和cmp_e_mail返回运行。因此,例如,如果QueryA返回以下内容,我需要单独为每个人运行电子邮件查询。
C0001 email1@asdf.com
C0002 email2@asdf.com
C0003 email3@asdf.com
QueryA:
SELECT DISTINCT
[cmp_code]
,[cmp_e_mail]
FROM Table1
查询电子邮件:
DECLARE @email nvarchar(50)
DECLARE @cmp_code nvarchar (5)
DECLARE @profile nvarchar(50)
DECLARE @subject nvarchar(100)
DECLARE @querystr nvarchar (MAX)
set @email = QueryA.[cmp_e_mail]
set @cmp_code = QueryA.[cmp_code]
set @profile = 'Reports'
set @subject = 'Test'+@cmp_code
set @querystr = 'SELECT [Year],[Week],[DueDate]
FROM Table1
WHERE [cmp_code] = '''+@cmp_code+'''';
EXEC msdb.dbo.sp_send_dbmail
@profile_name = @profile,
@recipients = @email,
@subject = @subject,
@body = 'This message is to inform you that we have not received your financial report for the following weeks.
Please remit as soon as possible and pay by the due date listed.',
@query = @querystr
答案 0 :(得分:1)
尝试创建一个如下所示的存储过程,循环遍历表,然后调用传入数据的另一个存储过程,确保在最后解除分配并关闭游标
Declare @Code nvarchar(50)
Declare @EmailAddress nvarchar(Max)
Declare dbCurSP Cursor
For SELECT DISTINCT [cmp_code] FROM Table1
Open dbCurSP
Fetch Next From dbCurSP Into @Code
While @@fetch_status = 0
Begin
-- find email address
SELECT @EmailAddress= [cmp_e_mail] FROM Table1 where [cmp_code]=@Code
execute SP_SendEmail @EmailAddress, @Code
Fetch Next From dbCurSP Into @Code
End
Close dbCurSP
Deallocate dbCurSP