100% found this document useful (1 vote)
346 views

Advanced SQL and PL-SQL

This PPT contains SQL and PL-SQL concepts and commands to help you easily go through them.

Uploaded by

Vishal Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
346 views

Advanced SQL and PL-SQL

This PPT contains SQL and PL-SQL concepts and commands to help you easily go through them.

Uploaded by

Vishal Mishra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 78

Advanced SQL

Procedural Constructs in SQL

Database System Concepts - 6th Edition 5.1 ©Silberschatz, Korth and Sudarshan
SQL Views

 SQL view is a virtual table that is


constructed from other tables or views
 It has no data of its own, but obtains data
from tables or other views
 It only has a definition
 SELECT statements are used to define
views
 Views can be used as regular tables in
SELECT statements

Database System Concepts - 6th Edition 5.2 ©Silberschatz, Korth and Sudarshan
SQL Views
 CREATE VIEW command:
 CREATE VIEW view_name AS select_statement
 Use the view:
 In SELECT statements
 Sometimes in INSERT statements
 Sometimes in UPDATE statements
 Sometimes in DELETE statements

Database System Concepts - 6th Edition 5.3 ©Silberschatz, Korth and Sudarshan
SQL Views

 CREATE VIEW command:


CREATE VIEW CustomerNameView AS
SELECT CustName AS CustomerName
FROM CUSTOMER;
 To use the view:
SELECT * FROM CustomerNameView ORDER
BY CustomerName;

Database System Concepts - 6th Edition 5.4 ©Silberschatz, Korth and Sudarshan
Uses of SQL Views

 Security: hide columns and rows


 Display results of computations
 Provide a level of isolation between actual
data and the user’s view of data
 three-tier architecture
 Assign different processing permissions to
different views on same table

Database System Concepts - 6th Edition 5.5 ©Silberschatz, Korth and Sudarshan
SQL Views
 Faculty (EmpID, LName, FName, Department,
AreaCode, LocalPhone)
 Create a view to display 2 columns:
 Name = Fname LName
 Phone = (AreaCode) LocalPhone
 SELECT, INSERT, UPDATE, DELETE?

Database System Concepts - 6th Edition 5.6 ©Silberschatz, Korth and Sudarshan
SQL Views
 Mid(AdmNo, LName, FName, Class, Age)
 Course(CourseID, Description, Textbook)
 Enroll(AdmNo, CourseID, Semester, Grade)
 Create a view to display the student admno, name,
CourseID and description of courses they are/were enrolled
CREATE VIEW JoinView AS
SELECT Mid.AdmNo, Lname, Fname, Course.CourseID,
Course. Description FROM Mid, Course, Enroll
WHERE Course. CourseID= Enroll. CourseID
AND Mid.AdmNo=Enroll.AdmNo

Database System Concepts - 6th Edition 5.7 ©Silberschatz, Korth and Sudarshan
SQL Views

 VIEWs are either updatable or read-only,


but not both
 An updatable VIEW is one that can have
each of its rows associated with exactly
one row in an underlying base table

Database System Concepts - 6th Edition 5.8 ©Silberschatz, Korth and Sudarshan
SQL Views
 When the VIEW is changed, the changes pass unambiguously
through the VIEW to that underlying base table
 Updatable VIEWs are defined only for queries that meet
these criteria:
 Built on only one table
 No GROUP BY clause
 No HAVING clause
 No aggregate functions
 No calculated columns
 No UNION, INTERSECT, or EXCEPT
 No SELECT DISTINCT clause
 In short, Each row in the VIEW maps back to one and only
one row in the base table

Database System Concepts - 6th Edition 5.9 ©Silberschatz, Korth and Sudarshan
SQL Views
 CREATE VIEW Foo1 -- updatable, has a key!
 AS SELECT * FROM Foobar WHERE x IN (1, 2);

 CREATE VIEW Foo2 -- not updatable!


 AS SELECT * FROM Foobar WHERE x = 1 UNION ALL
SELECT * FROM Foobar WHERE x = 2;

 INSERT, UPDATE, and DELETE operations are allowed on


updatable VIEWs and base tables, subject to any other
constraints

 INSERT, UPDATE, and DELETE are not allowed on read-


only VIEWs, but you can change their base tables, as you
would expect

