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

OCL4 Oracle 10g: SQL & PL/SQL Session #6: Matthew P. Johnson Cisdd, Cuny June, 2005

This document provides an agenda and overview for a session on stored procedures in PL/SQL. The session will cover what stored procedures are, how they integrate SQL and programming languages, and examples of PL/SQL code including basic syntax like blocks, variables, literals, and procedures. Stored procedures allow storing programs in the database and are another way to connect application programming to SQL functionality.

Uploaded by

rajtrivedi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

OCL4 Oracle 10g: SQL & PL/SQL Session #6: Matthew P. Johnson Cisdd, Cuny June, 2005

This document provides an agenda and overview for a session on stored procedures in PL/SQL. The session will cover what stored procedures are, how they integrate SQL and programming languages, and examples of PL/SQL code including basic syntax like blocks, variables, literals, and procedures. Stored procedures allow storing programs in the database and are another way to connect application programming to SQL functionality.

Uploaded by

rajtrivedi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 63

OCL4 Oracle 10g:

SQL & PL/SQL


Session #6
Matthew P. Johnson
CISDD, CUNY
June, 2005

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 1


Agenda
 Last time:
 Programming for SQL
 Pro*C, JDBC

 This time:
 SPs in PL/SQL

 Next time:
 More PL/SQL
 Triggers

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 2


Step back
 Recall basic problem: need SQL plus stronger
programming lang
  need to connect the two langs

 In all these cases (and in the web app case),


idea is: put SQL in (traditional-lang) programs

 Another way: put programs in SQL


 i.e., store programs on the DBMS
 “stored procedures”
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 3
Next topic: SPs
 “Persistent, Stored Modules” / “Stored Procedures /
“PL/SQL programs” (in Oracle)

 Another way to connect application programming


language and SQL

 Supports usual things:


 Declare, set vars to vals of expressions
 Print output
 Define (optional) procedures, functions
 Cursors

 PL/SQL can compute n!


Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 4
Integration with SQL
DECLARE
DECLARE
l_book_count
l_book_countINTEGER;
INTEGER;
BEGIN
BEGIN
SELECT
SELECTCOUNT(*)COUNT(*)
INTO
INTOl_book_count
l_book_count
FROM
FROMbooks books
WHERE
WHEREauthorauthorLIKE
LIKE'%FEUERSTEIN,
'%FEUERSTEIN,STEVEN%';STEVEN%';
DBMS_OUTPUT.PUT_LINE
DBMS_OUTPUT.PUT_LINE((
'Steven
'Stevenhashaswritten
written(or
(orco-written)
co-written)' '||||l_book_count
l_book_count||||
' 'books.');
books.');
----Oh,Oh,and
andIIchanged
changedmymyname,
name,so...
so...
UPDATE
UPDATEbooks books
SET
SETauthor
author==REPLACE
REPLACE(author,
(author,'STEVEN',
'STEVEN','STEPHEN')
'STEPHEN')
WHERE
WHEREauthor authorLIKE
LIKE'%FEUERSTEIN,
'%FEUERSTEIN,STEVEN%';STEVEN%';
END;
END; Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 5
PL/SQL
 “Procedural Language/SQL”
 Oracle’s language for stored procedures
 Simple, interpreted, procedural language

 But Pascal-like:
 BEGIN END, not { }
 AND OR, not && ||
 vars defined at top of procedure
 how return works

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 6


PL/SQL
 Generally speaking can be used wherever
SQL can be
 sqlplus
 embeded SQL
 JDBC

 Can store programs in files (.sql), run later


 @myprog.sql runs code in myprog.sql

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 7


Scripting languages
 Big problems v. small problems
 Big solutions v. small solutions

 Programming languages:
 C/C++, Java, etc.

 Scripting languages:
 PL/SQL, Perl, PHP, Unix shell, DOS batch files, Python, Excel

macros, VBA, JavaScript


 Usual properties of scripting languages:
 Interpreted

 Though now compiled to bytecode or (optionally) to native


 Don’t require functions/procedures
 Though now supported
 Weakly typed
 Lots of auto-conversion

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 8


PL/SQL: Hello, World
 http://pages.stern.nyu.edu/~mjohnson/oracle/plsql/hello.sql

BEGIN
BEGIN
----print
printout
outmessage
message
DBMS_OUTPUT.PUT_LINE('Hello
DBMS_OUTPUT.PUT_LINE('HelloWorld,
World,from
fromPL/SQL');
PL/SQL');
END;
END;
//

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 9


Hello, World
 Try again…
SET
SETSERVEROUTPUT
SERVEROUTPUTON ON
BEGIN
BEGIN
----print
printout
outmessage
message
DBMS_OUTPUT.PUT_LINE('Hello
DBMS_OUTPUT.PUT_LINE('HelloWorld,
World,from
fromPL/SQL');
PL/SQL');
END;
END;
//

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 10


Use start-up script
 Go to <Orahome>\sqlplus\admin\glogin.sql
 Start-up script run upon login to SQL*Plus
 Add “SET SERVEROUTPUT ON” to it

 If running non-i version of SQL*Plus, also


looks in current dir for login.sql script

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 11


How to run code
 The code before ended with a forward slash
 Not SQL and not PL/SQL – just for SQL*Plus
to tell it to run the code entered
 Must go on its own line
 O.w., will be ignored and then interpreted as part
of code, causing an error
 To call a procedure in SQL*Plus, can also
use execute/exec:
exec
execDBMS_OUTPUT.PUT_LINE('Hello
DBMS_OUTPUT.PUT_LINE('HelloWorld,
World,from
fromPL/SQL')
PL/SQL')

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 12


How to run code
 EXEC is just short-hand:

SQL>
SQL> exec
execdbms_output.put_line('hi
dbms_output.put_line('hi');
');
dbms_output.put_line('there'
dbms_output.put_line('there'

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 13


PL/SQL operators/symbols
 ; end statement
 % attribute indicator (cursor attributes like
%ISOPEN and indirect declaration attributes
like %ROWTYPE
 : host variable indicator
 <> and != not-equal-to
 = equal-to
 := assignment op
 ** exponentiation operator
 -- , /* and */, rem comments
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 14
Var names
 identifiers limited to 30 alpha-num chars
 Must start with letter, $, _, or #
 E.g.: abc, $a$, $$$

 PL/SQL is case INsensitive


 abc, ABC, AbC all the same
 Unless you use double-quotes…

 Also supports constants:


 Varname datatype CONSTANT := val;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 15


Literals
 Numbers: 123, 12.3, 3.05E19, 12e-5, null
 String: 'abc', 'AbC', null
 String comparison is case-SENSitive
 Boolean: true, false, null
 true != ‘true’

 No date literals, as in regular SQL


 To_date('31-JAN-94')
 Escape single-quotes in strings with two single-
quotes
 'it''s'  it's
 ''''''  ''

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 16


Blocks
 PL/SQL is a block-structured language

 Block = seq. of instructions, with scope


 Can have anonymous blocks
 And named blocks
 Procedures
 Functions

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 17


Structure of a block
header
header --if
--ifnamed
named
DECLARE
DECLARE --optional
--optional
--var
--var declarations
declarations
BEGIN
BEGIN
--executable
--executablestatements
statements
--queries/updates,
--queries/updates, etc.
etc.
EXCEPTION
EXCEPTION--optional
--optional
--catch
--catchexceptions
exceptions
END;
END;
// --to
--toexecute
execute
 As in Pascal, var declars precede body
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 18
PL/SQL code examples
 One example:
 Likes(drinker, beverage)

BEGIN
BEGIN
INSERT
INSERTINTO
INTOLikes
LikesVALUES(‘Izzy',
VALUES(‘Izzy',‘milk');
‘milk');
DELETE
DELETEFROM
FROMLikes
Likes
WHERE
WHEREdrinker
drinker==‘Izzy'
‘Izzy'AND
AND
beverage
beverage==‘Beaujolais
‘BeaujolaisNouveau
Nouveau';';
COMMIT;
COMMIT;
END;
END;//

 Another example:
 http://pages.stern.nyu.edu/~mjohnson/oracle/plsql/age.sql
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 19
Procedures
 Stored database objects that use a PL/SQL
statement(s) in their body
 Create/drop similar to other SQL objects:
CREATE
CREATEPROCEDURE
PROCEDURE<my-proc>
<my-proc>
(<params>)
(<params>) AS
AS
<procedure
<procedurebody
bodyas
asabove>;
above>;
CREATE
CREATEOR ORREPLACE
REPLACEPROCEDURE
PROCEDURE
<my-proc>(<params>)
<my-proc>(<params>)AS
AS
<procedure
<procedurebody
bodyas
asabove>;
above>;
DROP
DROPPROCEDURE
PROCEDURE<my-proc>;
<my-proc>;
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 20
Example procedure
 Define the procedure:
CREATE
CREATEPROCEDURE
PROCEDUREtestProcedure
testProcedureAS
AS
BEGIN
BEGIN
INSERT
INSERTINTO
INTOStudent
StudentVALUES
VALUES(5,
(5,'Joe');
'Joe');
END;
END;

 Now we can call it:


EXEC
EXECtestProcedure
testProcedure

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 21


More details on procedures
 Parameter list has name-mode-type triples:
 Modes: IN, OUT, or IN OUT
 Fulfills role similar to pass-by-value v. pass-by-
reference
 Default is IN

 Types must match, so can get exact field


type:
relation.attribute%TYPE
relation.attribute%TYPE

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 22


Procedure I/O example
 A procedure to take a beer and price and add
it to Joe's menu: Sells(bar, beer, price)
CREATE
CREATE PROCEDURE
PROCEDURE izzyMenu(
izzyMenu( 
Are these
bb IN char(20),
IN char(20), the right
pp IN
IN double)
double) ASAS types?
BEGIN
BEGIN
INSERT
INSERT INTO
INTO Sells
Sells
VALUES('Izzy''s',
VALUES('Izzy''s', b,
b, p);
p);
END;
END;
//

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 23


Procedure I/O example
 A procedure to take a beer and price and add
it to Joe's menu: Sells(bar, beer, price)
CREATE
CREATE PROCEDURE
PROCEDURE izzyMenu(
izzyMenu(
bb IN
IN Sells.beer%TYPE,
Sells.beer%TYPE,
pp IN
IN Sells.price%TYPE)
Sells.price%TYPE) AS
AS
BEGIN
BEGIN
INSERT
INSERT INTO
INTO Sells
Sells
VALUES('Izzy''s',
VALUES('Izzy''s', b,
b, p);
p);
END;
END;
//

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 24


Larger procedure e.g.

CREATE
CREATEororreplace
replacePROCEDURE
PROCEDUREhike_prices(old_price
hike_prices(old_pricenumber,
number,
new_price
new_priceout
outnumber,
number,
percent_hike
percent_hikenumber
number:=:=5)
5)is
is
Begin
Begin
new_price
new_price:=:=old_price
old_price++old_price
old_price**percent_hike/100;
percent_hike/100;
End;
End;
//

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 25


Call the procedure
Declare
Declare
currprice
currpricenumber
number:=:=20;
20;
newprice
newpricenumber;
number;
Begin
Begin
hike_prices(currprice,newprice,5);
hike_prices(currprice,newprice,5);
dbms_output.put_line(newprice);
dbms_output.put_line(newprice);
End;
End;

 But how to use to modify table data?

 Convert to a function

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 26


Functions
 Like procedures but with return values
CREATE
CREATE FUNCTION
FUNCTION <functionName>
<functionName>
(<paramList>)
(<paramList>) RETURN
RETURN type
type AS
AS
<localDeclarations>
<localDeclarations>
BEGIN
BEGIN
<functionBody>
<functionBody>
END;
END;

DROP
DROP FUNCTION
FUNCTION <functionName>;
<functionName>;
 Big strength: can be called from SQL itself
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 27
Function example

CREATE
CREATEOR ORREPLACE
REPLACEFUNCTION
FUNCTIONmaxval(a
maxval(a
IN
INint,
int,bbIN
INint)
int) RETURN
RETURNint
int AS
AS
BEGIN
BEGIN
IF
IFaa>>bbTHEN
THENRETURN
RETURNa;a;
ELSE
ELSERETURN
RETURNb; b;
END
ENDIF; IF;
END
ENDmaxval;
maxval;

INSERT
INSERTINTO
INTORRVALUES('abc',
VALUES('abc', maxval(5,10));
maxval(5,10));

 http://pages.stern.nyu.edu/~mjohnson/oracle/plsql/maxval.sql

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 28


Hike function
CREATE
CREATEor orreplace
replaceFUNCTION
FUNCTIONhike_pricesf(old_price
hike_pricesf(old_pricenumber,
number,
percent_hike
percent_hikenumber
number:=:=5)
5)return
returnnumber
numberisis
Begin
Begin
return
returnold_price
old_price++old_price
old_price**percent_hike/100;
percent_hike/100;
End;
End;
//

 Now can use directly in update statements

 NB: had to use different name for ftn


 Same namespace for ftns & procs, although different

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 29


How to run scripts
 Don’t want to type ftns into sqlplus by hand
 Define them in a .sql file
 In sqlplus, execute .sql file
SQL>
SQL> @maxval.sql
@maxval.sql
 Runs commands in file
 Here, defines function
 Now, we can call functions
SQL>
SQL> exec
exec DBMS_OUTPUT.PUT_LINE
DBMS_OUTPUT.PUT_LINE
(maxval(5,10))
(maxval(5,10))
 See
http://pages.stern.nyu.edu/~mjohnson/oracle/plsql/plsql.txt

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 30


How to run scripts
 Can also use the start command:
SQL>
SQL> START
START maxval.sql
maxval.sql

 If no file extension is given, .sql is assumed


 Can use full paths:
SQL>
SQL> @c:\somewhere\maxval.sql
@c:\somewhere\maxval.sql
 Scripts can call other scripts
 Use @ for current dir, @@ for dir of current script
 Scripts are not (by default) echoed. Can use:
SQL>
SQL> SET
SET ECHO
ECHO ON
ON
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 31
Calling functions and procedures
 Procedures can simple executed, ftns can’t
 How to just call a ftn?
 Can use dbms_output, as seen
 Can also select the ftn value from dual
SQL>
SQL> select(wordcount('hi
select(wordcount('hi there')
there') from
from dual;
dual;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 32


Stored ftns & procs persist
 Once a function or procedure is created, it
persists until it’s dropped
CREATE
CREATE OR
OR REPLACE
REPLACE FUNCTION
FUNCTION …

 Stored procs are stored in the DB itself


 In user_procedures in Oracle
SELECT
SELECT object_name
object_name from
from user_procedures;
user_procedures;
 Also, can describe ftns and procs:
SQL>
SQL> describe
describe wordcount
wordcount
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 33
Look up procedures, functions
 In Oracle, functions & procedures in
user_procedures:
SELECT
SELECT object_name
object_name from
from user_procedures;
user_procedures;

 Also, can describe ftns and procs:


SQL>
SQL> describe
describe wordcount
wordcount

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 34


Getting errors
 Simply says:
Warning:
Warning: Function
Function created
created with
with compilation
compilation
errors.
errors.
 To get actual errors, say SHOW ERR(ORS)
 Can also get errors per object:
SQL>
SQL> show
show errors
errors function
function wordcount
wordcount

 Warning: must get object type right!


 Can also look at user_errors tbl directly
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 35
More on PL/SQL
 O’Reilly’s Oracle PL/SQL Programming:
 http://www.unix.org.ua/orelly/oracle/prog2/
 This lecture somewhat follows 3rd edition of this book

 PL/SQL Reference & Tutorial:


 http://www.ilook.fsnet.co.uk/ora_sql/sqlmain2.htm

 Introduction to PL/SQL:
 http://www.geocities.com/cliktoprogram/plsql/introduction.html

 Oracle FAQ's Script and Code Exchange:


 http://www.orafaq.com/scripts/

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 36


Break
 Lab 5, lab 6 (exercises 1-3)

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 37


Agenda
 A little more PL/SQL lecture
 Go through some exercises

 More PL/SQL lab…


 Later: go through some PL/SQL exercises…

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 38


Subblocks
Blocks may contain blocks, for narrower scope:
CREATE
CREATE OR OR REPLACE
REPLACE PROCEDURE
PROCEDURE calc_totals
calc_totals IS
IS
year_total
year_total NUMBER;
NUMBER;
BEGIN
BEGIN
year_total
year_total :=
:= 0;
0;
/*/* Nested
Nested anonymous
anonymous block
block */*/
DECLARE
DECLARE
month_total
month_total NUMBER;
NUMBER;
BEGIN
BEGIN
month_total
month_total :=
:= year_total
year_total // 12;
12;
END;
END;
END;
END;
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 39
Branching
 IF–THEN statements use THEN
 Must end with END IF
 Use ELSIF in place of ELSE IF
IF
IF <condition>
<condition> THEN
THEN
<statement(s)>
<statement(s)>
ELSIF
ELSIF
<statement(s)>
<statement(s)>
END
END IF;
IF;
 Example:
 http://pages.stern.nyu.edu/~mjohnson/dbms/eg/lec19/maxval.sql

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 40


More ifs

IF
IF <condition>
<condition> THEN
THEN IF
IF <expression>
<expression> THEN
THEN
ELSE
ELSE ELSEIF
ELSEIF <expression>
<expression>
END
END IF;
IF; ELSE
ELSE
END
END IF;
IF;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 41


Multiple elsifs
 An if statement can have multiple elseifs:
IF
IF salary
salary >=
>= 10000
10000 AND
AND salary
salary <=
<= 20000
20000
THEN
THEN give_bonus(employee_id,
give_bonus(employee_id, 1500);
1500);
ELSIF
ELSIF salary
salary >> 20000
20000 AND
AND salary
salary <=
<= 40000
40000
THEN
THEN give_bonus(employee_id,
give_bonus(employee_id, 1000);
1000);
ELSIF
ELSIF salary
salary >> 40000
40000
THEN
THEN give_bonus(employee_id,
give_bonus(employee_id, 400);
400);
END
END IF;
IF;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 42


Nested ifs IF
IFcondition1
condition1
THEN
THEN
 As usual, if statements IF
IFcondition2
condition2
can be nested: THEN
THEN
statements2
statements2
ELSE
ELSE
 Can often be replaced IF
IFcondition3
condition3
THEN
with an ANDed condition THEN
statements3
statements3
ELSIF
ELSIFcondition4
condition4
THEN
THEN
statements4
statements4
END
ENDIF;IF;
END
ENDIF;IF;
END
ENDIF;IF;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 43


Case-statements
 Saw if and if-else statements last time
 Oracle 8i added support for case stmts
 Two kinds:
 Simple cast stmt
 “searched” case stmt

 Also: case expressions

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 44


Simple case statements
 General form: CASE
CASEexpression
expression
WHEN
WHENresult1
result1THEN
THEN
statements1
statements1
WHEN
WHENresult2
result2THEN
THEN
statements2
statements2
...
...
ELSE
ELSE
statements_else
statements_else
 ELSE is optional END
ENDCASE;CASE;
 expression and results are scalars
 numbers, chars, strings, etc.; not tables
 Literals or vars
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 45
Simple case e.g.
CASE
CASEemployee_type
employee_type
WHEN
WHEN'S''S'THEN
THEN
award_salary_bonus(employee_id);
award_salary_bonus(employee_id);
WHEN
WHEN'H''H'THEN
THEN
award_hourly_bonus(employee_id);
award_hourly_bonus(employee_id);
WHEN
WHEN'C''C'THEN
THEN
award_commissioned_bonus(employee_id);
award_commissioned_bonus(employee_id);
ELSE
ELSE
RAISE
RAISEinvalid_employee_type;
invalid_employee_type;
END
ENDCASE;
CASE;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 46


Simple case’s ELSE clause
 This ELSE is optional, but if omitted, you get an
implicit else clause:
ELSE
ELSE
RAISE
RAISECASE_NOT_FOUND;
CASE_NOT_FOUND;

declare
 Run example: declare
xxnumber
number:= :=1;
1;
begin
begin
case
casexx
when
when22then
then
dbms_output.put_line('2');
dbms_output.put_line('2');
……

 Can use a NULL statement in the ELSE clause


Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 47
CASE statements in SQL
 By the way: CASE statements are now
supported in Oracle SQL itself

SELECT
SELECT
CASE
CASE
WHEN
WHENcomm
commisisnull
nullTHEN
THEN00
ELSE
ELSEcomm
comm
END
END
FROM
FROM emp;
emp;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 48


Loop example
DECLARE
DECLARE        
ii NUMBER
NUMBER := := 1;
1;
BEGIN
BEGIN    
   
LOOP
LOOP        
       
INSERT
INSERT INTO INTO T1VALUES(i,i);
T1VALUES(i,i);
ii :=
:= i+1;
i+1;        
       
EXIT
EXIT WHEN WHEN i>100;i>100;    
   
END
END LOOP;
LOOP;
END;
END;
//

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 49


More loops
LOOP
LOOP
 Infinite loop:
executable_statements;
executable_statements;
END
END LOOP;
LOOP;

WHILE
WHILE condition
condition
LOOP
LOOP
 while loop:
executable_statements;
executable_statements;
END
END LOOP;
LOOP;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 50


More loops
 Numerical for loop:
FOR
FOR for_index
for_index IN
IN low_value
low_value .... high_value
high_value
LOOP
LOOP
executable_statements;
executable_statements;
END
END LOOP;
LOOP;

 Cursor for loop:


FOR
FOR record_index
record_index IN
IN my_cursor
my_cursor
LOOP
LOOP
executable_statements;
executable_statements;
END
END LOOP;
LOOP;
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 51
http://pages.stern.nyu.edu/~mjohnson/oracle/plsql/wordcount.sql
CREATE
CREATEOR ORREPLACE
REPLACEFUNCTIONFUNCTIONwordcount
wordcount(str
(strIN
IN
Word VARCHAR2)
VARCHAR2)
RETURN
RETURNPLS_INTEGER
PLS_INTEGERAS AS
count /*/*words
wordsPLS_INTEGER
intentional
PLS_INTEGER:=
error***
intentional error*** */ */
:=0;
0; ***Commented
***Commentedout outfor
for

progra len
lenPLS_INTEGER
PLS_INTEGER:=
inside_a_word
inside_a_wordBOOLEAN;
:=NVL(LENGTH(str),0);
BOOLEAN;
NVL(LENGTH(str),0);

BEGIN
m BEGIN
FOR
FORi iIN IN1..len
1..len++11 LOOPLOOP
IF
IFASCII(SUBSTR(str,
ASCII(SUBSTR(str,i,i,1)) 1))<<33 33OR
ORi i>>len
len
THEN
THEN
IFIFinside_a_word
inside_a_word
THEN
THEN
words
words:= :=words
words++1; 1;
inside_a_word
inside_a_word:= :=FALSE;
FALSE;
END
ENDIF; IF;
ELSE
ELSE
inside_a_word
inside_a_word:= :=TRUE;
TRUE;
END
ENDIF; IF;
END
ENDLOOP;LOOP;
RETURN
RETURN words;
words;
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 52
END;
END;
Explicit cursors v. for loop cursors
DECLARE
DECLARE
CURSOR
CURSORoccupancy_cur
occupancy_curISIS
SELECT
SELECTpet_id,
pet_id,room_number
room_number
FROM
FROMoccupancy
occupancyWHERE
WHEREoccupied_dt
occupied_dt==TRUNC
TRUNC(SYSDATE);
(SYSDATE);
occupancy_rec
occupancy_recoccupancy_cur%ROWTYPE;
occupancy_cur%ROWTYPE;
BEGIN
BEGIN
OPEN
OPENoccupancy_cur;
occupancy_cur;
LOOP
LOOP
FETCH
FETCHoccupancy_cur
occupancy_curINTO
INTOoccupancy_rec;
occupancy_rec;
EXIT
EXITWHEN
WHENoccupancy_cur%NOTFOUND;
occupancy_cur%NOTFOUND;
update_bill
update_bill
(occupancy_rec.pet_id,
(occupancy_rec.pet_id,occupancy_rec.room_number);
occupancy_rec.room_number);
END
ENDLOOP;
LOOP;
CLOSE
CLOSEoccupancy_cur;
occupancy_cur;
END;
END; Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 53
Explicit cursors v. for loop cursors

DECLARE
DECLARE
CURSOR
CURSORoccupancy_cur
occupancy_curISIS
SELECT
SELECTpet_id,
pet_id,room_number
room_number
FROM
FROMoccupancy
occupancyWHERE
WHEREoccupied_dt
occupied_dt==TRUNC
TRUNC(SYSDATE);
(SYSDATE);
BEGIN
BEGIN
FOR
FORoccupancy_rec
occupancy_recIN INoccupancy_cur
occupancy_cur
LOOP
LOOP
update_bill
update_bill(occupancy_rec.pet_id,
(occupancy_rec.pet_id,occupancy_rec.room_number);
occupancy_rec.room_number);
END
ENDLOOP;
LOOP;
END;
END;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 54


Using query results: SELECT … INTO
create
createor
orreplace
replacefunction
functiongetprod(manuf
getprod(manufvarchar)
varchar)return
returnvarchar
varcharas
as
pn
pnvarchar(255);
varchar(255);
begin
begin

select
selectprodname
prodnameinto
intopn
pn
from
fromproducts
products
where
wheremfg
mfg==manuf;
manuf;

return
returnpn;
pn;
end;
end;
//

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 55


SELECT … INTO and exceptions
create
createor
orreplace
replacefunction
functiongetprod(manuf
getprod(manufvarchar)
varchar)return
returnvarchar
varcharas
as
pn
pnvarchar(255);
varchar(255);
begin
begin

select
selectprodname
prodnameinto
intopn
pn
from
fromproducts
products
where
wheremfg
mfg==manuf;
manuf;

return
returnpn;
pn;
Exception
Exception
When
WhenTOO_MANY_ROWS
TOO_MANY_ROWSthen then
dbms_output.put_line('got
dbms_output.put_line('gottoo
toomany');
many');
end;
end;
//
Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 56
Programs and rights
 By default, only the creator of a program may run it
(apart from the admin)
 If others should run, must GRANT them permission:

SQL>
SQL> GRANT
GRANT EXECUTE
EXECUTE ON ON wordcount
wordcount TO
TO george;
george;
 Permissions can be revoked:
SQL>
SQL> REVOKE
REVOKE EXECUTE
EXECUTE FROM FROM wordcount
wordcount TO
TO george;
george;
 Can also grant to particular roles or everyone:

SQL>
SQL> GRANT
GRANT EXECUTE
EXECUTE ON ON wordcount
wordcount TOTO dba_role;
dba_role;
SQL>
SQL> GRANT
GRANT EXECUTE
EXECUTE ON ON wordcount
wordcount TOTO public;
public;
 Wider/narrower grant ops are independent…

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 57


Packages
 Functions and procedures (and vars) can be
grouped in packages
 Like Java packages, C++ namespaces, etc.
 A pkg has a specification and a body
 Somewhat like C++ class definitions
 Specification: declares public functions
 “public” means: can be run by a user with
EXECUTE authority on this pkg
 Body: defines all functions
 Vars defined here are visible to the pkg’s
programs

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 58


Package e.g.
 Run example:
 http://pages.stern.nyu.edu/~mjohnson/oracle/
plsql/numsys.sql

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 59


Dynamic PL/SQL
 Saw “dynamic SQL” in the cases of Pro*C
and JDBC
 Ability to run ad-hoc (non-hard-coded) SQL in
programs/scripts
 Can also do this in PL/SQL
EXECUTE
EXECUTEIMMEDIATE
IMMEDIATE<string>;
<string>;

 The string can be passed in, created from


concatenation, etc.

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 60


Dynamic PL/SQL
 E.g.: write function to return number rows in
an arbitrary table

CREATE
CREATEOR ORREPLACE
REPLACEFUNCTION
FUNCTIONrowCountrowCount((
tabname
tabnameIN INVARCHAR2)
VARCHAR2)return
returninteger
integer asas
retval
retvalinteger;
integer;
begin
begin
execute
executeimmediate
immediate'select
'select count(*)
count(*) from
from ' '||||tabname
tabnameinto
into
retval;
retval;
return
returnretval;
retval;
end;
end;
//

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 61


Dynamic PL/SQL for DDL
 Ordinarily can’t do DDL in PL/SQL
 But you can in dynamic PL/SQL

 Here’s an e.g.:
CREATE
CREATEOR ORREPLACE
REPLACEprocedure
procedure
dropproc(procname
dropproc(procnameininvarchar2)
varchar2) as
as
begin
begin
execute
executeimmediate
immediate'drop
'dropprocedure
procedure' '||||procname;
procname;
end;
end;
//

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 62


Live examples
 Factorial function:
 http://pages.stern.nyu.edu/~mjohnson/dbms/plsql/
fact.sql

 Converting between bases:


 http://pages.stern.nyu.edu/~mjohnson/dbms/plsql/
numsys.sql

 Directory of examples:
 http://pages.stern.nyu.edu/~mjohnson/dbms/plsql/

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 2005 63

You might also like