Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

ERROR LOGGING IN STORED PROCEDURES

$
0
0

Hello,
I need to build a error logging framework to have stepwise log.
We are using SQL server 2008 R2.The requirements are to have detailed error logging in the stored procedures based on an input flag.

1) If the stored procedure has 4 update statements and the last one failed, I need to log to an error table the details on the ones successfully updated and where the error occured.

2) And I also need to log the Stored Procedure call itself (as it was called with the argument values). Is there a way to do this from within the SP itself. A generic piece of code that I can use in any SP.


I have template for error handling in stored procedure. I need to include the above 2 requirements.
I am looking for ideas/ suggestions on how best to implement this.

- BGOP

 


-------------------------------------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[TEMPLATE]
AS
BEGIN

 SET NOCOUNT ON
  DECLARE    
   @ErrorMessage VARCHAR(4000), 
   @Source VARCHAR(100),
   @ErrorNumber INT,
   @ErrorSeverity INT,
   @ErrorState INT,
   @ErrorLine INT,

 
 
 SET @Source =OBJECT_NAME(@@PROCID)

 -- CHECK BUSINESS RULES AGAINST VIOLATIONS  
 
    IF <CHECK RULE1>
    BEGIN
  RAISERROR (50001,
        16, -- Severity.  
        1   -- State. 
        );
  RETURN -1  
 END
 
 IF <CHECK RULE2>
 BEGIN
  RAISERROR (50002,  
        16, -- Severity.  
        1, -- State.
        @Variable1, -- variable to substitute in error message
        @Variable2  -- variable to substitute in error message
        );     
  RETURN -1  
 END

 BEGIN TRAN;
  
 
 BEGIN TRY

  SELECT 'insert code here'
  COMMIT
 END TRY
 
 BEGIN CATCH
  SET @LogDesc = ERROR_MESSAGE()
  SET @ErrorNumber = ERROR_NUMBER()
  SET @ErrorSeverity = ERROR_SEVERITY()
  SET @ErrorState = ERROR_STATE()
  SET @ErrorLine = ERROR_LINE()
  
  IF @@TRANCOUNT > 0
   ROLLBACK TRANSACTION
   
  -- The SP below, inserts to the errorlog table and does a RAISERROR
  EXEC LogErrorToTable  @ErrorMessage, @Source, @ErrorNumber, @ErrorSeverity,  @ErrorState , @ErrorLine
  
  RETURN -1
 END CATCH
 
    RETURN 0
END
GO


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>