RAISERROR

Transacties en foutafhandeling in SQL Server

Miriam Antona

Software Engineer

Foutmeldingen genereren

  • RAISERROR
  • THROW
  • Microsoft raadt THROW aan
Transacties en foutafhandeling in SQL Server

RAISERROR-syntaxis

RAISERROR ( { msg_str | msg_id | @local_variable_message },  
    severity, 
    state,
    [ argument [ ,...n ] ] )  
    [ WITH option [ ,...n ] ]
Transacties en foutafhandeling in SQL Server

RAISERROR met berichtstring

IF NOT EXISTS (SELECT * FROM staff WHERE staff_id = 15)
    RAISERROR('No staff member with such id.', 16, 1);
Msg. 50000, Level 16, State 1, Line 3
No staff member with such id.
Transacties en foutafhandeling in SQL Server

RAISERROR met berichtstring

IF NOT EXISTS (SELECT * FROM staff WHERE staff_id = 15)
    RAISERROR('No %s with id %d.', 16, 1, 'staff member', 15);
Msg. 50000, Level 16, State 1, Line 3
No staff member with id 15.
RAISERROR('%d%% discount', 16, 1, 50);
Msg. 50000, Level 16, State 1, Line 1
50% discount
  • Andere placeholders: %i, %o, %x, %X, %u...
Transacties en foutafhandeling in SQL Server

RAISERROR with error number

RAISERROR(60000, 16, 1);
Msg. 60000, Level 16, State 1, Line 1
This is a test message.
SELECT * FROM sys.messages
| message_id | language_id | severity | is_event_logged | text                      |
|------------|-------------|----------|-----------------|---------------------------|
| ...        | ...         | ...      | ...             | ...                       |
| 60000      | 1033        | 16       | 0               | This is a test message    |
| ...        | ...         | ...      | ...             | ...                       |
Transacties en foutafhandeling in SQL Server

RAISERROR - Voorbeeld met TRY...CATCH

BEGIN TRY
    IF NOT EXISTS (SELECT * FROM staff WHERE staff_id = 15)
        RAISERROR('No staff member with such id.', 9, 1);
END TRY
BEGIN CATCH
    SELECT 'You are in the CATCH block' AS message
END CATCH
No staff member with such id.
Msg. 50000, Level 9, State 1
Transacties en foutafhandeling in SQL Server

RAISERROR - Voorbeeld met TRY...CATCH

BEGIN TRY
    IF NOT EXISTS (SELECT * FROM staff WHERE staff_id = 15)
        RAISERROR('No staff member with such id.', 16, 1);
END TRY
BEGIN CATCH
    SELECT 'You are in the CATCH block' AS message
END CATCH
| message                    |
|----------------------------|
| You are in the CATCH block |
Transacties en foutafhandeling in SQL Server

Laten we oefenen!

Transacties en foutafhandeling in SQL Server

Preparing Video For Download...