SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Downloaden Sie, um offline zu lesen
Assertions and Triggers
Rose-Hulman Institute of Technology
Curt Clifton
Assertions
 Like constraints:
 Recall: state IN {'IA', 'MN', 'WI', 'MI', 'IL'}
 But can reference all tables
 Defined by:
 CREATE ASSERTION <name>
CHECK ( <condition> );
Example: Assertion
 In Sells(rest, soda, price), no rest may charge
an average of more than $3.
 CREATE ASSERTION NoRipoffs CHECK (
NOT EXISTS (
SELECT rest FROM Sells
GROUP BY rest
HAVING AVG(price) > 3
));
Example: Assertion
 The minimum price charged for products
made by Coca-Cola Co. is $2
 Recall:
 Soda(name, manf)
 Sells(rest, soda, price)
Example: Assertion
 The minimum price charged for products made by
Coca-Cola Co. is $2
 CREATE ASSERTION NoCheapCoke
CHECK(
NOT EXISTS(
SELECT * FROM Sells, Soda
WHERE Sells.soda = Soda.name
AND Soda.manf = 'Coca-Cola Co.'
AND Sells.price < 2.00
))
Timing of Assertion Checks
 Logically, assertions always are true
 So when do we have to check them?
Timing of Assertion Checks
 Logically, assertions always are true
 So when do we have to check them?
 Logically, after any change
 Practically, the DBMS could calculate the set of
important changes
Triggers: Motivation
 All the power of assertions
 But easier to implement:
 Column- and row-based checks
 Programmer specifies when they are activated
 Most DBMS just include triggers, not assertions
What Is a Trigger?
 Associated with a Table
 Invoked Automatically
 Cannot Be Called Directly
 Is Part of a Transaction
 Along with the statement that calls the trigger
 Can ROLLBACK transactions (use with care)
Uses of Triggers
 Cascade Changes Through Related Tables in
a Database
 Enforce More Complex Data Integrity Than a
CHECK Constraint
 Define Custom Error Messages
 Automatically update redundant data
 Compare Before and After States of Data
Under Modification
Creating Triggers
 Requires Appropriate Permissions
 Cannot Contain Certain Statements:
 e.g., DROP DATABASE
Use Northwind
GO
CREATE TRIGGER Empl_Delete ON Employees
FOR DELETE
AS
IF (SELECT COUNT(*) FROM Deleted) > 1
BEGIN
RAISERROR(
'You cannot delete more than one employee at a time.', 16, 1)
ROLLBACK TRANSACTION
END
USE Northwind
GO
ALTER TRIGGER Empl_Delete ON Employees
FOR DELETE
AS
IF (SELECT COUNT(*) FROM Deleted) > 6
BEGIN
RAISERROR(
'You cannot delete more than six employees at a time.', 16, 1)
ROLLBACK TRANSACTION
END
Altering and Dropping Triggers
 Altering a Trigger
 DISABLE TRIGGER Empl_Delete ON Employees
 ENABLE TRIGGER Empl_Delete ON Employees
 DROP TRIGGER Empl_Delete
How Triggers Work
 How an INSERT Trigger Works
 How a DELETE Trigger Works
 How an UPDATE Trigger Works
 How an INSTEAD OF Trigger Works
 How Nested Triggers Work
 Recursive Triggers
How an INSERT Trigger Works
 Consider:
USE Northwind
CREATE TRIGGER OrdDet_Insert
ON [Order Details]
FOR INSERT
AS
UPDATE P SET
UnitsInStock = (P.UnitsInStock – I.Quantity)
FROM Products AS P INNER JOIN Inserted AS I
ON P.ProductID = I.ProductID
INSERT [Order Details] VALUES
(10523, 2, 19.00, 5, 0.2)
Order Details
Order Details
OrderID
10522
10523
10524
ProductID
10
41
7
UnitPrice
31.00
9.65
30.00
Quantity
7
9
24
Discount
0.2
0.15
0.0
5
19.00
2 0.2
10523
Insert statement logged
inserted
inserted
10523 2 19.00 5 0.2
Products
Products
ProductID UnitsInStock … …
1
2
3
4
15
10
65
20
2 5
How an INSERT Trigger Works
How a DELETE Trigger Works
 Consider:
