邮件从sql发送

时间:2018-06-06 09:06:06

标签: sql-server email jobs

执行结果但是邮件没有发送,必须指定错误是收件人。

我已声明收件人列表,并将多封邮件添加到收件人列表中,执行查询并显示多个收件人邮件。

BEGIN 
 Use [register ] 
 DECLARE Receipientlist varchar(8000) 
 SET ReceipientList = STUFF(
     ( 
       SELECT ';' + Manager_Login_Id 
       FROM dbo.Login 
       FOR XML PATH('')
     ),1,1,'') 

 SELECT Idea_Id, Login_Id, Manager_Login_Id, Idea_Date_Of_Submission, Idea_Status ='PENDING' 
 FROM dbo.Idea 
 WHERE Manager_Login_Id IS NOT NULL 
   and Idea_Date_Of_Submission <= DATEADD(day, -5, GETDATE()); 

 EXEC msdb.dbo.sp_send_dbmail profile_name = ' ', recipients = Receipientlist, body =' ',subject=' ', 

 END

1 个答案:

答案 0 :(得分:1)

你拥有的SQL(由LukStorms格式化)是不完整的,它不会运行。你的陈述有一个&#34;任性的&#34;逗号最后:

EXEC msdb.dbo.sp_send_dbmail profile_name = ' ', recipients = Receipientlist, body =' ',subject=' ', <-- What is this comma here for?

然而,除了漫无边际的逗号之外,你的SQL不起作用的原因是你的语法对你的参数和变量也是错误的。两者都以@开头。因此,正确的语法是:

USE [register ] 
DECLARE @Recipientlist varchar(8000); --Variables begin with a @. Also changed the name to the correct spelling
SET @Recipientlist = STUFF((SELECT ';' + Manager_Login_Id 
                            FROM dbo.[Login] --Login is a reserved word, i suggest using a different name for your table.
                            FOR XML PATH('')),1,1,'');


SELECT Idea_Id,
       Login_Id,
       Manager_Login_Id,
       Idea_Date_Of_Submission,
       Idea_Status AS PENDING
FROM dbo.Idea 
WHERE Manager_Login_Id IS NOT NULL 
  AND Idea_Date_Of_Submission <= DATEADD(day, -5, GETDATE());  

 EXEC msdb.dbo.sp_send_dbmail @profile_name = ' ',
                              @recipients = @Recipientlist,
                              @body =' ',--Why are you sending an empty body?
                              @subject=' ';--, Removed the comma, although I suggest having a subject too.