Matthew P. Johnson, OCL4, CISDD CUNY, Sept 20051 OCL4 Oracle 10g: SQL & PL/SQL Session #6 Matthew P. Johnson CISDD, CUNY June, 2005.

Slides:



Advertisements
Similar presentations
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
Advertisements

Oracle PL/SQL IV Exceptions Packages.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
SQL*PLUS, PLSQL and SQLLDR Ali Obaidi. SQL Advantages High level – Builds on relational algebra and calculus – Powerful operations – Enables automatic.
PL/SQL.
Murali Mani Persistent Stored Modules (Stored Procedures) : PSM.
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
PHP Intro/Overview Squirrel Book pages Server-side Scripting Everything you need to know in one slide 1.Web server (with PHP “plug-in”) gets a.
M.P. Johnson, DBMS, Stern/NYU, Sp20041 C : Database Management Systems Lecture #19 Matthew P. Johnson Stern School of Business, NYU Spring, 2004.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #21 M.P. Johnson Stern School of Business, NYU Spring, 2008.
PL/SQL Agenda: Basic PL/SQL block structure
Matthew P. Johnson, OCL1, CISDD CUNY, F20041 OCL1 Oracle 10g: SQL & PL/SQL Session #7 Matthew P. Johnson CISDD, CUNY Fall, 2004.
Programming in Oracle with PL/SQL
Introduction to PL/SQL
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #19 M.P. Johnson Stern School of Business, NYU Spring, 2005.
Matthew P. Johnson, OCL2, CISDD CUNY, January OCL2 Oracle 10g: SQL & PL/SQL Session #8 Matthew P. Johnson CISDD, CUNY Fall, 2004.
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
Dr. James Dullea, CSC8490 Introduction to PL/SQLSlide 1 of 36 7From Prof. Dullea CSC8490 Introduction to PL/SQL Module 01-9 Revised: June 12, 2005 Dr.
Distributed Database Applications COSC 5050 Week Three.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
Stored Procedures, Transactions, and Error-Handling
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
Distributed Database Applications COSC 5050 Week One.
PL SQL Block Structures. What is PL SQL A good way to get acquainted with PL/SQL is to look at a sample program. PL/SQL combines the data manipulating.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Matthew P. Johnson, OCL3, CISDD CUNY, June OCL3 Oracle 10g: SQL & PL/SQL Session #8 Matthew P. Johnson CISDD, CUNY June, 2004.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
1 PL\SQL Dev Templates. 2 TEMPLATE DEFINITION Whenever you create a new program unit, its initial contents are based upon a template which contains pre-defined.
Stored Procedures. Definition a stored procedure is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Implementing The Middle Tier These slides.
1 Real SQL Programming Persistent Stored Modules (PSM) PL/SQL Embedded SQL.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
CREATING STORED PROCEDURES AND FUNCTIONS. Objectives After completing this lecture, you should be able to do the following: Differentiate between anonymous.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Just a Little PHP Programming PHP on the Server. Common Programming Language Features Comments Data Types Variable Declarations Expressions Flow of Control.
PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
Lab 2 Writing PL/SQL Blocks CISB514 Advanced Database Systems.
Introduction to PL/SQL N. Dimililer. About PL/SQL –PL/SQL is an extension to SQL with design features of programming languages. –Data manipulation and.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Matthew P. Johnson, OCL3, CISDD CUNY, June OCL3 Oracle 10g: SQL & PL/SQL Session #7 Matthew P. Johnson CISDD, CUNY June, 2005.
1 Database Design: DBS CB, 2 nd Edition SQL in a Server Environment: Stored Procedure & Embedded SQL Ch. 9.3, 9.4.
1 Introduction to Database Systems, CS420 SQL Persistent Stored Modules (PSM) – Stored Procedure.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
C : Database Management Systems Lecture #20
CMSC-461 Database Management Systems
PL/SQL.
Database Application Development
CPSC-310 Database Systems
CPSC-310 Database Systems
Sa0951a PL/SQL 1: Introduction
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
T. Jumana Abu Shmais – AOU - Riyadh
PL/SQL week10.
Persistent Stored Modules (PSM) PL/SQL Embedded SQL
Chapter 8 Advanced SQL.
Chapter 8 Advanced SQL Pearson Education © 2009.
Database Application Development
Presentation transcript:

