PL/SQL
PL/SQL
Agenda:
Basic PL/SQL block structure
Example procedures and
functions
Executing PL/SQL from SQL*Plus
Exceptions
Packages
BEGIN
Execution Section
EXCEPTION
Exception Section
END;
REQUIRED
PL/SQL
Is not case sensitive
Uses the same datatypes as SQL
Also has boolean, record, table, varray and LOB
Allows reference datatypes
%type and %rowtype
Allows comments
/* and */ for multiline and -- for single line
PL/SQL - example
DECLARE
loop_count BINARY_INTEGER := 0;
BEGIN
LOOP
INSERT INTO count_table VALUES (loop_count);
DBMS_output.put_line
(loop_count is || to_char(loop_count));
loop_count := loop_count + 1;
EXIT WHEN loop_count = 6;
END LOOP;
END;
Scott.GIVE_RAISE
CREATE OR REPLACE PROCEDURE give_raise (
p_deptno IN number,
p_raise_percent IN number )
AS
BEGIN
update emp
set sal = sal + (sal * p_raise_percent * .01)
where deptno = p_deptno;
commit;
END give_raise;
Another example
CREATE OR REPLACE FUNCTION get_company_name
(comp_id_in IN company.id%TYPE)
RETURN varchar2
IS
cname company.name%TYPE;
BEGIN
SELECT name INTO cname FROM company
WHERE id = comp_id_in;
RETURN cname;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NULL;
WHEN OTHERS
DBMS_OUTPUT.PUT_LINE (error code= || SQLCODE);
DBMS_OUTPUT.PUT_LINE (error msg= || SQLERRM);
END;
Cursors
Implicit
Created automatically in Oracle
Dont need to be declared
Can be used only when 1 and only 1 record is
returned
Explicit
Declared in declaration section
attributes specifying the state of the cursor
%notfound, %found, %rowcount, %isopen
then
select get_company_name(1) from dual;
exec :a := f1;
execute :a := f1;
call f1() into :a;
begin :a := f1; end;
select f1 from dual;
exec p1;
execute p1;
call p1();
begin p1; end;
Debugging PL/SQL
Remember the Oracle error message
facility will help figure out the problem
Comment out lines that may be causing
problems
Use dbms_output.put_line to show
variable values
Fix from the top down 1 error may
cause multiple error messages
Data dictionary views: user_errors,
user_source
Exception types
NO_DATA_FOUND
TOO_MANY_ROWS
DUP_VAL_ON_INDEX
And more
Create your own
DBMS_OUTPUT.PUT_LINE
(Unable to determine gender of individual!);
END;
Packages
Structure of Packages
package header vs. package body
Advantages of Packages
invalidated objects
hiding details of code
code maintainability