Professional Documents
Culture Documents
Plsqlacc PDF
Plsqlacc PDF
Prerequisites
SQL
SQL
SQL
Application SQL Other DBMSs
SQL
SQL
IF...THEN
SQL Oracle with
Application PL/SQL
ELSE
SQL
END IF;
2003 Accenture All Rights Reserved. SQL 7
Benefits of PL/SQL
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
3 vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
xxxxxxxxxxxxxx vvvvvvvvvvvvvv
Oracle Oracle Oracle vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
Portal Discoverer Forms vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
Developer vvvvvvvvvvvvvv
xxxxxxxxxxxxxx
vvvvvvvvvvvvvv
4
Scott
BEGIN [Mandatory] <Variables>
<Cursors>
<User defined exceptions>
EXCEPTION [Optional] [begin]
<PL/SQL statements>
[exception]
END; [Mandatory] <Exception handling>
end;
Anonymous block
Stored Procedure
Function
Package
Trigger
An anonymous block
cannot take input arguments and return output values
cannot be called concurrently by multiple users
is not stored in the data dictionary
Example1:
DECLARE
Emp_number INTEGER := 7369;
Emp_name VARCHAR2(10);
BEGIN
SELECT Ename INTO Emp_name FROM Emp
WHERE Empno = emp_number;
DBMS_OUTPUT.PUT_LINE('Employee name is ' || Emp_name);
EXCEPTION WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No such employee: ' ||
Emp_number);
END;
/
Anonymous/Named Block or
DECLARE (Optional) Stored Procedure or Function
Variables, Cursors
Variable Declaration Section
Exceptions etc...
BEGIN (Mandatory)
SQL Statements
Program Section
PL/SQL Statements
EXCEPTION (Optional)
END; (Mandatory)
/
PL/SQL variables
Scalar (ex: NUMBER, VARCHAR2 etc...)
Composite (ex: TABLE, VARRAY etc...)
Reference (ex: REF cursors etc...)
LOB (large objects) (ex: LOB, BLOB etc...)
Non-PL/SQL variables
Bind and host variables
Front End
Display
O/S
Bind Variable
Server
SQL> begin
2 select ename, sal
3 into :h_ename, :h_sal
4 from emp
5 where empno=7369;
6 end;
/
View Output
Use DBMS_OUTPUT.PUT_LINE() in the PL/SQL block
Type set serverout on; from the SQL prompt
View Error
Type show errors; form the SQL prompt
IF Statement (IF ... THEN [ELSIF ... THEN ELSE ...] END IF;)
CASE Statement
Simple Loop
While Loop
FOR Loop
CASE
WHEN bool_expr1 THEN
sequence_of_statements;
WHEN bool_expr2 THEN
sequence_of_statements;
...
[ELSE
sequence_of_statements;]
END CASE;
Select creates a virtual table, which exists only for the duration of
execution of the SQL statement
The select statement can be used with the BULK Collect clause.
This is used to retrieve multiple rows of data
1)DECLARE
emp_rec emp%ROWTYPE;
CURSOR c1 IS
SELECT deptno, dname, loc FROM dept;
2)dept_rec c1%ROWTYPE;
COMMIT
ROLLBACK
SAVEPOINT
- If you make a mistake like deleting the wrong row from a table, a
rollback restores the original data
CURSOR Variable
1. Writing a Cursor in the PL/SQL - Declaring Cursor Variable
2. Opening Cursor - Cursor Variable points to the Context
Area/Cursor
Types of cursors
1. Implicit Cursor
2. Explicit Cursor
%FOUND
Boolean variable, which evaluates to true if the last fetch,
succeeded
%ROWCOUNT
Its a numeric attribute, which returns number of rows fetched by
the cursor so far
%ISOPEN
A Boolean variable, which evaluates to true if the cursor is opened
otherwise to false
2003 Accenture All Rights Reserved. 59
Distinguish between Implicit
and Explicit Cursor
Implicit Cursors
Any SQL or DML statements that are written in the PL/SQL
executable section is declared as an implicit cursor by PL/SQL
Engine
Cursor operations are automatically performed by Oracle.
We do not have any programmatic control on the Implicit
cursors
Only recently executed SQL or DML statements information
can be read from the cursors attributes
Explicit Cursors
Only SQL statements that are explicitly declared as cursors in
the declaration section of the PL/SQL block is treated as an
Explicit Cursor
OPEN
OPEN <cursor-name>;
FETCH
FETCH <cursor-name> INTO <var1,var2,...>;
CLOSE
CLOSE <cursor-name>;
for t1 in c_emp(10)
loop
dbms_output.put_line(t1.ename);
end loop;
ELSE
for t1 in c_emp(20)
loop
dbms_output.put_line(t1.ename);
end loop;
END IF;
END;
/
The OF list of the FOR UPDATE clause does not restrict you to
changing only those columns listed
DECLARE
CURSOR c_emp IS SELECT ename FROM emp FOR UPDATE
OF sal NOWAIT;
BEGIN
FOR v_emp IN c_emp LOOP
UPDATE emp SET sal = (sal+comm)*1.2
WHERE CURRENT OF c_emp;
END LOOP;
END;
PROCEDURE sp_cur_example
(pc_emp OUT c_emptype) AS
BEGIN
OPEN c_emp FOR select * FROM emp;
END;
PL/SQL Table
PL/SQL Record
Example:
Unbounded or Unconstrained
There is no predefined limit to the number of rows in a PL/SQL
table. The PL/SQL table grows dynamically as you add more rows
to the table
No rows for PL/SQL tables are allocated for this structure when it
is defined
Homogeneous elements
As a PL/SQL table can have only a single column, all rows in a
PL/SQL table contain values of the same datatype
Indexed by integers
PL/SQL tables currently support a single indexing mode: by
BINARY_INTEGER. This number acts as the "primary key" of the
PL/SQL table. The range of a BINARY_INTEGER is from -231-1
to 231-1
2003 Accenture All Rights Reserved. 85
PL/SQL Table Characteristics
The PL/SQL table structure is not a part of the SQL language
Declare the actual table based on that table type. The declaration
of a PL/SQL table is a specific instance of a generic datatype
<table_name> <table_type>;
Syntax:
<table_name> ( <primary_key_value> )
1) Direct assignment
2) Iterative assignment
3) Aggregate assignment
FOR j IN 1..10
LOOP
DBMS_OUTPUT.PUT_LINE(TO_CHAR(iter_tab(j)));
END LOOP;
2003 Accenture All Rights Reserved. 95
Delete data from PL/SQL
Table
iter_tab := null_tab;
FOR j IN 1..10
LOOP
DBMS_OUTPUT.PUT_LINE(to_char(iter_tab(j)));
END LOOP;
DBMS_OUTPUT.PUT_LINE('After Print');
END;
/
PL/SQL record as a whole does not have value of its own; instead,
each individual component or field has a value
Example:
PRAGMA Exception
You cannot return to that block after you finish handling the
exception. Instead, control is passed to the enclosing block, if any
DECLARE DECLARE
BEGIN BEGIN
Exception Exception
is raised is raised
EXCEPTION
Exception Exception
END; END;
is trapped is not
trapped
Exception
propagates to
calling environment
2003 Accenture All Rights Reserved. 111
Common Exceptions
System Exceptions the most common errors
WHERE
error_number is a negative integer in the range
20000 .. -20999
message is a character string up to 2048 bytes long
If TRUE, the error is placed on the stack of previous errors
If FALSE (the default), the error replaces all previous errors
The error number and message can be trapped like any Oracle
error
Only one user defined exception can be associated with one Oracle
error with each occurrence of PRAGMA EXCEPTION_INIT
declare
empname VARCHAR2(12);
no_record EXCEPTION;
PRAGMA EXCEPTION_INIT(no_record, 100);
BEGIN
select ename into empname from emp where empno=&9999;
dbms_output.put_line('Name :'||empname);
EXCEPTION
when no_record then
dbms_output.put_line('Error code is ' || SQLCODE);
dbms_output.put_line('Error message is '||SQLERRM);
dbms_output.put_line('No Record found');
END;
/
2003 Accenture All Rights Reserved. 122
PRAGMA Exception
Example 2
Trap for Oracle server error number 2292, an integrity constraint violation
DECLARE
p_deptno number := &deptno;
e_emps_remaining EXCEPTION;
PRAGMA EXCEPTION_INIT (e_emps_remaining, -2292);
BEGIN
DELETE FROM dept WHERE deptno = p_deptno;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE ('No such dept '||to_char(p_deptno));
END IF;
EXCEPTION
WHEN e_emps_remaining THEN
DBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || TO_CHAR(p_deptno)
|| '. Employees exist. ');
END;
2003 Accenture All Rights Reserved. 123
PL/SQL Subprograms
Agenda
Subprogram Structure
Stored Procedures
Functions
Overloading
Has a name
Can take input parameters, and can return output values
Is stored in the data dictionary
Can be called by many concurrent users
Synonyms can be created on stored program units
Data Access and execute privileges can be provided on stored
program units
Procedure
IN parameter
Calling
environment OUT parameter
IN OUT parameter
procedure
BEGIN
EXCEPTION
END;
OUT parameter is like the return value for a function, but it appears in
the parameter list and you can have as many OUT parameters as you
like. Inside the program OUT parameter acts like a variable that has
not been initialized
Example
Alternatively, you can type, SHO ERR (short for SHOW ERRORS) to
see the most recent compilation error
Example:
SELECT empno, ename, total_sal(empno) FROM emp WHERE empno
=7369;
Overloaded functions must differ by more than their return type (the
datatype specified in the RETURN clause of the function)
USER_OBJECTS
USER_SOURCE
To Drop a Function
DROP <Function> <Function_Name>;
Example
DROP FUNCTION total_sal;
/
DROP PROCEDURE MyProc;
/
2003 Accenture All Rights Reserved. 144
Triggers
Agenda
Definition and Advantages
Types of Triggers
INSTEAD OF Triggers
Manipulating Triggers
Within a ROW trigger, reference the value of a column before and after
the data change by prefixing it with the OLD and NEW qualifier
The OLD and NEW qualifiers are available only in ROW triggers
Prefix these qualifiers with a colon (:) in every SQL and PL/SQL
statement
INSERT
TABLE1
INSTEAD OF
Trigger
UPDATE
MY_VIEW TABLE2
Begin
Executable statements
[Exception]
[Exception statements]
End <Package Name> ;