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

Chapter5_session2-Function, Store procedure, Trigger

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)
7 views

Chapter5_session2-Function, Store procedure, Trigger

Uploaded by

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

Database Systems

Chapter 5
T-SQL Programming
Session 2:
Function, Store procedure, Trigger
Outline

1 Function

2 Store procedures

3 Trigger

2
Functions
hang loat cac cau lenh thuc hien mot tac vu cu the
A function is a set of SQL statements that perform a
specific task. muc dich chinh la sudung lai code
The main purpose of function is codekich reusability.
ban
nhieu lan
If you have to repeatedly write large SQL scripts to
perform the same task, you can create a function that
performs that task.
Next time instead of rewriting the SQL, you can simply call
that function.
A function accepts inputs in the form of
parameters and returns a value.
tham so

3
Functions
Some rules when creating functions in SQL Server
A function must have an unique name
Functions only work with select statements
Functions compile every time. compile : biên dch
Functions must return a value or result.
Functions only work with input parameters.
Try and catch statements are not used in functions
try catch kh duoc sudung trong cac ham

4
Functions
SQL Server supports two types of functions:
User-Defined function (also call UDF): 3 types
vo huong• Scalar Valued Functions: returns a single value
• Inline table-valued function: returns a table
• Multi-statement table-valued function: returns a table and
can have more than one T-SQL statement. ham co gia tri bang
nhieu cau lenh
System Defined function (Built-in function)
Syntax ham do he thong xac dinh

CREATE FUNCTION [schema_name.]function_name(parameter_list)


RETURNS data_type
AS
BEGIN statements
RETURN value
END

5
Scalar Valued Functions
Example:
CREATE FUNCTION fn_Sale(
@quantity INT, @list_price DEC(10,2), @discount DEC(4,2))
RETURNS DEC(10,2)
AS
BEGIN
RETURN @quantity * @list_price * (1 - @discount)
END

ham gia tri vo huong


Calling a scalar function
SELECT
dbo.fn_Sale(10,100,0.1) sale

6
Scalar Valued Functions
Calling the function to get the sale of sales of sales
orders in the order_items table
SELECT
order_id,
SUM(dbo.fn_Sale(quantity,
list_price, discount)) sale_amount
FROM
sales.order_items
GROUP BY
order_id
ORDER BY
sale_amount DESC

7
Inline Table-Valued Functions
tra ve dulieu ca mot bang co gia tri duoc lay
tu mot cau lenh select
Returns data of a table type whose values is
derived from a single SELECT statement.
Example
CREATE FUNCTION fn_getProducts()
RETURNS TABLE
AS
RETURN SELECT * FROM products

Executing an inline table-valued functions

SELECT * FROM fn_getProducts()

8
Inline Table-Valued Functions
co tham so
Example the function requires input parameters
CREATE FUNCTION fn_ProductInYear(@model_year INT)
RETURNS TABLE
AS
RETURN
SELECT product_name,model_year, list_price
FROM products
WHERE model_year = @model_year
Executing an inline table-valued functions
SELECT
product_name, list_price
FROM fn_ProductInYear(2017)

9
Multi-statement table-valued
function
The function can take one or more paramenters
and returns a table.
You must define the table structure that is being
returned. ban phai xac dinh duoc cau truc cua bang
duoc tra ve
After creating this type of user-defined function,
we can use it in the FROM clause of a T-SQL
command. sau khi tao loai ham do nguoi dung xac dinh ,
chung ta co the sd no trong menh de from

10
Multi-statement table-valued
function
Example
CREATE FUNCTION fn_rowOfTables() RETURNS
@table table (TableName varchar(50), rows_count int)
AS
BEGIN
DECLARE @num int
SELECT @num = count(product_id) FROM products
INSERT INTO @table values('My product', @num)
IF @@ROWCOUNT =0
BEGIN
INSERT INTO @table VALUES('', 'No row is added')
END
RETURN
END
Executing a table-valued functions
SELECT * FROM fn_rowOfTables()

11
Alter/drop a function
You can modify an existing scalar function by ALTER
FUNCTION ban co the sua doi ham gia tri vo huong bang alter

ALTER FUNCTION [schema_name.]function_name(parameter_list)


RETURNS data_type
AS
BEGIN statements
RETURN value
END

You can delete an existing scalar function by DROP


FUNCTION
DROP FUNCTION [schema_name.]function_name

12
Functions
You can you can find the functions under
Programmability -> Functions of the database that
you’re working

