错误结构与不可捕获错误

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)

一条错误消息,突出显示"State 1",对应错误状态。

  • 1:由 SQL Server 显示的错误
  • 0–255:自定义错误
SQL Server 中的事务与错误处理

错误结构

行(Line)

一条错误消息,突出显示"Line 1",对应出错的行。

过程(Procedure)

一条错误消息,突出显示"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 中的事务与错误处理

Passons à la pratique !

SQL Server 中的事务与错误处理

Preparing Video For Download...