为了提供一些背景细节,假设有一个“Person”表和一个存储过程“PersonPerformance”,它返回给定 PersonId 的 Person 的性能。这两个对象都驻留在链接的 sql server 2000 实例上。
我的目标是为每个 PersonId 运行 PersonPerformance proc,并将结果存储在驻留在 Sql Server 2008 实例上的表中。如果在存储过程的执行过程中发生执行错误,我想指出它“失败”并在存储过程完成时发送一封电子邮件,列出所有失败的 PersonId。
我试过使用 try..catch 块并检查 @@error != 0 但都没有奏效。我假设这是因为存储过程在抛出错误后继续执行并最终返回结果,即使它们无效。存储过程本身是一个长批次,没有错误处理。
这是我到目前为止的代码:
{@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
我想我理解为什么它没有像我预期的那样工作,原因是我之前提到的(存储过程继续),但我想知道是否有办法绕过这个问题并捕获执行错误,即使过程继续。
这是执行期间生成的输出的快照:
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 的输出这一事实使我相信必须有一种方法来捕获它。我只是很难找到方法,所以我希望在这里得到一些帮助。
最后的手段我可能只需要将整个输出保存到日志文件并搜索错误。这不是一个糟糕的选择,但我仍然想知道是否有办法在执行期间捕获错误。