SQL Stored procedure with error handling using Try/Catch
This is improved version of the script from 2009 using try/catch syntax
USE [MyDatabase]GOPRINT 'DROP PROCEDURE [usp_mysproc]'GOif exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_mysproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)drop procedure [dbo].[usp_mysproc]GOPRINT 'CREATE PROCEDURE [usp_mysproc]'GOCREATE PROCEDURE [dbo].[usp_mysproc](@RaiseError bit = 0)ASBEGIN TRYBEGIN TRANIF @RaiseError = 1BEGINDECLARE @TEMP TABLE (Column1 varchar(2))INSERT INTO @TEMP(Column1) VALUES ('123')ENDCOMMIT TRANEND TRYBEGIN CATCHDECLARE @ErrorInfo VARCHAR(4000)SET @ErrorInfo = 'ERROR ['+LTRIM(STR(ERROR_NUMBER()))+']['+ERROR_PROCEDURE()+':'+LTRIM(STR(ERROR_LINE()))+'] - ' + ERROR_MESSAGE()PRINT CONVERT(VARCHAR,GETDATE(),21) + ': '+@ErrorInfoROLLBACK TRANRAISERROR( @ErrorInfo, 16, 1)RETURN 1END CATCHGOGRANT EXECUTE ON [dbo].[usp_mysproc] TO [MyDatabaseEditor]GOGRANT EXECUTE ON [dbo].[usp_mysproc] TO [MyDatabaseAdmin]GO-- SUCCESS TEST
EXEC usp_mysproc-- FAILURE TEST
EXEC usp_mysproc @RaiseError = 1-- ERROR MESSAGE
-- 2011-03-16 12:23:12.893: ERROR [8152][usp_mysproc:14] - String or binary data would be truncated.
Comments
Post a Comment