T-SQL Programming, Transactions and Isolation

Article · 6:00

Procedures and TRY CATCH, why XACT_ABORT is not optional, the locking isolation levels, and the row-versioning ones that fix the blocking.

Stored procedures are a strength here. They give a stable interface, a cached plan, and a permission boundary - you can grant EXECUTE on a procedure without granting any access to the tables it touches, which is a real security tool.

Error handling is where T-SQL surprises people. TRY ... CATCH catches most runtime errors, but a CATCH block alone does not roll back the transaction, and some errors leave it in a doomed state where only a rollback is legal. SET XACT_ABORT ON makes any runtime error abort the whole transaction, which is almost always what you want; without it, a failed statement inside a multi-statement transaction can leave the earlier statements committed and the application unaware. Treat SET XACT_ABORT ON as a mandatory first line in any procedure that writes.

XACT_STATE() tells you whether the transaction is committable (1), doomed (-1) or absent (0), and a correct CATCH block checks it before deciding.

Isolation. SQL Server has two families.

The locking levels: READ UNCOMMITTED (dirty reads - and NOLOCK is this, which is why it can return rows twice or miss them entirely during a page split), READ COMMITTED (the default, taking shared locks so readers block behind writers), REPEATABLE READ, and SERIALIZABLE (range locks, and the most blocking).

The row-versioning levels: READ_COMMITTED_SNAPSHOT changes the default level to use row versions instead of shared locks, so readers see the last committed version and never block. SNAPSHOT isolation gives a transaction-wide consistent snapshot. Both keep versions in tempdb, which is the cost.

Turning on READ_COMMITTED_SNAPSHOT is usually the single highest-value change you can make to a blocking-prone SQL Server application. It is a database-level setting, it requires a brief exclusive lock to enable, and it moves load onto tempdb.

Deadlocks are detected automatically and one transaction is chosen as the victim with error 1205. The fix is almost always consistent object access order, not a retry loop - though a retry loop is also necessary, because you cannot eliminate every deadlock.

Laboratory exercise 3 - a service under concurrency.

Build a small service over your Module 2 schema with at least two write operations and one read-heavy report. Run at least 50 concurrent clients mixing both.

Demonstrate the problems in order. Show readers blocking behind a writer at default READ COMMITTED. Show NOLOCK returning inconsistent results under concurrent updates - not just dirty rows, but a row counted twice. Then enable READ_COMMITTED_SNAPSHOT and measure the change to blocking and to tempdb.

Produce a deadlock deliberately with two procedures taking locks in opposite orders, capture it from the system_health extended event session, and fix it by ordering.

Write a procedure with TRY CATCH but without XACT_ABORT, and demonstrate a partial commit. Then add it and show the difference.

Deliverable: the service, the load script, measurements of blocking and throughput at each configuration, the deadlock graph with your explanation, and the partial-commit demonstration before and after.

-- ------------------------------------------------------------------
-- A write procedure, with the error handling that is actually correct.
-- ------------------------------------------------------------------
CREATE OR ALTER PROCEDURE sales.place_order
    @customer_id int,
    @product_id  int,
    @quantity    int,
    @order_id    bigint OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;
    -- ^^^^^^^^^^^^^^^^ NOT OPTIONAL. Without it, an error inside the
    -- transaction below can leave the first INSERT committed and the
    -- second not, with the caller never told.

    BEGIN TRY
        BEGIN TRANSACTION;

            DECLARE @price decimal(19,4);

            SELECT @price = list_price
            FROM sales.product WITH (UPDLOCK, HOLDLOCK)
            --                      ^^^^^^^^^^^^^^^^^^ take the update
            --   lock NOW rather than a shared lock we must upgrade
            --   later. Upgrading is how two readers deadlock.
            WHERE product_id = @product_id;

            IF @price IS NULL
                THROW 50001, 'No such product', 1;

            INSERT INTO sales.[order] (customer_id, status)
                VALUES (@customer_id, 'pending');
            SET @order_id = SCOPE_IDENTITY();
            --              ^^^^^^^^^^^^^^^ SCOPE_IDENTITY(), never
            --   @@IDENTITY: @@IDENTITY crosses scopes and returns a
            --   value generated by a TRIGGER if one fired.

            INSERT INTO sales.order_line2 (order_id, line_no, product_id,
                                           quantity, unit_price)
                VALUES (@order_id, 1, @product_id, @quantity, @price);

        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        -- A CATCH block does NOT roll back by itself, and some errors
        -- leave the transaction doomed - only a rollback is legal.
        IF XACT_STATE() <> 0
            ROLLBACK TRANSACTION;
        --    1 = committable,  -1 = doomed,  0 = none open

        THROW;      -- rethrow with the original number and line.
                    -- RAISERROR would lose both.
    END CATCH
END;
GO

-- ------------------------------------------------------------------
-- Isolation: the two families.
-- ------------------------------------------------------------------
-- LOCKING levels. The default takes shared locks, so a reader WAITS
-- behind a writer:
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;     -- default, blocks
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;    -- holds read locks
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;       -- range locks

-- And the one everybody reaches for and should not:
SELECT COUNT(*) FROM sales.[order] WITH (NOLOCK);
-- NOLOCK is READ UNCOMMITTED. It does not merely show uncommitted
-- rows. During a page split it can return the same row TWICE or MISS
-- one entirely, in a query with no uncommitted data anywhere near it.
-- It is not "a hint that makes reads faster".

-- ROW VERSIONING. Usually the highest-value change available:
ALTER DATABASE SalesWorkshop SET READ_COMMITTED_SNAPSHOT ON;
-- Readers now see the last committed version and never block. Needs a
-- brief exclusive lock to enable, and moves version storage to tempdb.

ALTER DATABASE SalesWorkshop SET ALLOW_SNAPSHOT_ISOLATION ON;
SET TRANSACTION ISOLATION LEVEL SNAPSHOT;   -- transaction-wide snapshot

-- ------------------------------------------------------------------
-- Watching the blocking, live.
-- ------------------------------------------------------------------
SELECT r.session_id, r.blocking_session_id, r.wait_type, r.wait_time,
       r.wait_resource, t.text AS running_sql
FROM sys.dm_exec_requests AS r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t
WHERE r.blocking_session_id <> 0;

-- Deadlocks are already being recorded. system_health runs by default
-- and nobody looks at it:
SELECT XEvent.value('(data/value)[1]', 'varchar(max)') AS deadlock_graph
FROM (
    SELECT CAST(target_data AS xml) AS TargetData
    FROM sys.dm_xe_session_targets st
    JOIN sys.dm_xe_sessions s ON s.address = st.event_session_address
    WHERE s.name = 'system_health' AND st.target_name = 'ring_buffer'
) AS Data
CROSS APPLY TargetData.nodes('RingBufferTarget/event[@name="xml_deadlock_report"]')
    AS XEventData(XEvent);

-- The fix for a deadlock is ORDER, not a longer timeout. If every
-- procedure touches product before order before order_line, a cycle
-- cannot form. A retry loop on error 1205 is still needed, because
-- you cannot eliminate every one.

Discussion

No questions on this topic yet. Sign in to ask the first one.