Wednesday, February 27, 2019

SQL RAISEERROR and Log the error

Put all SQL Stored Procedures in BEGIN TRY > BEGIN TRANSACTION > IF  ELSE blocks and use the following as a TEMPLATE

Create an output parameter so the source code can log the error and you can check the DB table for the error.


@ELog_ID int = 0 OUTPUT 

SET XACT_ABORT, NOCOUNT ON;

BEGIN TRY
BEGIN TRANSACTION


IF
            IF EXISTS (SELECT 'x' FROM People_tbl WHERE Email_Address = @Email_Address)
RAISERROR (N'Person is already in the database.',11,11, 'usr_Person_Add')
--PRINT 'Person is already in the database!'

ELSE

-- CRUD work

END TRY

BEGIN CATCH

--PRINT 'In the Catch Statement'
IF @@trancount > 0 ROLLBACK TRANSACTION
PRINT 'Process has reached the CATCH'

EXECUTE dbo.[usr_InsertErrorInfo];

SELECT @ELog_ID = max(ELog_ID)
FROM ErrorLog_tbl;


END CATCH