13
System Defined function
System Defined function or Built-in function. Some common
functions: cast ( gia_tri as kieu_dl_moi )
chuyen gia tri sang kieu dl khac
 CAST – cast a value of one type to another. convert ( kieudlmoi ,
giatri , style )
nhu cast , nhung ho tro dinh dang kieu ngay , gio
 CONVERT – convert a value of one type to another.
 CHOOSE – return doi so
one of the two values based on the result of
the first argument. Choose (index , value1 , value2 , value3 ,.. )
thay the null bang gia tri da chi dinh
 ISNULL – replace NULL with a specified value.
 ISNUMERIC – check if an expression is a valid numeric type.
kiem tra xem mot bieu thuc co phai
 IIF – add if-else logic to a query. la kieu so hop le k
them logic if- else vao truy van

14
System Defined function
 TRY_CAST – cast a value of one type to another and return
NULL if the cast fails.
 TRY_CONVERT – convert a value of one type to another and
return the value to be translated into the specified type. It
returns NULL if the cast fails.
 TRY_PARSE – convert a string to a date/time or a number and
return NULL if the conversion fails.
 Convert datetime to string – show you how to convert a
datetime value to a string in a specified format.
 Convert string to datetime – describe how to convert a string
to a datetime value.
 Convert datetime to date – convert a datetime to a date.

15
Example
Convert datetime to string
Syntax
CONVERT(VARCHAR, datetime [,style])

Example: display the current date with dd/mm/yyyy format

SELECT CONVERT(VARCHAR, GETDATE(),103) AS 'Now'

16
Example
Using IFF function
Example: returns the corresponding order status based on the
status number in order table

SELECT
IIF(order_status = 1,'Pending',
IIF(order_status=2, 'Processing',
IIF(order_status=3, 'Rejected',
IIF(order_status=4,'Completed','N/A')
)
)
) order_status,
COUNT(order_id) order_count
FROM orders
GROUP BY
order_status;
17
Store Procedures thu tuc luu tru cua sql la mot loat cac cau lenh duoc
nhom
thanh mot don vi logic va duoc luu trong csdl

SQL Server stored procedure (SP) is a batch of


statements grouped as a logical unit and stored in the
database.
plan cache
Procedure is stored in cache area of memory when
the stored procedure is created so that it can be used
repeatedly. SQL Server does not have to recompile it
every time the stored procedure is run.
It can accept input parameters, return output values
as parameters, or return success or failure status
messages

18
Store Procedures vs SQL
SQL Statement Stored Procedure
Creating
- Check syntax
- Compile

First Time First Time


- Check syntax - Execute
- Compile - Return data
- Execute
- Return data

Second Time Second Time


- Check syntax - Execute
- Compile - Return data
- Execute
- Return data

19
Store Procedures
Benefits of SP
Reusable Tai sudung
It can be easily modified
Performance hieu suat

Reduced network traffic giam luu luuong mang

Security

20
Store Procedures
There are two types of stored procedures available
co san
in SQL Server:
User defined stored procedures
System stored procedures
Nguoi dung xac dinh va he thong

21
Store Procedures
Naming conventions for stored procedures
It is a good idea to come up with a standard prefix to use
for your stored procedures: usp_ , sp , usp… tien to chuan
Do not use sp_ as a prefix
• This is a standard naming convention that is used in the
master database
Give the action that the stored procedure takes and then
give it a name representing the object it will affect.
• uspInsertProduct dai dien
• uspGetProductById
• spValidateProduct
Consider using the schema that you will use when saving
the objects. The schema is useful if you want to keep all
utility like objects together
22
Store Procedures
Example: create a store procedure that returns a
list of products from the products table
CREATE PROCEDURE uspProductList
AS co the viet ngan thanh create proc

BEGIN
SELECT product_name, list_price
FROM products
ORDER BY product_name
END2

Executing the sp EXECUTE sp_name or EXEC sp_name

EXEC uspProductList

23
Store Procedures
Modifying an existing stored procedure
By using the ALTER PROCEDURE statement.
ALTER PROCEDURE uspProductList
AS
BEGIN
SELECT *
FROM products
ORDER BY product_name
END

Deleting a stored procedure


using the DROP PROCEDURE or DROP PROC statement:
DROP PROCEDURE sp_name DROP PROCEDURE sp_name
24
Store Procedures
From the UI for SP

25
Store Procedures
 Parameters in SPs are used to pass input values
and return output values. There are two types of
parameters:
Input parameters – By default, pass values to a stored
procedure.
Output parameters - Return values from a stored
procedure, use OUTPUT keyword

26
Store Procedures
 Example: SELECT query SP with parameters
CREATE PROCEDURE uspGetProductByName
@productName nvarchar(30)
AS
BEGIN
SET NOCOUNT ON
SELECT * FROM products
WHERE product_name LIKE '%'+@productName+'%'
END

