Control flow statements are essential for directing the execution path of your T-SQL code. They allow you to make decisions, repeat actions, and manage the logic of your stored procedures, functions, and scripts.
The IF...ELSE
statement allows you to execute a block of code conditionally based on whether a specified condition evaluates to true or false.
IF EXISTS (SELECT 1 FROM sys.tables WHERE name = 'MyTable')
BEGIN
PRINT 'MyTable already exists.';
END
ELSE
BEGIN
PRINT 'MyTable does not exist.';
END
DECLARE @Score INT = 75;
IF @Score >= 90
BEGIN
PRINT 'Grade: A';
END
ELSE IF @Score >= 80
BEGIN
PRINT 'Grade: B';
END
ELSE IF @Score >= 70
BEGIN
PRINT 'Grade: C';
END
ELSE
BEGIN
PRINT 'Grade: D';
END
The WHILE
loop repeatedly executes a block of Transact-SQL statements as long as a specified condition remains true.
DECLARE @Counter INT = 1;
WHILE @Counter <= 5
BEGIN
PRINT 'Count: ' + CAST(@Counter AS VARCHAR(10));
SET @Counter = @Counter + 1;
END
BEGIN...END
blocks are used to group one or more Transact-SQL statements into a single logical unit. This is particularly useful within control flow statements like IF
and WHILE
when you need to execute multiple statements.
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MyFunction]') AND type IN (N'FN', N'IF', N'TF'))
BEGIN
PRINT 'Function exists.';
-- Additional logic here
DROP FUNCTION [dbo].[MyFunction];
PRINT 'Function dropped.';
END
ELSE
BEGIN
PRINT 'Function does not exist.';
END
The CASE
expression allows you to perform conditional logic within a query or statement. It returns one of several possible result expressions based on the evaluation of a condition.
SELECT
ProductName,
Price,
CASE
WHEN Price < 10 THEN 'Low Price'
WHEN Price BETWEEN 10 AND 50 THEN 'Medium Price'
ELSE 'High Price'
END AS PriceCategory
FROM
Products;
The GOTO
statement transfers control to another Transact-SQL statement within the same batch or stored procedure. It should be used sparingly as it can make code difficult to read and maintain.
DECLARE @LoopCount INT = 0;
LoopStart:
SET @LoopCount = @LoopCount + 1;
PRINT 'Iteration: ' + CAST(@LoopCount AS VARCHAR(10));
IF @LoopCount < 3
BEGIN
GOTO LoopStart;
END
PRINT 'Loop finished.';