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

Chapter5_session1-Introduction, Variables, Control-Flow statements

Uploaded by

tindepzai91
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-Introduction, Variables, Control-Flow statements

Uploaded by

tindepzai91
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
T-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.
It is a full-featured programming language that
dramatically extends the power of SQL.

3
Introduction to T-SQL Programming
tinh nang
The 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
Giao dch

4
Introduction to T-SQL Programming
SQL and T-SQL are the query languages used to
manipulate the database and are an important part of
Thao tác

the DBMS.
Database management system

What are the differences between SQL and T-SQL?

5
Using Variables
Variables are the object which acts as a placeholder
to a memory location. Variable hold single data value.
In 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. nguoi dung kh the khai bao bien toan cuc
• The global variable starts with @@
• It stores session related information.
6
Using Variables
Before using any variables, they must be declared
variable using DECLARE statement.
Syntax
DECLARE @variable_name [AS] datatype
Example
DECLARE @Product_name NVARCHAR(30)
DECLARE @Product_Id int = 7

You can declare multiple variables in one statement,


co the khai bao nhieu bien tren mot cau lenh
separated by commas cach nhau dau phay
DECLARE @Product_name NVARCHAR(30), @Product_Id int

7
Using Variables mac dinh bien ban dau se gan gia tri la null

By default, variables are initially set to Null


You can assign a value to a variable
DECLARE statement ban co the gan gia tri cho mot bien
bang cach :
Using SET khai bao
sudung set
• Must declare a variable first.
sudung select
• 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
Example to assign value to a variable
By DECLARE dung khai bao

DECLARE @Product_name NVARCHAR(30) = N'Bút chì', @Product_Id int = 7


PRINT @Product_name
PRINT @Product_Id moi cau lenh set
dung set hoac select phai
By SET/SELECT rieng biet
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 truy van con phai tra ve 1 gia tri
neu tra ve hang 0 thi bien nhan gtri null

Get 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
Using 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

Result

12
Using Variables luu tru ket qua trruy van duoi dang
bien
Using 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'

Result

13
Using Variables lua chon bang ghi thanh cac
bien

Using 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
duoc xac dinh
Global variables are pre-defined system functions.
Their names begin with an @@ prefix
Some common global variables
mot so bien pho bien
@@IDENTITY
@@ERROR
@@ROWCOUNT
@@TOTAL_ERRORS
@@SERVERNAME

15
Using Global variables example
Example
@@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
IF/ IF…ELSE statement
CASE statement
WHILE statement

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

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

18
IF/IF…ELSE statement
Example
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
Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END
cau lenh case luon di voi select
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
Example
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
Syntax
WHILE Boolean_expression
BEGIN
statement_block
END

In WHILE, you can use


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

22
WHILE statement
Example
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
Result

24

You might also like