Pages

Wednesday, May 2, 2012

Catch SQL Exception and Raise Error in Stored Procedure

CREATE PROCEDURE [dbo].[spc_ProcName]
(
    @Ids varchar(max) = ''
)
WITH EXECUTE AS 'dbo'
AS

BEGIN TRY
SET NOCOUNT ON;

SELECT * FROM [dbo].[Table] R
       WHERE R.ID IN  (SELECT items FROM dbo.tblfn_SplitIds(@Ids))
      
END TRY

BEGIN CATCH
    EXEC [dbo].[spc_RaiseError];
END CATCH

  

CREATE PROCEDURE [dbo].[spc_RaiseError]
AS

BEGIN
SET NOCOUNT ON
DECLARE @ErrorMessage    NVARCHAR(4000),
        @ErrorSeverity   INT,
        @ErrorState      INT,
        @ErrorNumber     INT,
        @ErrorLine       INT,
        @ErrorProcedure  NVARCHAR(200)

        SELECT
        @ErrorMessage   =ERROR_MESSAGE(),      
        @ErrorSeverity  = ERROR_SEVERITY(),
        @ErrorState     =ERROR_STATE(),
        @ErrorNumber    = ERROR_NUMBER(),               
        @ErrorProcedure =ERROR_PROCEDURE(),
        @ErrorLine      =ERROR_LINE();
       
        IF @ErrorSeverity < 11
            SET @ErrorSeverity = 11   
    --Raise the ERROR AND send back to the Web Service       
RAISERROR( N'Error IN Line Number: %d  of SP: %s. Error Number: %d. ErrorMsg: %s',           @ErrorSeverity,@ErrorState, @ErrorLine, @ErrorProcedure, @ErrorNumber, @ErrorMessage) WITH NOWAIT;
END

No comments:

Post a Comment