USE Northwind
CREATE TRIGGER Category_Delete
ON Categories
FOR DELETE
AS
UPDATE P SET Discontinued = 1
FROM Products AS P INNER JOIN deleted
AS d
ON P.CategoryID = d.CategoryID
Deleted
Deleted
4 Dairy Products Cheeses 0x15…
DELETE statement logged
Categories
Categories
CategoryID
1
2
3
CategoryName
Beverages
Condiments
Confections
Description
Soft drinks, coffees…
Sweet and savory …
Desserts, candies, …
Picture
0x15…
0x15…
0x15…
0x15…
Cheeses
Dairy Products
4
DELETE Categories
WHERE
CategoryID = 4
Products
Products
ProductID Discontinued … CategoryID
1
2
3
4
0
0
0
0
1
4
2
3
2 1 4
How a DELETE Trigger Works
How an UPDATE Trigger Works
 Consider:
USE Northwind
GO
CREATE TRIGGER Employee_Update
ON Employees
FOR UPDATE
AS
IF UPDATE (EmployeeID)
BEGIN
RAISERROR ('Transaction cannot be processed.
***** Employee ID number cannot be modified.',
10, 1)
ROLLBACK TRANSACTION
END
UPDATE Employees
SET EmployeeID = 17
WHERE EmployeeID = 2
Employees
Employees
EmployeeID LastName FirstName Title HireDate
1
2
3
4
Davolio
Barr
Leverling
Peacock
Nancy
Andrew
Janet
Margaret
Sales Rep.
R
Sales Rep.
Sales Rep.
~~~
~~~
~~~
~~~
2 Fuller Andrew Vice Pres. ~~~
UPDATE Statement logged as INSERT and DELETE Statements
inserted
inserted
17 Fuller Andrew Vice Pres. ~~~
deleted
deleted
2 Fuller Andrew Vice Pres. ~~~
Transaction cannot be processed.
***** Member number cannot be modified
Employees
Employees
EmployeeID LastName FirstName Title HireDate
1
2
3
4
Davolio
Barr
Leverling
Peacock
Nancy
Andrew
Janet
Margaret
Sales Rep.
R
Sales Rep.
Sales Rep.
~~~
~~~
~~~
~~~
2 Fuller Andrew Vice Pres. ~~~
How an UPDATE Trigger Works
INSTEAD OF Triggers
 INSTEAD OF trigger lets us interpret view
modifications that wouldn’t be allowed
 Example view:
 CREATE VIEW Synergy(cust,soda,rest)
AS
SELECT Likes.customer, Sells.soda, Sells.rest
FROM Likes, Sells, Frequents
WHERE Likes.customer = Frequents.customer
AND Sells.soda = Likes.soda
AND Sells.rest = Frequents.rest
Interpreting a View Insertion
 INSERT INTO Synergy(cust, soda, rest)
VALUES ('Molly', 'Sunkist', 'Regal Beagle')
 What does that mean?
 Can use INSTEAD OF trigger to decide
The Trigger
 CREATE TRIGGER SynergyInsert ON Synergy
INSTEAD OF INSERT
AS
DECLARE @c nvarchar(30)
DECLARE @s nvarchar(30)
DECLARE @r nvarchar(30)
SELECT @c=cust, @s=soda, @r=rest
From Inserted
INSERT INTO Likes VALUES(@c, @s)
INSERT INTO Frequents VALUES(@c, @r)
INSERT INTO Sells VALUES(@r, @s, null)
INSTEAD OF Triggers
 Can use them on views to define action
 Can also use them on regular tables
 Optionally perform or ignore actions
How Nested Triggers Work
UnitsInStock + UnitsOnOrder
is < ReorderLevel for ProductID 2
OrDe_Update
Placing an order causes the
OrDe_Update trigger to
execute
Executes an UPDATE
statement on the Products
table
InStock_Update
Products
Products
ProductID UnitsInStock … …
1
3
4
15
10
65
20
2 15
InStock_Update trigger
executes
Sends message
Order_Details
Order_Details
OrderID
10522
10523
10524
ProductID
10
41
7
UnitPrice
31.00
9.65
30.00
Quantity
7
9
24
Discount
0.2
0.15
0.0
10525 19.00
2 0.2
5
Recursive Triggers
 Activating a Trigger Recursively
 See ALTER DATABASE command
 Types of Recursive Triggers
 Direct recursion occurs when a trigger fires and performs
an action that causes the same trigger to fire again
 Indirect recursion occurs when a trigger fires and
performs an action that causes a trigger on another table
to fire that … causes the original trigger to fire again
Examples of Triggers
 Enforcing Data Integrity
 Enforcing Business Rules
CREATE TRIGGER BackOrderList_Delete
ON Products FOR UPDATE
AS
IF (SELECT BO.ProductID FROM BackOrders AS BO JOIN
Inserted AS I ON BO.ProductID = I.Product_ID
) > 0
BEGIN
DELETE BO FROM BackOrders AS BO
INNER JOIN Inserted AS I
ON BO.ProductID = I.ProductID
END
Products
Products
ProductID UnitsInStock … …
1
3
4
15
10
65
20
2 15 Updated
BackOrders
BackOrders
ProductID UnitsOnOrder …
1
12
3
15
10
65
2 15
Trigger Deletes Row
Products
Products
ProductID UnitsInStock … …
1
2
3
4
15
10
65
20
Products with Outstanding Orders Cannot Be Deleted
IF (Select Count (*)
FROM [Order Details] INNER JOIN deleted
ON [Order Details].ProductID = deleted.ProductID
) > 0
ROLLBACK TRANSACTION
DELETE statement executed on
Product table
Trigger code
checks the Order Details
table Order Details
Order Details
OrderID
10522
10523
10524
10525
ProductID
10
2
41
7
UnitPrice
31.00
19.00
9.65
30.00
Quantity
7
9
24
Discount
0.2
0.15
0.0
9
'Transaction cannot be processed'
'This product has order history'
Transaction
rolled back
Products
Products
ProductID UnitsInStock … …
1
3
4
15
10
65
20
2 0
Considerations for Using Triggers
 Triggers vs. Constraints
 Constraints are proactive
 Triggers reactive (FOR) or proactive (INSTEAD OF)
 Constraints checked before triggers
 Can have multiple triggers for any action
 Use sp_settriggerorder to designate order
 Views and temporary tables may only have
INSTEAD OF triggers
Performance Considerations
 Triggers Work Quickly — Inserted and
Deleted Tables Are in Cache
 Execution Time Is Determined by:
 Number of tables that are referenced
 Number of rows that are affected
 Actions Contained in Triggers Implicitly Are
Part of Transaction

Weitere ähnliche Inhalte

Ähnlich wie Triggers (1).pdf

Set Focus SQL Portfolio
Set Focus SQL PortfolioSet Focus SQL Portfolio
Set Focus SQL Portfoliobrentbybee
 
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
 
Database Development Replication Security Maintenance Report
Database Development Replication Security Maintenance ReportDatabase Development Replication Security Maintenance Report
Database Development Replication Security Maintenance Reportnyin27
 
Intro to trigger and constraint
Intro to trigger and constraintIntro to trigger and constraint
Intro to trigger and constraintLearningTech
 
Chapter 07 ddl_sql
Chapter 07 ddl_sqlChapter 07 ddl_sql
Chapter 07 ddl_sqlNazir Ahmed
 
SQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhh
SQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhhSQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhh
SQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhhNaveeN547338
 
Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlnishantdavid9
 
Build .NET Applications with Reporting and Dashboard
Build .NET Applications with Reporting and DashboardBuild .NET Applications with Reporting and Dashboard
Build .NET Applications with Reporting and DashboardIron Speed
 
Database Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingDatabase Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingMoutasm Tamimi
 
Complex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxComplex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxmetriohanzel
 
Oracle Training in Kochi | Trivandrum |Thrissur
Oracle Training in Kochi | Trivandrum |ThrissurOracle Training in Kochi | Trivandrum |Thrissur
Oracle Training in Kochi | Trivandrum |ThrissurIndiaOptions Softwares
 
PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)
PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)
PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)Shakil Zaman
 

Ähnlich wie Triggers (1).pdf (20)

Module06
Module06Module06
Module06
 
Set Focus SQL Portfolio
Set Focus SQL PortfolioSet Focus SQL Portfolio
Set Focus SQL Portfolio
 
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
 
