Sql Server 2008 - 由链接服务器上运行的存储过程引发的捕获执行错误

问题描述 投票:0回答:1

为了给出一些背景细节,假设有一个'Person'表和一个存储过程'PersonPerformance',它返回给定PersonId的Person的性能。这两个对象都驻留在链接的sql server 2000实例上。

我的目标是为每个PersonId运行PersonPerformance proc并将结果存储在驻留在Sql Server 2008实例上的表中。如果在执行存储过程中发生执行错误,我想注意它“失败”并发送一封电子邮件,列出存储过程完成时所有失败的PersonId。

我尝试过使用try..catch块并检查@@ error!= 0但是都没有用。我假设它是因为存储的proc在抛出错误后继续执行并最终返回结果,即使它们无效。存储过程本身是一个长批处理,没有错误处理。

这是我到目前为止的代码:

{@ReturnTable is defined here}

declare cur cursor for 
select PersonId from [linked-server-name].DB.dbo.Person
open cur
declare @pId int
fetch next from cur into @pId
while (@@FETCH_STATUS = 0)
begin
    begin try
        print(@pId)
        insert into @ReturnTable exec [linked-server-name].DB.dbo.PersonPerformance @pId
    end try
    begin catch
        print('store person that failed here')
    end catch

    fetch next from cur into @pId
end
close cur
deallocate cur

我想我理解为什么它没有像我预期的那样工作,因为我之前提到过(存储过程继续)但是我想知道是否有办法绕过那个问题并捕获执行错误,即使proc继续。

这是执行期间生成的输出的快照:

101
The statement has been terminated.
Msg 2627, Level 14, State 1, Procedure OSPerfAttribution_ps, Line 626
Violation of PRIMARY KEY constraint 'PK__@SecMaster__2CD2DAF1'. Cannot insert duplicate key in object '#2BDEB6B8'.
The statement has been terminated.
Msg 515, Level 16, State 2, Procedure OSPerfAttribution_ps, Line 1047
Cannot insert the value NULL into column 'BasketBenchmarkId', table '@ReturnTable'; column does not allow nulls. INSERT fails.

(3 row(s) affected)
102

(36 row(s) affected)
106

(32 row(s) affected)

错误消息从存储过程传播到外部sql的输出的事实使我相信必须有一种方法来捕获它。我很难发现我是多么希望在这里得到一些帮助。

最后,我可能只需将整个输出保存到日志文件并搜索错误。这不是一个选项,但我仍然想知道是否有办法在执行过程中捕获错误。

sql-server sql-server-2008 error-handling try-catch linked-server
1个回答
0
投票

如果你想要整批回滚,我会使用SET XACT_ABORT ON

http://msdn.microsoft.com/en-us/library/ms188792.aspx

© www.soinside.com 2019 - 2024. All rights reserved.