I have a couple stored procedures that write and delete data from some tables.
My idea is that those stored procedures would either write to the production table or to a debug table with what went wrong.
Is this a good idea? Any recommendations on how to do?
Here's what I have:
CREATE TABLE dbo.ErrorLog
(
[ErrorID] int IDENTITY(1,1) PRIMARY KEY,
[SQLUser] varchar(50) NOT NULL DEFAULT ORIGINAL_LOGIN(),
[ErrorDate] datetime NOT NULL DEFAULT GETDATE(),
[How] varchar(50) NOT NULL, --The name of the stored procedure that was running
[ErrorMessage] varchar(50) NOT NULL,
[ErrorProcedure] varchar(50) NOT NULL,
[ErrorLine] varchar(50) NOT NULL,
[ErrorState] varchar(50) NOT NULL,
[ErrorSeverity] varchar(50) NOT NULL,
[ErrorNumber] varchar(50) NOT NULL
)
And then the stored procedure is something like this:
CREATE PROCEDURE [dbo].[proc_xxx]
@A int,
@B int,
@C int,
@D int
AS
BEGIN
DECLARE @BusinessRule_1_Fail int =
(SELECT IIF(@A < 3, 1, 0))--some business rule that might result in 1 or 0
DECLARE @BusinessRule_2_Fail int =
(SELECT IIF(@C < 7, 1, 0))--some business rule that might result in 1 or 0
IF @BusinessRule_1_Fail = 1
RAISERROR('Rule #1 failed because XYZ', 16, 16)
ELSE IF @BusinessRule_2_Fail = 1
RAISERROR('Rule #2 failed because ZYX', 16, 16)
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO [INV].[Table_A] (ColA, ColB, ColC, ColD)
VALUES (@A, @B, @C, @D)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
INSERT INTO [dbo].[ErrorLog] ([SQLUser], [ErrorDate], [How], [ErrorMessage], [ErrorProcedure], [ErrorLine], [ErrorState], [ErrorSeverity], [ErrorNumber])
VALUES (ORIGINAL_LOGIN() , -- [SQLUser],
GETDATE() , -- [ErrorDate],
'[dbo].[proc_xxx]' , -- [How],
ERROR_MESSAGE() , -- [ErrorMessage],
ERROR_PROCEDURE() , -- [ErrorProcedure],
ERROR_LINE() , -- [ErrorLine],
ERROR_STATE() , -- [ErrorState],
ERROR_SEVERITY() , -- [ErrorSeverity],
ERROR_NUMBER() , -- [ErrorNumber]
)
END CATCH
END
Is this a good idea? Bad? Anything you would do differently?
I was wondering to include the function parameters as well (to be able to reproduce the error) but given that each stored procedure has different input parameters it gets quite tricky (maybe having a varchar(8000) column that is calculated as something like 'A;10,B;2,C;323,D;42' for this stored procedure and as 'AA;1,BA;202,par8;3' for another stored procedure)
I wonder what the best practices for something like this are...