SQL-Query Basics  «Prev  Next»
Lesson 5 Logic within queries
Objective Practice writing logic within your queries.

Logic within Queries of SQL-Server 2012

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 Server’s 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:
  1. BEGIN…END – Defines a block of Transact-SQL code
  2. GOTO – Instructs the processor to go to a specific label defined in the procedure
  3. 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.
  4. RETURN – Exits the procedure
  5. WAITFOR – Delays the execution of a statement until specific conditions exist
  6. WHILE – Loops until a specific condition exists
  7. BREAK – Unconditionally exits a WHILE loop
  8. CONTINUE – Restarts the WHILE loop
  9. CASE…WHEN – Tests multiple possibilities for a given condition
The Transact-SQL statement in the following Carousel uses most of the keywords listed above:


Logic in Stored Procedure
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