Triggers and Stored Procedures in DB 1. Objectives Learn what triggers and stored procedures are Learn the benefits of using them Learn how DB2 implements.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

SQL*PLUS, PLSQL and SQLLDR Ali Obaidi. SQL Advantages High level – Builds on relational algebra and calculus – Powerful operations – Enables automatic.
Stored Procedure Language Stored Procedure Overview Stored Procedure is a function in a shared library accessible to the database server can also write.
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
Chapter 7 Triggers and Active Databases. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 7-2 Trigger Overview Element of the database schema.
Chapter 3: System design. System design Creating system components Three primary components – designing data structure and content – create software –
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
Getting Started (Excerpts) Chapter One DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
© 2007 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.1 Computer Networks and Internets with Internet Applications, 4e By Douglas.
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Fundamentals, Design, and Implementation, 9/e Chapter 7 Using SQL in Applications.
Concepts of Database Management Sixth Edition
Database Administration Part 1 Chapter Six CSCI260 Database Applications.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 7-1 David M. Kroenke’s Chapter Seven: SQL for Database Construction and.
SEMESTER 1, 2013/2014 DB2 APPLICATION DEVELOPMENT OVERVIEW.
PL/SQL and the Table API. Benefits of Server-Side Code Speedy Pizza MENU NAPOLITAINE PIZZA Reduced network traffic Maintainability Data integrity Triggers.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 7-1 David M. Kroenke’s Chapter Seven: SQL for Database Construction and.
Database Systems: Design, Implementation, and Management Tenth Edition Chapter 8 Advanced SQL.
Triggers Event handlers in the DBMS. Triggers are event handlers Triggers a executed when an event happens in the DBMS Example events – INSERT, UPDATE.
Chapter 4 The Relational Model 3: Advanced Topics Concepts of Database Management Seventh Edition.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 7-1 David M. Kroenke’s Chapter Seven: SQL for Database Construction and.
CSE 3330 Database Concepts Stored Procedures. How to create a user CREATE USER.. GRANT PRIVILEGE.
Database Design and Management CPTG /23/2015Chapter 12 of 38 Functions of a Database Store data Store data School: student records, class schedules,
Cohesion and Coupling CS 4311
Accessing Your MySQL Database from the Web with PHP (Ch 11) 1.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 8 Advanced SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Fall 2001Database Systems1 Triggers Assertions –Assertions describe rules that should hold for a given database. –An assertion is checked anytime a table.
Advanced SQL: Triggers & Assertions
1 Chapter 7 Triggers and Active Databases. 2 Trigger Overview Element of the database schema General form: ON IF THEN –Event- request to execute database.
1 Chapter 7 Triggers and Active Databases. 2 Trigger Overview Element of the database schema General form: ON IF THEN –Event- request to execute database.
What is a Package? A package is an Oracle object, which holds other objects within it. Objects commonly held within a package are procedures, functions,
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
IT System Administration Lesson 3 Dr Jeffrey A Robinson.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
1 Intro stored procedures Declaring parameters Using in a sproc Intro to transactions Concurrency control & recovery States of transactions Desirable.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
Database Management COP4540, SCS, FIU Database Trigger.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
IT420: Database Management and Organization Triggers and Stored Procedures 24 February 2006 Adina Crăiniceanu
Chapter 8 Advanced SQL Pearson Education © Chapter 8 - Objectives How to use the SQL programming language How to use SQL cursors How to create stored.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
SQL Triggers, Functions & Stored Procedures Programming Operations.
Create Stored Procedures and Functions Database Management Fundamentals LESSON 2.4.
1. Advanced SQL Functions Procedural Constructs Triggers.
Copyright © 2004 Pearson Education, Inc.. Chapter 24 Enhanced Data Models for Advanced Applications.
7.5 Using Stored-Procedure and Triggers NAME MATRIC NUM GROUP Muhammad Azwan Bin Khairul Anwar CS2305A Muhammad Faiz Bin Badrol Shah CS2305B.
Trigger used in PosgreSQL
Chapter 6 - Database Implementation and Use
Instructor: Jason Carter
Database Systems: Design, Implementation, and Management Tenth Edition
UNIT - V STORED PROCEDURE.
Chapter 8 Advanced SQL Pearson Education © 2014.
Introduction to Database Systems, CS420
PL/SQL Scripting in Oracle:
PRACTICE OVERVIEW PL/SQL Part - 2.
Database Fundamentals
Database Processing: David M. Kroenke’s Chapter Seven:
Business Application Development
Chapter 7 Using SQL in Applications
Chapter 7 Using SQL in Applications
Chapter 8 Advanced SQL.
Information Management
Database Systems: Design, Implementation, and Management Tenth Edition
Stored Procedure Language
Assertions and Triggers
Presentation transcript:

Triggers and Stored Procedures in DB 1

Objectives Learn what triggers and stored procedures are Learn the benefits of using them Learn how DB2 implements triggers and stored procedures Learn how to create and call a stored procedure 1 1 To be revisited when we have migrated to v. 7. 2

What is a Trigger? A trigger is a specialized program that is not called directly, but is event-driven. When a data modification statement, such as an insert or an update occurs, a trigger is executed, or “fired”, which may make other database updates or call a stored procedure. A trigger is not directly called or executed. After being created, it is always executed when its firing event occurs. 3

Why Use Triggers? Support data integrity – if a change to one column dictates a change to another, a trigger ensures they always stay in sync. Simplify scheduling – if an action needs to happen every time a particular column is updated, the trigger avoids having to schedule it. Support complex business rules – having business rules in the database ensures everyone uses the same logic to accomplish the same process. 4

Timing Considerations for Triggers DB2 supports “BEFORE” and “AFTER” triggers. A BEFORE trigger occurs before the database event that causes it to fire. An AFTER trigger occurs after the database event. A trigger can fire once for a particular database event, or once per affected row. These are called statement-level triggers or row-level triggers and are defined using the FOR EACH STATEMENT or FOR EACH ROW clause. 5

Trigger Examples CREATE TRIGGER CRITICAL_PROJECT AFTER UPDATE OF PROJ_END_DATE ON PROJ REFERENCING NEW AS NEWPROJ FOR EACH ROW WHEN (NEWPROJ.PROJ_END_DATE < CURRENT DATE + 14 DAYS) BEGIN ATOMIC CALL CRITPROJ (NEWPROJ.PROJNO); END Here, when a project end date is updated and is within the next 2 weeks, a critical project routine is called. This could print an alert for management, put a rush on a supply order, or whatever is needed for the business. Note the project number can be referenced and passed to the stored procedure. 6

Another Trigger Example CREATE TRIGGER TOT_COMP AFTER UPDATE OF SALARY, BONUS, COMM ON EMP REFERENCING NEW AS INSERTED, OLD AS DELETED FOR EACH ROW WHEN (INSERTED.SALARY <> DELETED.SALARY OR INSERTED.BONUS <> DELETED.BONUS OR INSERTED.COMM <> DELETED.COM) BEGIN ATOMIC UPDATE EMP_SALARY SET TOT_COMP = INSERTED.SALARY + INSERTED.BONUS + INSERTED COMM WHERE EMP_SALARY.EMPNO = INSERTED.EMPNO; END Here, when an employee’s salary, bonus or commission is changed on the emp table, his total compensation is updated accordingly on the emp_salary table. 7

What is a Stored Procedure? A stored procedure is a specialized program that is stored in the relational database management system instead of in an external code library. It may access and/or modify data in one or more tables, but it is not physically associated with a table, or any other object. A stored procedure must be invoked, or called, before it can be executed. It is not event-driven. A major motivating reason for using stored procedures is to move SQL code from a client to the database server. One client request to a stored procedure can replace many SQL calls, reducing network traffic and speeding up processing. 8

Why use Stored Procedures? Performance: In a client/server or internet environment, stored procedures can reduce network traffic because multiple SQL statements can be invoked with a single stored procedure. Only the request and the final results need to be sent across the network. Reusability: Stored procedures allow code to reside in one place, the database server. Multiple client programs can call the procedures as needed, without duplicating code. Consistency: business rules are implemented only one way, not interpreted differently by each programmer. Maintenance: Code changes are only required in one place. 9

Why use Stored Procedures, cont. Data Integrity: Stored procedures can perform column validations, so if all applications use the same procedure, the data is always validated. Security: If a given group of users requires access to specific data items, you can provide a stored procedure that returns just those items. You can then grant access to call the stored procedure, without giving those users any additional authorization to the underlying database objects. Database protection: Stored procedures run in a separate address space from the database engine, eliminating the possibility of users corrupting the DBMS. 10

Parameters Parameters allow data to be passed to and received from a stored procedure. They are used similarly to how they are used to call a subroutine. For example, to call the DATECALC program, you need to send a date, and a few switches to indicate what you want back – do you want the date converted to another format? The day of the week? The program returns the results to you in another parameter. Three types of parameters may be defined: IN (input parameter), OUT (output parameter) and INOUT (parameter that is used for both input and output). 11

Preparing a Stored Procedure for Execution After a stored procedure’s source statements have been created, they are precompiled, compiled, link- edited and bound, producing an executable program and a DB2 package. If the stored procedure is written in SPL, it is converted to C source statements and compiled into a C executable program. Stored procedures are usually written as reentrant code that will be started with the command START PROCEDURE(procname) The procedure will stay resident and available to be called until a STOP command is issued. 12

Stored Procedure Example CREATE PROCEDURE UPDATE_SALARY (IN EMPLOYEE_NUMBER CHAR(10), IN RATE DECIMAL(6.2)) LANGUAGE SQL COMMIT ON RETURN YES IF RATE <= 0.50 THEN UPDATE EMP SET SALARY = SALARY + (SALARY * RATE) WHERE EMPNO = EMPLOYEE_NUMBER; ELSE UPDATE EMP SET SALARY = SALARY + (SALARY * 0.50) WHERE EMPNO = EMPLOYEE_NUMBER; END IF Here, the procedure accepts an employee number and rate. The employee’s salary is increased by the rate, and an IF THEN ELSE construct is used to ensure the raise is not greater than 50%. 13