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

时间:2018-12-11 18:24:50

标签: sql-server tsql sql-server-2012 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'

我想念什么?

1 个答案:

答案 0 :(得分:0)

您必须在@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