Database Development Replication Security Maintenance Report
Database Development Replication Security Maintenance ReportDatabase Development Replication Security Maintenance Report
Database Development Replication Security Maintenance Report
 
Intro to trigger and constraint
Intro to trigger and constraintIntro to trigger and constraint
Intro to trigger and constraint
 
Trigger
TriggerTrigger
Trigger
 
Chapter 07 ddl_sql
Chapter 07 ddl_sqlChapter 07 ddl_sql
Chapter 07 ddl_sql
 
Triggers
TriggersTriggers
Triggers
 
SQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhh
SQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhhSQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhh
SQL-AGG-FUN.pdfiiiijuyyttfffgyyuyyyyyhhh
 
Trigger
TriggerTrigger
Trigger
 
Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sql
 
Build .NET Applications with Reporting and Dashboard
Build .NET Applications with Reporting and DashboardBuild .NET Applications with Reporting and Dashboard
Build .NET Applications with Reporting and Dashboard
 
Introduction to mysql part 3
Introduction to mysql part 3Introduction to mysql part 3
Introduction to mysql part 3
 
Triggers and active database
Triggers and active databaseTriggers and active database
Triggers and active database
 
Database Management System - SQL Advanced Training
Database Management System - SQL Advanced TrainingDatabase Management System - SQL Advanced Training
Database Management System - SQL Advanced Training
 
Complex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptxComplex Queries using MYSQL00123211.pptx
Complex Queries using MYSQL00123211.pptx
 
Portfolio
PortfolioPortfolio
Portfolio
 
Oracle Training in Kochi | Trivandrum |Thrissur
Oracle Training in Kochi | Trivandrum |ThrissurOracle Training in Kochi | Trivandrum |Thrissur
Oracle Training in Kochi | Trivandrum |Thrissur
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)
PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)
PROCEDURE FOR MONTH END DAY 1 INCLUDING SCREEN SHOT & SCRIPTS (Final rev 090211)
 

Mehr von ShivareddyGangam

Student Voting Application for Election – Using SMS (1).pptx
Student Voting Application for Election – Using SMS (1).pptxStudent Voting Application for Election – Using SMS (1).pptx
Student Voting Application for Election – Using SMS (1).pptxShivareddyGangam
 
Project Management (2).pdf
Project Management (2).pdfProject Management (2).pdf
Project Management (2).pdfShivareddyGangam
 
The Product and Process(1).pdf
The Product and Process(1).pdfThe Product and Process(1).pdf
The Product and Process(1).pdfShivareddyGangam
 
Unit24_TopologicalSort (2).ppt
Unit24_TopologicalSort (2).pptUnit24_TopologicalSort (2).ppt
Unit24_TopologicalSort (2).pptShivareddyGangam
 
artificialintelligencea-200326090832.pdf
artificialintelligencea-200326090832.pdfartificialintelligencea-200326090832.pdf
artificialintelligencea-200326090832.pdfShivareddyGangam
 
Software Project Risks Management (1).pdf
Software Project Risks Management (1).pdfSoftware Project Risks Management (1).pdf
Software Project Risks Management (1).pdfShivareddyGangam
 
OS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptx
OS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptxOS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptx
OS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptxShivareddyGangam
 
machinelearningengineeringslideshare-160909192132 (1).pdf
machinelearningengineeringslideshare-160909192132 (1).pdfmachinelearningengineeringslideshare-160909192132 (1).pdf
machinelearningengineeringslideshare-160909192132 (1).pdfShivareddyGangam
 

Mehr von ShivareddyGangam (20)

Student Voting Application for Election – Using SMS (1).pptx
Student Voting Application for Election – Using SMS (1).pptxStudent Voting Application for Election – Using SMS (1).pptx
Student Voting Application for Election – Using SMS (1).pptx
 
Project Management (2).pdf
Project Management (2).pdfProject Management (2).pdf
Project Management (2).pdf
 
pca.ppt
pca.pptpca.ppt
pca.ppt
 
The Product and Process(1).pdf
The Product and Process(1).pdfThe Product and Process(1).pdf
The Product and Process(1).pdf
 
Unit24_TopologicalSort (2).ppt
Unit24_TopologicalSort (2).pptUnit24_TopologicalSort (2).ppt
Unit24_TopologicalSort (2).ppt
 
