SQL Triggers & Functions

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 16

CMSC325

SQL Functions & Triggers

DR. RICHA SHARMA


L O C K H AV E N U N I V E R S I T Y

1
Procedures for updating records
 An example:

create procedure updateDiscount


as
begin
update product set p_discount = 1+p_discount
where p_qoh >= p_min*2
end

exec updateDiscount;

 Exercise: create the same procedure with an input


parameter for modifying discount. The procedure should
check that the input value is >0.

2
Updating records with cursor
DECLARE @code INT, @areaCode INT, @state varchar(2);

DECLARE vendor_cursor CURSOR FOR


SELECT v_code, v_areacode, v_state FROM Vendor;

OPEN vendor_cursor
FETCH NEXT FROM vendor_cursor INTO @code, @areaCode, @state

while @@FETCH_STATUS = 0
BEGIN
IF @state = 'FL’
update vendor set v_areacode = 914 where v_state = @state
ELSE
print('No change required for ' + @state)
FETCH NEXT FROM vendor_cursor INTO @code, @areaCode, @state
END
CLOSE vendor_cursor;
DEALLOCATE vendor_cursor;
3
Functions
 Functions are similar to Stored Procedures except they return
a value! An example - function to compute area of circle:
create function findArea(@p_radius INT) returns
decimal(10,2)
AS
begin
DECLARE @v_area decimal(10,2), @v_pi decimal(10,2);
SET @v_pi = 3.14;

SET @v_area = @v_pi * @p_radius * @p_radius;


return @v_area;
end;

 We execute this function as: select dbo.findArea(10)


 This is an example of scalar function.
4
Functions
 Another example of a scalar function to find average balance
from customer table:

create function showAverageBalance() returns


decimal(10,2)
AS
begin
DECLARE @average decimal(10,2);

select @average = avg(cus_balance) from CUSTOMER;


return @average;
end;

 We execute this function as: select dbo.showAverageBalance()

5
Types of Functions
 Scalar Functions – these functions return a single data value
of the type defined in the RETURN clause.
 Table-valued Functions – these functions return a table data
type.

 Aggregate Functions – these functions perform a calculation


on a set of values and return a single value. These are
allowed in the select list or the HAVING clause in combination
with the GROUP BY clause to calculate the aggregation on
categories of rows.

 System Functions – these are built-in system functions that can


be used to perform various operations. Eg: getdate(),
current_timestamp.
6
Functions
 An example of table-valued function:

create function showVendorDetails(@state varchar(2))


returns table
AS
RETURN
(
SELECT v_code, v_areacode, v_state FROM Vendor where
v_state = @state
);

 We execute this function as:

select * from dbo.showVendorDetails('GA')

7
Exercises
 Create a function that returns the count of orders placed by a
customer from the invoice table.

8
Triggers
 Automating business process/rules and automatically
maintaining data integrity and consistency are critical when
business functionality is implemented through DB-intensive
applications.
 Triggers are a solution to such business requirement!

 A Trigger is a procedural SQL code that is automatically


invoked by the database upon the occurrence of a given data
manipulation event.
 A trigger is invoked before or after a row is inserted, updated,
or deleted.
 A trigger is executed as part of the transaction that triggered it.
 A trigger is associated with a database table.
 Each database table may have one or more triggers.

9
Triggers - syntax
 Syntax of the trigger is as follows:

CREATE OR REPLACE TRIGGER trigger_name

[BEFORE / AFTER] [DELETE / INSERT / UPDATE OF


column_name] ON table_name

[FOR EACH ROW]


[DECLARE block]
[WHEN trigger_condition]
BEGIN
trigger_body / SQL statements;
END;

10
Triggers (ctd.)
 Parts of trigger syntax include:

 Triggering timing as BEFORE or AFTER indicating when


the trigger should get executed.

 Triggering event – the statement that causes the trigger to


execute (INSERT, UPDATE, or DELETE). A triggering
event may two levels of triggering action – statement-level
or row-level trigger.

 Triggering action – the procedural SQL code is enclosed


between the BEGIN and END keywords for the action part
of the trigger.

11
Triggers (ctd.)
 Levels of trigger include:
 Statement-level – this is the default case of triggering, and
is assumed if ‘FOR EACH ROW’ keywords are omitted.
This type of trigger is executed once, before or after the
triggering statement is completed

 Row-level – this trigger requires use of the FOR EACH


ROW keywords. This type of trigger is executed once for
each row affected by the triggering statement. For
example: if we update 10 rows, then the trigger will
executes 10 times!
 Trigger can be executed in response to DDL or DML
commands!

12
Triggers – Example 1
 An example of statement-level trigger:
CREATE TRIGGER Trg_After_ProdDiscount ON Product
For UPDATE
AS
BEGIN
Update product set P_DISCOUNT = 0.10 where p_price >
100;
END;

 To execute the trigger, we need to update one record on


Product table say using statement:

update product set p_price = 120.0 where p_code = '1558-Qw1’

Source: https://www.mssqltips.com/sqlservertip/5909/sql-server-trigger-example/

13
Triggers – Example 2
 An example of row - level trigger:

CREATE TRIGGER before_employee_update


BEFORE UPDATE ON employees
FOR EACH ROW

INSERT INTO employees_audit


SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedat = NOW();

Source: https://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx
https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html

14
Triggers – Exercise
 Create a trigger on EMP table whenever there is a delete
operation performed. The triggering action includes deleting
the same employee from the EMPLOYEE table (try with any
one EMP_NUM value).
Create or alter trigger After_Delete_EMP on EMP
after delete
as begin
declare @empNum int
select @empNum = d.emp_num from deleted d;
delete from EMPLOYEE where EMP_NUM = @empNum;
End

15
16

You might also like