Control SQL Server Batch Execution with IF and ELSE

Use IF...ELSE when a batch or stored procedure should execute different statements depending on a condition. Use CASE when a query needs to calculate a different value for each row. Keeping those responsibilities separate makes both forms easier to read.

Run a Complete Branching Example

SQL
DECLARE @PendingCount int = 3;

IF @PendingCount IS NULL
BEGIN
    SELECT N'Count unavailable' AS Message;
END
ELSE IF @PendingCount > 0
BEGIN
    SELECT N'Work remains' AS Message;
    SELECT @PendingCount AS PendingCount;
END
ELSE
BEGIN
    SELECT N'No pending work' AS Message;
END;

The value 3 selects the middle branch and produces two result sets. Set the variable to 0 to take the final branch, or to NULL to take the first branch. A negative value currently also takes the final branch. If negative counts are invalid in your contract, reject them explicitly.

Group All Statements That Belong Together

BEGIN and END group multiple statements under one branch. Indentation alone has no effect. Without a block, the conditional applies only to its following statement, which can leave a second statement executing unexpectedly.

A comparison with NULL is not true, so use IS NULL when absence needs its own branch. Keep the complete construct in one batch. GO is a client batch separator and cannot split an IF block or preserve its local variables.

Test Whether Rows Exist

SQL
DECLARE @Queue TABLE (ItemId int NOT NULL, IsReady bit NOT NULL);
INSERT @Queue (ItemId, IsReady) VALUES (1, 1), (2, 0);

IF EXISTS (SELECT 1 FROM @Queue WHERE IsReady = 1)
BEGIN
    SELECT ItemId FROM @Queue WHERE IsReady = 1 ORDER BY ItemId;
END
ELSE
BEGIN
    SELECT N'Nothing ready' AS Message;
END;

This returns item 1. An existence check does not reserve rows against concurrent workers. If the branch will claim or modify shared work, design the transaction and concurrency rule separately rather than assuming IF EXISTS makes the later action atomic.

Microsoft References

Author: Herman Schoenfeld