THROW

SQL Server 中的事务与错误处理

Miriam Antona

Software Engineer

THROW 语法

  • 微软推荐优先使用此语句而非 RAISERROR
THROW [ error_number, message, state ][ ; ]
SQL Server 中的事务与错误处理

THROW - 无参数

BEGIN TRY
    SELECT price/0 from orders;
END TRY
BEGIN CATCH
    THROW;    
    SELECT 'This line is executed!' as message;
END CATCH
(0 rows affected) 
Msg. 8134, Level 16, State 1, Line 2
Divide by zero error encountered.
SQL Server 中的事务与错误处理

THROW - 歧义

BEGIN TRY
    SELECT price/0 from orders;
END TRY
BEGIN CATCH
    SELECT 'This line is executed!'
    THROW;
END CATCH
| THROW                  |
|------------------------|
| This line is executed! |
SQL Server 中的事务与错误处理

THROW - 歧义

BEGIN TRY
    SELECT price/0 from orders;
END TRY
BEGIN CATCH
    SELECT 'This line is executed!';
    THROW;
END CATCH
| (No column name)       |
|------------------------|
| This line is executed! |
(0 rows affected) 
(1 rows affected)
Msg. 8134, Level 16, State 1, Line 2
Divide by zero error encountered.
SQL Server 中的事务与错误处理

THROW - 带参数

THROW error_number, message, state [ ; ]
THROW 52000, 'This is an example', 1;
Msg. 52000, Level 16, State 1, Line 1
This is an example
SQL Server 中的事务与错误处理

THROW - 带参数

BEGIN TRY
    IF NOT EXISTS (SELECT * FROM staff WHERE staff_id = 15)
        THROW 51000, 'This is an example', 1;
END TRY
BEGIN CATCH
    SELECT ERROR_MESSAGE() AS message;
END CATCH
| THROW                      |
|----------------------------|
| This is an example         |
SQL Server 中的事务与错误处理

Passons à la pratique !

SQL Server 中的事务与错误处理

Preparing Video For Download...