mbev

TRY CATCH

Aug 22nd, 2024 (edited)
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 0.88 KB | Source Code | 0 0
  1. BEGIN TRY
  2.     RAISERROR('Starting the script', 0, 1) WITH NOWAIT;
  3.  
  4. END TRY
  5. BEGIN CATCH
  6.     -- Capture and print the error message
  7.     DECLARE @ErrorMessage NVARCHAR(4000);
  8.     SET @ErrorMessage = ERROR_MESSAGE();
  9.     RAISERROR('Error occurred: %s', 16, 1, @ErrorMessage) WITH NOWAIT;
  10. END CATCH;
  11.  
  12. or
  13.  
  14. BEGIN CATCH
  15.     DECLARE @ErrorMessage NVARCHAR(4000);
  16.     DECLARE @ErrorSeverity INT;
  17.     DECLARE @ErrorState INT;
  18.  
  19.     SELECT
  20.         @ErrorMessage = ERROR_MESSAGE(),
  21.         @ErrorSeverity = ERROR_SEVERITY(),
  22.         @ErrorState = ERROR_STATE();
  23.  
  24.     -- Use RAISERROR inside the CATCH block to return error
  25.     -- information about the original error that caused
  26.     -- execution to jump to the CATCH block.
  27.     RAISERROR (@ErrorMessage, -- Message text.
  28.                @ErrorSeverity, -- Severity.
  29.                @ErrorState -- State.
  30.                );
  31. END CATCH;
Tags: sql
Advertisement
Add Comment
Please, Sign In to add comment