Menu

SQL Server Error Handling: TRY...CATCH, THROW and Transactions
📰

SQL Server Error Handling: TRY...CATCH, THROW and Transactions

DEV Community: database·LingamSuyambu·12 days ago
#Coj7TLpd
#devtodatabase#devto#dev#transaction#catch
Long article (681 words) — no AI summary yet.
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.