Variables and Control of Flow: Functions
Variables and Control of Flow: Functions
Lab 4
Variables
• Local Variables
• Global Variables
• Dynamic SQL
• What Are T-SQL Expressions?
• Control-of-flow Statements
What Are T-SQL Variables?
A Transact-SQL local variable is an object that can hold a single data value of a
specific type
• Example:
declare @mynumber int
select @mynumber
-
NULL
• This is the same select that is used to query data from tables
Assigning Values to Local
Variables
• Three methods
• During Declaration
• Assignment select using an expression
• Assignment select using a table value
• Assignment update
During Declaration
• Example1:
declare @x int=1
• Example2:
declare @x int
Set @x=1
Assignment select and
Expressions
• Simplified syntax:
select variable_name = expression
[, variable_name = expression ...]
• Examples:
declare @number int,
@copy int,
@sum int
select @number = 10
select @copy = @number,
@sum = @number + 100
• @@error
• Returns the error number generated by the last statement
• @@identity
• Returns the value last inserted into an IDENTITY column
• @@version
• Returns the version number of the server
Control-of-flow Statements
These are the control-of-flow keywords:
• BEGIN...END • BREAK
• GOTO • CONTINUE
• IF...ELSE • WHILE
• RETURN • WAITFOR
Case Expression
Evaluates a list of conditions and returns one of multiple
possible result expressions.
The CASE expression has two formats:
• The simple CASE expression compares an expression to a set of simple
expressions to determine the result.
• The searched CASE expression evaluates a set of Boolean expressions
to determine the result.
Both formats support an optional ELSE argument.
Case Expression Cont.
Syntax
Simple CASE expression:
CASE input_expression
WHEN when_exp THEN result_exp[ ..n ] [ ELSE
else_result_exp]
END
BEGIN TRY
-- Generate divide-by-zero error.
SELECT 1/0;
END TRY
BEGIN CATCH
-- Execute error retrieval routine.
EXECUTE usp_GetErrorInfo;
END CATCH;
RAISERROR
COMMIT TRANSACTION
COMMIT { TRAN | TRANSACTION } [
transaction_name | @tran_name_variable ]
ROLLBACK TRANSACTION
ROLLBACK { TRAN | TRANSACTION } [
transaction_name | @tran_name_variable |
savepoint_name | @savepoint_variable ]
ROLLBACK TRAN T1;
Using Nested Transactions
• Explicit transactions can be nested to support transactions in stored
procedures
✔ Scalar Functions
✔ Built-in Functions
How To Implement Different
Types Of User-Defined Functions
Types Usage
Can return any data type except for text, ntext, image,
✔
cursor, and timestamps