Database System Concepts - 6th Edition 5.10 ©Silberschatz, Korth and Sudarshan
PL/SQL

 Allows using general programming tools


with SQL, for example: loops, conditions,
functions, etc.
 Allows a lot more freedom than general
SQL
 Write PL/SQL code in a regular file, for
example PL.sql, and load it with @PL in the
sqlplus console

Database System Concepts - 6th Edition 5.11 ©Silberschatz, Korth and Sudarshan
PL/SQL Blocks

 PL/SQL code is built of Blocks, with a unique


structure
 Two types of blocks in PL/SQL:
1. Anonymous Blocks: have no name (like scripts)
 Can be written and executed immediately in SQLPLUS
 Can be used in a trigger

2. Named Blocks:
 Procedures
 Functions

Database System Concepts - 6th Edition 5.12 ©Silberschatz, Korth and Sudarshan
Anonymous Block Structure:

DECLARE (optional)
/* Here you declare the variables you will
use in this block */
BEGIN (mandatory)
/* Here you define the executable
statements (what the block DOES!)*/
EXCEPTION (optional)
/* Here you define the actions that take
place if an exception is thrown during
the run of this block */
END; (mandatory)
A correct completion of a block
/
Always put a new line with only
will generate the following
message:
a / at the end of a block! (This
PL/SQL procedure successfully
tells Oracle to run the block)
completed
Database System Concepts - 6th Edition 5.13 ©Silberschatz, Korth and Sudarshan
DECLARE
Syntax
identifier
identifier [CONSTANT]
[CONSTANT] datatype
datatype [NOT
[NOT NULL]
NULL]

[:=
[:= || DEFAULT
DEFAULT expr];
expr];Notice that PL/SQL
Examples includes all SQL types,
and more…

Declare
Declare
birthday
birthday DATE;
DATE;
age
age NUMBER(2)
NUMBER(2) NOT
NOT NULL
NULL :=
:= 27;
27;
name
name VARCHAR2(13)
VARCHAR2(13) :=:= 'Levi';
'Levi';
magic
magic CONSTANT
CONSTANT NUMBER
NUMBER :=:= 77;
77;
valid
valid BOOLEAN
BOOLEAN NOT
NOT NULL
NULL :=
:= TRUE;
TRUE;

Database System Concepts - 6th Edition 5.14 ©Silberschatz, Korth and Sudarshan
Declaring Variables with the
%TYPE Attribute

Examples
Accessing column
sname in table Sailors

DECLARE
sname Sailors.sname%TYPE;
fav_boat VARCHAR2(30);
my_fav_boat fav_boat%TYPE := 'Pinta';
...
Accessing
another variable

Database System Concepts - 6th Edition 5.15 ©Silberschatz, Korth and Sudarshan
Declaring Variables with
the
%ROWTYPE Attribute
Declare a variable with the type of
Accessing
a ROW of a table table
Reserves
reserves_record Reserves%ROWTYPE;

To access the fields in


reserves_record
reserves_record.sid:=9;
reserves_record.bid:=877;

Database System Concepts - 6th Edition 5.16 ©Silberschatz, Korth and Sudarshan
Creating a PL/SQL Record

A record is a type of variable which we can


define (like ‘struct’ in C or ‘object’ in Java)
DECLARE
DECLARE
TYPE
TYPE sailor_record_type
sailor_record_type ISIS RECORD
RECORD
(sname
(sname VARCHAR2(10),
VARCHAR2(10),
sid
sid VARCHAR2(9),
VARCHAR2(9),
age
age NUMBER(3),
NUMBER(3),
rating
rating NUMBER(3));
NUMBER(3));
sailor_record
sailor_record
sailor_record_type;
sailor_record_type;
...
...
BEGIN
BEGIN
Sailor
Sailor__record.sname:=‘peter’;
record.sname:=‘peter’;
Sailor
Sailor__record.age:=45;
record.age:=45;
Database System Concepts - 6 Edition
th
5.17 ©Silberschatz, Korth and Sudarshan
Creating a Cursor
 We create a Cursor when we want to go
over a result of a query (like ResultSet in
JDBC)
 Syntax Example:
sailorData is
DECLARE a variable
that can hold
cursor c is select * from sailors; a ROW from
the sailors
sailorData sailors%ROWTYPE; table

