The Transact-SQL Statements for Script Processing

Below is the presentation of the Transact-SQL statements used to process scripts. These statements, which are sometimes referred to as T-SQL statements, are specific to SQL Server. You’ll learn how to code many of these statements throughout this chapter.

Two statements I want to present right now are USE and PRINT. You can see both of these statements in the script presented below. You use the USE statement to change the current database within a script. In this example, the USE statement makes the AP database the current database. That way, you don’t have to worry about setting the current database using the drop-down list in the Management Studio. And when you create stored procedures, functions, and triggers as you’ll learn in the next chapter, you have to use the USE statement.

You use the PRINT statement to return a message to the client. If the client is the Management Studio, for example, the message is displayed in the Mes-sages tab of the Query Editor. The script in this section includes two PRINT statements. Notice that the first statement uses concatenation to combine a literal string with the value of a variable. You’ll learn how to work with variables as well as the other statements in this script in a moment.

Two statements I won’t present in this chapter are GOTO and RETURN. I recommend that you don’t use the GOTO statement because it can make your scripts difficult to follow. And the RETURN statement is used most often with stored procedures, so I’ll present it in the next chapter.

Transact-SQL statements for controlling the flow of execution

KeywordDescription
IF … ELSEControls the flow of execution based on a condition
BEGIN… ENDDefines a statement block
WHILERepeats statements while a specific condition is true
BREAKExits the innermost WHILE loop
CONTINUEReturns to the beginning of a WHILE loop
TRY…CATCHControls the flow of execution when an error occurs
GOTOUnconditionally changes the flow of execution
RETURNExits unconditionally.

 

Other Transact-SOL statements for script processing

KeywordDescription
USEChanges the database context to the specified database
PRINTReturns a message to the client
DECLAREDeclares a local variable
SETSets the value of a local variable or a session variable
EXECExecutes a dynamic SQL statement or stored procedure

 

The syntax of the USE statement

 

The syntax of the PRINT statement

 

A script that uses some of the statements shown above

 

Description

  • These statements are used within SQL scripts to add functionality similar to that provided by procedural programming languages.
  • These statements are part of the Transact-SQL, or T-SQL, language and aren’t available on SQL-based systems other than SQL Server.