如何从SQL Server 2005中的sp_send_dbmail确定错误代码?

时间:2011-06-23 19:17:26

标签: sql-server-2005 sp-send-dbmail

我正在尝试使用SQL Server 2005中的sp_send_dbmail发送附件。我首先编写了一个CLR存储过程,将一些内容保存到服务器上的文件中,然后调用下面列出的存储过程,然后删除文件创建。我从我的ASP.NET 2010应用程序中调用此CLR存储过程。从本地来说,这个功能在SQL Management Studio和我的应用程序中都有效。

这是我的CLR sproc的基本内容:

public static void SendExportAttachment(string email, string fileContents, string mailProfile, string temporaryFileName)
{
    // First save the file to the file system
    StreamWriter sw = new StreamWriter(temporaryFileName);
    sw.Write(fileContents);
    sw.Close();
    sw = null;

    // Execute the SendExportResultEmail (see below)
    using (SqlConnection connection = new SqlConnection("context connection=true"))
    {
        connection.Open();
        SqlCommand command = new SqlCommand("SendExportResultEmail", connection);
        command.CommandType = System.Data.CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@ProfileName", mailProfile));
        command.Parameters.Add(new SqlParameter("@Recipients", email));
        command.Parameters.Add(new SqlParameter("@TemporaryFileName", temporaryFileName));
        command.ExecuteNonQuery();
    }

    // Remove the file from the file system
    File.Delete(temporaryFileName);
}

以下是发送电子邮件的存储过程:

CREATE PROCEDURE [dbo].[SendExportResultEmail]
     @ProfileName NVARCHAR(50)
    ,@Recipients NVARCHAR(100)
    ,@TemporaryFileName NVARCHAR(2000)
AS

SET NOCOUNT ON

DECLARE @ErrorID INT
DECLARE @RtnCode INT
DECLARE @Body VARCHAR(8000)
DECLARE @Subject VARCHAR(1000)
DECLARE @mailitem_id INT

SET @Body = 'Some Body'
SET @Subject = 'Some title'

EXEC @RtnCode = msdb.dbo.sp_send_dbmail
     @profile_name = @ProfileName
    ,@recipients   = @Recipients
    ,@body         = @Body
    ,@subject      = @Subject
    ,@body_format = 'TEXT'
    ,@file_attachments = @TemporaryFileName
    ,@mailitem_id = @mailitem_id OUTPUT

SET @ErrorID = @@ERROR

IF @RtnCode <> 0 BEGIN
    SELECT @ErrorID
END

在本地成功测试此代码作为我的应用程序的一部分后,我将其移动到我们的测试服务器。在测试服务器上,当我从Management Studio执行CLR sproc时,它会成功发送邮件。但是,当我从ASP.NET应用程序执行它时,msdb.dbo.sp_send_dbmail的返回代码为1,@@ ERROR为0 - 我没有其他错误。我知道在SQL 2008中,我可能会得到一个更有用的@@ ERROR代码,至少根据2008年的文档。

有人有什么建议吗?您认为我可能做错了什么?

非常感谢Jim,

1 个答案:

答案 0 :(得分:0)

因为您正在运行msdb.dbo.sp_send_dbmail,它将捕获与电子邮件相关的任何错误,所有错误信息都来自返回值:@RtnCode。只有对msdb.dbo.sp_send_dbmail的格式错误调用才会产生任何@@ ERROR值。为什么不转到SQL Server 2005 +中使用的BEGIN TRY - BEGIN CATCH

  • 当我用错误的@ProfileName(我的第一个想法)运行你的代码时,我得到@ RtnCode = 4

  • 当我使用错误的@TemporaryFileName运行您的代码时,我得到@ RtnCode = 1,这就是您要报告的内容。您是否已检查文件路径和名称​​是否有效且可访问 来自 SQL Server