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 

Sept 2005 4 . set vars to vals of expressions Print output Define (optional) procedures.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. OCL4. Johnson. functions Cursors    PL/SQL can compute n! Matthew P. CISDD CUNY.

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

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

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

CISDD CUNY. VBA. OCL4. PHP. Sept 2005 8 Don¶t require functions/procedures  Weakly typed  . Excel macros. small problems Big solutions v. Python. Unix shell. etc. Java. Perl. Johnson. 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. Scripting languages: PL/SQL. DOS batch files.Scripting languages   Big problems v. small solutions Programming languages: C/C++.

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

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

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

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

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

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

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

OCL4. null true != µtrue¶  No date literals. 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. 12e-5.05E19. 12. 'AbC'.Literals   Numbers: 123. 3. CISDD CUNY. Sept 2005 16 . false.3. Johnson. null String: 'abc'.

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

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

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

OCL4. CREATE OR REPLACE PROCEDURE <my-proc>(<params>) AS <procedure body as above>. Sept 2005 20 .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>. DROP PROCEDURE <my-proc>. Johnson. Matthew P. CISDD CUNY.

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

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

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

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

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

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

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

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

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

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

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

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

can describe ftns and procs: SQL> describe wordcount Matthew P. 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.Stored ftns & procs persist  Once a function or procedure is created. CISDD CUNY. Johnson. OCL4. Sept 2005 33 .  Also.

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

CISDD CUNY. Sept 2005 35 .   To get actual errors. Johnson. 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. OCL4.Getting errors  Simply says: Warning: Function created with compilation errors.

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

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

Sept 2005 38 .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. Johnson. OCL4.

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

nyu.stern.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.sql Matthew P. Johnson. Sept 2005 40 .edu/~mjohnson/dbms/eg/lec19/maxval. CISDD CUNY. OCL4.

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

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

END IF. CISDD CUNY. 43 Matthew P. 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. END IF. Johnson. Sept 2005 . OCL4.Nested ifs  As usual.

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

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

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

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

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

48

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

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

49

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

50

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

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

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

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

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

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

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

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

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

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

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

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

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

Sign up to vote on this title
UsefulNot useful