日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

SQL SERVER 里的 try catch

發布時間:2024/4/15 数据库 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SQL SERVER 里的 try catch 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

sql server 2005中新增加的try catch,可以很容易捕捉異常了

基本用法:

begin try
???? {? sql_statement |
?statement_block? }
end try
begin catch
???? {? sql_statement |
?statement_block }
end catch


注意:sql server只捕捉那些不是嚴重的異常,當比如數據庫不能連接等這類異常時,是不能捕捉的一個例子:



BEGIN TRY
?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;
?


另外try catch可以嵌套


begin try
? delete from grandparent where name = 'john smith'
? print 'grandparent deleted successfully'
end try
begin catch
?? print 'error deleting grandparent record'
?? begin try
???? delete from parent where grandparentid =
???? (select distinct id from grandparent where name = 'john smith')
???? print 'parent deleted successfully'
?? end try
?? begin catch
???? print 'error deleting parent'
???? begin try
?????? delete from child where parentid =
???? (select distinct id from parent where grandparentid =
???? (select distinct id from grandparent where name = 'john smith'))
?????? print 'child deleted successfully'
???? end try


???? begin catch
?????? print 'error deleting child'
???? end catch
?? end catch
?end catch


另外,sql server 2005在異常機制中,提供了error類的方法方便調試,現摘抄如下:

error_number(): returns a number associated with the error.

error_severity(): returns the severity of the error

.error_state(): returns the error state number associated with the error.

error_procedure(): returns the name of the stored procedure or trigger in which the error occurred.

error_line(): returns the line number inside the failing routine that caused the error.

error_message(): returns the complete text of the error message. the text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.


最后舉例子如下,使用了error類的方法

BEGIN TRY
?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;
?


print 'command after try/catch blocks'


輸出error detected


err_num err_sev err_state err_proc???????????? err_line? err_msg
------- ------- --------- -------------------- --------- --------------------------------
8134??????? 16????????? 1 null???????????????? 4??????? divide by zero error encountered.


總結

以上是生活随笔為你收集整理的SQL SERVER 里的 try catch的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。