gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
how to make sql server script print out error if it goes into a catch block
- User
how to make sql server script print out error if it goes into a catch block
- Assistant
To print out an error message when a SQL Server script encounters an error in a TRY...CATCH block, you can use the RAISERROR function or the PRINT statement.
Here's a sample SQL script using the RAISERROR function:
sqlBEGIN TRY -- Your SQL statement here -- Example: Divide by zero error for demo SELECT 1 / 0; END TRY BEGIN CATCH DECLARE @ErrorMessage NVARCHAR(4000); DECLARE @ErrorSeverity INT; DECLARE @ErrorState INT; -- Capture error information SELECT @ErrorMessage = ERROR_MESSAGE(), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE(); -- Print error message RAISERROR (@ErrorMessage, -- Message text @ErrorSeverity, -- Severity @ErrorState -- State ); END CATCH;