如何解决如何在SQL Server 2005中从sp_send_dbmail确定错误代码?
| 我试图在SQL Server 2005中使用sp_send_dbmail发送附件。我首先编写了一个CLR存储过程,该过程将一些内容保存到服务器上的文件中,然后调用下面列出的存储过程,然后删除它创建的文件。我从ASP.NET 2010应用程序调用此CLR存储过程。在本地,此功能在SQL Management Studio和我的应用程序中均有效。 这是我的CLR存储过程中的重要内容: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 proc时,它将成功发送邮件。但是,当我从ASP.NET应用程序执行它时,从msdb.dbo.sp_send_dbmail返回的代码是1,而@@ ERROR是0-我没有收到其他错误。我知道在SQL 2008中,至少根据2008文档,我可能会得到更有用的@@ ERROR代码。
有人有什么建议吗?您认为我可能做错了什么?
吉姆,非常感谢
解决方法
由于您正在运行
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访问?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。