SQL SERVER 2000中異常處理: sql
CREATE PROC usp_AccountTransaction @AccountNum INT, @Amount DECIMAL AS BEGIN BEGIN TRANSACTION --beginning a transaction.. UPDATE MyChecking SET Amount = Amount - @Amount WHERE AccountNum = @AccountNum IF @@ERROR != 0 --check @@ERROR variable after each DML statements.. BEGIN ROLLBACK TRANSACTION --RollBack Transaction if Error.. RETURN END ELSE BEGIN UPDATE MySavings SET Amount = Amount + @Amount WHERE AccountNum = @AccountNum IF @@ERROR != 0 --check @@ERROR variable after each DML statements.. BEGIN ROLLBACK TRANSACTION --RollBack Transaction if Error.. RETURN END ELSE BEGIN COMMIT TRANSACTION --finally, Commit the transaction if Success.. RETURN END END END GO
上面是Sql server 2000的一個存儲過程,在每一個數據庫操做以後當即必須檢查@@ERROR ,進行Commit / RollBack該事務.
Sql server 2000中監測錯誤,只能經過監測全局遍歷 @@ERROR.因爲@@ERROR會被下一個數據庫操做所覆蓋. 因此在每次操做完後必須當即監測.數據庫
TRY...CATCH是SQL Server 2005提供的更具備可讀性的語法.每一個開發人員都熟悉這種寫法.SQL Server 2005仍然支持@@ERROR這種用法.ide
BEGIN TRY Try Statement 1 Try Statement 2 ... Try Statement M END TRY BEGIN CATCH Catch Statement 1 Catch Statement 2 ... Catch Statement N END CATCH
下面系統函數在CATCH塊有效.能夠用來獲得更多的錯誤信息:函數
函數 | 描述 |
---|---|
ERROR_NUMBER() | 返回致使運行 CATCH 塊的錯誤消息的錯誤號。 |
ERROR_SEVERITY() | 返回致使 CATCH 塊運行的錯誤消息的嚴重級別 |
ERROR_STATE() | 返回致使 CATCH 塊運行的錯誤消息的狀態號 |
ERROR_PROCEDURE() | 返回出現錯誤的存儲過程名稱 |
ERROR_LINE() | 返回發生錯誤的行號 |
ERROR_MESSAGE() | 返回致使 CATCH 塊運行的錯誤消息的完整文本 |
簡單示例:spa
BEGIN TRY SELECT GETDATE() SELECT 1/0--Evergreen divide by zero example! END TRY BEGIN CATCH SELECT 'There was an error! ' + ERROR_MESSAGE() RETURN END CATCH;
3.try catch回滾/提交事務的示例.net
ALTER PROC usp_AccountTransaction @AccountNum INT, @Amount DECIMAL AS BEGIN BEGIN TRY --Start the Try Block.. BEGIN TRANSACTION -- Start the transaction.. UPDATE MyChecking SET Amount = Amount - @Amount WHERE AccountNum = @AccountNum UPDATE MySavings SET Amount = Amount + @Amount WHERE AccountNum = @AccountNum COMMIT TRAN -- Transaction Success! END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK TRAN --RollBack in case of Error -- you can Raise ERROR with RAISEERROR() Statement including the details of the exception RAISERROR(ERROR_MESSAGE(), ERROR_SEVERITY(), 1) END CATCH END GO