Lecture1_jps (1).ppt
Lecture1_jps (1).pptLecture1_jps (1).ppt
Lecture1_jps (1).ppt
 
2 semai.pptx
2 semai.pptx2 semai.pptx
2 semai.pptx
 
artificialintelligencea-200326090832.pdf
artificialintelligencea-200326090832.pdfartificialintelligencea-200326090832.pdf
artificialintelligencea-200326090832.pdf
 
Software Project Risks Management (1).pdf
Software Project Risks Management (1).pdfSoftware Project Risks Management (1).pdf
Software Project Risks Management (1).pdf
 
Introduction (1).pdf
Introduction (1).pdfIntroduction (1).pdf
Introduction (1).pdf
 
Unit 3 (1) (1).pdf
Unit 3 (1) (1).pdfUnit 3 (1) (1).pdf
Unit 3 (1) (1).pdf
 
Unit 1 (1).pdf
Unit 1 (1).pdfUnit 1 (1).pdf
Unit 1 (1).pdf
 
Strassen.ppt
Strassen.pptStrassen.ppt
Strassen.ppt
 
Notion of Algorithms.pdf
Notion of Algorithms.pdfNotion of Algorithms.pdf
Notion of Algorithms.pdf
 
11_Automated_Testing.ppt
11_Automated_Testing.ppt11_Automated_Testing.ppt
11_Automated_Testing.ppt
 
OS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptx
OS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptxOS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptx
OS-Final-Transform-Manual-Testing-Processes-to-incorporate-Automatio....pptx
 
Project Management.pdf
Project Management.pdfProject Management.pdf
Project Management.pdf
 
PP
PPPP
PP
 
chapter2.ppt
chapter2.pptchapter2.ppt
chapter2.ppt
 
machinelearningengineeringslideshare-160909192132 (1).pdf
machinelearningengineeringslideshare-160909192132 (1).pdfmachinelearningengineeringslideshare-160909192132 (1).pdf
machinelearningengineeringslideshare-160909192132 (1).pdf
 

Kürzlich hochgeladen

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 

Kürzlich hochgeladen (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

Triggers (1).pdf

  • 1. Assertions and Triggers Rose-Hulman Institute of Technology Curt Clifton
  • 2. Assertions  Like constraints:  Recall: state IN {'IA', 'MN', 'WI', 'MI', 'IL'}  But can reference all tables  Defined by:  CREATE ASSERTION <name> CHECK ( <condition> );
  • 3. Example: Assertion  In Sells(rest, soda, price), no rest may charge an average of more than $3.  CREATE ASSERTION NoRipoffs CHECK ( NOT EXISTS ( SELECT rest FROM Sells GROUP BY rest HAVING AVG(price) > 3 ));
  • 4. Example: Assertion  The minimum price charged for products made by Coca-Cola Co. is $2  Recall:  Soda(name, manf)  Sells(rest, soda, price)
  • 5. Example: Assertion  The minimum price charged for products made by Coca-Cola Co. is $2  CREATE ASSERTION NoCheapCoke CHECK( NOT EXISTS( SELECT * FROM Sells, Soda WHERE Sells.soda = Soda.name AND Soda.manf = 'Coca-Cola Co.' AND Sells.price < 2.00 ))
  • 6. Timing of Assertion Checks  Logically, assertions always are true  So when do we have to check them?
  • 7. Timing of Assertion Checks  Logically, assertions always are true  So when do we have to check them?  Logically, after any change  Practically, the DBMS could calculate the set of important changes
  • 8. Triggers: Motivation  All the power of assertions  But easier to implement:  Column- and row-based checks  Programmer specifies when they are activated  Most DBMS just include triggers, not assertions
  • 9. What Is a Trigger?  Associated with a Table  Invoked Automatically  Cannot Be Called Directly  Is Part of a Transaction  Along with the statement that calls the trigger  Can ROLLBACK transactions (use with care)
  • 10. Uses of Triggers  Cascade Changes Through Related Tables in a Database  Enforce More Complex Data Integrity Than a CHECK Constraint  Define Custom Error Messages  Automatically update redundant data  Compare Before and After States of Data Under Modification
  • 11. Creating Triggers  Requires Appropriate Permissions  Cannot Contain Certain Statements:  e.g., DROP DATABASE Use Northwind GO CREATE TRIGGER Empl_Delete ON Employees FOR DELETE AS IF (SELECT COUNT(*) FROM Deleted) > 1 BEGIN RAISERROR( 'You cannot delete more than one employee at a time.', 16, 1) ROLLBACK TRANSACTION END
  • 12. USE Northwind GO ALTER TRIGGER Empl_Delete ON Employees FOR DELETE AS IF (SELECT COUNT(*) FROM Deleted) > 6 BEGIN RAISERROR( 'You cannot delete more than six employees at a time.', 16, 1) ROLLBACK TRANSACTION END Altering and Dropping Triggers  Altering a Trigger  DISABLE TRIGGER Empl_Delete ON Employees  ENABLE TRIGGER Empl_Delete ON Employees  DROP TRIGGER Empl_Delete
  • 13. How Triggers Work  How an INSERT Trigger Works  How a DELETE Trigger Works  How an UPDATE Trigger Works  How an INSTEAD OF Trigger Works  How Nested Triggers Work  Recursive Triggers
  • 14. How an INSERT Trigger Works  Consider: USE Northwind CREATE TRIGGER OrdDet_Insert ON [Order Details] FOR INSERT AS UPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity) FROM Products AS P INNER JOIN Inserted AS I ON P.ProductID = I.ProductID
  • 15. INSERT [Order Details] VALUES (10523, 2, 19.00, 5, 0.2) Order Details Order Details OrderID 10522 10523 10524 ProductID 10 41 7 UnitPrice 31.00 9.65 30.00 Quantity 7 9 24 Discount 0.2 0.15 0.0 5 19.00 2 0.2 10523 Insert statement logged inserted inserted 10523 2 19.00 5 0.2 Products Products ProductID UnitsInStock … … 1 2 3 4 15 10 65 20 2 5 How an INSERT Trigger Works
  • 16. How a DELETE Trigger Works  Consider: USE Northwind CREATE TRIGGER Category_Delete ON Categories FOR DELETE AS UPDATE P SET Discontinued = 1 FROM Products AS P INNER JOIN deleted AS d ON P.CategoryID = d.CategoryID
  • 17. Deleted Deleted 4 Dairy Products Cheeses 0x15… DELETE statement logged Categories Categories CategoryID 1 2 3 CategoryName Beverages Condiments Confections Description Soft drinks, coffees… Sweet and savory … Desserts, candies, … Picture 0x15… 0x15… 0x15… 0x15… Cheeses Dairy Products 4 DELETE Categories WHERE CategoryID = 4 Products Products ProductID Discontinued … CategoryID 1 2 3 4 0 0 0 0 1 4 2 3 2 1 4 How a DELETE Trigger Works
  • 18. How an UPDATE Trigger Works  Consider: USE Northwind GO CREATE TRIGGER Employee_Update ON Employees FOR UPDATE AS IF UPDATE (EmployeeID) BEGIN RAISERROR ('Transaction cannot be processed. ***** Employee ID number cannot be modified.', 10, 1) ROLLBACK TRANSACTION END
  • 19. UPDATE Employees SET EmployeeID = 17 WHERE EmployeeID = 2 Employees Employees EmployeeID LastName FirstName Title HireDate 1 2 3 4 Davolio Barr Leverling Peacock Nancy Andrew Janet Margaret Sales Rep. R Sales Rep. Sales Rep. ~~~ ~~~ ~~~ ~~~ 2 Fuller Andrew Vice Pres. ~~~ UPDATE Statement logged as INSERT and DELETE Statements inserted inserted 17 Fuller Andrew Vice Pres. ~~~ deleted deleted 2 Fuller Andrew Vice Pres. ~~~ Transaction cannot be processed. ***** Member number cannot be modified Employees Employees EmployeeID LastName FirstName Title HireDate 1 2 3 4 Davolio Barr Leverling Peacock Nancy Andrew Janet Margaret Sales Rep. R Sales Rep. Sales Rep. ~~~ ~~~ ~~~ ~~~ 2 Fuller Andrew Vice Pres. ~~~ How an UPDATE Trigger Works
  • 20. INSTEAD OF Triggers  INSTEAD OF trigger lets us interpret view modifications that wouldn’t be allowed  Example view:  CREATE VIEW Synergy(cust,soda,rest) AS SELECT Likes.customer, Sells.soda, Sells.rest FROM Likes, Sells, Frequents WHERE Likes.customer = Frequents.customer AND Sells.soda = Likes.soda AND Sells.rest = Frequents.rest
  • 21. Interpreting a View Insertion  INSERT INTO Synergy(cust, soda, rest) VALUES ('Molly', 'Sunkist', 'Regal Beagle')  What does that mean?  Can use INSTEAD OF trigger to decide
  • 22. The Trigger  CREATE TRIGGER SynergyInsert ON Synergy INSTEAD OF INSERT AS DECLARE @c nvarchar(30) DECLARE @s nvarchar(30) DECLARE @r nvarchar(30) SELECT @c=cust, @s=soda, @r=rest From Inserted INSERT INTO Likes VALUES(@c, @s) INSERT INTO Frequents VALUES(@c, @r) INSERT INTO Sells VALUES(@r, @s, null)
  • 23. INSTEAD OF Triggers  Can use them on views to define action  Can also use them on regular tables  Optionally perform or ignore actions
  • 24. How Nested Triggers Work UnitsInStock + UnitsOnOrder is < ReorderLevel for ProductID 2 OrDe_Update Placing an order causes the OrDe_Update trigger to execute Executes an UPDATE statement on the Products table InStock_Update Products Products ProductID UnitsInStock … … 1 3 4 15 10 65 20 2 15 InStock_Update trigger executes Sends message Order_Details Order_Details OrderID 10522 10523 10524 ProductID 10 41 7 UnitPrice 31.00 9.65 30.00 Quantity 7 9 24 Discount 0.2 0.15 0.0 10525 19.00 2 0.2 5
  • 25. Recursive Triggers  Activating a Trigger Recursively  See ALTER DATABASE command  Types of Recursive Triggers  Direct recursion occurs when a trigger fires and performs an action that causes the same trigger to fire again  Indirect recursion occurs when a trigger fires and performs an action that causes a trigger on another table to fire that … causes the original trigger to fire again
  • 26. Examples of Triggers  Enforcing Data Integrity  Enforcing Business Rules
  • 27. CREATE TRIGGER BackOrderList_Delete ON Products FOR UPDATE AS IF (SELECT BO.ProductID FROM BackOrders AS BO JOIN Inserted AS I ON BO.ProductID = I.Product_ID ) > 0 BEGIN DELETE BO FROM BackOrders AS BO INNER JOIN Inserted AS I ON BO.ProductID = I.ProductID END Products Products ProductID UnitsInStock … … 1 3 4 15 10 65 20 2 15 Updated BackOrders BackOrders ProductID UnitsOnOrder … 1 12 3 15 10 65 2 15 Trigger Deletes Row
  • 28. Products Products ProductID UnitsInStock … … 1 2 3 4 15 10 65 20 Products with Outstanding Orders Cannot Be Deleted IF (Select Count (*) FROM [Order Details] INNER JOIN deleted ON [Order Details].ProductID = deleted.ProductID ) > 0 ROLLBACK TRANSACTION DELETE statement executed on Product table Trigger code checks the Order Details table Order Details Order Details OrderID 10522 10523 10524 10525 ProductID 10 2 41 7 UnitPrice 31.00 19.00 9.65 30.00 Quantity 7 9 24 Discount 0.2 0.15 0.0 9 'Transaction cannot be processed' 'This product has order history' Transaction rolled back Products Products ProductID UnitsInStock … … 1 3 4 15 10 65 20 2 0
  • 29. Considerations for Using Triggers  Triggers vs. Constraints  Constraints are proactive  Triggers reactive (FOR) or proactive (INSTEAD OF)  Constraints checked before triggers  Can have multiple triggers for any action  Use sp_settriggerorder to designate order  Views and temporary tables may only have INSTEAD OF triggers
  • 30. Performance Considerations  Triggers Work Quickly — Inserted and Deleted Tables Are in Cache  Execution Time Is Determined by:  Number of tables that are referenced  Number of rows that are affected  Actions Contained in Triggers Implicitly Are Part of Transaction