// sailorData c%ROWTYPE
BEGIN
Here the first
open c; row of
sailors is
fetch c into sailorData; inserted into
sailorData

Database System Concepts - 6th Edition 5.18 ©Silberschatz, Korth and Sudarshan
Cursor Example
RAD_VALS
DECLARE
DECLARE
PiPi constant
constant NUMBER(8,7)
NUMBER(8,7) := :=3.1415926;
3.1415926;
radius area
areaNUMBER(14,2);
NUMBER(14,2);
cursor
cursor rad_cursor
rad_cursor is
is select
select**from
fromRAD_VALS;
RAD_VALS;
Rad_cursor
3 rad_val
rad_val rad_cursor%ROWTYPE;
rad_cursor%ROWTYPE;
//// rad_val
rad_val RAD_VALS
RAD_VALS %ROWTYPE
%ROWTYPE
f BEGIN
e 6 BEGIN
open
openrad_cursor;
rad_cursor;
t fetch
fetchrad_cursor
rad_cursor into
intorad_val;
rad_val;
c
8 area:=pi*power(rad_val.radius,2);
area:=pi*power(rad_val.radius,2);
insert
insert into
intoAREAS
AREAS values
values (rad_val.radius,
(rad_val.radius,
h area);
area);
Rad_val close
closerad_cursor;
rad_cursor;
END;
END;
//
AREAS
Radius Area
1st value is fetched and inserted into AREAS
3 28.27
Database System Concepts - 6th Edition 5.19 ©Silberschatz, Korth and Sudarshan
Explicit Cursor Attributes

Obtain status information about a cursor

Attribute Type Description


%ISOPEN Boolean Evaluates to TRUE if the cursor
is open.
%NOTFOUND Boolean Evaluates to TRUE if the most
recent fetch does not return a row.
%FOUND Boolean Evaluates to TRUE if the most
recent fetch returns a row;
complement of %NOTFOUND
%ROWCOUNT Number Evaluates to the total number of
rows returned so far.

Database System Concepts - 6th Edition 5.20 ©Silberschatz, Korth and Sudarshan
SELECT Statements

DECLARE
v_sname VARCHAR2(10);
v_rating NUMBER(3);
BEGIN
SELECT sname, rating
INTO v_sname, v_rating
FROM Sailors
WHERE sid = '112';
END;
/
 INTO clause is required
 Query must return exactly one row
 Otherwise, a NO_DATA_FOUND or
TOO_MANY_ROWS exception is thrown
Database System Concepts - 6th Edition 5.21 ©Silberschatz, Korth and Sudarshan
Conditional logic

Condition: Nested conditions:


If <cond>
If <cond>
then <command>
elsif <cond2> then
then <command2> if <cond2>
else
<command3>
then
end if; <command1>
end if;
else <command2>
end if;

Database System Concepts - 6th Edition 5.22 ©Silberschatz, Korth and Sudarshan
IF-THEN-ELSIF Statements

. . .
IF rating > 7 THEN
v_message := 'You are great';
ELSIF rating >= 5 THEN
v_message := 'Not bad';
ELSE
v_message := 'Pretty bad';
END IF;
. . .

Database System Concepts - 6th Edition 5.23 ©Silberschatz, Korth and Sudarshan
Suppose we have the following
table:
create table mylog( mylog
who varchar2(30), who logon_num
logon_num number
); Peter 3

 Want to keep track of how John 4


many times someone
logged on to the DB Moshe 2
 When running, if user is
already in table, increment
logon_num. Otherwise,
insert user into table
Database System Concepts - 6th Edition 5.24 ©Silberschatz, Korth and Sudarshan
Solution
DECLARE
cnt NUMBER;
BEGIN
select count(*)
into cnt
from mylog
where who = user;

if cnt > 0 then


update mylog
set logon_num = logon_num + 1
where who = user;
else
insert into mylog values(user, 1);
end if;
commit;
end;
/
Database System Concepts - 6th Edition 5.25 ©Silberschatz, Korth and Sudarshan
SQL Implicit Cursor

SQL cursor is automatically created after each SQL


query
It has 4 useful attributes:
SQL%ROWCOUNT Number of rows affected by the
most recent SQL statement (an
integer value).
SQL%FOUND Boolean attribute that evaluates to
TRUE if the most recent SQL
statement affects one or more rows.
SQL%NOTFOUND Boolean attribute that evaluates to
TRUE if the most recent SQL
statement does not affect any rows.
SQL%ISOPEN Always evaluates to FALSE because
PL/SQL closes implicit cursors
immediately after they are executed.

