简体   繁体   English

SQL Server 2005中的链接服务器的TRY CATCH不起作用

[英]TRY CATCH with Linked Server in SQL Server 2005 Not Working

I am trying to catch sql error raised when I execute a stored procedure on a linked server. 我正在尝试捕获在链接服务器上执行存储过程时引发的sql错误。 Both Servers are running SQL Server 2005. 两台服务器都运行SQL Server 2005。

To prove the issue I have created a stored procedure on the linked server called Raise error that executes the following code: 为了证明这个问题,我在链接服务器上创建了一个名为Raise error的存储过程,该存储过程执行以下代码:

RAISERROR('An error', 16, 1);

If I execute the stored procedure directly on the linked server using the following code I get a result set with 'An error', '16' as expected (ie the code enters the catch block): 如果我使用以下代码直接在链接服务器上执行存储过程,则会得到一个结果集,其结果为“错误”,如预期的那样为“ 16”(即代码进入catch块):

BEGIN TRY
EXEC [dbo].[RaiseError];
END TRY
BEGIN CATCH
    DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int;
    SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY();
    SELECT @ErrMsg, @ErrSeverity;
END CATCH

If I run the following code on my local server to execute the stored procedure on the linked server then SSMS gives me the message 'Query completed with errors', .Msg 50000, Level 16, State 1, Procedure RaiseError, Line 13 An error' 如果我在本地服务器上运行以下代码以在链接服务器上执行存储过程,则SSMS会向我显示消息“查询已完成,但有错误”。Msg50000,级别16,状态1,过程RaiseError,第13行有错误”

BEGIN TRY
    EXEC [Server].[Catalog].[dbo].RaiseError
END TRY
BEGIN CATCH
    DECLARE @SPErrMsg nvarchar(4000), @SPErrSeverity int;
    SELECT @SPErrMsg = ERROR_MESSAGE(), @SPErrSeverity = ERROR_SEVERITY();
    SELECT @SPErrMsg, @SPErrSeverity;
END CATCH

My Question is can I catch the error generated when the Linked server stored procedure executes? 我的问题是,我可以捕获链接服务器存储过程执行时生成的错误吗?

Thanks in advance! 提前致谢!

See Handling Errors in Server-to-Server Remote Stored Procedures : 请参阅服务器到服务器远程存储过程中的处理错误

Calling RAISERROR with severity less than 20 from inside a remote stored procedure causes a statement abort error on the remote server. 从远程存储过程内部以低于20的严重性调用RAISERROR会导致远程服务器上的语句中止错误。 A TRY…CATCH construct on the local server handles remote batch abort errors only. 本地服务器上的TRY…CATCH构造仅处理远程批处理中止错误。 If a remote stored procedure calls RAISERROR with severity less than 20 and the remote stored procedure is scoped within a TRY block on the local server, RAISERROR does not cause control to pass to the CATCH block of the TRY…CATCH construct. 如果远程存储过程以低于20的严重性调用RAISERROR,并且远程存储过程的作用域位于本地服务器上的TRY块内,则RAISERROR不会导致控制权传递给TRY…CATCH构造的CATCH块。 However, RAISERROR with severity 20 or greater on the remote server breaks the connection, and execution on the local server passes to the CATCH block. 但是,远程服务器上严重性为20或更高的RAISERROR断开了连接,本地服务器上的执行传递给CATCH块。

这将在本地返回错误信息:

EXEC ('your.fullyqualified.storedprocname') AT YOUR_LINKED_SERVER;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM