SlideShare a Scribd company logo
1 of 15
Hệ quản trị cơ sở dữ liệu

Trigger
Dư Phương Hạnh
Bộ môn Hệ thống thông tin
Khoa CNTT, trường Đại học Công nghệ
Đại học Quốc gia Hanoi
hanhdp@vnu.edu.vn
Outline





Introduction
Create trigger
Managing trigger
Exercises

Tài liệu tham khảo:
http://www.mysqltutorial.org/mysql-triggers.aspx

2

Hệ quản trị CSDL @ BM HTTT
Introduction
 Trigger is a set of SQL statements which is stored to
be activated or fired when an event associating with
a database table occurs. The event can be any
event including INSERT, UPDATE and DELETE.
 Sometimes a trigger is referred as a special kind of
stored procedure in term of procedural code inside
its body. The difference between a trigger and a
stored procedure is that a trigger is activated or
called when an event happens in a database table,
a stored procedure must be called explicitly.

3

Hệ quản trị CSDL @ BM HTTT
Advantages
 Trigger provides an alternative way to check
integrity.
 Trigger can catch the errors in business logic in the
database level.
 Trigger provides an alternative way to run
scheduled tasks. With SQL trigger, you don’t have
to wait to run the scheduled tasks. You can handle
those tasks before or after changes being made to
database tables.
 SQL trigger is very useful when you use it to audit
the changes of data in a database table.
4

Hệ quản trị CSDL @ BM HTTT
Disadvantages
 Trigger only can provide extended validation and
cannot replace all the validations. Some simple
validations can be done in the application level.
– For example, you can validate input check in
the client side by using javascript or in the server side by
server script using PHP or ASP.NET…

5

Hệ quản trị CSDL @ BM HTTT
Disadvantages
 Triggers executes invisibly from client-application
which connects to the database server so it is
difficult to figure out what happen underlying
database layer.
 SQL Triggers run every updates made to the table
therefore it adds workload to the database and
cause system runs slower.

6

Hệ quản trị CSDL @ BM HTTT
Create trigger
CREATE TRIGGER trig_name trig_time trig_event
ON table_name
FOR EACH ROW
BEGIN
...
END
Trig_time: BEFORE, AFTER
Trig_even: INSERT, UPDATE and DELETE
– A trigger only can fire with one event. To define trigger
which are fired by multiple events, you have to define
multiple triggers, one for each event.
7

Hệ quản trị CSDL @ BM HTTT
Create trigger
 MySQL gives you OLD and NEW keyword to help you write
trigger more efficient.
– The OLD keyword refers to the existing row before you update data
– The NEW keyword refers to the new row after you update data.

 When you create a trigger in MySQL, its definition stores in
the file with extension .TRG in a database folder with specific
name as follows:
/data_folder/database_name/table_name.trg

8

Hệ quản trị CSDL @ BM HTTT
Examples
 Consider that we want to keep the changes
of employee's data in another table whenever data
of an employee's record changed.
 In order to do so you create a new table
called employees_audit  to keep track the changes
as follows:

9

Hệ quản trị CSDL @ BM HTTT
Examples
CREATE TABLE employees_audit
(
id int(11) NOT NULL AUTO_INCREMENT,
employeeNumber int(11) NOT NULL,
lastname varchar(50) NOT NULL,
changedon datetime DEFAULT NULL,
action varchar(50) DEFAULT NULL,
PRIMARY KEY (id)
)
10

Hệ quản trị CSDL @ BM HTTT
Examples
DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedon = NOW();
END$$
DELIMITER ;
11

Hệ quản trị CSDL @ BM HTTT
Managing trigger
 Trigger is stored as plain text file in the database folder as
follows: /data_folder/database_name/table_name.trg, with
any plain text editor such as notepad you can view it.
 MySQL provides you another way to view the trigger by
executing SQL statement:
SELECT * FROM Information_Schema.Trigger
WHERE Trigger_schema = 'database_name' AND
Trigger_name = 'trigger_name';

12

Hệ quản trị CSDL @ BM HTTT
Managing trigger
 If you want to retrieve all triggers associated with a
database just executing the following SQL
statement:
SELECT * FROM Information_Schema.Trigger
WHERE Trigger_schema = 'database_name';

 To find all triggers associating with a database
table, just executing the following SQL statement:
SELECT * FROM Information_Schema.Trigger
WHERE Trigger_schema = 'database_name' AND
Event_object_table = 'table_name';
13

Hệ quản trị CSDL @ BM HTTT
Managing trigger
 In MySQL you are not only able to view the trigger
but also remove an existing trigger. To remove a
trigger you can use the SQL statement DROP
TRIGGER as follows:
DROP TRIGGER table_name.trigger_name
 To modify a trigger, you have to delete it first and
recreate it. MySQL doesn't provide you SQL
statement to alter an existing trigger like altering
other database objects such as tables or stored
procedures.
14

Hệ quản trị CSDL @ BM HTTT
Exercises
1. Viết một trigger thực hiện công việc sau: Với những đơn
hàng trị giá >1.000.000 thì chiết khấu 5%.
2. Viết trigger đảm bảo rằng: nếu số lượng hàng hoá khách
hàng đặt mua lớn hơn số lượng hàng còn trong kho thì đưa
ra thông báo ‘không đủ lượng hàng theo yêu cầu’, sau đó
huỷ bỏ dòng đặt hàng đối với mặt hàng này.

15

Hệ quản trị CSDL @ BM HTTT

More Related Content

What's hot

Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data RedactionAlex Zaballa
 
Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data RedactionIvica Arsov
 
Starburst by Umar danjuma maiwada presentation
Starburst by Umar danjuma maiwada presentationStarburst by Umar danjuma maiwada presentation
Starburst by Umar danjuma maiwada presentationumardanjumamaiwada
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Khaled Anaqwa
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)Khaled Anaqwa
 
Java database connecticity steps
Java database connecticity stepsJava database connecticity steps
Java database connecticity stepsSKMohamedKasim
 
Doctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWorkDoctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWorkIllia Antypenko
 
Tutorial windows service with java (procrun)
Tutorial windows service with java (procrun)Tutorial windows service with java (procrun)
Tutorial windows service with java (procrun)muhammad arif nasution
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database TutorialPerfect APK
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android ApplicationMark Lester Navarro
 

What's hot (16)

Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data Redaction
 
Oracle Data Redaction
Oracle Data RedactionOracle Data Redaction
Oracle Data Redaction
 
Les14
Les14Les14
Les14
 
Starburst by Umar danjuma maiwada presentation
Starburst by Umar danjuma maiwada presentationStarburst by Umar danjuma maiwada presentation
Starburst by Umar danjuma maiwada presentation
 
Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)Android Training (Storing & Shared Preferences)
Android Training (Storing & Shared Preferences)
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
Module05
Module05Module05
Module05
 
MS Sql Server: Creating Views
MS Sql Server: Creating ViewsMS Sql Server: Creating Views
MS Sql Server: Creating Views
 
Java database connecticity steps
Java database connecticity stepsJava database connecticity steps
Java database connecticity steps
 
iOS training (advanced)
iOS training (advanced)iOS training (advanced)
iOS training (advanced)
 
Doctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWorkDoctrine ORM Internals. UnitOfWork
Doctrine ORM Internals. UnitOfWork
 
Tutorial windows service with java (procrun)
Tutorial windows service with java (procrun)Tutorial windows service with java (procrun)
Tutorial windows service with java (procrun)
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database Tutorial
 
Lesson 4
Lesson 4Lesson 4
Lesson 4
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android Application
 
Columnrename9i
Columnrename9iColumnrename9i
Columnrename9i
 

Viewers also liked

Sql server ___________session_19(triggers)
Sql server  ___________session_19(triggers)Sql server  ___________session_19(triggers)
Sql server ___________session_19(triggers)Ehtisham Ali
 
An Introduction To PostgreSQL Triggers
An Introduction To PostgreSQL TriggersAn Introduction To PostgreSQL Triggers
An Introduction To PostgreSQL TriggersJim Mlodgenski
 
Part 15 triggerr
Part 15  triggerrPart 15  triggerr
Part 15 triggerrDenny Yahya
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersAlexey Furmanov
 

Viewers also liked (8)

Oracle PLSql 4
Oracle PLSql 4Oracle PLSql 4
Oracle PLSql 4
 
Sql server ___________session_19(triggers)
Sql server  ___________session_19(triggers)Sql server  ___________session_19(triggers)
Sql server ___________session_19(triggers)
 
An Introduction To PostgreSQL Triggers
An Introduction To PostgreSQL TriggersAn Introduction To PostgreSQL Triggers
An Introduction To PostgreSQL Triggers
 
Part 15 triggerr
Part 15  triggerrPart 15  triggerr
Part 15 triggerr
 
Database trigger
Database triggerDatabase trigger
Database trigger
 
07 trigger view
07 trigger view07 trigger view
07 trigger view
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML Triggers
 
Sql triggers
Sql triggersSql triggers
Sql triggers
 

Similar to 4 trigger

Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu   (obscure) tools of the trade for tuning oracle sq lsTony Jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu (obscure) tools of the trade for tuning oracle sq lsInSync Conference
 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq lsInSync Conference
 
Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Thuan Nguyen
 
PostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
PostgreSQL Performance Tables Partitioning vs. Aggregated Data TablesPostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
PostgreSQL Performance Tables Partitioning vs. Aggregated Data TablesSperasoft
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL IISankhya_Analytics
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersAbdul Rahman Sherzad
 
DBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowDBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowAlex Zaballa
 
OTech magazine article - Principle of Least Privilege
OTech magazine article - Principle of Least PrivilegeOTech magazine article - Principle of Least Privilege
OTech magazine article - Principle of Least PrivilegeBiju Thomas
 
Introducing ms sql_server_updated
Introducing ms sql_server_updatedIntroducing ms sql_server_updated
Introducing ms sql_server_updatedleetinhf
 
DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2Alex Zaballa
 
DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2Alex Zaballa
 
Native tables in NonStop SQL/MX
Native tables in NonStop SQL/MXNative tables in NonStop SQL/MX
Native tables in NonStop SQL/MXFrans Jongma
 
Native tables in NonStop SQL database
Native tables in NonStop SQL databaseNative tables in NonStop SQL database
Native tables in NonStop SQL databaseFrans Jongma
 

Similar to 4 trigger (20)

Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu   (obscure) tools of the trade for tuning oracle sq lsTony Jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
 
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Tony jambu   (obscure) tools of the trade for tuning oracle sq lsTony jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
 
T-SQL & Triggers
T-SQL & TriggersT-SQL & Triggers
T-SQL & Triggers
 
Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17Oracle - Program with PL/SQL - Lession 17
Oracle - Program with PL/SQL - Lession 17
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
PostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
PostgreSQL Performance Tables Partitioning vs. Aggregated Data TablesPostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
PostgreSQL Performance Tables Partitioning vs. Aggregated Data Tables
 
Introduction to triggers
Introduction to triggersIntroduction to triggers
Introduction to triggers
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
 
Triggers
TriggersTriggers
Triggers
 
Sq lite
Sq liteSq lite
Sq lite
 
DBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should KnowDBA Commands and Concepts That Every Developer Should Know
DBA Commands and Concepts That Every Developer Should Know
 
OTech magazine article - Principle of Least Privilege
OTech magazine article - Principle of Least PrivilegeOTech magazine article - Principle of Least Privilege
OTech magazine article - Principle of Least Privilege
 
Introducing ms sql_server_updated
Introducing ms sql_server_updatedIntroducing ms sql_server_updated
Introducing ms sql_server_updated
 
DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2
 
DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2DBA Commands and Concepts That Every Developer Should Know - Part 2
DBA Commands and Concepts That Every Developer Should Know - Part 2
 
Usertracing
UsertracingUsertracing
Usertracing
 
Native tables in NonStop SQL/MX
Native tables in NonStop SQL/MXNative tables in NonStop SQL/MX
Native tables in NonStop SQL/MX
 
Trigger in DBMS
Trigger in DBMSTrigger in DBMS
Trigger in DBMS
 
Native tables in NonStop SQL database
Native tables in NonStop SQL databaseNative tables in NonStop SQL database
Native tables in NonStop SQL database
 

More from Trần Thanh

More from Trần Thanh (20)

8.replication
8.replication8.replication
8.replication
 
7. backup & restore data
7. backup & restore data7. backup & restore data
7. backup & restore data
 
6.3 my sql queryoptimization_part2
6.3 my sql queryoptimization_part26.3 my sql queryoptimization_part2
6.3 my sql queryoptimization_part2
 
6.2 my sql queryoptimization_part1
6.2 my sql queryoptimization_part16.2 my sql queryoptimization_part1
6.2 my sql queryoptimization_part1
 
6.1 query optimization overview
6.1 query optimization overview6.1 query optimization overview
6.1 query optimization overview
 
5. indexing
5. indexing5. indexing
5. indexing
 
4.2 transaction 2
4.2 transaction 24.2 transaction 2
4.2 transaction 2
 
4.2 transaction
4.2 transaction4.2 transaction
4.2 transaction
 
2.3 quan ly truy cap
2.3 quan ly truy cap2.3 quan ly truy cap
2.3 quan ly truy cap
 
01 gioithieu
01 gioithieu01 gioithieu
01 gioithieu
 
2.2 cac chuong trinh my sql
2.2 cac chuong trinh my sql2.2 cac chuong trinh my sql
2.2 cac chuong trinh my sql
 
9. partitioning
9. partitioning9. partitioning
9. partitioning
 
Chuan
ChuanChuan
Chuan
 
C4 1 tuan 14
C4 1 tuan 14C4 1 tuan 14
C4 1 tuan 14
 
C3 2
C3 2C3 2
C3 2
 
C3 2 (tuan6,7)
C3 2 (tuan6,7)C3 2 (tuan6,7)
C3 2 (tuan6,7)
 
C3 1
C3 1C3 1
C3 1
 
C2 2
C2 2C2 2
C2 2
 
C2 1
C2 1C2 1
C2 1
 
C1
C1C1
C1
 

Recently uploaded

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 

4 trigger

  • 1. Hệ quản trị cơ sở dữ liệu Trigger Dư Phương Hạnh Bộ môn Hệ thống thông tin Khoa CNTT, trường Đại học Công nghệ Đại học Quốc gia Hanoi hanhdp@vnu.edu.vn
  • 2. Outline     Introduction Create trigger Managing trigger Exercises Tài liệu tham khảo: http://www.mysqltutorial.org/mysql-triggers.aspx 2 Hệ quản trị CSDL @ BM HTTT
  • 3. Introduction  Trigger is a set of SQL statements which is stored to be activated or fired when an event associating with a database table occurs. The event can be any event including INSERT, UPDATE and DELETE.  Sometimes a trigger is referred as a special kind of stored procedure in term of procedural code inside its body. The difference between a trigger and a stored procedure is that a trigger is activated or called when an event happens in a database table, a stored procedure must be called explicitly. 3 Hệ quản trị CSDL @ BM HTTT
  • 4. Advantages  Trigger provides an alternative way to check integrity.  Trigger can catch the errors in business logic in the database level.  Trigger provides an alternative way to run scheduled tasks. With SQL trigger, you don’t have to wait to run the scheduled tasks. You can handle those tasks before or after changes being made to database tables.  SQL trigger is very useful when you use it to audit the changes of data in a database table. 4 Hệ quản trị CSDL @ BM HTTT
  • 5. Disadvantages  Trigger only can provide extended validation and cannot replace all the validations. Some simple validations can be done in the application level. – For example, you can validate input check in the client side by using javascript or in the server side by server script using PHP or ASP.NET… 5 Hệ quản trị CSDL @ BM HTTT
  • 6. Disadvantages  Triggers executes invisibly from client-application which connects to the database server so it is difficult to figure out what happen underlying database layer.  SQL Triggers run every updates made to the table therefore it adds workload to the database and cause system runs slower. 6 Hệ quản trị CSDL @ BM HTTT
  • 7. Create trigger CREATE TRIGGER trig_name trig_time trig_event ON table_name FOR EACH ROW BEGIN ... END Trig_time: BEFORE, AFTER Trig_even: INSERT, UPDATE and DELETE – A trigger only can fire with one event. To define trigger which are fired by multiple events, you have to define multiple triggers, one for each event. 7 Hệ quản trị CSDL @ BM HTTT
  • 8. Create trigger  MySQL gives you OLD and NEW keyword to help you write trigger more efficient. – The OLD keyword refers to the existing row before you update data – The NEW keyword refers to the new row after you update data.  When you create a trigger in MySQL, its definition stores in the file with extension .TRG in a database folder with specific name as follows: /data_folder/database_name/table_name.trg 8 Hệ quản trị CSDL @ BM HTTT
  • 9. Examples  Consider that we want to keep the changes of employee's data in another table whenever data of an employee's record changed.  In order to do so you create a new table called employees_audit  to keep track the changes as follows: 9 Hệ quản trị CSDL @ BM HTTT
  • 10. Examples CREATE TABLE employees_audit ( id int(11) NOT NULL AUTO_INCREMENT, employeeNumber int(11) NOT NULL, lastname varchar(50) NOT NULL, changedon datetime DEFAULT NULL, action varchar(50) DEFAULT NULL, PRIMARY KEY (id) ) 10 Hệ quản trị CSDL @ BM HTTT
  • 11. Examples DELIMITER $$ CREATE TRIGGER before_employee_update BEFORE UPDATE ON employees FOR EACH ROW BEGIN INSERT INTO employees_audit SET action = 'update', employeeNumber = OLD.employeeNumber, lastname = OLD.lastname, changedon = NOW(); END$$ DELIMITER ; 11 Hệ quản trị CSDL @ BM HTTT
  • 12. Managing trigger  Trigger is stored as plain text file in the database folder as follows: /data_folder/database_name/table_name.trg, with any plain text editor such as notepad you can view it.  MySQL provides you another way to view the trigger by executing SQL statement: SELECT * FROM Information_Schema.Trigger WHERE Trigger_schema = 'database_name' AND Trigger_name = 'trigger_name'; 12 Hệ quản trị CSDL @ BM HTTT
  • 13. Managing trigger  If you want to retrieve all triggers associated with a database just executing the following SQL statement: SELECT * FROM Information_Schema.Trigger WHERE Trigger_schema = 'database_name';  To find all triggers associating with a database table, just executing the following SQL statement: SELECT * FROM Information_Schema.Trigger WHERE Trigger_schema = 'database_name' AND Event_object_table = 'table_name'; 13 Hệ quản trị CSDL @ BM HTTT
  • 14. Managing trigger  In MySQL you are not only able to view the trigger but also remove an existing trigger. To remove a trigger you can use the SQL statement DROP TRIGGER as follows: DROP TRIGGER table_name.trigger_name  To modify a trigger, you have to delete it first and recreate it. MySQL doesn't provide you SQL statement to alter an existing trigger like altering other database objects such as tables or stored procedures. 14 Hệ quản trị CSDL @ BM HTTT
  • 15. Exercises 1. Viết một trigger thực hiện công việc sau: Với những đơn hàng trị giá >1.000.000 thì chiết khấu 5%. 2. Viết trigger đảm bảo rằng: nếu số lượng hàng hoá khách hàng đặt mua lớn hơn số lượng hàng còn trong kho thì đưa ra thông báo ‘không đủ lượng hàng theo yêu cầu’, sau đó huỷ bỏ dòng đặt hàng đối với mặt hàng này. 15 Hệ quản trị CSDL @ BM HTTT