Using Control-of-Flow Language

Transact-SQL provides special keywords called control-of-flow language that allow you to control the flow of execution of SQL statements, statement blocks, and stored procedures. These keywords can be used in ad hoc SQL statements, in batches, and in stored procedures.

Without control-of-flow language, separate SQL statements are performed sequentially, as they occur. Control-of-flow language permits statements to be connected, related to each other, and made interdependent using programming-like constructs.

These are the control-of-flow keywords:

Keyword Description
BEGIN...END Defines a statement block.
GOTO label Continues processing at the statement following the label as defined by label.
IF...ELSE Defines conditional and, optionally, alternate execution when a condition is false.
RETURN Exits unconditionally.
WAITFOR Sets a delay for statement execution.
WHILE Repeats statements while a specific condition is true.
...BREAK Exits the innermost WHILE loop.
...CONTINUE Restarts a WHILE loop.

In addition to the keywords used for conditional processing and control-of-flow for SQL statements, a variety of helpful Transact-SQL extensions and ANSI-standard additions are available:

Feature Description
CASE Expression Allows an expression to have conditional return values. This is the ANSI SQL-92 standard CASE expression.
Comments Inserts a comment anywhere in an SQL statement. Two commenting styles are supported: Transact-SQL style (/* and */) and ANSI-standard comment style (--).
DECLARE Statement Declares local variables as well as cursors.
PRINT Statement Prints a user-defined message on the user's screen.
RAISERROR Statement Returns a sysmessages entry or a dynamically built message with user-specified severity and state. RAISERROR also sets a system flag (in the global variable @@ERROR) to record that an error condition has occurred.
Execute (@string) Allows a command to be dynamically constructed as a character string, and then executed, without requiring any communication between client and server.

For details on control-of-flow language, see Control-of-Flow Language in the Microsoft SQL Server Transact-SQL Reference.