Presentation is loading. Please wait.

Presentation is loading. Please wait.

IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.

Similar presentations


Presentation on theme: "IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server."— Presentation transcript:

1 IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Stored Procedures in SQL Server Constraints Triggers –Trigger logic –IF tests in T-SQL –INSERTED & DELETED tables in Triggers –FOR vs. INSTEAD OF Triggers –Trigger Uses & Issues

2 IMS 4212: Constraints & Triggers 2 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Constraints Constraints are defined on a table and checked whenever data is updated or inserted Excellent for controlling valid values of fields when the domain would otherwise allow –Positive price and quantity values –Allowable values for fields ('Freshman', 'Sophomore', 'Junior', 'Senior') Constraints are excellent way to enforce business rules when the rule pertains to values of a field that can be tested strictly on the desired value or other fields in the same record

3 IMS 4212: Constraints & Triggers 3 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Creating Constraints Open table in design view The Expression must be true for all records Constraints added to object browser

4 IMS 4212: Constraints & Triggers 4 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Creating Constraints (cont.) SQL Version ALTER TABLE Customers ADD Constraint CK_Customers_NoLMNPhone CHECK ([Phone] <> 'LMN')

5 IMS 4212: Constraints & Triggers 5 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Try It Out The Employees table already has a constraint ensuring that the employees birthdate is prior to the current date. Add a new constraint to ensure that employees are at least 16 years old when hired. Add a constraint to ensure that an employee cannot be assigned to supervise themselves (ReportsTo holds the EmployeeID of the employee's supervisor)

6 IMS 4212: Constraints & Triggers 6 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Constraints—Final Thoughts The constraint expression must be true for all records added or updated in table Primary and Foreign Keys are actually implemented as special types of Constraints Using the IN expression –Class IN ('Freshman', 'Sophomore', 'Junior', 'Senior') Constraints can be set to ignore existing data if applicable

7 IMS 4212: Constraints & Triggers 7 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Triggers Triggers are database objects containing SQL Statements They run automatically when specified events take place on tables (or views) –INSERT –UPDATE –DELETE Triggers are important tools for enforcing certain classes of business rules

8 IMS 4212: Constraints & Triggers 8 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Triggers (cont.) Triggers must specify –Table (View) to act on –Event(s) to respond to INSERT, UPDATE, DELETE –When trigger fires Before SQL executes (INSTEAD OF) After SQL executes (FOR or AFTER)

9 IMS 4212: Constraints & Triggers 9 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Try This Out CREATE TRIGGER trChkSalesRepStatus ON Orders FOR INSERT, UPDATE AS IF EXISTS ( SELECT 'True' FROM Inserted INNER JOIN Employees ON Inserted.EmployeeID = Employees.EmployeeID WHERE Employees.Title <> 'Sales Representative') BEGIN RAISERROR('Not a Sales Representative',16,1) ROLLBACK TRAN END

10 IMS 4212: Constraints & Triggers 10 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Try This Out (cont.) Do the next two together and look at employees SELECT Top 10 OrderID, EmployeeID FROM Orders SELECT * FROM Employees Do this statement and rerun top two statements UPDATE Orders SET EmployeeID = 3 WHERE OrderID = 10258 Now rerun update but change SET EmployeeID = 2

11 IMS 4212: Constraints & Triggers 11 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Trigger Logic A typical way to set up triggers is to use an IF EXISTS test –Surrounds a query that will return records if the business rule is violated –Since you don't care about the content of the records SELECT 'True' is conventionally used If the test is true (violating records are found) then the action to cancel the event is invoked IF EXISTS ( SELECT 'True' FROM Inserted INNER JOIN Employees ON Inserted.EmployeeID = Employees.EmployeeID WHERE Employees.Title <> 'Sales Representative')

12 IMS 4212: Constraints & Triggers 12 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Trigger Logic (cont.) When the trigger finds a violation it must cancel the action –Triggers automatically create a Transaction surrounding their actions (more about Transactions later) –ROLLBACK TRAN cancels the transaction without writing to the database The trigger should raise an error –RAISERROR('Not a Sales Representative', 16, 1) Error message string Severity level (use 16) State (position indicator)

13 IMS 4212: Constraints & Triggers 13 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Transact-SQL (T-SQL) IF—THEN Logic IF EXISTS ( SELECT 'True' FROM Inserted INNER JOIN Employees ON Inserted.EmployeeID = Employees.EmployeeID WHERE Employees.Title <> 'Sales Representative') BEGIN RAISERROR('Not a Sales Representative',16,1) ROLLBACK TRAN END IF test to be checked then statement to be executed [ELSE else statement to be executed] BEGIN & END surround multiple lines to be executed in a THEN or ELSE block The THEN statement is not used—it is assumed THEN action

14 IMS 4212: Constraints & Triggers 14 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu INSERTED & DELETED Tables When a trigger runs on a table it will generate one or both of the following temporary tables –INSERTED—Contains a copy of the row(s) being inserted into the table –DELETED—Contains a copy of the row(s) being deleted from the table These tables exist within the running life of the trigger Both have the exact column structure as the table on which the trigger is created

15 IMS 4212: Constraints & Triggers 15 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu INSERTED & DELETED Tables (cont.) The syntax above gives us access to the row about to be inserted and lets us test it using any query available in the database The tables can conceivably contain many rows if an UPDATE or DELETE SQL statement WHERE clause permits SELECT 'True' FROM Inserted INNER JOIN Employees ON Inserted.EmployeeID = Employees.EmployeeID WHERE Employees.Title <> 'Sales Representative')

16 IMS 4212: Constraints & Triggers 16 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Try It Out Create a trigger on the Customers table that will prevent adding a new customer if the first ten letters of the address, the city, region, and postal code match an existing customer. Then query the customers table to find an existing customer and see if the trigger works. Hint: You can try to add the new customer directly in the Open Table mode, though using an INSERT INTO statement would be much cooler.

17 IMS 4212: Constraints & Triggers 17 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu INSERTED & DELETED Tables (cont.) INSERTED & DELETED tables generated when: INSERT INTO –INSERTED table only DELETE FROM –DELETED table only UPDATE –INSERTED table—new version of the row(s) –DELETED table—old version of the row(s)

18 IMS 4212: Constraints & Triggers 18 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Try It Out Write a Trigger on the Products table that will prevent price changes of more than 5%

19 IMS 4212: Constraints & Triggers 19 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu FOR / AFTER vs. INSTEAD OF Triggers FOR triggers let action go forward but ROLLBACK can cancel the action –Most common type –All we will use INSTEAD OF intercepts the action and lets you do something completely different –Useful in some special circumstances –New in SQL Server v. 2000 CREATE TRIGGER trTriggerName ON TableName FOR INSERT AS CREATE TRIGGER trTriggerName ON TableName INSTEAD OF INSERT AS

20 IMS 4212: Constraints & Triggers 20 Dr. Lawrence West, Management Dept., University of Central Florida lwest@bus.ucf.edu Trigger Uses & Issues Trigger Uses –Data integrity checks—most important use –Logging changes to data in log files –Avoid using triggers to perform business logic Trigger execution is not obvious in code or SP logic Trigger Issues –Multiple triggers can exist on a single table—firing order may be important and can be controlled –Triggers create performance issues –Triggers may be suspended without being dropped


Download ppt "IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server."

Similar presentations


Ads by Google