SQL Triggers & Functions
SQL Triggers & Functions
1
Procedures for updating records
An example:
exec updateDiscount;
2
Updating records with cursor
DECLARE @code INT, @areaCode INT, @state varchar(2);
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;
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.
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!
9
Triggers - syntax
Syntax of the trigger is as follows:
10
Triggers (ctd.)
Parts of trigger syntax include:
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
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;
Source: https://www.mssqltips.com/sqlservertip/5909/sql-server-trigger-example/
13
Triggers – Example 2
An example of row - level trigger:
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