Matthew P. Johnson, OCL4, CISDD CUNY, Sept OCL4 Oracle 10g: SQL & PL/SQL Session #6 Matthew P. Johnson CISDD, CUNY June, 2005

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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 PL/SQL Generally speaking can be used wherever SQL can be  sqlplus  embeded SQL  JDBC Can store programs in files (.sql), run later runs code in myprog.sql

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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 PL/SQL: Hello, World BEGIN -- print out message DBMS_OUTPUT.PUT_LINE('Hello World, from PL/SQL'); END; / BEGIN -- print out message DBMS_OUTPUT.PUT_LINE('Hello World, from PL/SQL'); END; /

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept Use start-up script Go to \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 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 DBMS_OUTPUT.PUT_LINE('Hello World, from PL/SQL')

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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 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 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 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 Structure of a block As in Pascal, var declars precede body header--if named DECLARE--optional --var declarations BEGIN --executable statements --queries/updates, etc. EXCEPTION--optional --catch exceptions END; /--to execute header--if named DECLARE--optional --var declarations BEGIN --executable statements --queries/updates, etc. EXCEPTION--optional --catch exceptions END; /--to execute

Matthew P. Johnson, OCL4, CISDD CUNY, Sept PL/SQL code examples One example:  Likes(drinker, beverage) Another example:  BEGIN INSERT INTO Likes VALUES(‘Izzy', ‘milk'); DELETE FROM Likes WHERE drinker = ‘Izzy' AND beverage = ‘Beaujolais Nouveau '; COMMIT; END; / BEGIN INSERT INTO Likes VALUES(‘Izzy', ‘milk'); DELETE FROM Likes WHERE drinker = ‘Izzy' AND beverage = ‘Beaujolais Nouveau '; COMMIT; END; /

Matthew P. Johnson, OCL4, CISDD CUNY, Sept Procedures Stored database objects that use a PL/SQL statement(s) in their body Create/drop similar to other SQL objects: CREATE PROCEDURE ( ) AS ; CREATE PROCEDURE ( ) AS ; DROP PROCEDURE ; CREATE OR REPLACE PROCEDURE ( ) AS ; CREATE OR REPLACE PROCEDURE ( ) AS ;

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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

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

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

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

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept Functions Like procedures but with return values Big strength: can be called from SQL itself CREATE FUNCTION ( ) RETURN type AS BEGIN END; CREATE FUNCTION ( ) RETURN type AS BEGIN END; DROP FUNCTION ;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept Function example CREATE OR REPLACE FUNCTION maxval(a IN int, b IN int) RETURN int AS BEGIN IF a > b THEN RETURN a; ELSE RETURN b; END IF; END maxval; CREATE OR REPLACE FUNCTION maxval(a IN int, b IN int) RETURN int AS BEGIN IF a > b THEN RETURN a; ELSE RETURN b; END IF; END maxval; INSERT INTO R VALUES('abc', maxval(5,10));

