Originally published at SQL & Cloud Lab .
This post was drafted with AI assistance.
Error handling in T-SQL decides whether a failure leaves your data clean or half-updated, and whether the application gets a clear error or a mysterious timeout from a transaction left open. A small, consistent pattern covers almost every stored procedure.
The template
CREATE OR ALTER PROCEDURE dbo . PostPayrollRun @ PayrollRunId INT AS BEGIN SET NOCOUNT ON ; SET XACT_ABORT ON ;
BEGIN TRY BEGIN TRANSACTION ;
UPDATE dbo . PayrollRun SET Status = 'Posted' WHERE PayrollRunId = @ PayrollRunId ;
INSERT INTO dbo . PayrollAudit ( PayrollRunId , Action , CreatedAt ) VALUES ( @ PayrollRunId , 'Posted' , SYSUTCDATETIME ());
COMMIT TRANSACTION ; END TRY BEGIN CATCH IF XACT_STATE () <> 0 ROLLBACK TRANSACTION ;
THROW ; -- re-raise the original error to the caller END CATCH END ;
Enter fullscreen mode
Exit fullscreen mode
Each piece has a job.…