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

CS2202_MySQL_Trigger

The document explains triggers and cursors in MySQL, detailing how triggers are automatically invoked during data changes and their various types. It also covers the use of cursors for row-by-row data manipulation, including their declaration, opening, fetching, and closing processes. Additionally, the document discusses the advantages and disadvantages of triggers, as well as providing syntax examples for creating triggers and cursors.

Uploaded by

Sparsh Rastogi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CS2202_MySQL_Trigger

The document explains triggers and cursors in MySQL, detailing how triggers are automatically invoked during data changes and their various types. It also covers the use of cursors for row-by-row data manipulation, including their declaration, opening, fetching, and closing processes. Additionally, the document discusses the advantages and disadvantages of triggers, as well as providing syntax examples for creating triggers and cursors.

Uploaded by

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

Trigger and Cursor in MySQL

CS2202

1
Trigger
• In MySQL, a trigger is a set of SQL statements that is invoked automatically when a
change is made to the data on the associated table.
• A trigger can be defined to be invoked either before or after the data is changed by
INSERT, UPDATE or DELETE statement.

2
Trigger Types
• BEFORE INSERT - activated before data is inserted into the table.
• AFTER INSERT - activated after data is inserted into the table.
• BEFORE UPDATE - activated before data in the table is updated.
• AFTER UPDATE - activated after data in the table is updated.
• BEFORE DELETE - activated before data is removed from the table.
• AFTER DELETE - activated after data is removed from the table.

3
• When we use a statement that does not use INSERT, DELETE or UPDATE statement
to change data in a table, the triggers associated with the table are not invoked.
– For example, the TRUNCATE statement removes all data of a table but does
not invoke the trigger associated with that table.
– Truncate operations drop and re-create the table
– Syntax: mysql:>truncate table table_name;
– If there is any FOREIGN KEY constraints from other tables which reference the
table that you truncate, the TRUNCATE TABLE statement will fail.

4
• There are some statements that use the INSERT statement behind the scenes such
as REPLACE statement or LOAD DATA statement.
• If you use these statements, the corresponding triggers associated with the table
are invoked.
• You must use a unique name for each trigger associated with a table.

5
Replace statement
• Replace statement works as below-
• Step 1. Insert a new row into the table, if a duplicate key error occurs.
• Step 2. If the insertion fails due to a duplicate-key error occurs:
– Delete the conflicting row that causes the duplicate key error from the table.
– Insert the new row into the table again.

6
Replace to insert
• Using MySQL REPLACE to insert a new row
• Syntax
– mysql:> REPLACE [INTO] table_name(column_list)
VALUES(value_list);
Let’s create a table Let’s insert some records
CREATE TABLE cities ( REPLACE INTO cities(name,population)
id INT AUTO_INCREMENT PRIMARY KEY, VALUES('New York',8008278),
name VARCHAR(50), ('Los Angeles',3694825),
population INT NOT NULL ('San Diego',1223405);
);

7
Replace
Use the REPLACE statement to update the population of the Los
Angeles city to 3696820.

id name population REPLACE INTO cities(id,population)


1 New York 8008278 VALUES(2,3696820);
2 Los Angeles 3694825
3 San Diego 1223405

id name population
1 New York 8008278
2 null 3696820
3 San Diego 1223405

8
Replace to update
• Using MySQL REPLACE statement to update a row
– Syntax
– mysql:> REPLACE INTO table
SET column1 = value1,
column2 = value2;

No where clause

9
Replace to update
REPLACE INTO cities
SET id = 4,
name = 'Phoenix',
population = 1768980;

Can be used to update the population of the Phoenix city to 1768980

10
MySQL Trigger Synatx
Syntax :
Trigger name convention: after the CREATE
CREATE TRIGGER trigger_name
TRIGGER statement, the trigger name should
trigger_time trigger_event
follow the naming convention
ON table_name
[trigger time]_[table name]_[trigger event], for
FOR EACH ROW
example before_employees_update.
BEGIN
.........
END;

Reference: www.mysqltutorial.org
11
Activation time and trigger event
• One must specify the activation time when a trigger is defined.
– You use the BEFORE keyword if you want to process action prior to the change
is made on the table and AFTER if you need to process action after the change
is made.
• The trigger event can be INSERT, UPDATE or DELETE.
– This event causes the trigger to be invoked. A trigger only can be invoked by
one event. To define a trigger that is invoked by multiple events, you have to
define multiple triggers, one for each event.

