Programming the Database Today s Lecture 1. Stored Procedures 2. Functions BBM471 Database Management Systems Dr. Fuat Akal akal@hacettepe.edu.tr 3. Cursors 4. Triggers 5. Dynamic SQL 2 Stored Procedures Example Stored Procedure: Definition A stored procedure contains a sequence of SQL commands stored in the database catalog so that it can be invoked later by a program Stored procedures are declared using the following syntax (I refer to MySQL in this presentation): Create Procedure <proc-name> (param_spec 1, param_spec 2,, param_spec n ) begin -- execution code end; where each param_spec is of the form: [in out inout] <param_name> <param_type> in mode: allows you to pass values into the procedure, out mode: allows you to pass value back from procedure to the calling program Suppose we want to keep track of the total salaries of employees working for each department We need to write a procedure to update the salaries in the deptsaltable 4
Create the Stored Procedure Call the Stored Procedure 1. Change the delimiter (i.e., terminating character) of SQL statement from semicolon (;) to something else (e.g., //) 2. Define a procedure called updatesalary which takes as input a department number. 3. The body of the procedure is an SQL command to update the totalsalary column of the deptsal table. 4. Terminate the procedure definition using the delimiter you had defined in step 1 (//) 5. Change the delimiter back to semicolon (;) 5 6 Debugging a Stored Procedure Using a select statement SELECT Comment ; -- Put the literal Comment out to console Insert into a table Putting the current time and date stamp into a column with the comment. Programming Structures Google for XXX reference manual XXX à MySQL, SQL Server, Oracle, Sybase, etc. e.g., to locate IF statement, click on Functions and Operators Control Flow Functions Log messages to an output file Select <time_stamp>, Comment into outfile <file_name> ; Which might be blocked by the security mechanism. https://dev.mysql.com/doc/refman/8.0/en/ 7 8
Database Cursors A database cursor is a control structure that enables traversal over the records in a database. Cursors facilitate subsequent processing in conjunction with the traversal, such as retrieval, addition and removal of database records. A cursor can't be used by itself. It is an essential component in stored procedures. Example Cursor Use cursor to iterate the rows Drop the old procedure 9 10 Cursor Example (Oracle Pl/SQL) DECLARE Pi constant NUMBER(8,7) := 3.1415926; area NUMBER(14,2); cursor rad_cursor is select * from RAD_VALS; rad_val rad_cursor%rowtype; BEGIN open rad_cursor; fetch rad_cursor into rad_val; area:=pi*power(rad_val.radius,2); insert into AREAS values (rad_val.radius, area); close rad_cursor; END; Rad_cursor f e t c h Rad_val RAD_VALS radius 3 6 8 AREAS Radius Area 3 28.27 Select For Update Cursors can also be used to perform updates cursor <cname> is <select-statement> for update; Select statement should involve only one database table update <table-name> set <set-clause> where current of <cname>; delete from < table-name > where current of <cname>; 11 12
Functions Example Function Functions return some value and are declared using the following syntax: function <function-name> (param_spec 1,, param_spec k ) returns <return_type> [not] deterministic Begin -- execution code end; where param_spec is: [in out in out] <param_name> <param_type> 13 14 Function Call Triggers 15
What is a Trigger? A trigger is a statement that is executed automatically by the system as a side effect of a modification to the database. To design a trigger mechanism, we must: Specify the conditions under which the trigger is to be executed. Specify the actions to be taken when the trigger executes. Triggers introduced to SQL standard in SQL:1999, but supported even earlier using non-standard syntax by most databases. Trigger vs. Vendors Available in most enterprise DBMSs (Oracle, IBM DB2, MS SQL server) and some public domain DBMSs (Postgres, MySQL) Some vendor DBMS permit native extensions to SQL for specifying the triggers e.g. PL/SQL in Oracle, Transact SQL in MS SQL Server Some DBMS also allow use of general purpose programming language instead of SQL e.g. Java in Oracle, C#/VB in SQL Server Some DBMS extend the triggers beyond tables for example also to views as in Oracle 17 18 Types of Triggers How many times should the trigger body execute when the triggering event takes place? Per statement: the trigger body executes once for the triggering event. This is the default. For each row: the trigger body executes once for each row affected by the triggering event. When the trigger can be fired Relative to the execution of an SQL DML statement (before or after or instead of it) Exactly in a situation depending on specific system resources (e.g. signal from the system clock, expiring timer, exhausting memory) Triggering Events and Actions in SQL Triggering event can be insert, delete or update Values of attributes before and after an update can be referenced referencing old row as : for deletes and updates referencing new row as : for inserts and updates Triggers can be activated before an event, which can serve as extra constraints. E.g. convert blanks to null. create trigger setnull-trigger before update on r referencing new row as nrow for each row when nrow.phone-number = set nrow.phone-number = null 19 20
Firing Sequence of Database Triggers on a Single Row Firing Sequence of Database Triggers on Multiple Rows DEPT table DEPTNO DNAME 10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS LOC NEW YORK DALLAS CHICAGO BOSTON BEFORE statement trigger BEFORE row trigger AFTER row trigger EMP table EMPNO ENAME 7839 KING 7698 BLAKE 7788 SMITH DEPTNO 30 30 30 BEFORE statement trigger BEFORE row trigger AFTER row trigger BEFORE row trigger AFTER row trigger BEFORE row trigger AFTER row trigger AFTER statement trigger AFTER statement trigger 21 22 Trigger Example - 1 Trigger Example - 1 We want to create a trigger to update the total salary of a department when a new employee is hired Create a trigger to update the total salary of a department when a new employee is hired The keyword new refers to the new row inserted 23 24
Trigger Example - 1 Trigger Example - 2 A trigger to update the total salary of a department when an employee tuple is modified: totalsalary increases by 90K totalsalary did not change 25 26 Trigger Example - 2 Trigger Example - 3 A trigger to update the total salary of a department when an employee tuple is deleted: 27 28
Trigger Example - 3 Using Database Triggers for Information Processing Auditing Table Operations each time a table is accessed auditing information is recorded against it Tracking Record Value Changes each time a record value is changed the previous value is recorded Protecting Database Referential Integrity: if foreign key points to changing records referential integrity must be maintained Maintenance of Semantic Integrity e.g. when the factory is closed, all employees should become unemployed Storing Derived Data e.g. the number of items in the trolley should correspond to the current session selection Security Access Control e.g. checking user privileges when accessing sensitive information 29 30 When Not To Use Triggers Dynamic SQL Triggers were used earlier for tasks such as maintaining summary data (e.g. total salary of each department) Replicating databases by recording changes to special relations (called change or delta relations) and having a separate process that applies the changes over to a replica There are better ways of doing these now: Databases today provide built in materialized view facilities to maintain summary data Databases provide built-in support for replication Encapsulation facilities can be used instead of triggers in many cases Define methods to update fields Carry out actions as part of the update methods instead of through a trigger Sometimes you need to operate against a table or columns that are not known at compile time. CREATE DEFINER=`root`@`localhost` PROCEDURE `dynamic`(in tablename varchar(40)) begin end set @statement = concat('select * from ', tablename); prepare stmt from @statement; execute stmt; set @statement = concat('select count(*) from ', tablename, ' into @count'); prepare stmt from @statement; execute stmt; select concat('count was: ', @count, ' from table: ', tablename); deallocate prepare stmt; 31 32
Summary It is not possible to perform all tasks by using a single SQL statement Sometimes you need to implement the business logic at the database side There you can use stored procedures, functions, cursors, trigger, etc. There are few more structures not covered in this lecture Acknowledgements The course material used for this lecture is mostly taken and/or adopted from: www.cse.msu.edu/~pramanik/teaching/courses/cse480/14s/lectures/ 12/lecture13.ppt by Sakti Pramanik at Michigan State University Database System Concepts, Avi Silberschatz, Henry F. Korth, S. Sudarshan 33 34