Assertions and Triggers Rose-Hulman Institute of Technology Curt Clifton.

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Advertisements

1 Constraints, Triggers and Active Databases Chapter 9.
What Is a User-defined Function? Scalar Functions –Similar to a built-in function Multi-Statement Table-valued Functions –Content like a stored procedure.
Chapter 7 Notes on Foreign Keys Local and Global Constraints Triggers.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Index Blocking Factors, Views Rose-Hulman Institute of Technology Curt Clifton.
Constraints and Triggers Foreign Keys Local and Global Constraints Triggers.
A Guide to SQL, Seventh Edition. Objectives Create a new table from an existing table Change data using the UPDATE command Add new data using the INSERT.
Structured Query Language – Continued Rose-Hulman Institute of Technology Curt Clifton.
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #4.
Module 11: Implementing Triggers. Overview Introduction Defining Create, drop, alter triggers How Triggers Work Examples Performance Considerations Analyze.
Module 8: Implementing Views. Overview Introduction Advantages Definition Modifying Data Through Views Optimizing Performance by Using Views.
Creating Tables, Defining Constraints Rose-Hulman Institute of Technology Curt Clifton.
Database Systems More SQL Database Design -- More SQL1.
Chapter 7 Constraints and Triggers Spring 2011 Instructor: Hassan Khosravi.
Triggers Event handlers in the DBMS. Triggers are event handlers Triggers a executed when an event happens in the DBMS Example events – INSERT, UPDATE.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
Module 1: Introduction to Transact-SQL
Triggers How triggers work Creating triggers Using triggers to maintain referential integrity Multirow considerations Nesting triggers Rules associated.
SQL Server 7.0 Maintaining Referential Integrity.
Module 3: Retrieving Data. Overview Retrieving Data by Using the SELECT Statement Filtering Data Formatting Result Sets How Queries Are Processed Performance.
Triggers A Quick Reference and Summary BIT 275. Triggers SQL code permits you to access only one table for an INSERT, UPDATE, or DELETE statement. The.
SQL SERVER.  DML Triggers  DDL Trigers  INSERT triggers  DELETE triggers  UPDATE triggers  A mix and match of any of the above.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
IST 210 Constraints and Triggers. IST Constraints and Triggers Constraint: relationship among data elements DBMS should enforce the constraints.
Advanced SQL: Triggers & Assertions
Constraints cis 407 Types of Constraints & Naming Key Constraints Unique Constraints Check Constraints Default Constraints Misc Rules and Defaults Triggers.
Module 4: Implementing Data Integrity
7 1 Constraints & Triggers Chapter Constraints and triggers? Constraints: Certain properties that the DBMS is required to enforce –E.g. primary.
Objectives Database triggers and syntax
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Module 7: Modifying Data. Overview Using Transactions Inserting Data Deleting Data Updating Data Performance Considerations.
Module 7: Implementing Views. Overview Introducing Views Defining and Using Views Using Views to Optimize Performance.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E) 1.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
Copyright © 2013 Curt Hill Triggers The Generation of Indirect Actions.
A Guide to SQL, Eighth Edition Chapter Six Updating Data.
A database trigger is a stored PL/SQL program unit associated with a specific database table. ORACLE executes (fires) a database trigger automatically.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
Ch 5. Introducing More Database Objects. Database Objects Table (ch2) View (ch3) Stored Procedure Trigger Function User-defined types.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
A Guide to SQL, Sixth Edition 1 Chapter 5 Updating Data.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
SQL Triggers, Functions & Stored Procedures Programming Operations.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Trigger used in PosgreSQL
SQL Query Getting to the data ……..
Module 3: Retrieving Data
Creating Database Triggers
Foreign Keys Local and Global Constraints Triggers
Implementing Triggers
Introduction to Triggers
Module 10: Implementing Triggers
Structured Query Language – The Basics
Introduction to Database Systems, CS420
CPSC-310 Database Systems
Module 5: Implementing Data Integrity by Using Constraints
Overview Implementing Triggers Implementing XML Schemas.
Introduction to Triggers
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
CPSC-608 Database Systems
Prof. Arfaoui. COM390 Chapter 9
SQL – Constraints & Triggers
CPSC-608 Database Systems
Responding to Data Manipulation Via Triggers
Presentation transcript:

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 CHECK ( );

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 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 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) INSERT [Order Details] VALUES (10523, 2, 19.00, 5, 0.2) Order Details OrderID ProductID UnitPrice Quantity Discount Insert statement logged insertedinserted ProductsProducts ProductID UnitsInStock … … … … 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

DeletedDeleted 4 4 Dairy Products Cheeses 0x15… DELETE statement logged CategoriesCategories CategoryID CategoryName Beverages Condiments Confections Beverages Condiments Confections Description Soft drinks, coffees… Sweet and savory … Desserts, candies, … Soft drinks, coffees… Sweet and savory … Desserts, candies, … Picture 0x15… 0x15…0x15… CheesesDairy Products4 DELETE Categories WHERE CategoryID = 4 DELETE Categories WHERE CategoryID = 4ProductsProducts ProductID Discontinued … … CategoryID 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 UPDATE Employees SET EmployeeID = 17 WHERE EmployeeID = 2EmployeesEmployees EmployeeID LastName FirstName Title HireDate Davolio Barr Leverling Peacock Davolio Barr Leverling Peacock Nancy Andrew Janet Margaret Nancy Andrew Janet Margaret Sales Rep. R Sales Rep. R Sales Rep. ~~~ 2FullerAndrewVice Pres. ~~~ UPDATE Statement logged as INSERT and DELETE Statementsinsertedinserted 17 Fuller Andrew Vice Pres. ~~~ deleteddeleted 2 2 Fuller Andrew Vice Pres. ~~~ Transaction cannot be processed. ***** Member number cannot be modified Transaction cannot be processed. ***** Member number cannot be modified EmployeesEmployees EmployeeID LastName FirstName Title HireDate Davolio Barr Leverling Peacock Davolio Barr Leverling Peacock Nancy Andrew Janet Margaret Nancy Andrew Janet Margaret Sales Rep. R Sales Rep. R Sales Rep. ~~~ 2FullerAndrewVice 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 nvarchar(30) nvarchar(30) @r=rest From Inserted INSERT INTO INSERT INTO INSERT INTO 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 ProductsProducts ProductID UnitsInStock … … … … InStock_Update trigger executes Sends messageOrder_DetailsOrder_Details OrderID ProductID UnitPrice Quantity Discount

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 ProductsProducts ProductID UnitsInStock … … … … Updated BackOrdersBackOrders ProductID UnitsOnOrder … … Trigger Deletes Row

ProductsProducts ProductID UnitsInStock … … … … 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 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 OrderID ProductID UnitPrice Quantity Discount ' Transaction cannot be processed ' ' This product has order history ' ' Transaction cannot be processed ' ' This product has order history ' Transaction rolled backProductsProducts ProductID UnitsInStock … … … …

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