修改后,SQL电子邮件作业失败

时间:2015-07-03 08:38:16

标签: sql tsql email report

我目前有一个SQL作业,它执行特定软件的所有用户列表。

但是,我现在想要将名字和姓氏一起添加到一个完整的名称。我已经创建了简单的SQL来处理这样的请求但是当我尝试将它包含到SQL JOB中时它会失败:

失败原因:

[SQLSTATE 42000] (Error 102).  The step failed.

失败的SQL JOB:

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'test=email',
    @recipients = 'test@hotmail.co.uk',
    @subject = 'Users Report',
@body = '<b> Please follow the correct procedure (see other email)
@body_format = 'HTML',    
    @query = 'SELECT   [testDB].[dbo].[base_user].buser_userid  AS [N4 User ID]
            , [testDB].[dbo].[base_user].buser_firstName + ' ' +
           [testDB].[dbo].[base_user].buser_lastName as [Users Name]
            ,[testDB].[dbo].[sec_role].role_name  as [Role]
            ,[testDB].[dbo].[sec_role].role_description as [Description]
            ,[testDB].[dbo].[base_user].buser_active AS [Active?]
FROM      [testDB].[dbo].base_user
INNER JOIN [testDB].[dbo].[sec_user_role_map] ON testDB.dbo.base_user.[buser_gkey] = testDB.dbo.[sec_user_role_map].[usrrolm_user_gkey]
INNER JOIN [testDB].[dbo].[sec_role] ON testDB.dbo.[sec_user_role_map].[usrrolm_role_gkey] = testDB.[dbo].[sec_role].role_gkey

',
    @attach_query_result_as_file = 1;

1 个答案:

答案 0 :(得分:0)

您需要在CONCAT

上转义单引号

你也错过了一行@body

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'test=email',
    @recipients = 'test@hotmail.co.uk',
    @subject = 'Users Report',
@body = '<b> Please follow the correct procedure (see other email)',
@body_format = 'HTML',    
    @query = 'SELECT   [testDB].[dbo].[base_user].buser_userid  AS [N4 User ID]
            , [testDB].[dbo].[base_user].buser_firstName + '' '' +
           [testDB].[dbo].[base_user].buser_lastName as [Users Name]
            ,[testDB].[dbo].[sec_role].role_name  as [Role]
            ,[testDB].[dbo].[sec_role].role_description as [Description]
            ,[testDB].[dbo].[base_user].buser_active AS [Active?]
FROM      [testDB].[dbo].base_user
INNER JOIN [testDB].[dbo].[sec_user_role_map] ON testDB.dbo.base_user.[buser_gkey] = testDB.dbo.[sec_user_role_map].[usrrolm_user_gkey]
INNER JOIN [testDB].[dbo].[sec_role] ON testDB.dbo.[sec_user_role_map].[usrrolm_role_gkey] = testDB.[dbo].[sec_role].role_gkey

',
    @attach_query_result_as_file = 1;