0% found this document useful (0 votes)
1 views

Chapter5_session1

Uploaded by

xuanliem2209
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Chapter5_session1

Uploaded by

xuanliem2209
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Database Systems

Chapter 5
T-SQL Programming
Session 1:
Introduction, Variables, Control-Flow
statements
Outline

1 Introduction to T-SQL Programming

2 Using Variables

3 Control-Flow statements

2
Introduction to T-SQL
Programming
qT-SQL
§ Stands for Transact-SQL
§ It is an extension to SQL
§ It is a procedural language used on both Microsoft SQL
Server and Sybase SQL Server systems.
qIt is a full-featured programming language that
dramatically extends the power of SQL.

3
Introduction to T-SQL
Programming
qThe language provides programmers with a broad
range of features, including:
§ A rich set of data types, including specialized types for
identifiers, timestamps, images, and long text fields
§ Local and global variables
§ Fully programmable server objects like views, triggers,
stored procedures, and batch command files
§ Conditional processing
§ Exception and error handling
§ Full transaction control

4
Introduction to T-SQL
Programming
qSQL and T-SQL are the query languages used to
manipulate the database and are an important part
of the DBMS.

qWhat are the differences between SQL and T-SQL?

5
Using Variables
qVariables are the object which acts as a placeholder
to a memory location. Variable hold single data value.
qIn MS SQL, there are 2 types of variables:
§ Local variable
• A user declares the local variable.
• A local variable starts with @.
• Every local variable scope has the restriction to the current
batch or procedure within any given session.
§ Global variable
• The system maintains the global variable. A user cannot
declare them.
• The global variable starts with @@
• It stores session related information.
6
Using Variables
qBefore using any variables, they must be declared
variable using DECLARE statement.
qSyntax
DECLARE @variable_name [AS] datatype
qExample
DECLARE @Product_name NVARCHAR(30)
DECLARE @Product_Id int = 7

qYou can declare multiple variables in one statement,


separated by commas
DECLARE @Product_name NVARCHAR(30), @Product_Id int
7
Using Variables
qBy default, variables are initially set to Null
qYou can assign a value to a variable
§ DECLARE statement
§ Using SET
• Must declare a variable first.
• Each variable requires a separate SET statement.
§ Using SELECT
• Must declare a variable first.
• Can assign a value to multiple variables separated by the
comma

8
Using Variables
qExample to assign value to a variable
§ By DECLARE
DECLARE @Product_name NVARCHAR(30) = N'Bút chì', @Product_Id int = 7
PRINT @Product_name
PRINT @Product_Id

§ By SET/SELECT
DECLARE @Product_name NVARCHAR(30), @Product_Id int
SET @Product_name = N'Bút chì' SELECT @Product_name = N'Bút
SET @Product_Id = 7 chì', @Product_Id = 7
PRINT @Product_name + N' với id =' + CAST(@Product_Id AS
NVARCHAR(30))

9
The contents of Products table

10
Using Variables
qGet value from a subquery by SET/SELECT
§ A subquery must return one value
§ When subquery returns zero row as a result, the variable
is assigned NULL value
DECLARE @Product_name NVARCHAR(30)
SET @Product_name = (SELECT product_name FROM products WHERE
product_id = 1)
PRINT @Product_name

You can replace SET by SELECT

11
Using Variables
qUsing variables in a query
DECLARE @Product_id INT
SET @Product_id = 1
SELECT product_name, model_year, list_price
FROM products
WHERE product_id = @Product_id
ORDER BY product_name

qResult

12
Using Variables
qUsing variables in a query
§ Storing query result in a variable
DECLARE @product_count int
SET @product_count = (
SELECT
COUNT(*)
FROM
products
)
SELECT @product_count AS 'Number of Products'

qResult

13
Using Variables
qUsing variables in a query
§ Selecting a record into variables
DECLARE @product_name VARCHAR(MAX), @list_price DECIMAL(10,2)
SELECT @product_name = product_name,@list_price = list_price
FROM products
WHERE product_id = 1
SELECT @product_name AS product_name,
@list_price AS list_price

§ Result

14
Using Global variables
qGlobal variables are pre-defined system functions.
Their names begin with an @@ prefix
qSome common global variables
§ @@IDENTITY
§ @@ERROR
§ @@ROWCOUNT
§ @@TOTAL_ERRORS
§ @@SERVERNAME

15
Using Global variables
example
qExample
§ @@IDENTITY is used to get the last value inserted into
an IDENTITY column by an insert statement.
§ Example: get the last inserted product_id which is the
identity column in previous product table

INSERT INTO products


VALUES('Electra - 2020', 1, 3, 2020, 2000)
GO
SELECT @@IDENTITY AS NewProductId

SELECT @@rowcount as 'Number of Rows


affected'
16
Control-Flow statements
qIF/ IF…ELSE statement
qCASE statement
qWHILE statement

17
IF/IF…ELSE statement
qIF statement
IF boolean_expression
BEGIN statement_block
END

qIF…ELSE statement
IF Boolean_expression
BEGIN Statement block
END
ELSE
BEGIN Statement block
END

18
IF/IF…ELSE statement
qExample
DECLARE @product_count int
SET @product_count = (SELECT COUNT(*) FROM products
WHERE list_price >1000)
IF @product_count > 0
BEGIN
PRINT 'The products have price are greater than 100'
SELECT product_id, product_name, list_price
FROM products
WHERE list_price >1000
END
ELSE
BEGIN
PRINT 'There is no product that has price is less than
or equal to 1000'
END

19
CASE statement
qSyntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END

§ The CASE statement always goes in the SELECT clause


§ CASE must include the following components: WHEN,
THEN, and END. ELSE is an optional component.

20
CASE statement
qExample
SELECT product_id, list_price,
CASE
WHEN list_price > 1000 THEN 'The price is greater than 1000'
WHEN list_price = 1000 THEN 'The price is 1000'
ELSE 'The price is under 1000'
END AS PriceText
FROM products
WHERE model_year = 2016

21
WHILE statement
qSyntax
WHILE Boolean_expression
BEGIN
statement_block
END

qIn WHILE, you can use


§ BREAK statement to exit from the WHILE LOOP
§ CONTINUE to restart the WHILE LOOP from the
beginning

22
WHILE statement
qExample
DECLARE @Counter INT , @MaxId INT,
@ProductName NVARCHAR(100)
SELECT @Counter = min(product_id) , @MaxId = max(product_id)
FROM products
WHERE model_year= 2016
WHILE(@Counter IS NOT NULL
AND @Counter <= @MaxId)
BEGIN
SELECT @ProductName = product_name
FROM products WHERE product_id = @Counter

PRINT CONVERT(VARCHAR(MAX),@Counter) + '. product name is '


+ @ProductName
SET @Counter = @Counter + 1
END

23
WHILE statement
qResult

24

You might also like