Está en la página 1de 29

Enforcing Business Logic

What is Business Logic?


A non-technical term for the rules associated with the data in a database that encode business policies. E.g. Automatically adding late fees for overdue items It is in addition to input/output data validation provided by constraints (such as check, not null, unique, primary key, foreign key) and data types (such as int, datetime) to ensure data is consistent Triggers, along with stored procedures can be used to implement business logic
2

Business Logic is specific to the company


The Northwind Traders sample database contains

the sales data for a company called Northwind Traders, which imports and exports speciality foods from around the world. The business rules for Northwind may be very different from the business rules for a local trading company or a global trading company which has a different business model to Northwind Traders The developer would be told which business rules need to be implemented

Triggers and Constraints


Constraints Column are associated with a specific ------ within a table Primary Key foreign key constraints reference the --------- of another table. are suitable for simple data validation. Triggers can be programmed to take data from a number of tables, manipulate that data, insert, update or delete data in many tables are pieces of code that look at lot like stored procedures but are attached to tables and views act only when the appropriate action (such as INSERT, UPDATE, or DELETE) for which the trigger has been set up has been executed. You can't fire a trigger directlyonly the triggering action can do that.

Trigger or Constraint?
1. 2. 3. 4. 5.

6.

Creating Audit trails to track users and the tables they Trigger have modified Automatically updating Quantity in Stock Trigger Ensuring a phone number is entered using the correct format Check Constraint Ensuring a customer cannot be deleted if they have orders recorded in the orders table FK Constraint Providing an error message if the credit limit is exceeded by a customer order and blocking the Trigger transaction Uniquely identify a row of data PK Constraint
5

Triggers
Triggers, along with stored procedures can be used to

implement business logic Triggers were used to implement referential integrity but that is now done using foreign key constraints Triggers were used to update CHILD tables when an update or delete was applied to a PARENT table but that is now done using CASCADES

CASCADE a FK property
Use EM

Select a FK
Check the appropriate

CASCADE UPDATE or CASCADE DELETE in properties

What will the CASCADE do? If we select 'Cascade


Update Related Fields' in this property box, what will it do?
It will update the ProductID in the Order Detail Table if it is modified in the Products table

Draw the relationship for

these tables
Products Order Details
8

In 2008
The same

principle applies but the properties have been presented in a different format

When would you use it in Northwind? When might a


When would a

CASCADE UPDATE be useful?

CASCADE DELETE be dangerous?

An 'INSTEAD OF' trigger may be safer - we will look at types of trigger next

10

Types of trigger
AFTER ( or FOR ) The

INSTEAD OF Trigger
An different action happens

trigger actions happen AFTER the INSERT, UPDATE or DELETE You can have multiple 'after' triggers on a table They execute in the order they were created

INSTEAD of the INSERT, UPDATE or DELETE can be used to perform validation before the data is altered in the table used to implement updates on Views which would normally not be updateable only 1 INSTEAD OF trigger is allowed per process is executed before any AFTER triggers

11

Trigger Syntax
AFTER ( or FOR )
CREATE TRIGGER trigger_name ON table_name FOR DELETE, INSERT, UPDATE AS [action that you want the trigger to make e.g.] INSERT into another_table VALUES (current_user, current_timestamp) GO

INSTEAD OF Trigger
CREATE TRIGGER trigger_name ON table_name INSTEAD OF DELETE AS [action that you want the trigger to do instead of deleting e.g. changing the status of a column named 'expired' to Y] GO

12

'After or For' Trigger


CREATE TRIGGER reminder1 ON Employee AFTER INSERT, UPDATE AS PRINT 'Notify HR' GO

Constraints

Employee 7, '25- 12- 03', 'Smith, 1000 TRIGGER

INSERTED 7, '25- 12- 03', 'Smith, 1000 notify HR

INSERT UPDATE DELETE

Notify HR

