Chapter5 - Session2-Function, Store Procedure, Trigger
Chapter5 - Session2-Function, Store Procedure, Trigger
Chapter 5
T-SQL Programming
Session 2:
Function, Store procedure, Trigger
Outline
1 Function
2 Store procedures
3 Trigger
2
Functions
A function is a set of SQL statements that perform a
specific task.
The main purpose of function is code reusability.
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.
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.
Functions must return a value or result.
Functions only work with input parameters.
Try and catch statements are not used in functions
4
Functions
SQL Server supports two types of functions:
User-Defined function (also call UDF): 3 types
• 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.
System Defined function (Built-in function)
Syntax
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
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
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
8
Inline Table-Valued Functions
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.
After creating this type of user-defined function,
we can use it in the FROM clause of a T-SQL
command.
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
ALTER FUNCTION [schema_name.]function_name(parameter_list)
RETURNS data_type
AS
BEGIN statements
RETURN value
END
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 – cast a value of one type to another.
CONVERT – convert a value of one type to another.
CHOOSE – return one of the two values based on the result of
the first argument.
ISNULL – replace NULL with a specified value.
ISNUMERIC – check if an expression is a valid numeric type.
IIF – add if-else logic to a query.
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])
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
SQL Server stored procedure (SP) is a batch of
statements grouped as a logical unit and stored in the
database.
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
19
Store Procedures
Benefits of SP
Reusable
It can be easily modified
Performance
Reduced network traffic
Security
20
Store Procedures
There are two types of stored procedures available
in SQL Server:
User defined stored procedures
System stored procedures
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…
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
• 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
BEGIN
SELECT product_name, list_price
FROM products
ORDER BY product_name
END2
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
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
Executing the SP
EXEC uspInsertProduct @category_id =6, @brand_id = 1,
@pro_name = 'Heller 2020',@year = 2020,
@pro_price = 1000
30
Store Procedures
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.
32
Store Procedures
You can use TRY-CATCH statement with error
handling in SQL Server
Example
CREATE PROCEDURE uspTryCatchTest
AS
BEGIN TRY
SELECT 1/0
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,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.
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
39
Trigger
Syntax CREATE TRIGGER [schema_name.]trigger_name
ON table_name
{FOR | AFTER | INSTEAD OF} {[INSERT] [,] [UPDATE] [,]
[DELETE]}
AS
{sql_statements}
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
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
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
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')
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