IC Improve Code Recipes

Recipe 2.1 · Python

A Stored Procedure Template

This recipe has no Python listing. The explanation and any SQL below apply to both languages; switch to C# for the .NET code.

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.

SQL
-- 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

SQL
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

  • THROW needs a terminated previous statement. The statement before THROW must end with a semicolon, or the parser can read THROW as part of it, for example as a transaction name after ROLLBACK. Terminate every statement and the problem disappears.
  • RAISERROR vs THROW. RAISERROR does not stop execution and does not honor XACT_ABORT. Use THROW in new code. Keep RAISERROR only where you need printf-style formatting or severity below 11 for progress messages, and then use WITH NOWAIT.
  • Nested procedures. If a procedure that opens a transaction calls another that does the same, the inner ROLLBACK rolls back everything and the outer COMMIT fails. With this template the inner THROW reaches the outer CATCH, which checks @@TRANCOUNT before 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 @@ERROR problem again.
  • Read-only procedures need SET NOCOUNT ON but usually not the transaction or TRY/CATCH.