Many times in your SQL procedures you need to test the value of a variable, then take some action based on that value.
You can do this with SQL Servers Transact-SQL control-of-flow logic. Control-of-flow logic is a specific set of Transact-SQL commands that you can enter into your Transact-SQL procedures to dynamically control which statements are executed.
The following is a list of the keywords available in Transact-SQL:
BEGIN END Defines a block of Transact-SQL code
GOTO Instructs the processor to go to a specific label defined in the procedure
IF ELSE Tests for conditions that you specify. The results of these conditions always return values of TRUE or FALSE. As such, they are known as Boolean expressions.
RETURN Exits the procedure
WAITFOR Delays the execution of a statement until specific conditions exist
WHILE Loops until a specific condition exists
BREAK Unconditionally exits a WHILE loop
CONTINUE Restarts the WHILE loop
CASE WHEN Tests multiple possibilities for a given condition
The Transact-SQL statement in the following series of images uses most of the keywords listed above:
Using While Statement in SQL-Server
This SQL Server tutorial explains how to use the WHILE LOOP in SQL Server (Transact-SQL) with syntax and examples.
In SQL Server, you use a WHILE LOOP when you are not sure how many times you will execute the loop body and the loop body may not execute even once.
WHILE condition
BEGIN
{...statements...}
END;
Parameters or Arguments
condition: The condition is test each pass through the loop. If condition evaluates to TRUE, the loop body is executed. If condition evaluates to FALSE, the loop is terminated.
statements: The statements of code to execute each pass through the loop.
Pay attention to the following facts:
You would use a WHILE LOOP statement when you are unsure of how many times you want the loop body to execute.
Since the WHILE condition is evaluated before entering the loop, it is possible that the loop body may not execute even once.
See also the BREAK statement to exit from the WHILE LOOP early.
See also the CONTINUE statement to restart the WHILE LOOP from the beginning.
Note that the SELECT statement is covered in a later lesson in this module.
The main point of this lesson is to show the structure of how to use logic in your queries. The actual SELECT statements shown are not significant. In the next lesson, the benefits of constructing SQL statements dynamically will be discussed.
Logic with Queries - Exercise
Before moving on to the next lesson, click the Exercise link below to practice writing query logic. Logic within Queries - Exercise