Database System Concepts - 6th Edition 5.26 ©Silberschatz, Korth and Sudarshan
Solution (2)

BEGIN
update mylog
set logon_num = logon_num + 1
where who = user;

if SQL%ROWCOUNT = 0 then
insert into mylog values(user, 1);
end if;
commit;
END;
/

Database System Concepts - 6th Edition 5.27 ©Silberschatz, Korth and Sudarshan
Loops: Simple Loop
create table number_table(
num NUMBER(10)
);

DECLARE
i number_table.num%TYPE := 1;
BEGIN
LOOP
INSERT INTO number_table
VALUES(i);
i := i + 1;
EXIT WHEN i > 10;
END LOOP;
END;
Database System Concepts - 6th Edition 5.28 ©Silberschatz, Korth and Sudarshan
Loops: Simple Cursor Loop
create table number_table(
num NUMBER(10)
);

DECLARE
cursor c is select * from number_table;
cVal c%ROWTYPE;
BEGIN
open c;
LOOP
fetch c into cVal;
EXIT WHEN c%NOTFOUND;
insert into doubles values(cVal.num*2);
END LOOP;
END;
Database System Concepts - 6th Edition 5.29 ©Silberschatz, Korth and Sudarshan
Loops: FOR Loop

DECLARE
i number_table.num%TYPE;
BEGIN
FOR i IN 1..10 LOOP
INSERT INTO number_table VALUES(i);
END LOOP;
END;

Notice that i is incremented


automatically

Database System Concepts - 6th Edition 5.30 ©Silberschatz, Korth and Sudarshan
Loops: For Cursor Loops

DECLARE
cursor c is select * from number_table;

BEGIN
for num_row in c loop
insert into doubles_table
values(num_row.num*2);
end loop;
END;
/
Here, many works are done implicitly:
declaration of num_row, open cursor,
fetch cursor, the exit condition
Database System Concepts - 6th Edition 5.31 ©Silberschatz, Korth and Sudarshan
Loops: WHILE Loop

DECLARE
TEN number:=10;
i number_table.num%TYPE:=1;
BEGIN
WHILE i <= TEN LOOP
INSERT INTO number_table VALUES(i);
i := i + 1;
END LOOP;
END;

Database System Concepts - 6th Edition 5.32 ©Silberschatz, Korth and Sudarshan
Printing Output
 You need to use a function in the
DBMS_OUTPUT package in order to print to
the output
 If you want to see the output on the screen,
you must type the following (before starting):
set serveroutput on

 Then print using


 dbms_output. put_line(your_string);
 dbms_output.put(your_string);

Database System Concepts - 6th Edition 5.33 ©Silberschatz, Korth and Sudarshan
Input and output example
set serveroutput on
ACCEPT high PROMPT 'Enter a number: '

DECLARE
i number_table.num%TYPE:=1;
BEGIN
dbms_output.put_line('Look, I can print from PL/SQL!!!');
WHILE i <= &high LOOP
INSERT INTO number_table VALUES(i);
i := i + 1;
END LOOP;
END;
/

Database System Concepts - 6th Edition 5.34 ©Silberschatz, Korth and Sudarshan
block
DECLARE (optional)
/* Here you declare the variables you
will use in this block */
BEGIN (mandatory)
/* Here you define the executable
statements (what the block DOES!)*/
EXCEPTION (optional)
/* Here you define the actions that take place if
an exception is thrown during the run of this
block */
END; (mandatory)
/

Database System Concepts - 6th Edition 5.35 ©Silberschatz, Korth and Sudarshan
Trapping Exceptions

 Define the actions that should happen when an exception is


thrown
 Example Exceptions:
 NO_DATA_FOUND
 TOO_MANY_ROWS
 ZERO_DIVIDE
 When handling an exception, consider performing a rollback

Database System Concepts - 6th Edition 5.36 ©Silberschatz, Korth and Sudarshan
DECLARE
num_row number_table%ROWTYPE;
BEGIN
select *
into num_row
from number_table;
dbms_output.put_line(1/num_row.num);

EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line('No data!');
WHEN TOO_MANY_ROWS THEN
dbms_output.put_line('Too many!');
WHEN OTHERS THEN
dbms_output.put_line(‘Error’);
end;
Database System Concepts - 6th Edition 5.37 ©Silberschatz, Korth and Sudarshan
User-Defined Exception
DECLARE
e_number1 EXCEPTION;
cnt NUMBER;
BEGIN
select count(*)
into cnt
from number_table;

IF cnt = 1 THEN RAISE e_number1;


ELSE dbms_output.put_line(cnt);
END IF;

EXCEPTION
WHEN e_number1 THEN
dbms_output.put_line('Count = 1');
end;
Database System Concepts - 6 Edition
th
5.38 ©Silberschatz, Korth and Sudarshan
Example

Database System Concepts - 6th Edition 5.39 ©Silberschatz, Korth and Sudarshan
Functions and Procedures
 Up until now, the code was in an anonymous
block
 It was run immediately
 It is useful to put code in a function or
procedure so it can be called several times
 Once create a procedure or function in a
Database, it will remain until deleted (like a
table)
 Can be called from:
 Standard languages
 Scripting languages
 SQL command prompt

Database System Concepts - 6th Edition 5.40 ©Silberschatz, Korth and Sudarshan
Stored Procedure

 Advantages:
 Greater security as store procedures
are always stored on the database
server
 SQL can be optimized by the DBMS
compiler
 Code sharing resulting in:
Less work
Standardized processing
Specialization among developers

Database System Concepts - 6th Edition 5.41 ©Silberschatz, Korth and Sudarshan
Procedural Extensions, Stored
Procedures and Functions
 Stored Procedures
 Can store procedures in the database
 Then execute them using the call statement
 Permit external applications to operate on the
database without knowing about internal
details
 SQL:1999
 Supports functions and procedures
 Functions/procedures can be written in SQL
itself, or in an external programming
language.

Database System Concepts - 6th Edition 5.42 ©Silberschatz, Korth and Sudarshan
Creating Procedures
CREATE
CREATE [OR
[OR REPLACE]
REPLACE] PROCEDURE
PROCEDURE
procedure_name
procedure_name
[(parameter1
[(parameter1 [mode1]
[mode1] datatype1,
datatype1,
parameter2
parameter2 [mode2]
[mode2] datatype2,
datatype2,
.. .. .)]
.)]
IS|AS
IS|AS
PL/SQL
PL/SQL Block;
Block;
 Modes:
 IN: procedure must be called with a value for the
parameter. Value cannot be changed (Default Mode)
 OUT: procedure must be called with a variable for the
parameter. Changes to the parameter are seen by the
user (i.e., call by reference)
 IN OUT: value can be sent, and changes to the
parameter are seen by the user
Database System Concepts - 6th Edition 5.43 ©Silberschatz, Korth and Sudarshan
 IN mode:
 These types of parameters are used to
send values to stored procedures. 
 Similar to passing parameters in
programming languages.
 We can pass values to the stored
procedure through these parameters or
variables. This type of parameter is a read
only parameter. 
 We cannot change its value inside the
procedure.

Database System Concepts - 6th Edition 5.44 ©Silberschatz, Korth and Sudarshan
 OUT Mode:
 These types of parameters are used to get
values from stored procedures.
 Used to send the OUTPUT from a
procedure or a function
 This is a write-only parameter i.e., we
cannot pass values to OUT parameters
while executing the stored procedure, but
we can assign values to OUT parameter
inside the stored procedure and the
calling program can receive this output
value.

Database System Concepts - 6th Edition 5.45 ©Silberschatz, Korth and Sudarshan
 IN-OUT Mode:
  Allows us to pass values into a procedure
and get output values from the procedure.
 Used if the value of the IN parameter can
be changed in the calling program.
 By using IN OUT parameter we can pass
values into a parameter and return a value
to the calling program using the same
parameter. But this is possible only if the
value passed to the procedure and output
value have a same datatype. 

Database System Concepts - 6th Edition 5.46 ©Silberschatz, Korth and Sudarshan
Example- what does this do?
Table create
create or
or replace
replace procedure
procedure
mylog
num_logged
num_logged
_logon (person
who (person ININ mylog.who%TYPE,
mylog.who%TYPE,
num num
num OUT
OUT mylog.logon_num%TYPE)
mylog.logon_num%TYPE)
IS
IS
BEGIN
Pete 3 BEGIN
select
select logon_num
logon_num
into
into num
num
from
from mylog
John 4
where
mylog
where who
who == person;
person;
END;
END;
//
Joe 2
Database System Concepts - 6th Edition 5.47 ©Silberschatz, Korth and Sudarshan
Calling the Procedure