Executing the SP
EXEC uspGetProductByName @productName = 'Electra'

27
Store Procedures
 Example: INSERT query SP with parameters
CREATE PROC uspInsertProduct
@category_id INT, @brand_id INT,
@pro_name VARCHAR(50), @year INT,
@pro_price DECIMAL(10,2) = 0
AS
BEGIN
DECLARE @checkExist int
SELECT @checkExist = category_id FROM products
WHERE category_id = @category_id
IF (@checkExist IS NULL)
BEGIN
PRINT 'This product category does not exist in system!'
RETURN
END
INSERT INTO products
VALUES (@pro_name,@brand_id,@category_id, @year, @pro_price)
END

28
Store Procedures
co tham so

Executing the SP
EXEC uspInsertProduct @category_id =6, @brand_id = 1,
@pro_name = 'Heller 2020',@year = 2020,
@pro_price = 1000

Default Parameter Values


In most cases it is always a good practice to pass in all
parameter values, but sometimes it is not possible.
So you can assign value to parameter with NULL or an
valid value
So with default parameter, you don’t need to pass in a
parameter value when you execute the SP
29
Store Procedures
Exercises: create and execute store procedures:
To update/delete a products
To find products with product price whose list prices are
in range of min and max list prices and the product
name also contain a piece of text that you pass in.
To insert an order and order items tables

30
Store Procedures
sudung tham so output

SP with OUTPUT parameter


CREATE PROCEDURE uspGetProductCount
@productName nvarchar(30), @productCount int OUTPUT
AS
SELECT @productCount = count(*)
FROM products
WHERE product_name LIKE @productName +'%'

31
Store Procedures
Executing the SP with OUTPUT parameter
First we are going to declare a variable, execute the
stored procedure
Then select the returned valued.

DECLARE @product_Count INT


EXEC uspGetProductCount @productName= 'Su',
@productCount = @product_Count OUTPUT
SELECT @product_Count AS 'Number of Product'

32
Store Procedures
You can use TRY-CATCH statement with error
handling in SQL Server xu ly ngoai le
Example
CREATE PROCEDURE uspTryCatchTest
AS
BEGIN TRY xu ly loi trong khoi try
SELECT 1/0 loi chi cho 0
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber tra ve so loi
tra ve muc do nghiem trong cua loi
,ERROR_SEVERITY() AS ErrorSeverity tra ve trang thai loi
,ERROR_STATE() AS ErrorState tra ve ten cua thu tuc luu tru hoac
,ERROR_PROCEDURE() AS ErrorProcedure ham gay ra loi
tra ve so dong noi loi xay ra
,ERROR_LINE() AS ErrorLine tra ve thong bao loi
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH
33
Trigger
A trigger is a special type of stored procedure that
is executed automatically as part of a data
modification. thuc thi tu dong nhu mot phan cua viec sua doi dl lien ket
A trigger is created on a table and associated with
one or more actions linked with a data modification
(INSERT, UPDATE, or DELETE).
When one of the actions for which the trigger is
defined occurs, the trigger fires automatically

34
Trigger
Following are some examples of trigger uses:
 Maintenance of duplicate and derived data
 Complex business rules
 Cascading referential integrity
 Complex defaults
 Implement complex security authorizations
Disadvantages of trigger
 It increases the overhead of the database server.
 Providing an extended validation, not replacing all the
validation which can be done only by the application layer.
 SQL triggers are executed from the client applications, which
will be challenging to figure out what is happening in the
database layer.
35
Trigger
There are two types of triggers:
DDL (Data Definition Language) triggers: triggers fires
upon events that change the structure (like creating,
modifying or dropping a table)
DML (Data Modification Language) triggers. This is the
most used class of triggers. The firing event is a data
modification statement; it could be an insert, update or
delete statement either on a table or a view. DML triggers
have different types:
• FOR or AFTER [INSERT, UPDATE, DELETE]: These types of triggers are
executed after the firing statement ends (either an insert, update or
delete).
• INSTEAD OF [INSERT, UPDATE, DELETE]: the INSTEAD OF triggers
executes instead of the firing statement.

36
Deleted and Inserted tables
When you create a trigger, you have access to two
temporary tables (the deleted and inserted tables).
They are referred to as tables, but they are different
from true database tables. They are stored in
memory—not on disk.

37
Deleted and Inserted tables
When the insert, update or delete statement is
executed. All data will be copied into these tables
with the same structure.

Update

old

The values in the inserted and deleted tables are


accessible only within the trigger. Once the trigger is
completed, these tables are no longer accessible.
38
Deleted and Inserted tables
The following table shows the content of the
INSERTED and DELETED tables before and after each
event:

