0% found this document useful (0 votes)
21 views

11 Programming The Database

The document discusses various database programming concepts including stored procedures, functions, cursors, and triggers. Stored procedures allow grouping SQL statements together that can be invoked later by a program. Functions return a value and are declared with parameters. Cursors facilitate traversal over database records and are used within stored procedures. Triggers automatically execute SQL statements in response to data changes, such as inserts or updates.

Uploaded by

mcsurmeli39
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

11 Programming The Database

The document discusses various database programming concepts including stored procedures, functions, cursors, and triggers. Stored procedures allow grouping SQL statements together that can be invoked later by a program. Functions return a value and are declared with parameters. Cursors facilitate traversal over database records and are used within stored procedures. Triggers automatically execute SQL statements in response to data changes, such as inserts or updates.

Uploaded by

mcsurmeli39
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Programming the Database

BBM632 Database Systems


Dr. Fuat Akal
[email protected]

Hacettepe University Computer Engineering Department


Today’s Lecture

1. Stored Procedures

2. Functions

3. Cursors

4. Triggers

5. Dynamic SQL

Hacettepe University Computer Engineering Department 2


Stored Procedures
• 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_spec1, param_spec2, …, param_specn )
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

Hacettepe University Computer Engineering Department


Example Stored Procedure: Definition

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 deptsal table

Hacettepe University Computer Engineering Department 4


Create 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 (;)

Hacettepe University Computer Engineering Department 5


Call the Stored Procedure

Hacettepe University Computer Engineering Department 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.

• Log messages to an output file


• Select <time_stamp>, ‘Comment’ into outfile ‘<file_name>’;
• Which might be blocked by the security mechanism.

Hacettepe University Computer Engineering Department 7


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

https://dev.mysql.com/doc/refman/8.0/en/

Hacettepe University Computer Engineering Department 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.

Hacettepe University Computer Engineering Department 9


Drop the old procedure
Example Cursor

Use cursor to iterate the rows

Hacettepe University Computer Engineering Department 10


Cursor Example (Oracle Pl/SQL) RAD_VALS

DECLARE radius
Rad_cursor
Pi constant NUMBER(8,7) := 3.1415926;
3
area NUMBER(14,2);
f
e
cursor rad_cursor is select * from RAD_VALS;
6
rad_val rad_cursor%ROWTYPE;
t
BEGIN c 8
open rad_cursor; h
fetch rad_cursor into rad_val; Rad_val
area:=pi*power(rad_val.radius,2);
insert into AREAS values (rad_val.radius, area);
AREAS
close rad_cursor; Radius Area
END; 3 28.27

Hacettepe University Computer Engineering Department 11


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>;

Hacettepe University Computer Engineering Department 12


Functions
• Functions return some value and are declared using the following syntax:

function <function-name> (param_spec1, …, param_speck)


returns <return_type>
[not] deterministic
Begin
-- execution code
end;

where param_spec is:


[in | out | in out] <param_name> <param_type>

Hacettepe University Computer Engineering Department 13


Example Function

Hacettepe University Computer Engineering Department 14


Function Call

Hacettepe University Computer Engineering Department 15


Triggers

Hacettepe University Computer Engineering Department


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.

Hacettepe University Computer Engineering Department 17


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

Hacettepe University Computer Engineering Department 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)

Hacettepe University Computer Engineering Department 19


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

Hacettepe University Computer Engineering Department 20


Firing Sequence of Database Triggers on a
Single Row

DEPT table BEFORE statement trigger

DEPTNO DNAME LOC


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS BEFORE row trigger
30 SALES CHICAGO AFTER row trigger
40 OPERATIONS BOSTON

AFTER statement trigger

Hacettepe University Computer Engineering Department 21


Firing Sequence of Database Triggers on
Multiple Rows
EMP table
BEFORE statement trigger

EMPNO ENAME DEPTNO


7839 KING 30 BEFORE row trigger
AFTER row trigger
7698 BLAKE 30 BEFORE row trigger
AFTER row trigger
7788 SMITH 30 BEFORE row trigger
AFTER row trigger

AFTER statement trigger

Hacettepe University Computer Engineering Department 22


Trigger Example - 1
• We want to create a
trigger to update
the total salary of a
department when a
new employee is
hired

Hacettepe University Computer Engineering Department 23


Trigger Example - 1
• 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

Hacettepe University Computer Engineering Department 24


Trigger Example - 1

totalsalary increases by 90K

totalsalary did not change

Hacettepe University Computer Engineering Department 25


Trigger Example - 2
• A trigger to update the total salary of a department when an
employee tuple is modified:

Hacettepe University Computer Engineering Department 26


Trigger Example - 2

Hacettepe University Computer Engineering Department 27


Trigger Example - 3
• A trigger to update the total salary of a department when an
employee tuple is deleted:

Hacettepe University Computer Engineering Department 28


Trigger Example - 3

Hacettepe University Computer Engineering Department 29


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

Hacettepe University Computer Engineering Department 30


When Not To Use Triggers
• 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

Hacettepe University Computer Engineering Department 31


Dynamic SQL
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
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;
end

Hacettepe University Computer Engineering Department 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

Hacettepe University Computer Engineering Department 33


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

Hacettepe University Computer Engineering Department 34

You might also like