SQL Create stored procedure script with error handling
Click here to see improved version of this script 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]ASBEGIN TRANDECLARE @errorNo int, @rowCount int, @errorStr varchar(4000)DELETE FROM Table1 Where SampleDate < getdate()SELECT @errorNo = @@ERROR, @rowCount = @@ROWCOUNTIF @errorNo <> 0 BEGINSET @errorStr = 'Error deleting old load records "load_Master"'GOTO ErrHandlerENDCOMMITRETURN 0ErrHandler:ROLLBACKDECLARE @procName sysnameSELECT @procName = object_name( @@procid ), @errorStr = ISNULL( @errorStr, 'Unknown error' )IF @errorNo <> 0 BEGINSELECT @errorStr = @errorStr + ': procedure=%s, error=%i'RAISERROR( @errorStr, 16, 1, @procName, @errorNo )ENDELSE BEGINSELECT @errorStr = @errorStr + ': procedure=%s'RAISERROR( @errorStr, 16, 1, @procName )ENDRETURN 1GOGRANT EXECUTE ON [dbo].[usp_mysproc] TO [MyDatabaseEditor]GOGRANT EXECUTE ON [dbo].[usp_mysproc] TO [MyDatabaseAdmin]GO
Comments
Post a Comment