OCL4 Oracle 10g: SQL & PL/SQL Session #6

Matthew P. Johnson CISDD, CUNY June, 2005

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



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 

Johnson. functions Cursors    PL/SQL can compute n! Matthew P.Next topic: SPs  ³Persistent. Sept 2005 4 . Stored Modules´ / ³Stored Procedures / ³PL/SQL programs´ (in Oracle) Another way to connect application programming language and SQL Supports usual things: Declare. CISDD CUNY. set vars to vals of expressions Print output Define (optional) procedures. OCL4.

STEVEN%'.'). END. 'STEPHEN') WHERE author LIKE '%FEUERSTEIN. STEVEN%'.. Matthew P. OCL4.Oh. UPDATE books SET author = REPLACE (author. CISDD CUNY. DBMS_OUTPUT.PUT_LINE ( 'Steven has written (or co-written) ' || l_book_count || ' books. BEGIN SELECT COUNT(*) INTO l_book_count FROM books WHERE author LIKE '%FEUERSTEIN.. Sept 2005 5 . Johnson.Integration with SQL DECLARE l_book_count INTEGER. -. 'STEVEN'. so. and I changed my name.

Johnson. interpreted. CISDD CUNY. procedural language But Pascal-like: BEGIN END. OCL4. not { } AND OR.PL/SQL  ³Procedural Language/SQL´ Oracle¶s language for stored procedures  Simple. Sept 2005 6 . not && || vars defined at top of procedure how return works  Matthew P.

sql).sql runs code in myprog.PL/SQL  Generally speaking can be used wherever SQL can be sqlplus embeded SQL JDBC  Can store programs in files (. Johnson. run later @myprog.sql Matthew P. Sept 2005 7 . OCL4. CISDD CUNY.

Scripting languages: PL/SQL. JavaScript Usual properties of scripting languages: Interpreted     Though now compiled to bytecode or (optionally) to native Though now supported Lots of auto-conversion Matthew P. etc. OCL4. Unix shell. DOS batch files. small solutions Programming languages: C/C++. CISDD CUNY. Excel macros. Java.Scripting languages   Big problems v. Perl. Johnson. PHP. Sept 2005 8 Don¶t require functions/procedures  Weakly typed  . small problems Big solutions v. VBA. Python.

PUT_LINE('Hello World. OCL4.nyu.PL/SQL: Hello.stern. World  http://pages. END. / Matthew P.sql BEGIN -. from PL/SQL').print out message DBMS_OUTPUT. CISDD CUNY. Johnson.edu/~mjohnson/oracle/plsql/hello. Sept 2005 9 .

Sept 2005 10 . from PL/SQL'). / Matthew P. World  Try again« SET SERVEROUTPUT ON BEGIN -.print out message DBMS_OUTPUT.Hello. Johnson. END. CISDD CUNY.PUT_LINE('Hello World. OCL4.

Sept 2005 11 .sql script  Matthew P. CISDD CUNY.Use start-up script    Go to <Orahome>\sqlplus\admin\glogin. also looks in current dir for login. Johnson.sql Start-up script run upon login to SQL*Plus Add ³SET SERVEROUTPUT ON´ to it If running non-i version of SQL*Plus. OCL4.

from PL/SQL') Matthew P. causing an error  To call a procedure in SQL*Plus.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. will be ignored and then interpreted as part of code. OCL4..PUT_LINE('Hello World. CISDD CUNY. can also use execute/exec: exec DBMS_OUTPUT.w. Johnson. Sept 2005 12 .

How to run code  EXEC is just short-hand: SQL> exec dbms_output. OCL4.put_line('hi '). Sept 2005 13 .put_line('there' Matthew P. dbms_output. Johnson. CISDD CUNY.

rem comments Matthew P. OCL4.PL/SQL operators/symbols         . Johnson. Sept 2005 14 . 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 */.. CISDD CUNY.

g. Matthew P. AbC all the same Unless you use double-quotes«   Also supports constants: Varname datatype CONSTANT := val.: abc. ABC. $. $a$.Var names  identifiers limited to 30 alpha-num chars Must start with letter. Johnson. Sept 2005 15 . $$$ PL/SQL is case INsensitive abc. OCL4. or #  E. _. CISDD CUNY.

3. 3. 12e-5. null true != µtrue¶  No date literals. 12. Johnson. Sept 2005 16 .05E19. as in regular SQL To_date('31-JAN-94')    Escape single-quotes in strings with two singlequotes 'it''s' it's '''''' '' Matthew P. null String comparison is case-SENSitive  Boolean: true. false. CISDD CUNY. OCL4. null String: 'abc'. 'AbC'.Literals   Numbers: 123.

OCL4. Johnson. of instructions. with scope Can have anonymous blocks And named blocks Procedures Functions    Matthew P.Blocks  PL/SQL is a block-structured language Block = seq. Sept 2005 17 . CISDD CUNY.

etc. OCL4.Structure of a block header --if named DECLARE --optional --var declarations BEGIN --executable statements --queries/updates. var declars precede body Matthew P. Sept 2005 18 . Johnson. EXCEPTION --optional --catch exceptions END. CISDD CUNY. / --to execute  As in Pascal.

COMMIT. Johnson. CISDD CUNY.sql Matthew P.stern. DELETE FROM Likes WHERE drinker = µIzzy' AND beverage = µBeaujolais Nouveau '. Sept 2005 19 .PL/SQL code examples  One example: Likes(drinker. µmilk'). END. OCL4.edu/~mjohnson/oracle/plsql/age. /  Another example: http://pages. beverage) BEGIN INSERT INTO Likes VALUES(µIzzy'.nyu.

OCL4. Johnson. CREATE OR REPLACE PROCEDURE <my-proc>(<params>) AS <procedure body as above>. CISDD CUNY. DROP PROCEDURE <my-proc>. Sept 2005 20 . Matthew P.Procedures   Stored database objects that use a PL/SQL statement(s) in their body Create/drop similar to other SQL objects: CREATE PROCEDURE <my-proc> (<params>) AS <procedure body as above>.

Johnson. CISDD CUNY. OCL4.  Now we can call it: EXEC testProcedure Matthew P.Example procedure  Define the procedure: CREATE PROCEDURE testProcedure AS BEGIN INSERT INTO Student VALUES (5. 'Joe'). Sept 2005 21 . END.

Sept 2005 22 . pass-byreference Default is IN  Types must match. Johnson.More details on procedures   Parameter list has name-mode-type triples: Modes: IN. OUT. CISDD CUNY.attribute%TYPE Matthew P. OCL4. or IN OUT Fulfills role similar to pass-by-value v. so can get exact field type: relation.

Procedure I/O example  A procedure to take a beer and price and add it to Joe's menu: Sells(bar. CISDD CUNY. p). price) CREATE PROCEDURE izzyMenu( Are these b IN char(20). END. b. the right p IN double) AS types? BEGIN INSERT INTO Sells VALUES('Izzy''s'. Johnson. beer. Sept 2005 23 . / Matthew P. OCL4.

b. END. p). price) CREATE PROCEDURE izzyMenu( b IN Sells. / Matthew P. OCL4. p IN Sells. beer. Sept 2005 24 .price%TYPE) AS BEGIN INSERT INTO Sells VALUES('Izzy''s'. Johnson.beer%TYPE.Procedure I/O example  A procedure to take a beer and price and add it to Joe's menu: Sells(bar. CISDD CUNY.

CREATE or replace PROCEDURE hike_prices(old_price number. percent_hike number := 5) is Begin new_price := old_price + old_price * percent_hike/100. End. / Matthew P.g. CISDD CUNY. new_price out number. OCL4. Sept 2005 25 .Larger procedure e. Johnson.

dbms_output. Begin hike_prices(currprice.5).Call the procedure Declare currprice number := 20. OCL4.newprice.  But how to use to modify table data? Convert to a function Matthew P. CISDD CUNY. Sept 2005 26  . End.put_line(newprice). newprice number. Johnson.

Johnson. Sept 2005 27 .  Big strength: can be called from SQL itself Matthew P. CISDD CUNY. DROP FUNCTION <functionName>. OCL4.Functions  Like procedures but with return values CREATE FUNCTION <functionName> (<paramList>) RETURN type AS <localDeclarations> BEGIN <functionBody> END.

Sept 2005 28 . END maxval.stern. CISDD CUNY.edu/~mjohnson/oracle/plsql/maxval. Johnson. b IN int) RETURN int AS BEGIN IF a > b THEN RETURN a.10)).nyu.  http://pages. maxval(5. ELSE RETURN b. END IF. INSERT INTO R VALUES('abc'. OCL4.sql Matthew P.Function example CREATE OR REPLACE FUNCTION maxval(a IN int.

Sept 2005 29  . OCL4. although different Matthew P.Hike function CREATE or replace FUNCTION hike_pricesf(old_price number. percent_hike number := 5) return number is Begin return old_price + old_price * percent_hike/100. Johnson. CISDD CUNY. End. /  Now can use directly in update statements NB: had to use different name for ftn Same namespace for ftns & procs.

Johnson. CISDD CUNY.sql file In sqlplus.PUT_LINE (maxval(5.10))  http://pages.nyu. execute .How to run scripts    Don¶t want to type ftns into sqlplus by hand Define them in a . we can call functions See SQL> exec DBMS_OUTPUT.stern. OCL4. Sept 2005 30 .edu/~mjohnson/oracle/plsql/plsql.txt Matthew P.sql Runs commands in file Here. defines function  Now.sql file SQL> @maxval.

Can use: SQL> SET ECHO ON Matthew P. CISDD CUNY.How to run scripts  Can also use the start command: SQL> START maxval. Johnson. OCL4.sql   If no file extension is given. Sept 2005 31    .sql Scripts can call other scripts Use @ for current dir. . @@ for dir of current script Scripts are not (by default) echoed.sql is assumed Can use full paths: SQL> @c:\somewhere\maxval.

Johnson. Matthew P. as seen Can also select the ftn value from dual SQL> select(wordcount('hi there') from dual.Calling functions and procedures     Procedures can simple executed. OCL4. ftns can¶t How to just call a ftn? Can use dbms_output. Sept 2005 32 . CISDD CUNY.

OCL4.  Also. it persists until it¶s dropped CREATE OR REPLACE FUNCTION «  Stored procs are stored in the DB itself In user_procedures in Oracle SELECT object_name from user_procedures. CISDD CUNY. Sept 2005 33 .Stored ftns & procs persist  Once a function or procedure is created. Johnson. can describe ftns and procs: SQL> describe wordcount Matthew P.

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

Johnson.Getting errors  Simply says: Warning: Function created with compilation errors. CISDD CUNY. OCL4. Sept 2005 35 . say SHOW ERR(ORS) Can also get errors per object: SQL> show errors function wordcount   Warning: must get object type right! Can also look at user_errors tbl directly Matthew P.   To get actual errors.

orafaq.fsnet.unix.ilook.co.More on PL/SQL  O¶Reilly¶s Oracle PL/SQL Programming: http://www. Sept 2005 36 . OCL4.com/scripts/ Matthew P. Johnson.uk/ora_sql/sqlmain2.org.html  Oracle FAQ's Script and Code Exchange: http://www. CISDD CUNY.geocities.com/cliktoprogram/plsql/introduction.htm  Introduction to PL/SQL: http://www.ua/orelly/oracle/prog2/ This lecture somewhat follows 3rd edition of this book  PL/SQL Reference & Tutorial: http://www.

Sept 2005 37 . Johnson. lab 6 (exercises 1-3) Matthew P.Break  Lab 5. OCL4. CISDD CUNY.

Agenda   A little more PL/SQL lecture Go through some exercises More PL/SQL lab« Later: go through some PL/SQL exercises«   Matthew P. CISDD CUNY. Sept 2005 38 . OCL4. Johnson.

CISDD CUNY. END. BEGIN year_total := 0. Johnson.Subblocks  Blocks may contain blocks. Matthew P. /* Nested anonymous block */ DECLARE month_total NUMBER. BEGIN month_total := year_total / 12. END. Sept 2005 39 . for narrower scope: CREATE OR REPLACE PROCEDURE calc_totals IS year_total NUMBER. OCL4.

nyu.sql Matthew P. Johnson. Sept 2005 40 .Branching    IF±THEN statements use THEN Must end with END IF Use ELSIF in place of ELSE IF IF <condition> THEN <statement(s)> ELSIF <statement(s)> END IF.  Example: http://pages.edu/~mjohnson/dbms/eg/lec19/maxval. CISDD CUNY. OCL4.stern.

Johnson. CISDD CUNY.More ifs IF <condition> THEN ELSE END IF. Sept 2005 41 . OCL4. Matthew P. IF <expression> THEN ELSEIF <expression> ELSE END IF.

Multiple elsifs  An if statement can have multiple elseifs: IF salary >= 10000 AND salary <= 20000 THEN give_bonus(employee_id. END IF. Sept 2005 42 . 1000). ELSIF salary > 40000 THEN give_bonus(employee_id. Matthew P. Johnson. 400). OCL4. CISDD CUNY. 1500). ELSIF salary > 20000 AND salary <= 40000 THEN give_bonus(employee_id.

OCL4. END IF. Johnson. 43 Matthew P.Nested ifs  As usual. if statements can be nested: Can often be replaced with an ANDed condition  IF condition1 THEN IF condition2 THEN statements2 ELSE IF condition3 THEN statements3 ELSIF condition4 THEN statements4 END IF. CISDD CUNY. Sept 2005 . END IF.

Johnson. CISDD CUNY. Sept 2005 44 . OCL4.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.

not tables Literals or vars Matthew P. numbers. Johnson. CISDD CUNY. ELSE statements_else END CASE. chars.Simple case statements  General form:   ELSE is optional expression and results are scalars CASE expression WHEN result1 THEN statements1 WHEN result2 THEN statements2 . etc.. Sept 2005 45 ... strings. OCL4.

OCL4. Matthew P. CISDD CUNY. ELSE RAISE invalid_employee_type.Simple case e.g. Johnson. CASE employee_type WHEN 'S' THEN award_salary_bonus(employee_id). END CASE. Sept 2005 46 . WHEN 'H' THEN award_hourly_bonus(employee_id). WHEN 'C' THEN award_commissioned_bonus(employee_id).

Johnson. «  Can use a NULL statement in the ELSE clause Matthew P.Simple case·s ELSE clause  This ELSE is optional. OCL4. but if omitted. begin case x when 2 then dbms_output.  Run example: declare x number := 1. you get an implicit else clause: ELSE RAISE CASE_NOT_FOUND. Sept 2005 47 . CISDD CUNY.put_line('2').

CASE statements in SQL 

By the way: CASE statements are now supported in Oracle SQL itself
SELECT CASE WHEN comm is null THEN 0 ELSE comm END FROM emp;

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


Loop example

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


More loops 

Infinite loop:

LOOP executable_statements; END LOOP; 

while loop:

WHILE condition LOOP executable_statements; END LOOP;

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


More loops  Numerical for loop: FOR for_index IN low_value . high_value LOOP executable_statements. Sept 2005 51 . Johnson.  Cursor for loop: FOR record_index IN my_cursor LOOP executable_statements.. END LOOP. OCL4. END LOOP. Matthew P. CISDD CUNY.

CISDD CUNY. inside_a_word := FALSE.stern. 1)) < 33 OR i > len THEN IF inside_a_word THEN words := words + 1.len + 1 LOOP IF ASCII(SUBSTR(str. Johnson. RETURN words. inside_a_word BOOLEAN. BEGIN FOR i IN 1. Sept 2005 END. i.sql Word count program CREATE OR REPLACE FUNCTION wordcount (str IN VARCHAR2) RETURN PLS_INTEGER AS /* words PLS_INTEGER := 0.http://pages. END IF.edu/~mjohnson/oracle/plsql/wordcount.nyu. OCL4. END LOOP. 52 . ***Commented out for intentional error*** */ len PLS_INTEGER := NVL(LENGTH(str). ELSE inside_a_word := TRUE. Matthew P. END IF..0).

Sept 2005 53 .room_number). update_bill (occupancy_rec. OCL4. BEGIN OPEN occupancy_cur. occupancy_rec. CISDD CUNY. END. Johnson. occupancy_rec occupancy_cur%ROWTYPE. for loop cursors DECLARE CURSOR occupancy_cur IS SELECT pet_id. room_number FROM occupancy WHERE occupied_dt = TRUNC (SYSDATE). END LOOP. CLOSE occupancy_cur. LOOP FETCH occupancy_cur INTO occupancy_rec.pet_id. Matthew P. EXIT WHEN occupancy_cur%NOTFOUND.Explicit cursors v.

Explicit cursors v.pet_id. BEGIN FOR occupancy_rec IN occupancy_cur LOOP update_bill (occupancy_rec. for loop cursors DECLARE CURSOR occupancy_cur IS SELECT pet_id. Sept 2005 54 . CISDD CUNY. OCL4. END LOOP. END. occupancy_rec. Johnson.room_number). room_number FROM occupancy WHERE occupied_dt = TRUNC (SYSDATE). Matthew P.

CISDD CUNY. end. Johnson. / Matthew P. begin select prodname into pn from products where mfg = manuf. Sept 2005 55 . OCL4. return pn.Using query results: SELECT « INTO create or replace function getprod(manuf varchar) return varchar as pn varchar(255).

Johnson. begin select prodname into pn from products where mfg = manuf. Exception When TOO_MANY_ROWS then dbms_output. return pn.put_line('got too many'). Sept 2005 56 . / Matthew P. OCL4.SELECT « INTO and exceptions create or replace function getprod(manuf varchar) return varchar as pn varchar(255). end. CISDD CUNY.

  Can also grant to particular roles or everyone: SQL> GRANT EXECUTE ON wordcount TO dba_role.Programs and rights By default. Sept 2005 57  . CISDD CUNY. Johnson. must GRANT them permission: SQL> GRANT EXECUTE ON wordcount TO george. OCL4. Wider/narrower grant ops are independent« Matthew P.  Permissions can be revoked: SQL> REVOKE EXECUTE FROM wordcount TO george. only the creator of a program may run it (apart from the admin)  If others should run. SQL> GRANT EXECUTE ON wordcount TO public.

etc. Johnson.Packages  Functions and procedures (and vars) can be grouped in packages Like Java packages. C++ namespaces. Sept 2005 58 .  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. CISDD CUNY. OCL4.

g. Sept 2005 59 .edu/~mjohnson/oracle/ plsql/numsys.sql Matthew P. OCL4.Package e.   Run example: http://pages. Johnson.stern.nyu. CISDD CUNY.

etc. CISDD CUNY. Sept 2005 60 . Matthew P.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 IMMEDIATE <string>. created from concatenation. OCL4.  The string can be passed in. Johnson.

/ Matthew P. return retval. CISDD CUNY. begin execute immediate 'select count(*) from ' || tabname into retval.: write function to return number rows in an arbitrary table CREATE OR REPLACE FUNCTION rowCount ( tabname IN VARCHAR2) return integer as retval integer. Sept 2005 61 . OCL4.Dynamic PL/SQL  E. end.g. Johnson.

OCL4.: CREATE OR REPLACE procedure dropproc(procname in varchar2) as begin execute immediate 'drop procedure ' || procname.Dynamic PL/SQL for DDL   Ordinarily can¶t do DDL in PL/SQL But you can in dynamic PL/SQL Here¶s an e. Johnson.g. / Matthew P. end. Sept 2005 62  . CISDD CUNY.

edu/~mjohnson/dbms/plsql/ Matthew P.sql  Converting between bases: http://pages.stern. Johnson.edu/~mjohnson/dbms/plsql/ fact.sql  Directory of examples: http://pages. Sept 2005 63 .Live examples  Factorial function: http://pages.nyu. OCL4.nyu.stern.edu/~mjohnson/dbms/plsql/ numsys.nyu. CISDD CUNY.stern.

Sign up to vote on this title
UsefulNot useful