Upload
dan-m-stone
View
217
Download
0
Embed Size (px)
Citation preview
7/27/2019 12 Triggers New-2012-13 (1)
1/29
Enforcing Business Logic
1
7/27/2019 12 Triggers New-2012-13 (1)
2/29
What is Business Logic?A non-technical term for the rules associated with
the data in a database that encode businesspolicies.
E.g. Automatically adding late fees for overdue items
It is in addition to input/output data validationprovided 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 beused to implement business logic
2
7/27/2019 12 Triggers New-2012-13 (1)
3/29
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 fromaround the world.
The business rules for Northwind may be verydifferent from the business rules for a local trading
company or a global trading company which has adifferent business model to Northwind Traders
The developer would be told which business rulesneed to be implemented
7/27/2019 12 Triggers New-2012-13 (1)
4/29
Triggers and ConstraintsConstraints are associated with a specific ------ within a table 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 manytables
are pieces of code that look at lot like stored procedures but areattached 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 beenexecuted. You can't fire a trigger directlyonly the triggeringaction can do that.
Primary Key
Column
7/27/2019 12 Triggers New-2012-13 (1)
5/29
Trigger or Constraint?1. Creating Audit trails to track users and the tables they
have modified
2. Automatically updating Quantity in Stock
3. Ensuring a phone number is entered using the correctformat
4. Ensuring a customer cannot be deleted if they haveorders recorded in the orders table
5. Providing an error message if the credit limit isexceeded by a customer order and blocking thetransaction
6. Uniquely identify a row of data
5
Trigger
Trigger
Check Constraint
FK Constraint
Trigger
PK Constraint
7/27/2019 12 Triggers New-2012-13 (1)
6/29
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 butthat is now done using CASCADES
6
7/27/2019 12 Triggers New-2012-13 (1)
7/29
CASCADE a FK property
Use EM
Select a FK
Check the
appropriateCASCADEUPDATE orCASCADEDELETE inproperties
7
7/27/2019 12 Triggers New-2012-13 (1)
8/29
What will the CASCADE do? If we select 'CascadeUpdate Related Fields' inthis property box, what
will it do?
Draw the relationship for
these tables
8
It will update the ProductID in the
Order Detail Table if it is modified
in the Products table
OrderDetails
Products
7/27/2019 12 Triggers New-2012-13 (1)
9/29
In 2008 The same
principle appliesbut the
properties havebeen presentedin a differentformat
9
7/27/2019 12 Triggers New-2012-13 (1)
10/29
When would you use it in
Northwind?When would a
CASCADE UPDATE beuseful?
When might aCASCADE DELETE bedangerous?
10
An 'INSTEAD OF' trigger
may be safer - we will look
at types of trigger next
7/27/2019 12 Triggers New-2012-13 (1)
11/29
Types of trigger AFTER ( or FOR ) The
trigger actions happenAFTER the INSERT,
UPDATE or DELETE You can have multiple
'after' triggers on a table
They execute in the order
they were created
INSTEAD OF Trigger An different action happens
INSTEAD of the INSERT,
UPDATE or DELETE can be used to perform
validation before the data isaltered in the table
used to implement updates
on Views which wouldnormally not be updateable
only 1 INSTEAD OF triggeris allowed per process
is executed before any
AFTER triggers 11
7/27/2019 12 Triggers New-2012-13 (1)
12/29
Trigger SyntaxAFTER ( or FOR )
CREATE TRIGGER trigger_name
ON table_nameFOR DELETE, INSERT, UPDATE
AS[action that you want the trigger to
make e.g.]
INSERT into another_tableVALUES (current_user,current_timestamp)
GO
INSTEAD OF Trigger
CREATE TRIGGER trigger_nameON table_name INSTEAD OFDELETE AS
[action that you want the trigger todo instead of deleting e.g.changing the status of a columnnamed 'expired' to Y]
GO
12
7/27/2019 12 Triggers New-2012-13 (1)
13/29
'After or For' TriggerCREATE TRIGGERreminder1 ON Employee
AFTER INSERT, UPDATEASPRINT 'Notify HR'GO
13
INSERTED
7, '25- 12- 03', 'Smith, 1000
EmployeeConstraints
TRIGGERINSERT
UPDATE
DELETE
7, '25- 12- 03', 'Smith, 1000
Notify
HR
Insert into employee values (7, '25- 12- 03', 'Smith, 1000)
notify
HR
7/27/2019 12 Triggers New-2012-13 (1)
14/29
'After or For' TriggerCREATE TRIGGER SalIncrease ON EmployeeAFTER UPDATEASif (SELECT SALARY FROM INSERTED)>1.1* (SELECT SALARY FROM DELETED)
BEGINROLLBACK TRANSACTION
RAISERROR ('TOO MUCH', 16, 10)
END
GO
14
DELETED
7, '25- 12- 03', 'Smith, 1000
EmployeeConstraints
TRIGGERINSERT
UPDATE
DELETE
7, '25- 12- 03', 'Smith, 1000
TOO
MUCH
UPDATE employee SET SAL= 1300 WHERE EMPID=7
TOO
MUCH
INSERTED
7, '25- 12- 03', 'Smith, 1300 7, '25- 12- 03', 'Smith, 13007, '25- 12- 03', 'Smith, 1000
7/27/2019 12 Triggers New-2012-13 (1)
15/29
Instead of' TriggerCREATE TRIGGER UrFiredON EmployeeINSTEAD OF DELETEASUpdate Employee SET EmpEnded = Y WHERE EmpID=(Select EmpID from Deleted)GO
15
DELETED
7, '25- 12- 03', 'Smith, 1000
EmployeeConstraints
TRIGGER
INSERT
UPDATEDELETE
7, '25- 12- 03', 'Smith, 1000
DELETE FROM employee WHERE EMPID = 7
7, '25- 12- 03', 'Smith, 1000, Y
The Employee table has been updated
instead of deleted so what will the updateevent have triggered?
SalIncrease trigger (previous slide) will fire and
check the salary column, but as the update do
infringe the conditions no action will be seen
7/27/2019 12 Triggers New-2012-13 (1)
16/29
Examples In the following slides examine the trigger codes then
say what action will occur for each event
7/27/2019 12 Triggers New-2012-13 (1)
17/29
Make a note of these triggersA
B
C
7/27/2019 12 Triggers New-2012-13 (1)
18/29
When the following transactions run what actions
occur and why? 1
2
3
4
7/27/2019 12 Triggers New-2012-13 (1)
19/29
1.Welcome to the team
7/27/2019 12 Triggers New-2012-13 (1)
20/29
2. For update
7/27/2019 12 Triggers New-2012-13 (1)
21/29
3. Sorry you are leaving
7/27/2019 12 Triggers New-2012-13 (1)
22/29
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 meansthat you cannot insert your own value
MS SQL Server prevents the insert so the trigger isnever executed
7/27/2019 12 Triggers New-2012-13 (1)
23/29
23
Triggers can be used for:
Single table complex data validation. What does this do?CREATE trigger GotEnough
ON [Order details]
For INSERT, UPDATE
ASif (SELECT Quantity FROM INSERTED)>
(SELECT UnitsInStock
FROM Products p Join INSERTED i ON p.product_ID =i.Product_ID )
BEGIN
ROLLBACK TRANSACTION
RAISERROR ('Not Got Enough in Stock', 16, 10)
END
Find theQuantity in Stock
in PRODUCTS
How many we have ordered in
the new or updated order
detail record which is held
temporarily in INSERTED
by taking the
ProductID held in
INSERTED and
matching it to the
ProductID in
PRODUCTS
7/27/2019 12 Triggers New-2012-13 (1)
24/29
24
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
This is the quantity
we want to insert
into Order Details
by taking the
ProductID from
the inserted
table andfinding the
matching
ProductID in
the Product
Table
7/27/2019 12 Triggers New-2012-13 (1)
25/29
25
What does this do?create trigger trOrderInsert
on [Order details]
for INSERT
AS
UPDATE ProductsSET p.UnitsInStock = (p.UnitsInStock - i.Quantity)
FROM Products p join Inserted i
on p.ProductID = i.ProductID
Use the quantity just
inserted into the
order_details table
To change the
UnitsInStock in the
Products table
Which can only be found by
matching the productID from the
INSERTED table with that in the
PRODUCTS table
Subtract that from the
current units in stock
for the ProductID inProducts
7/27/2019 12 Triggers New-2012-13 (1)
26/29
Triggers can be used for:
producing an audit trail in an audit table First create your table
CREATE TABLE tblAudit
(a_user char (10) ,a_date datetime ,
a_ID int IDENTITY (1, 1) NOT NULL ,
CONSTRAINT [PK_tblAudit] PRIMARY KEY(a_id))
Identity is essential forthe trigger to work
7/27/2019 12 Triggers New-2012-13 (1)
27/29
27
What does this trigger do?
CREATE TRIGGER trg_audit
ON deptAFTER 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()
7/27/2019 12 Triggers New-2012-13 (1)
28/29
What does this trigger do?
The DBA creates the following trigger.
CREATE TRIGGER [trg_delete_check]ON [dbo].[Order Details]
AFTER DELETEASIF (SELECT COUNT(*) FROM DELETED)>1BEGIN
RAISERROR (some sort of informational warningor instruction',16,1)ROLLBACK TRANSACTIONEND
This counts the
number of records in
the DELETED table
If the total is greater
than one the delete
will be prevented and
an error message
displayed
7/27/2019 12 Triggers New-2012-13 (1)
29/29
SummaryTriggers Can be programmed to take data from a number of tables,
manipulate that data, insert, update or delete data in manytables
Are pieces of code that look at lot like stored procedures but areattached 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 beenexecuted. You can't fire a trigger directlyonly the triggeringaction can do that.
Triggers take values from the temporary tables INSERTED andDELETED for any values needed in join statements, conditionsetc used in the trigger code
INSTEAD OF triggers fire before any AFTER/FOR triggers You can have multiple AFTER triggers on a table