2013-08-22 31 views
1
Begin Try 
Declare @SQL NVarchar(Max)='Exec [MyLinkedServer].master.dbo.sp_executesql N''Drop Table [tempdb].dbo.[T1]'''; 
Print @SQL; 
Exec master.dbo.sp_executesql @SQL; 
End Try 
Begin Catch 
Print Error_Message() 
End Catch 

當表T1中不MyLinkedServer ,而不是被引導到閉鎖段存在上述腳本失敗。 我錯過了什麼?sp_executesql的內部嘗試&抓住

需要說明的是:原始過程使用參數在過程內構建@SQL動態。

謝謝!

回答

1

號,上面的腳本並沒有失敗,正好可以作爲你期望它:

Begin Try 
Declare @SQL NVarchar(Max)='Exec [MyLinkedServer].master.dbo.sp_executesql N''Drop Table [tempdb].dbo.[T1]'''; 
Print @SQL; 
Exec master.dbo.sp_executesql @SQL; 
End Try 
Begin Catch 
print 'in catch' 
Print Error_Message() 
End Catch 

Exec [MyLinkedServer].master.dbo.sp_executesql N'Drop Table [tempdb].dbo.[T1]' 
in catch 
Could not find server 'MyLinkedServer' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers. 

請參閱「漁獲」的消息?證明catch塊已被執行。

但是你是對的,有一個衆所周知的問題是編譯錯誤無法在它們發生的範圍內捕獲。這絕對是可以預料的,就像在代碼編譯失敗時要求C#程序中的catch塊運行一樣......這個問題在Error Handling in SQL 2005 and Later中有詳細的解釋。您必須創建一個外部作用域來捕獲發生在內部作用域中的編譯錯誤。這正是你在你發佈的例子中做的事情!

+0

謝謝你,但你有一個不同的錯誤:你沒有一個名爲MyLinkedServer的鏈接服務器,而這樣一個本地錯誤由Try&Catch處理。 –

+0

你是XACT_ABORT開還是關?請參閱[處理服務器到服務器遠程存儲過程中的錯誤](http://msdn.microsoft.com/zh-cn/library/ms191515.aspx)。 –

+0

我試了兩種選擇,結果都一樣。 –