39
Trigger
Syntax CREATE TRIGGER [schema_name.]trigger_name
ON table_name
{FOR | AFTER | INSTEAD OF} {[INSERT] [,] [UPDATE] [,]
[DELETE]}
AS
{sql_statements}

[before | after]: This specifies when the trigger will be


executed.
{insert | update | delete}: This specifies the DML
operation.
on [table_name]: This specifies the name of the table
associated with the trigger.
[sql_statements]: is one or more Transact-SQL used to
carry out actions once an event occurs.
40
DML Trigger Example
Product table
CREATE TABLE Product
(
product_id INT PRIMARY KEY IDENTITY,
product_name varchar(30) NOT NULL,
unit_price DECIMAL(10,2) NOT NULL,
quantity INT NOT NULL
)

41
DML Trigger Example
Product_history table
CREATE TABLE Product_history
(
Id INT PRIMARY KEY IDENTITY,
Product_history varchar(200) NOT NULL,
update_at DATETIME NOT NULL,
operation VARCHAR(30) NOT NULL
CHECK (operation IN ('INSERT','DELETE'))
)

42
DML Trigger Example
Create a simple trigger that prevent DML on
product table
CREATE TRIGGER triggerTestDML
ON product
FOR INSERT, UPDATE, DELETE
AS
PRINT 'You can not insert, update, delete this product table'
ROLLBACK
GO

When we insert, update or delete in a table in a


database then the following message appears

43
DML Trigger Example
INSERT trigger
CREATE TRIGGER UTRG_Product_Insert
ON Product
FOR INSERT
AS
BEGIN
DECLARE @product_id int, @product_name varchar(40),
@unit_price DECIMAL(10,2)
SELECT @product_id = product_id, @product_name =
product_name, @unit_price = unit_price FROM inserted
INSERT INTO Product_history VALUES('New product with Id ' +
cast (@product_id As varchar(40)),GETDATE(), 'INSERT')
END

INSERT INTO Product


VALUES('P555',1000,20)
44
DML Trigger Example
INSERT INTO Product VALUES('P555',1000,20)
After insert a row into Product table, the trigger will be
occur.

SELECT * FROM dbo.Product


SELECT * FROM dbo.Product_history

45
DML Trigger Example
Exercises
Create trigger for Update/Delete?
Or create 1 trigger for INSERT/UPDATE/DELETE event
occur against the product table in one trigger?

46
INSTEAD OF trigger
The INSTEAD OF triggers are the DML triggers that
are fired instead of the triggering event such as the
INSERT, UPDATE or DELETE events.
So, when you fire any DML statements such as
Insert, Update, and Delete, then on behalf of the
DML statement, the instead of trigger is going to
execute.
In real-time applications, Instead Of Triggers are
used to correctly update a complex view.

47
INSTEAD OF trigger
Example: Department and Employee tables

48
INSTEAD OF trigger
Let create a view
CREATE VIEW vwEmployeeDetails
AS
SELECT emp.ID, emp.Name, Gender, Salary, dept.Name AS Department
FROM Employee emp
INNER JOIN Department dept
ON emp.DeptID = dept.ID

Get data from the view

49
INSTEAD OF trigger
Insert a record into the view vwEmployeeDetails
by executing the following query.
INSERT INTO vwEmployeeDetails VALUES(7, 'Saroj', 'Male',
50000, 'IT')

Will recieve an error message: ‘View or function


vwEmployeeDetails is not updatable because the modification
affects multiple base tables.’
=>Use INSTEAD OF trigger

50
INSTEAD OF trigger
CREATE TRIGGER tr_vwEmployeeDetails_InsteadOfInsert
ON vwEmployeeDetails
INSTEAD OF INSERT
AS
BEGIN
DECLARE @DepartmenttId int
-- First Check if there is a valid DepartmentId in the Department Table for
the given Department Name
SELECT @DepartmenttId = dept.ID After executing the trigger,
FROM Department dept
INNER JOIN INSERTED inst
the record is inserted into the
on inst.Department = dept.Name view and the Employee table.
--If the DepartmentId is null then throw an error
IF(@DepartmenttId is null)
BEGIN
RAISERROR('Invalid Department Name. Statement terminated',16, 1)
RETURN
END
-- Finally insert the data into the Employee table
INSERT INTO Employee(ID, Name, Gender, Salary, DeptID)
SELECT ID, Name, Gender, Salary, @DepartmenttId
FROM INSERTED
End
51
INSTEAD OF trigger
Exercises
Create INSTEAD OF trigger for Update/Delete operations

52

You might also like