Matthew P. Johnson, OCL4, CISDD CUNY, Sept Hike function Now can use directly in update statements NB: had to use different name for ftn  Same namespace for ftns & procs, although different 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; End; / 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; End; /

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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  Runs commands in file  Here, defines function Now, we can call functions See SQL> exec DBMS_OUTPUT.PUT_LINE (maxval(5,10))

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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> select(wordcount('hi there') from dual;

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

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

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept More on PL/SQL O’Reilly’s Oracle PL/SQL Programming:   This lecture somewhat follows 3 rd edition of this book PL/SQL Reference & Tutorial:  Introduction to PL/SQL:  Oracle FAQ's Script and Code Exchange: 

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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 Subblocks Blocks may contain blocks, for narrower scope: CREATE OR REPLACE PROCEDURE calc_totals IS year_total NUMBER; BEGIN year_total := 0; /* Nested anonymous block */ DECLARE month_total NUMBER; BEGIN month_total := year_total / 12; END; CREATE OR REPLACE PROCEDURE calc_totals IS year_total NUMBER; BEGIN year_total := 0; /* Nested anonymous block */ DECLARE month_total NUMBER; BEGIN month_total := year_total / 12; END;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept Branching IF–THEN statements use THEN Must end with END IF Use ELSIF in place of ELSE IF Example:  IF THEN ELSIF END IF; IF THEN ELSIF END IF;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept More ifs IF THEN ELSE END IF; IF THEN ELSE END IF; IF THEN ELSEIF ELSE END IF; IF THEN ELSEIF ELSE END IF;

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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; IF condition1 THEN IF condition2 THEN statements2 ELSE IF condition3 THEN statements3 ELSIF condition4 THEN statements4 END IF;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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 Simple case statements General form: ELSE is optional expression and results are scalars  numbers, chars, strings, etc.; not tables  Literals or vars CASE expression WHEN result1 THEN statements1 WHEN result2 THEN statements2... ELSE statements_else END CASE; CASE expression WHEN result1 THEN statements1 WHEN result2 THEN statements2... ELSE statements_else END CASE;

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

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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; SELECT CASE WHEN comm is null THEN 0 ELSE comm END FROM emp;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept Loop example DECLARE i NUMBER := 1; BEGIN LOOP INSERT INTO T1VALUES(i,i); i := i+1; EXIT WHEN i>100; END LOOP; END; / 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 More loops Infinite loop: while loop: LOOP executable_statements; END LOOP; LOOP executable_statements; END LOOP; WHILE condition LOOP executable_statements; END LOOP; WHILE condition LOOP executable_statements; END LOOP;

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept Word count program CREATE OR REPLACE FUNCTION wordcount (str IN VARCHAR2) RETURN PLS_INTEGER AS /* words PLS_INTEGER := 0; ***Commented out for intentional error*** */ len PLS_INTEGER := NVL(LENGTH(str),0); inside_a_word BOOLEAN; BEGIN FOR i IN 1..len + 1 LOOP IF ASCII(SUBSTR(str, i, 1)) len THEN IF inside_a_word THEN words := words + 1; inside_a_word := FALSE; END IF; ELSE inside_a_word := TRUE; END IF; END LOOP; RETURN words; END; CREATE OR REPLACE FUNCTION wordcount (str IN VARCHAR2) RETURN PLS_INTEGER AS /* words PLS_INTEGER := 0; ***Commented out for intentional error*** */ len PLS_INTEGER := NVL(LENGTH(str),0); inside_a_word BOOLEAN; BEGIN FOR i IN 1..len + 1 LOOP IF ASCII(SUBSTR(str, i, 1)) len THEN IF inside_a_word THEN words := words + 1; inside_a_word := FALSE; END IF; ELSE inside_a_word := TRUE; END IF; END LOOP; RETURN words; END;

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

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

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

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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: Permissions can be revoked: Can also grant to particular roles or everyone: Wider/narrower grant ops are independent… SQL> GRANT EXECUTE ON wordcount TO george; SQL> REVOKE EXECUTE FROM wordcount TO george; SQL> GRANT EXECUTE ON wordcount TO dba_role; SQL> GRANT EXECUTE ON wordcount TO public; SQL> GRANT EXECUTE ON wordcount TO dba_role; SQL> GRANT EXECUTE ON wordcount TO public;

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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 Package e.g. Run example: plsql/numsys.sql plsql/numsys.sql

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

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

Matthew P. Johnson, OCL4, CISDD CUNY, Sept 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 OR REPLACE procedure dropproc(procname in varchar2) as begin execute immediate 'drop procedure ' || procname; end; / CREATE OR REPLACE procedure dropproc(procname in varchar2) as begin execute immediate 'drop procedure ' || procname; end; /

Matthew P. Johnson, OCL4, CISDD CUNY, Sept Live examples Factorial function:  fact.sql fact.sql Converting between bases:  numsys.sql numsys.sql Directory of examples: 