12
Trigger
• A trigger must be associated with a specific table. Without a table trigger would
not exist therefore you have to specify the table name after the ON keyword.
• You place the SQL statements between BEGIN and END block. This is where you
define the logic for the trigger.
• To view all triggers in the current database, you use SHOW TRIGGERS statement as
follows:
– mysql:>SHOW TRIGGERS;

13
Trigger example
Let’s create a table Let’s create another table
DROP TABLE IF EXISTS WorkCenters; DROP TABLE IF EXISTS WorkCenterStats;

CREATE TABLE WorkCenters ( CREATE TABLE WorkCenterStats(


id INT AUTO_INCREMENT PRIMARY KEY, totalCapacity INT NOT NULL
name VARCHAR(100) NOT NULL, );
capacity INT NOT NULL
);
WorkCenters WorkCenterStats
id name capacity totalCapacity
1 Sector V 34
2 Sector IX 25
14
Creating before insert trigger
DELIMITER $$
CREATE TRIGGER before_workcenters_insert
BEFORE INSERT
WorkCenters
ON WorkCenters FOR EACH ROW id name capacity
BEGIN
DECLARE rowcount INT; 1 Sector V 34
SELECT COUNT(*)
INTO rowcount 2 Sector IX 25
FROM WorkCenterStats;
IF rowcount > 0 THEN
UPDATE WorkCenterStats
SET totalCapacity = totalCapacity + new.capacity;
ELSE WorkCenterStats
INSERT INTO WorkCenterStats(totalCapacity)
VALUES(new.capacity); totalCapacity
END IF;
END $$
59
34
DELIMITER ;

15
Another example
Let’s create members table create another table
DROP TABLE IF EXISTS members; called reminders that stores reminder
messages to members
CREATE TABLE members ( DROP TABLE IF EXISTS reminders;
id INT AUTO_INCREMENT,
name VARCHAR(100) NOT NULL, CREATE TABLE reminders (
email VARCHAR(255), id INT AUTO_INCREMENT,
birthDate DATE, memberId INT,
PRIMARY KEY (id) message VARCHAR(255) NOT NULL,
); PRIMARY KEY (id , memberId)
);
members reminders
id name email birthDate id memberId message

16
After insert trigger
members
DELIMITER $$ id name email birthDate

CREATE TRIGGER after_members_insert


AFTER INSERT reminders
ON members FOR EACH ROW id memberId message
BEGIN
IF NEW.birthDate IS NULL THEN
INSERT INTO reminders(memberId, message)
VALUES(NEW.id, CONCAT('Hi ', NEW.name, ', please update your date of birth.'));
END IF;
END$$
New: To access the new value
DELIMITER ; provided in the insert statement
17
Signal statement
• The SIGNAL statement in MySQL is used to raise a custom error within a trigger,
stored procedure, or function. It allows you to throw a specific error when certain
conditions are met.
• SIGNAL SQLSTATE 'error_code'
• SET MESSAGE_TEXT = 'error_message';
• SQLSTATE '45000' → A generic error code used for user-defined exceptions.
• MESSAGE_TEXT → A custom error message displayed when the error occurs.

18
Example
DROP TABLE IF EXISTS sales;

CREATE TABLE sales (


id INT AUTO_INCREMENT,
product VARCHAR(100) NOT NULL,
quantity INT NOT NULL DEFAULT 0,
fiscalYear SMALLINT NOT NULL,
fiscalMonth TINYINT NOT NULL,
UNIQUE(product, fiscalYear, fiscalMonth),
PRIMARY KEY(id)
);

id product quantity fiscalYear fiscalMonth


19
Before update trigger
DELIMITER $$
CREATE TRIGGER before_sales_update
BEFORE UPDATE Old and new values
ON sales FOR EACH ROW can be accessed using
BEGIN
OLD and NEW
DECLARE errorMessage VARCHAR(255);
SET errorMessage = CONCAT('The new quantity ',
modifiers
NEW.quantity,
' cannot be 3 times greater than the current quantity ',
OLD.quantity);

IF new.quantity > old.quantity * 3 THEN


SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = errorMessage;
END IF;
END $$
DELIMITER ; 20
Types of trigger
• Row level
– A row-level trigger is activated for each row that is inserted, updated, or
deleted. For example, if a table has 100 rows inserted, updated, or deleted,
the trigger is automatically invoked 100 times for the 100 rows affected.
• Statement level
– A statement-level trigger is executed once for each transaction regardless of
how many rows are inserted, updated, or deleted.

MySQL supports row level trigger only

21
Advantages of Trigger
• Triggers provide another way to check the integrity of data.
• Triggers handle errors from the database layer.
• Triggers give an alternative way to run scheduled tasks. By using triggers, you don’t
have to wait for the scheduled events to run because the triggers are invoked
automatically before or after a change is made to the data in a table.
• Triggers can be useful for auditing the data changes in tables.

22
Disadvantages
• Triggers can only provide extended validations, not all validations.
• For simple validations, you can use the NOT NULL, UNIQUE, CHECK and FOREIGN
KEY constraints.
• Triggers can be difficult to troubleshoot because they execute automatically in the
database, which may not be visible to the client applications.
• Triggers may increase the overhead of the MySQL Server.

23
Cursor
• A cursor is a database object that enables the end-user to retrieve, process, and
scroll through rows of the result set one at a time.
• While standard SQL queries usually operate on data sets, cursors perform
operations on one row at a time
• This can be very useful for complicated data manipulations and procedural logic.
• It enables the user to fetch and process each row individually, allowing for detailed
manipulation and analysis of data.
• By using cursors, developers can precisely control the flow of data processing, such
as updating or analyzing specific rows based on custom criteria.

24
Declare a cursor
• A cursor is declared within a stored procedure or function using
a CURSOR statement. This binds the cursor to a specified SQL query.

DECLARE cursor_name CURSOR FOR select_statement;

• cursor_name: This is the name given to cursor.


• select_statement: SQL statement to define a result set for the cursor.

25
Cursor: Open, Fetch and Close
• You need to open the cursor before you fetch rows from it. You do this with the
OPEN statement.
OPEN cursor_name;
• The FETCH statement retrieves the data from the cursor and moves the cursor to
the next line in the result set; it loads the data into variables
FETCH cursor_name INTO variable1, variable2, ...;
• variable1, variable2, … : Variables in which the fetched data has to be stored.
• Finally, you would close the cursor after you have processed all the data, so that
the resources that are allocated for it will be released.
CLOSE cursor_name;

26
sp sno pno qty dos
Use of Cursor … … … …
CREATE TABLE IF NOT EXISTS
• Create a Log Table: low_supply_log (
low_supply_log to store records
where qty < 600. log_id INT AUTO_INCREMENT
PRIMARY KEY,
• Create a Stored Procedure:
– Declare a cursor to iterate over the
sno VARCHAR(10),
sp table. pno VARCHAR(10),
– Process each record and check the qty SMALLINT,
quantity.
dos DATE,
– If qty is below 600, insert the
record into low_supply_log. log_time TIMESTAMP DEFAULT
CURRENT_TIMESTAMP
);
id sno pno qty dos log_time
… … … … … … 27
sp Log_supply_log
sno pno qty dos id sno pno qty dos log_time
… … … … … … … … … …
-- Start processing each row
DELIMITER //
read_loop: LOOP
CREATE PROCEDURE procSupplyData()
BEGIN -- Fetch the current row data
FETCH sp_cursor INTO v_sno, v_pno, v_qty, v_dos;
DECLARE done INT DEFAULT FALSE;
-- Exit if no more records
DECLARE v_sno VARCHAR(10);
IF done THEN
DECLARE v_pno VARCHAR(10);
LEAVE read_loop;
DECLARE v_qty SMALLINT;
END IF;
DECLARE v_dos DATE;
-- If quantity is below threshold, insert into log
-- Declare cursor
IF v_qty < 600 THEN
DECLARE sp_cursor CURSOR FOR
INSERT INTO low_supply_log (sno, pno, qty, dos)
SELECT sno, pno, qty, dos FROM sp;
VALUES (v_sno, v_pno, v_qty, v_dos);
-- Declare exit handler
END IF;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done =
TRUE; END LOOP;
-- Open the cursor -- Close the cursor
OPEN sp_cursor; CLOSE sp_cursor;
END // 28
DELIMITER ;

You might also like