如何设置sp_send_dbmail以通过电子邮件发送查询结果



我的任务是创建一个离职用户列表,我们需要将其存档在内部应用程序中。

我已经编写了select语句(SQL Server 2012(,它运行良好。我可以从EXEC sp_send_dbmail收到要发送的电子邮件,但电子邮件正文中只有我写的那一行。当我更改@body信息时,它仍然只是使用我输入的原始行。它不会因为我在那里添加的内容而改变,而且我无法让它发送Select的结果。

到目前为止我有什么:

Set @Results = 'SELECT  p.UID
,p.EMPNO
,p.FULLNAME AS FULL_NAME
,p.Archived
,p.COMPANY
,p.EMAIL
,p.SID
,e.TERMCODE AS TERM_CODE
,CONVERT(VARCHAR, e.FIREDATE, 101) AS FIRE_DATE
FROM app_table p
LEFT OUTER JOIN employee_table e ON e.EMPNO=p.EMPNO
WHERE p.EMPNO IS NOT NULL
AND p.ARCHIVED = 0
AND e.FIREDATE IS NOT NULL
ORDER BY e.FIREDATE DESC'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQL_Mailer',
@recipients = 'my.address@myemail.com', 
@subject = 'Departed Users being archived',
@body = @Results
END

我还尝试将@query添加到sp_send_dbmail中,并将Select放入@query:@query = 'Select statement above'

我错过了什么?

必须在@query参数中传递查询并指定@attach_query_result_as_file=1@body只是要包含在消息中的文本。有关详细信息,请参阅sp_send_dbmail。你说你试过了,但没有说明发生了什么,你的代码也没有这么做。

Set @Results = 'SELECT  p.UID
,p.EMPNO
,p.FULLNAME AS FULL_NAME
,p.Archived
,p.COMPANY
,p.EMAIL
,p.SID
,e.TERMCODE AS TERM_CODE
,CONVERT(VARCHAR, e.FIREDATE, 101) AS FIRE_DATE
FROM app_table p
LEFT OUTER JOIN employee_table e ON e.EMPNO=p.EMPNO
WHERE p.EMPNO IS NOT NULL
AND p.ARCHIVED = 0
AND e.FIREDATE IS NOT NULL
ORDER BY e.FIREDATE DESC'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQL_Mailer',
@recipients = 'my.address@myemail.com', 
@subject = 'Departed Users being archived',
@body = 'You can write something here',
@query = @Results,
@attach_query_result_as_file = 1

相关内容

  • 没有找到相关文章

最新更新