SQL Server2005 異常處理機(jī)制(Begin try Begin Catch)
begin?try
--SQL?
end?trybegin?catch?--sql
(處理出錯(cuò)動(dòng)作)
end?catch
我們將可能會(huì)出錯(cuò)的sql 寫在begin try...end?try 之間,若出錯(cuò),剛程序就跳到緊接著的begin try...end?try 的beign catch...end?catch
中,執(zhí)行beign catch...end?catch錯(cuò)誤處理SQL。try..catch 是可以嵌套的。
在begin catch ...end?catch中我們可以利用系統(tǒng)提供的下面四個(gè)函數(shù)得到出錯(cuò)信息:
error_number 返回錯(cuò)誤代碼
error_serverity 返回錯(cuò)誤的嚴(yán)重級(jí)別
error_state 返回錯(cuò)誤狀態(tài)代碼
error_message 返回完整的錯(cuò)誤信息
上面的四個(gè)函數(shù)在同一個(gè)begin catch ...end?catch可以在多次使用,值是不變的。
下面是一個(gè)簡單的小例子。
begin?try
select?2/0
end?try
begin?catch
select?error_number()?as?error_number ,
error_message()?as?error_message,
error_state()?as?error_state,
error_severity()?as?error_severity
end?catch
結(jié)果:
-----
error_number error_message error_state error_severity
8134?遇到以零作除數(shù)錯(cuò)誤。?1?16
-------------------------------------------------------
?不受 TRY…CATCH 構(gòu)造影響的錯(cuò)誤?
TRY…CATCH 構(gòu)造在下列情況下不捕獲錯(cuò)誤:?
嚴(yán)重級(jí)別為 10 或更低的警告或信息性消息。?
嚴(yán)重級(jí)別為 20 或更高且終止會(huì)話的 SQL Server 數(shù)據(jù)庫引擎任務(wù)處理的錯(cuò)誤。 如果所發(fā)生錯(cuò)誤的嚴(yán)重級(jí)別為 20 或更高,而數(shù)據(jù)庫連接未中斷,則 TRY…CATCH 將處理該錯(cuò)誤。?
需要關(guān)注的消息,如客戶端中斷請(qǐng)求或客戶端連接中斷。?
當(dāng)系統(tǒng)管理員使用 KILL 語句終止會(huì)話時(shí)。
?
USE?AdventureWorks;
GO
BEGIN?TRY
????--?Generate a divide-by-zero error.
????SELECT?1/0;
END?TRY
BEGIN?CATCH
????SELECT
??????? ERROR_NUMBER()?AS?ErrorNumber,
??????? ERROR_SEVERITY()?AS?ErrorSeverity,
??????? ERROR_STATE()?AS?ErrorState,
??????? ERROR_PROCEDURE()?AS?ErrorProcedure,
??????? ERROR_LINE()?AS?ErrorLine,
??????? ERROR_MESSAGE()?AS?ErrorMessage;
END?CATCH;
GO?
?
USE?AdventureWorks;
GO
BEGIN?TRANSACTION;
BEGIN?TRY
????--?Generate a constraint violation error.
????DELETE?FROM?Production.Product
????????WHERE?ProductID?=?980;
END?TRY
BEGIN?CATCH
????SELECT?
??????? ERROR_NUMBER()?AS?ErrorNumber,
??????? ERROR_SEVERITY()?AS?ErrorSeverity,
??????? ERROR_STATE()?as?ErrorState,
??????? ERROR_PROCEDURE()?as?ErrorProcedure,
??????? ERROR_LINE()?as?ErrorLine,
??????? ERROR_MESSAGE()?as?ErrorMessage;
????IF?@@TRANCOUNT?>?0
????????ROLLBACK?TRANSACTION;
END?CATCH;
IF?@@TRANCOUNT?>?0
????COMMIT?TRANSACTION;
GO