Most of that last objective is going to wait until we are at v.7. Stored procs were in their infancy in DB2 v.5 and are difficult to implement, requiring a lot of manual sql to register them into the system tables. In v6 there is a big leap. Triggers are not available at all until v. 6. So, I haven’t created a working stored procedure, but we’ll revisit this when we are at v.7.
A trigger will be executed, even if the event occurs due to a person using spufi.
1) For example – if inventory totals need adjusting every time an item is sold. 2) For example – maybe every time a student’s emergency contact info is changed, a new card needs to be printed for the school office. If a trigger calls the print routine every time the information is updated, no one has to remember to do this. 3) For example – complex conditions to check before allowing a certain class, like Drivers Ed. Once a trigger is defined, EVERY process uses it the same way. Even if a user does an update through SPUFI, the trigger is fired.
For example –If you are archiving some old data that is being deleted, you would want to capture it BEFORE the delete. If you are adding to inventory totals, you would want to do it AFTER you know the insert of a new order was successful. For example – For the student emergency contact cards, you would want to print one for each student row where the contact is changed. However, you might want to validate a complex transaction such as the student enrolling in Drivers Ed only once.
Must have BEGIN ATOMIC and END if you have more than one statement. All statements must end with a semicolon.
Think of a stored procedure as a database object, similar to a table, index or authorization. Originally dbms products were designed to hold only data – now they hold business processes and rules as well. Example of a use of a trigger and a stored proc: Warehouse kept table of inventory total records. Every time goods were delivered to the warehouse or there was a shipment out, the total rows were updated. The insert of a shipment or delivery into the shipment or receipts tables triggered a stored procedure that got the quantity and the item from the row being inserted, and called a stored proc to add or subtract that quantity to that item’s total row in the inventory totals table. There was an interesting problem however… Triggers and stored procs are rather invisible to a programmer unless he looks for them, and can be missed.
I learned in class that John Deere was sending SQL via Java and it was taking too long. When they changed to calling stored procedures they got a seven-fold improvement. This approach is preferable to cannibalizing sections of program code for each new application. Stored procs can reduce the overall maintenance effort, especially when code is distributed on multiple workstations.
Early stored procedures were similar to cobol subroutines, with a linkage section for passing data. In our next version we will have procedural SQL called SQL Procedures Language, or SPL. We will also be able to write them in Java. Stored procs may be called from any DB2 –compatible language. What is the difference between static and dynamic sql?? Static – much of the work is done at bind time. Dynamic – all done at execution. Stored procs cannot issue a few db2 commands like connect and commit.
Use appropriate data types for parameters – should be the same data type and length in calling program and stored proc. For a cobol stored proc, don’t use date, time and timestamp parameters – use the character version as we do in our cobol programs.
When we use SQL, it is non-procedural. The order in which it does the steps necessary to return requested rows is invisible to us. For writing stored procedures, IBM, and other database suppliers, have extended SQL to have procedural constructs.
This example is written in SPL. A COBOL stored procedure looks like a regular COBOL subroutine, where variables are passed via a linkage section.
Code/370 would be useful if we needed to implement stored procedures in our current v5 configuration. The Stored Procedure Builder only creates stored procs in SPL or Java, so it won’t help us now, but we’ll want to use it when we are at v. 7.
Triggers and Stored Procedures in DB2
Triggers and Stored Procedures in DB2 Pam Odden
Objectives <ul><li>Learn what triggers and stored procedures are </li></ul><ul><li>Learn the benefits of using them </li></ul><ul><li>Learn how DB2 implements triggers and stored procedures </li></ul><ul><li>Learn how to create and call a stored procedure 1 </li></ul><ul><li>1 To be revisited when we have migrated to v. 7. </li></ul>
What is a Trigger? <ul><li>A trigger is a specialized program that is not called directly, but is event-driven. </li></ul><ul><li>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. </li></ul><ul><li>A trigger is not directly called or executed. After being created, it is always executed when its firing event occurs. </li></ul><ul><li>DB2 version 5 does not support triggers. </li></ul>
Why Use Triggers? <ul><li>Support data integrity – if a change to one column dictates a change to another, a trigger ensures they always stay in sync. </li></ul><ul><li>Simplify scheduling – if an action needs to happen every time a particular column is updated, the trigger avoids having to schedule it. </li></ul><ul><li>Support complex business rules – having business rules in the database ensures everyone uses the same logic to accomplish the same process. </li></ul>
Timing Considerations for Triggers <ul><li>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. </li></ul><ul><li>Trigger timing also depends on any other triggers defined for the same database event. Two triggers of the same type fire in the order in which they were created. This means if the table is dropped and recreated for any reason, such as making a modification, it is important that the triggers are created in the same order each time. For this reason, it is best to avoid having more than one trigger on the same event. </li></ul><ul><li>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. </li></ul>
Trigger Examples <ul><li>CREATE TRIGGER CRITICAL_PROJECT </li></ul><ul><li>AFTER UPDATE OF PROJ_END_DATE ON PROJ </li></ul><ul><li>REFERENCING NEW AS NEWPROJ </li></ul><ul><li>FOR EACH ROW </li></ul><ul><li>WHEN (NEWPROJ.PROJ_END_DATE < CURRENT DATE + 14 DAYS) </li></ul><ul><li>BEGIN ATOMIC </li></ul><ul><li>CALL CRITPROJ (NEWPROJ.PROJNO); </li></ul><ul><li>END </li></ul><ul><li>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. </li></ul><ul><li>Note the project number can be referenced and passed to the stored procedure. </li></ul>
Another Trigger Example <ul><li>CREATE TRIGGER TOT_COMP </li></ul><ul><li>AFTER UPDATE OF SALARY, BONUS, COMM ON EMP </li></ul><ul><li>REFERENCING NEW AS INSERTED, OLD AS DELETED </li></ul><ul><li>FOR EACH ROW </li></ul><ul><li>WHEN (INSERTED.SALARY <> DELETED.SALARY </li></ul><ul><li>OR INSERTED.BONUS <> DELETED.BONUS </li></ul><ul><li>OR INSERTED.COMM <> DELETED.COM) </li></ul><ul><li>BEGIN ATOMIC </li></ul><ul><li>UPDATE EMP_SALARY </li></ul><ul><li>SET TOT_COMP = INSERTED.SALARY + INSERTED.BONUS + </li></ul><ul><li>INSERTED COMM </li></ul><ul><li>WHERE EMP_SALARY.EMPNO = INSERTED.EMPNO; </li></ul><ul><li>END </li></ul><ul><li>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. </li></ul>
What is a Stored Procedure? <ul><li>A stored procedure is a specialized program that is stored in the relational database management system instead of in an external code library. </li></ul><ul><li>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. </li></ul><ul><li>A stored procedure must be invoked, or called, before it can be executed. It is not event-driven. </li></ul><ul><li>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. </li></ul>
Why use Stored Procedures? <ul><li>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. </li></ul><ul><li>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. </li></ul><ul><li>Consistency : business rules are implemented only one way, not interpreted differently by each programmer. </li></ul><ul><li>Maintenance : Code changes are only required in one place. </li></ul>
Why use Stored Procedures, cont. <ul><li>Data Integrity : Stored procedures can perform column validations, so if all applications use the same procedure, the data is always validated. </li></ul><ul><li>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. </li></ul><ul><li>Database protection : Stored procedures run in a separate address space from the database engine, eliminating the possibility of users corrupting the DBMS. </li></ul>
DB2’s Stored Procedure Implementation <ul><li>DB2‘s implementation of stored procedures has changed quite a bit from v. 5 to v. 6 and 7. </li></ul><ul><li>Prior to v.6, stored procedures had to be written using LE/370 traditional programming languages. The supported languages are C, C++, COBOL, OO COBOL, and PL/I. (Note: VS COBOL II is not an LE/370 language.) </li></ul><ul><li>Prior to v.6 stored procedures had to be manually registered in the DB2 Catalog, as they were created like independent programs, rather than residing in the database. </li></ul><ul><li>As of v.6, they are created and managed within DB2 like any other DB2 object, using CREATE, ALTER, AND DROP statements. They can now be written in procedural SQL and Java, as well as LE/370 languages. </li></ul><ul><li>DB2’s stored procedures can issue static and dynamic SQL, access flat and VSAM files as well as DB2 tables and views, and access resources in CICS, IMS, and other MVS address spaces. </li></ul>
Parameters <ul><li>Parameters allow data to be passed to and received from a stored procedure. </li></ul><ul><li>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. </li></ul><ul><li>Three types of parameters may be defined: IN (input parameter), OUT (output parameter) and INOUT (parameter that is used for both input and output). </li></ul>
Procedural SQL <ul><li>IBM created a version of procedural SQL called SQL Procedures Language, or SPL. It is based on the ANSI Standard SQL/PSM (Persistent Stored Modules). </li></ul><ul><li>Other RDBMSs have proprietary procedural dialects – such as Oracle’s PL/SQL and MS SQL Server’s Transact SQL. </li></ul><ul><li>SPL contains procedural constructs like looping (WHILE or REPEAT), conditional processing (IF…THEN…ELSE) and blocking (BEGIN…END), and the ability to define and use variables. </li></ul><ul><li>With SPL, a stored procedure can be written quickly, without knowledge of COBOL or any other LE/370 language. </li></ul><ul><li>SPL stored procedures have their actual code defined in the CREATE PROCEDURE statement and stored in the database, unlike the external stored procedures of DB2 v. 4 and 5. </li></ul>
Preparing a Stored Procedure for Execution <ul><li>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. </li></ul><ul><li>If the stored procedure is written in SPL, it is converted to C source statements and compiled into a C executable program. </li></ul><ul><li>Stored procedures are usually written as reentrant code that will be started with the command START PROCEDURE( procname ) </li></ul><ul><li>The procedure will stay resident and available to be called until a STOP command is issued. </li></ul>
Stored Procedure Example <ul><li>CREATE PROCEDURE UPDATE_SALARY </li></ul><ul><li>(IN EMPLOYEE_NUMBER CHAR(10), </li></ul><ul><li>IN RATE DECIMAL(6.2)) </li></ul><ul><li>LANGUAGE SQL </li></ul><ul><li>COMMIT ON RETURN YES </li></ul><ul><li>IF RATE <= 0.50 </li></ul><ul><li>THEN UPDATE EMP </li></ul><ul><li>SET SALARY = SALARY + (SALARY * RATE) </li></ul><ul><li>WHERE EMPNO = EMPLOYEE_NUMBER; </li></ul><ul><li>ELSE UPDATE EMP </li></ul><ul><li>SET SALARY = SALARY + (SALARY * 0.50) </li></ul><ul><li>WHERE EMPNO = EMPLOYEE_NUMBER; </li></ul><ul><li>END IF </li></ul><ul><li>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%. </li></ul>
Tools and Enhancements <ul><li>Code/370 is an integrated toolset consisting of editing, compilation, and debugging tools provided by IBM. Without it, creating and managing stored procedures in DB2 v. 4 and 5 can be difficult. </li></ul><ul><li>Stored Procedure Builder is a free product for developing SPL and Java stored procedures. It provides a GUI development environment for creating and testing stored procedures, and can be launched independently, or from MS Visual Studio or Visual Basic, or IBM’s Visual Age for Java. </li></ul>
Summary <ul><li>Triggers are blocks of code that are automatically executed every time a particular database event occurs. </li></ul><ul><li>Stored procedures are blocks of code that are stored in the database and can be called by triggers, other stored procedures, and external programs. </li></ul><ul><li>Using triggers and stored procedures can help standardize processing by storing code in only one place, and help reduce network traffic by consolidating processing on the database server. </li></ul>