Insert into employee values (7, '25- 12- 03', 'Smith, 1000)

13

'After or For' Trigger


CREATE TRIGGER SalIncrease ON Employee AFTER UPDATE AS if (SELECT SALARY FROM INSERTED)>1.1* (SELECT SALARY FROM DELETED) BEGIN ROLLBACK TRANSACTION RAISERROR ('TOO MUCH', 16, 10) END GO

Constraints INSERTED 7, '25- 12- 03', 'Smith, 1300 DELETED 7, '25- 12- 03', 'Smith, 1000 TOO MUCH

Employee 7, '25- 12- 03', 'Smith, 1000 1300 TRIGGER

INSERT UPDATE DELETE

TOO MUCH

UPDATE employee SET SAL= 1300 WHERE EMPID=7

14

Instead of' Trigger


CREATE TRIGGER UrFired ON Employee INSTEAD OF DELETE AS Update Employee SET EmpEnded = Y WHERE EmpID=(Select EmpID from Deleted) GO

Constraints

DELETED

INSERT UPDATE DELETE

Employee 7, '25- 12- 03', 'Smith, 1000, 1000 Y TRIGGER

7, '25- 12- 03', 'Smith, 1000

The Employee table has been updated instead of deleted so what will the update event have triggered?
DELETE FROM employee WHERE EMPID = 7

SalIncrease trigger (previous slide) will fire and check the salary column, but as the update doe infringe the conditions no action will be seen
15

Examples
In the following slides examine the trigger codes then

say what action will occur for each event

Make a note of these triggers


A

When the following transactions run what actions occur and why?
1
2

3 4

1.Welcome to the team

2. For update

3. Sorry you are leaving

4. Data type property infringed


The EmployeeId field is set as integer data type with

the properties set to IDENTITY This automatically inserts an EmployeeID and means that you cannot insert your own value MS SQL Server prevents the insert so the trigger is never executed

Triggers can be used Find the Single table complex data validation. What does this do?

How many we have ordered in the new or updated order detail record which is held for: temporarily in INSERTED

CREATE trigger GotEnough ON [Order details] For INSERT, UPDATE AS if (SELECT Quantity FROM INSERTED)> (SELECT UnitsInStock FROM Products p Join INSERTED i ON p.product_ID = i.Product_ID ) BEGIN by taking the ROLLBACK TRANSACTION ProductID held in INSERTED and RAISERROR ('Not Got Enough in Stock', 16, 10) matching it to the END ProductID in
23

Quantity in Stock in PRODUCTS

PRODUCTS

This is the quantity we want to insert into Order Details

How does the join work?


if (SELECT Quantity FROM INSERTED)> (SELECT UnitsInStock FROM Products p Join INSERTED i ON p.product_ID = i.Product_ID )
Find the Quantity in Stock currently in Products

by taking the ProductID from the inserted table and finding the matching ProductID in the Product Table
24

What does this do?


create trigger trOrderInsert Use the quantity just on [Order details] To change the inserted into the for INSERT UnitsInStock in the order_details table Products table AS UPDATE Products SET p.UnitsInStock = (p.UnitsInStock - i.Quantity) FROM Products p join Inserted i Subtract that from the on p.ProductID = i.ProductID
Which can only be found by matching the productID from the INSERTED table with that in the PRODUCTS table
25

current units in stock for the ProductID in Products

Triggers can be used for: producing an audit trail in an audit table


First create your table
Identity is essential for CREATE TABLE tblAudit the trigger to work (a_user char (10) , a_date datetime , a_ID int IDENTITY (1, 1) NOT NULL , CONSTRAINT [PK_tblAudit] PRIMARY KEY(a_id))

What does this trigger do?


CREATE TRIGGER trg_audit ON dept AFTER INSERT, UPDATE, DELETE AS INSERT into tblAudit VALUES (current_user, current_timestamp)
This is a funtion that inserts usernames for any one with modification permissions who sends an insert, update or delete to the DEPT table

Displays the date and time this is a function equivalent to GETDATE()


27

What does this trigger do?


The DBA creates the following trigger. This counts the number of records in CREATE TRIGGER [trg_delete_check]the DELETED table

ON [dbo].[Order Details] AFTER DELETE AS IF (SELECT COUNT(*) FROM DELETED)>1 BEGIN RAISERROR (some sort of informational warning or instruction',16,1) If the total is greater ROLLBACK TRANSACTION than one the delete will be prevented and END
an error message displayed

Summary
Triggers Can be programmed to take data from a number of tables, manipulate that data, insert, update or delete data in many tables Are pieces of code that look at lot like stored procedures but are attached to tables and views Act only when the appropriate action (such as INSERT, UPDATE, or DELETE) for which the trigger has been set up has been executed. You can't fire a trigger directlyonly the triggering action can do that. Triggers take values from the temporary tables INSERTED and DELETED for any values needed in join statements, conditions etc used in the trigger code INSTEAD OF triggers fire before any AFTER/FOR triggers You can have multiple AFTER triggers on a table

También podría gustarte