Stored Procedure Trigger
Stored Procedure Trigger
Trigger
Introduction
A Procedure or Function is a logically grouped set of SQL
and PL/SQL statements that performs a specific task.
A stored procedure or stored function is a named PL/SQL
code block that has been compiled and stored in one of the
Oracle engine’s system tables.
Introduction
Procedures and functions are stored in Oracle database and can be
called by any PL/SQL block.
While creating a procedure or function, Oracle engine performs
following steps:
Compiles the procedure or function.
Stores procedure or function in database.
During compilation, if error occurs then an invalid procedure or
function is created. To view the errors,
SELECT * FROM USER_ERRORS;
When procedure or function is invoked, Oracle engine loads the
compiled procedure or function in a memory area called System
Global Area (SGA).
To execute the procedure or function, Oracle engine
performs following task:
Verifies user access
Verifies procedure or function validity
Executes procedure or function
To verify the validity of procedure or function following
select statement is used:
SELECT <ObjectName>, <ObjectType>, <Status> FROM
<UserObjects> where <ObjectType>=‘PROCEDURE’;
Advantages
Security
Performance
Memory Allocation
Productivity
Integrity
Difference between
Procedure and Function
A function must return a value back to caller. A function can
return only one value to the calling PL/SQL code block.
By defining multiple OUT parameters in a procedure,
multiple values can be passed to the caller.
Parts of Procedure
Declarative part: It can declare cursors, constants,
variables, exceptions and subprograms.
Executable part: It contains SQL and PL/SQL statements.
Exception-handling part (Optional): It deals with
exceptions that may be raised during the execution of code in
executable part.
Stored Procedure
CREATE OR REPLACE PROCEDURE [Schema.]
<ProcedureName>
(<Argument> {IN, OUT, IN OUT} <data_type>,…)
{IS,AS}
<variable> <datatype>;
BEGIN
<PL/SQL body>
EXCEPTION
<Exception PL/SQL block>
END:
Example
CREATE OR REPLACE Procedure UpdateE( name_in IN varchar2 )
IS
cnumber number; cursor c1 is SELECT EMPNO FROM EMP WHERE Ename =
name_in;
BEGIN
open c1; fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
INSERT INTO EMP ( ENAME, EMPNO )VALUES ( name_in, cnumber );
DBMS_OUTPUT.PUT_LINE('INSERTED');
ELSE
DBMS_OUTPUT.PUT_LINE(cnumber);
end if; close c1;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -
ERROR- '||SQLERRM);
END;
Call Procedure
Example:
If name is not present in emp table then it is inserted
BEGIN
UpdateE('ND');
END;