declare
declare
howmany
howmany mylog.logon_num%TYPE;
mylog.logon_num%TYPE;
begin
begin
num_logged(‘John',howmany);
num_logged(‘John',howmany);
dbms_output.put_line(howmany);
dbms_output.put_line(howmany);
end;
end;
//

Database System Concepts - 6th Edition 5.48 ©Silberschatz, Korth and Sudarshan
SQL Procedures
 The dept_count function could instead be written as procedure:
create procedure dept_count_proc (in dept_name varchar(20),
out d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name = dept_count_proc.dept_name
end
 Procedures can be invoked either from an SQL procedure or
from embedded SQL, using the call statement.
declare d_count integer;
call dept_count_proc( ‘Physics’, d_count);
Procedures and functions can be invoked also from dynamic
SQL
 SQL:1999 allows more than one function/procedure of the same
name (called name overloading), as long as the number of
arguments differ, or at least the types of the arguments differ

Database System Concepts - 6th Edition 5.49 ©Silberschatz, Korth and Sudarshan
SQL Procedures

 Students (AdmNo, LastName, FirstName,


Email, ClassYear, Major)
 Procedure: Insert a student only if
ClassYear > 2013

Database System Concepts - 6th Edition 5.50 ©Silberschatz, Korth and Sudarshan
SQL Procedures
CREATE PROCEDURE insertStudents (AdmNoVar char(6),
LastNamevar varchar(50), FirstNamevar varchar(50),
Emailvar varchar(100), ClassYearvar int, MajorVar char(4))
BEGIN
if ClassYearvar > 2013 then
INSERT INTO Students(AdmNo, LastName, FirstName, Email,
ClassYear, Major)
VALUES (AdmNoVar, LastNamevar, FirstNamevar, Emailvar,
ClassYearvar, MajorVar);
end if;
END;
Execute:
call insertStudents(’14Co11’, ‘Patel’,’Dip’, ’[email protected]’,
2014, null)

Database System Concepts - 6th Edition 5.51 ©Silberschatz, Korth and Sudarshan
SQL Procedures

 Add code to the previous procedure to


prevent anyone named ‘Dip, Patel’ to be
inserted into the DB.
 Procedure: Insert a student only if
ClassYear > 2013 and name should not be
Dip Patel

Database System Concepts - 6th Edition 5.52 ©Silberschatz, Korth and Sudarshan
SQL Procedures
CREATE PROCEDURE insertStudents (AdmNoVar char(6),
LastNamevar varchar(50), FirstNamevar varchar(50),
Emailvar varchar(100), ClassYearvar int, Majorvar char(4))
BEGIN
if ClassYearvar > 2013 AND (LastNamevar != ‘Patel’ OR
FirstNamevar != ‘Dip’) then
INSERT INTO Students(AdmNo, LastName, FirstName,
Email, ClassYear, Major)
VALUES (AdmNoVar, LastNamevar, FirstNamevar, Emailvar,
ClassYearvar, Majorvar);
end if;
END;

Database System Concepts - 6th Edition 5.53 ©Silberschatz, Korth and Sudarshan
Procedural Constructs (Cont.)
 For loop
 Permits iteration over all results of a query
 Example:

declare n integer default 0;


for r as
select budget from department
where dept_name = ‘Music’
do
set n = n + r.budget
end for

Database System Concepts - 6th Edition 5.54 ©Silberschatz, Korth and Sudarshan
Procedural Constructs
 Warning: most database systems implement their own variant of the
standard syntax below
 read your system manual to see what works on your system
 Compound statement: begin … end,
 May contain multiple SQL statements between begin and end.
 Local variables can be declared within a compound statements
 Whileand repeat statements :

declare n integer default 0;


while n < 10 do
set n = n + 1
end while

repeat
set n = n – 1
until n = 0
end repeat

Database System Concepts - 6th Edition 5.55 ©Silberschatz, Korth and Sudarshan
Procedural Constructs (cont.)

 Conditional statements (if-then-else)


SQL:1999 also supports a case statement similar
to C case statement
 Example procedure: registers student after
ensuring classroom capacity is not exceeded
 Returns 0 on success and -1 if capacity is
exceeded

Database System Concepts - 6th Edition 5.56 ©Silberschatz, Korth and Sudarshan
Creating a Function

 Almost exactly like creating a procedure,


but you supply a return type

CREATE
CREATE [OR
[OR REPLACE]
REPLACE] FUNCTION
FUNCTION
function_name
function_name
[(parameter1
[(parameter1 [mode1]
[mode1] datatype1,
datatype1,
parameter2
parameter2 [mode2]
[mode2] datatype2,
datatype2,
.. .. .)]
.)]
RETURN
RETURN datatype
datatype
IS|AS
IS|AS
PL/SQL
PL/SQL Block;
Block;

Database System Concepts - 6th Edition 5.57 ©Silberschatz, Korth and Sudarshan
A Function

create
create oror replace
replace function
function
rating_message(rating
rating_message(rating IN IN NUMBER)
NUMBER)
return
return VARCHAR2
VARCHAR2
AS
AS NOTE THAT YOU DON'T
SPECIFY THE SIZE
BEGIN
BEGIN
IF
IF rating
rating >> 77 THEN
THEN
return
return 'You
'You are
are great';
great';
ELSIF
ELSIF rating
rating >=
>= 55 THEN
THEN
return
return 'Not
'Not bad';
bad';
ELSE
ELSE
return
return 'Pretty
'Pretty bad';
bad';
END
END IF;
IF;
END;
END;
//
Database System Concepts - 6th Edition 5.58 ©Silberschatz, Korth and Sudarshan
Calling the function

declare
declare
paulRate:=9;
paulRate:=9;
Begin
Begin
dbms_output.put_line(ratingMessage(paulRate));
dbms_output.put_line(ratingMessage(paulRate));
end;
end;
//

Database System Concepts - 6th Edition 5.59 ©Silberschatz, Korth and Sudarshan
Creating a function:
create or replace function squareFunc(num in number)
return number
is
BEGIN
return num*num;
End;
/

Using the function:


BEGIN
dbms_output.put_line(squareFunc(3.5));
END;
/
Database System Concepts - 6th Edition 5.60 ©Silberschatz, Korth and Sudarshan
Example

 Find the department name and budget of


all departments with more than 12
instructors
 Department(dept_name, building, budget)

Database System Concepts - 6th Edition 5.61 ©Silberschatz, Korth and Sudarshan
SQL Functions
 Define a function that, given the name of a department,
returns the count of the number of instructors in that
department.
create function dept_count (dept_name varchar(20))
returns integer
begin
declare d_count integer;
select count (* ) into d_count
from instructor
where instructor.dept_name = dept_name
return d_count;
end
 Find the department name and budget of all
departments with more than 12 instructors.
select dept_name, budget
from department
where dept_count (dept_name ) > 12

Database System Concepts - 6th Edition 5.62 ©Silberschatz, Korth and Sudarshan
Table Functions
 Example: Return all details of instructor of a given
department.
create function instructors_of (dept_name char(20)
returns table ( ID varchar(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2))
Begin
return table
(select ID, name, dept_name, salary
from instructor
where instructor.dept_name =
instructors_of.dept_name)
End
 Usage
select *
from table (instructors_of (‘Music’))
Database System Concepts - 6th Edition 5.63 ©Silberschatz, Korth and Sudarshan
Triggers

Database System Concepts - 6th Edition 5.64 ©Silberschatz, Korth and Sudarshan
Triggers

 A trigger is a Stored program that is


executed automatically by the DBMS
whenever a specified event occurs.
 Associated with a table [or view]
 Trigger types: BEFORE, AFTER,
INSTEAD OF
 Each type can be declared for
INSERT, UPDATE, or DELETE

Database System Concepts - 6th Edition 5.65 ©Silberschatz, Korth and Sudarshan
Triggers

 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
 Syntax illustrated here may not work
exactly on your database system;
check the system manuals

Database System Concepts - 6th Edition 5.66 ©Silberschatz, Korth and Sudarshan
Triggering Events and Actions in
SQL

 Triggering event can be insert, delete or


update
 Triggers on update can be restricted to
specific attributes
 E.g., after update of takes on grade
 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

Database System Concepts - 6th Edition 5.67 ©Silberschatz, Korth and Sudarshan
Triggering Events and Actions in
SQL

 Triggers can be activated before an event,


which can serve as extra constraints. E.g.
convert blank grades to null
create trigger setnull_trigger before
update of takes
referencing new row as nrow
for each row
when (nrow.grade = ‘ ‘)
begin atomic
set nrow.grade = null;
end;

Database System Concepts - 6th Edition 5.68 ©Silberschatz, Korth and Sudarshan
Trigger Example
 Customers table

 Create a row-level trigger to display salary changes


that would fire for INSERT or UPDATE or DELETE
operations performed on the CUSTOMERS table.

Database System Concepts - 6th Edition 5.69 ©Silberschatz, Korth and Sudarshan
Trigger Example
CREATE [OR REPLACE] TRIGGER DisplaySalaryChanges
BEFORE DELETE OR UPDATE OR INSERT ON Customers
REFERENCING NEW ROW AS New
REFERENCING OLD ROW AS Old
For each row
When(New.ID>0)
Declare
Salary_diff_number;
BEGIN
Salary_dif:= New.Salary – Old.Salary
Dbms_output.put_line(‘Old Salary : ‘ || Old.Salary);
Dbms_output.put_line(‘New Salary : ‘ || New.Salary);
Dbms_output.put_line(‘Salary difference : ‘ || Salary_diff);
END;
/
Output: Trigger Created
Database System Concepts - 6th Edition 5.70 ©Silberschatz, Korth and Sudarshan
 Update statement on customers table

 Trigger will be fired and display the following result:

Database System Concepts - 6th Edition 5.71 ©Silberschatz, Korth and Sudarshan
Statement Level Triggers

 Instead of executing a separate action for each


affected row, a single action can be executed for
all rows affected by a transaction
 Use for each statement instead of for
each row
 Use referencing old table or referencing
new table to refer to temporary tables
(called transition tables) containing the
affected rows
 Can be more efficient when dealing with SQL
statements that update a large number of
rows

Database System Concepts - 6th Edition 5.72 ©Silberschatz, Korth and Sudarshan
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

Database System Concepts - 6th Edition 5.73 ©Silberschatz, Korth and Sudarshan
When Not To Use Triggers

 Risk of unintended execution of triggers, for


example, when
 Loading data from a backup copy
 Replicating updates at a remote site
 Trigger execution can be disabled before such
actions
 Other risks with triggers:
 Error leading to failure of critical transactions
that set off the trigger
 Cascading execution

Database System Concepts - 6th Edition 5.74 ©Silberschatz, Korth and Sudarshan
INSTEAD of Triggers
 INSTEAD OF triggers
 A view is defined by its body
 Very obvious for SELECT queries
 For UPDATE, DELETE and INSERT
 For some classes it is possible to make assumptions
on how the view defines obvious semantics,
 For most cases it does not
– This is where INSTEAD OF triggers jump into
– An INSTEAD OF trigger prevents DBMS from
trying to interpret the view definition for the
update operation
– "Instead of" doing that, it will execute the body of
the trigger, relying on the definer to come up with
meaningful semantics

Database System Concepts - 6th Edition 5.75 ©Silberschatz, Korth and Sudarshan
Trigger Example

Alternative: use triggers on section and timeslot to enforce integrity


constraints
create trigger timeslot_check1 after insert on section
referencing new row as nrow
for each row
when (nrow.time_slot_id not in (
select time_slot_id
from time_slot)) /* time_slot_id not present
in time_slot */
begin
rollback
end;

Database System Concepts - 6th Edition 5.76 ©Silberschatz, Korth and Sudarshan
Trigger Example Cont.

create trigger timeslot_check2 after delete on timeslot


referencing old row as orow
for each row
when (orow.time_slot_id not in (
select time_slot_id
from time_slot)
/* last tuple for time slot id deleted from time
slot */
and orow.time_slot_id in (
select time_slot_id
from section)) /* and time_slot_id still
referenced from section*/
begin
rollback
end;

Database System Concepts - 6th Edition 5.77 ©Silberschatz, Korth and Sudarshan
Trigger Example

Database System Concepts - 6th Edition 5.78 ©Silberschatz, Korth and Sudarshan

You might also like