Recipe 2.1 · C#
A Stored Procedure Template
Problem
A procedure that changes data needs to do four things right: validate its input, do its work in one transaction, roll back completely on any error, and tell the caller what went wrong. Most legacy procedures get one or two of these right. The rest leak open transactions, swallow errors, or return -1 to a caller that never checks the return value.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
-- Not to copy: SQL Server 2000-era error handling.
CREATE PROCEDURE CancelOrder @OrderId int, @User varchar(50)
AS
BEGIN TRAN
UPDATE SalesOrder SET Status = 'Cancelled', CancelledBy = @User
WHERE OrderId = @OrderId
IF @@ERROR <> 0
BEGIN
ROLLBACK TRAN
RETURN -1
END
INSERT INTO SalesOrderNote (OrderId, Note)
VALUES (@OrderId, 'Cancelled')
IF @@ERROR <> 0
BEGIN
ROLLBACK TRAN
RETURN -1
END
COMMIT TRAN
Every statement needs its own @@ERROR check, and forgetting one means the error is ignored. Some errors abort the batch before the check runs, leaving the transaction open. The DONE_IN_PROC row-count messages go back to the client for every statement. Nothing happens if the order does not exist: zero rows are updated and a note is inserted for an order that is not there.
The improved recipe
CREATE OR ALTER PROCEDURE dbo.SalesOrder_Cancel
@OrderId INT,
@CancelledBy NVARCHAR(128),
@Reason NVARCHAR(400) = NULL
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
IF @OrderId IS NULL OR @OrderId <= 0
THROW 50001, N'@OrderId must be a positive integer.', 1;
IF NULLIF(LTRIM(@CancelledBy), N'') IS NULL
THROW 50002, N'@CancelledBy is required.', 1;
BEGIN TRY
BEGIN TRANSACTION;
UPDATE dbo.SalesOrder
SET Status = 'Cancelled',
CancelledUtc = SYSUTCDATETIME(),
CancelledBy = @CancelledBy
WHERE OrderId = @OrderId
AND Status IN ('Open', 'OnHold');
IF @@ROWCOUNT = 0
THROW 50003, N'Order not found or not cancellable.', 1;
INSERT INTO dbo.SalesOrderNote (OrderId, NoteUtc, Note)
VALUES (@OrderId, SYSUTCDATETIME(),
CONCAT(N'Cancelled. ', @Reason));
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
THROW;
END CATCH;
END;
How it works
SET NOCOUNT ON stops the per-statement row-count messages. They cost a little network traffic, and some older client libraries misread them as result sets. Only about 10.2% of the SQL files in my archive (7,071 files) contain it.
SET XACT_ABORT ON makes SQL Server roll back the whole transaction on any run-time error, including the ones that TRY/CATCH cannot catch, such as a client timeout. Without it, a command timeout from .NET can leave the transaction open on a pooled connection, and the next unrelated request inherits it.
Input validation runs before the transaction starts, so bad input never takes a lock. THROW with a number of 50000 or higher raises a real error that .NET sees as a SqlException with that Number, which the application can map to a friendly message.
Inside TRY, the @@ROWCOUNT check turns a silent no-op into an explicit error. The CATCH block rolls back if a transaction is still open, then THROW; with no arguments rethrows the original error with its original number, message and line. That is the T-SQL equivalent of throw; in C#.
Variations and pitfalls
THROWneeds a terminated previous statement. The statement beforeTHROWmust end with a semicolon, or the parser can readTHROWas part of it, for example as a transaction name afterROLLBACK. Terminate every statement and the problem disappears.RAISERRORvsTHROW.RAISERRORdoes not stop execution and does not honorXACT_ABORT. UseTHROWin new code. KeepRAISERRORonly where you needprintf-style formatting or severity below 11 for progress messages, and then useWITH NOWAIT.- Nested procedures. If a procedure that opens a transaction calls another that does the same, the inner
ROLLBACKrolls back everything and the outerCOMMITfails. With this template the innerTHROWreaches the outerCATCH, which checks@@TRANCOUNTbefore rolling back, so the error surfaces cleanly. - Return values. Use output parameters or a result set for data, and errors for failure. A return code that every caller must remember to check is the
@@ERRORproblem again. - Read-only procedures need
SET NOCOUNT ONbut usually not the transaction orTRY/CATCH.