錯誤結構與不可攔截的錯誤

SQL Server 的交易與錯誤處理

Miriam Antona

Software Engineer

錯誤結構

INSERT INTO products (product_name, stock, price)
    VALUES ('Trek Powerfly 5 - 2018', 10, 3499.99);
Msg 2627, Level 14, State 1, Line 1
Violation of UNIQUE KEY constraint 'unique_name'. 
Cannot insert duplicate key in object 'dbo.products'. 
The duplicate key value is (Trek Powerfly 5 - 2018).
SQL Server 的交易與錯誤處理

錯誤結構

錯誤編號

一則錯誤訊息,標示出對應錯誤編號的「Msg 2627」文字。

  • SQL 錯誤:1 到 49999
  • 自訂錯誤:從 50001 起
    select * from sys.messages
| message_id | language_id | severity | ... | text                                                            |
|------------|-------------|----------|-----|-----------------------------------------------------------------|
| ...        | ...         | ...      | ... | ...                                                             |
| 2627       | 1033        | 14       | ... | Violation of %ls constraint '%.*ls'. Cannot insert duplicate... |
| ...        | ...         | ...      | ... | ...                                                             |
SQL Server 的交易與錯誤處理

錯誤結構

嚴重性等級

一則錯誤訊息,標示出對應錯誤嚴重性的「Level 14」文字。

  • 0-10:資訊訊息
  • 11-16:使用者可更正的錯誤(違反約束等)
  • 17-24:其他錯誤(軟體問題、嚴重錯誤)
SQL Server 的交易與錯誤處理

錯誤結構

狀態

一則錯誤訊息,標示出對應錯誤狀態的「State 1」文字。

  • 1:由 SQL Server 顯示的錯誤
  • 0-255:自訂錯誤
SQL Server 的交易與錯誤處理

錯誤結構

行號

一則錯誤訊息,標示出發生錯誤之行號的「Line 1」文字。

程序

一則錯誤訊息,標示出發生錯誤之預存程序名稱的「Procedure Insert_product」文字。

SQL Server 的交易與錯誤處理

不可攔截的錯誤

  • 嚴重性 低於 11(11-19 可攔截)

  • 嚴重性 20 以上且會中斷連線

  • 編譯 錯誤:物件或欄位不存在

SQL Server 的交易與錯誤處理

不可攔截的錯誤-編譯錯誤範例

BEGIN TRY
    SELECT non_existent_column FROM products;
END TRY
BEGIN CATCH
    SELECT 'You are in the CATCH block' AS message;
END CATCH
Msg 207, Level 16, State 1, Line 2
Invalid column name 'non_existent_column'.
SQL Server 的交易與錯誤處理

一起來練習吧!

SQL Server 的交易與錯誤處理

Preparing Video For Download...