Вы находитесь на странице: 1из 11

PL/SQL NOTES Page 1 of 11

PL/SQL Block consists of three sections:


 The Declaration section (optional).
 The Execution section (mandatory).
 The Exception Handling (or Error) section (optional).
Declaration Section:

The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This section is
optional and is used to declare any placeholders like variables, constants, records and cursors, which are
used to manipulate data in the execution section. Placeholders may be any of Variables, Constants and
Records, which stores data temporarily. Cursors are also declared in this section.

Execution Section:

The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends with END.
This is a mandatory section and is the section where the program logic is written to perform any task. The
programmatic constructs like loops, conditional statement and SQL statements from the part of execution
section.

Exception Section:

The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This section is
optional. Any errors in the program can be handled in this section, so that the PL/SQL Blocks terminates
gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abruptly
with errors.

Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks can be nested
within other PL/SQL blocks. Comments can be used to document code.

How a Sample PL/SQL Block Looks


DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;

1. Print Hello World.

Begin
dbms_output.put_line ('Hello World');
end;
/

2. Addition of two numbers.

Declare
NUM1 number:=20;
NUM2 number:=50;
res number:=0;
Begin
res := NUM1+NUM2;
dbms_output.put_line ('Addition '||res);
end;
/
PL/SQL NOTES Page 2 of 11

3. Program to use substitution variable.

DECLARE
v_sal NUMBER(9,2) := &p_annual_sal;
BEGIN
v_sal := v_sal/12;
DBMS_OUTPUT.PUT_LINE ('The monthly salary is ' ||v_sal);
END;
/

IF THEN ELSE STATEMENT

1)
IF condition
THEN
statement 1;
ELSE
statement 2;
END IF;

2)
IF condition 1
THEN
statement 1;
statement 2;
ELSIF condtion2 THEN
statement 3;
ELSE
statement 4;
END IF

4. FIND THE GREATES AMONG TWO NUMBER

Declare
a number;
b number;

Begin
dbms_output.put_line('Enter a:');
a:=&a;
dbms_output.put_line('Enter b:');
b:=&b;
if (a>b)
then
dbms_output.put_line('A is GREATEST'||A);
else
dbms_output.put_line('B is GREATEST'||B);
end if;
End;
/
PL/SQL NOTES Page 3 of 11

5. FIND THE GREATES AMONG THREE NUMBER

Declare
a number;
b number;
c number;
Begin
dbms_output.put_line('Enter a:');
a:=&a;
dbms_output.put_line('Enter b:');
b:=&b;
dbms_output.put_line('Enter c:');
c:=&C;
if (a>b) and (a>c)
then
dbms_output.put_line('A is GREATEST'||A);
elsif (b>a) and (b>c)
then
dbms_output.put_line('B is GREATEST'||B);
else
dbms_output.put_line('C is GREATEST'||C);
end if;
End;
/

WHILE <condition> LOOP

· <loop_body>

END LOOP;

6. --SUM OF 100 ODD NUMBER .. WHILE LOOP

declare
n number;
endvalue number;
sum1 number default 0;
begin
endvalue:=&endvalue;
n:=1;
while (n < endvalue)
loop
sum1:=sum1+n;
n:=n+2;
end loop;
dbms_output.put_line('Sum of odd numbers between 1 and ' || endvalue || ' is ' || sum1);
end;
/
PL/SQL NOTES Page 4 of 11

FOR <var> IN <start>..<finish> LOOP

· <loop_body>

END LOOP;

7. --SUM OF odd NUMBERS USING USER INPUT...for loop

declare
n number;
sum1 number default 0;
endvalue number;
begin
endvalue:=&endvalue;
n:=1;
for n in 1.. endvalue
loop
if mod(n,2)=1
then
sum1:=sum1+n;
end if;
end loop;
dbms_output.put_line('sum = ' || sum1);
end;
/

8. Program to insert a row /record in emp table

begin
insert into emp(empno,ename,hiredate,sal,comm,mgr,job,deptno) values(1000,'Kiran','10-Jan-
2001',12000,null,4422,'Manager',10);
commit;
end;
/

CURSORS

Cursor is a work area in pl/sql which is used by sql server used to store the result of a query. Each
column value is pointed using pointer. You can independently manipulate cursor values. A bit about it's
working..... suppose you ask for a query stored in the server ... at first a cursor consisting of query result
is created in server...now the cursor is transferred to the client where again cursor is created and hence
the result is displayed......

Cursors are of 2 types: implicit and explicit.......implicit cursors are created by oracle engine itself while
explicit cursors are created by the users......cursors are generally used in such a case when a query
returns more than one rows....normal pl/sql returning more than one rows givens error but using cursor
this limitation can be avoided....so cursors are used....
PL/SQL NOTES Page 5 of 11

Cursor attributes

%ISOPEN == returns true if Cursor is open, false otherwise


%FOUND == returns true if record was fetched successfully, false otherwise
%NOTFOUND == returns true if record was not fetched successfully, false otherwise
%ROWCOUNT == returns number of records processed from the cursor.

Very important: Cursor can be controlled using following 3 control statements. They are Open, Fetch,
Close.....open statement identifies the active set...i.e. query returned by select statement...close
statement closes the cursor...and fetch statement fetches rows into the variables...Cursors can be made
into use using cursor for loop and fetch statement...we will see the corresponding examples...

EXAMPLES

1. --EXAMPLE OF SQL%FOUND (IMPLICIT CURSORS)

begin
update emp set sal=sal+sal *0.15
where empno = &empno;
if sql%found then
dbms_output.put_line('employee record modified successfully');
else
dbms_output.put_line('employee no does not exist');
end if;
commit;
end;

2. --EXAMPLE FOR SQL%NOTFOUND (IMPLICIT CURSORS)

begin
update emp set sal = sal+sal*0.15 where empno = &empno;
if sql%notfound then
dbms_output.put_line('employee no . does not exist');
else
dbms_output.put_line('employee record modified successfully');
end if;
end;
/
PL/SQL NOTES Page 6 of 11

3. --EXAMPLE FOR SQL%ROWCOUNT (IMPLICIT CURSORS)

declare
rows_affected char(4);
begin
update emp set sal = sal+sal*0.15 where job='CLERK';
rows_affected := to_char(sql%rowcount);
if sql%rowcount > 0 then
dbms_output.put_line(rows_affected || 'employee records modified successfully');
else
dbms_output.put_line('There are no employees working as CLERKS');
end if;
end;
/

Syntax of explicit cursor: Cursor cursorname is sql select statement;


Syntax of fetch : fetch cursorname into variable1, variable2...;
Syntax of close; close cursorname;
Syntax of open cursor; open cursorname;

4. --ANOTHER EG DISPLAYING VALUE OF A TABLE

The %ROWTYPE attribute lets you declare a record that represents a row in a table or view. For each
column in the referenced table or view, the record has a field with the same name and data type. To
reference a field in the record, use record_name.field_name.

DECLARE
CURSOR c1 IS SELECT * FROM emp;
e_rec emp%rowtype;
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO e_rec;
DBMS_OUTPUT.PUT_LINE('Number: ' || ' ' || e_rec.empno);
DBMS_OUTPUT.PUT_LINE('Name : ' || ' ' || e_rec.ename);
DBMS_OUTPUT.PUT_LINE('Salary: ' || ' ' || e_rec.sal);
EXIT WHEN c1%NOTFOUND;
END LOOP;
CLOSE c1;
END;
/
PL/SQL NOTES Page 7 of 11

5. -- Display details of Highest 10 salary paid employee


DECLARE
CURSOR c1 IS SELECT * FROM emp ORDER BY sal DESC;
e_rec emp%rowtype;
BEGIN
FOR e_rec IN c1
LOOP
DBMS_OUTPUT.PUT_LINE('Number: ' || ' ' || e_rec.empno);
DBMS_OUTPUT.PUT_LINE('Name : ' || ' ' || e_rec.ename);
DBMS_OUTPUT.PUT_LINE('Salary: ' || ' ' || e_rec.sal);
EXIT WHEN c1%ROWCOUNT >= 10;
END LOOP;
END;
/

PROCEDURES AND FUNCTIONS


procedure is a subprogram...which consists of a set of sql statement. Procedures are not very different
from functions. A procedure or function is a logically grouped set of SQL and PL/SQL statements that
perform a specific task. A stored procedure or function is a named pl/sql code block that have been
compiled and stored in one of the oracle engines's system tables.

Procedures and function are made up of a declarative part, an executable part and an optional exception-
handling part.

A declaration part consists of declarations of variables. A executable part consists of the logic i.e. sql
statements....and exception handling part handles any error during run-time

Most important the difference between procedures and functions: A function must return a value back to
the caller. A function can return only one value to the calling pl/sql block. By defining multiple out
parameters in a procedure, multiple values can be passed to the caller. The out variable being global by
nature, its value is accessible by any pl/sql code block including the calling pl/sql block.

Syntax for stored procedure:


CREATE OR REPLACE PROCEDURE [schema] procedure name (argument { IN, OUT, IN OUT} data
type, ..) {IS, AS}
variable declarations; constant declarations; BEGIN
pl/sql subprogram body;
EXCEPTION
exception pl/sql block;
END;
/
PL/SQL NOTES Page 8 of 11

Syntax for stored function:


CREATE OR REPLACE FUNCTION [schema] functionname(argument IN data type, ..) RETURN data
type {IS, AS}
variable declarations; constant declarations; BEGIN
pl/sql subprogram body;
EXCEPTION
exception pl/sql block;
END;

The above syntax IN : specifies that a value for the argument must be specified when calling the
procedure or function. argument : is the name of an argument to the procedure or function. parentheses
can be omitted if no arguments are present. OUT : specifies that the procedure passes a value for this
argument back to its calling environment after execution. IN OUT : specifies that a value for the argument
must be specified when calling the procedure and that the procedure passes a value for this argument
back to its calling environment after execution. By default it takes IN. Data type : is the data type of an
argument.

EXAMPLES

1. --PROCEDURE USING NO ARGUMENT..AND USING CURSOR

CREATE OR REPLACE PROCEDURE P2 IS


cursor cur1 is select * from emp;
begin
for erec in cur1
loop
dbms_output.put_line(erec.ename);
end loop;
end;
/

SQL> exec p2

2. --PROCEDURE USING ARGUMENT


CREATE OR REPLACE PROCEDURE Mul (X IN NUMBER) IS
BEGIN
dbms_output.put_line(x*x);
end;
/

sql> exec mul(3);


PL/SQL NOTES Page 9 of 11

3. --DELETION PROCEDURE
create or replace procedure myproc is
begin
delete from emp where empno=1000;
commit;
end;
/

1. --FUNCTION using argument


CREATE OR REPLACE FUNCTION mulf (X IN NUMBER) RETURN NUMBER IS
BEGIN
return (x*x);
end;
/

SQL>select mulf(4) from dual;

2. Function to calculate total employees


CREATE OR REPLACE FUNCTION totalemployees
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM emp;

RETURN total;
END;
/

SQL> select totalemployees() from dual;

TOTALEMPLOYEES()
----------------
17
PL/SQL NOTES Page 10 of 11

TRIGGERS

A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete, Update is
executed on a database table. A trigger is triggered automatically when an associated DML statement is
executed.

Syntax of Triggers

Syntax for Creating a Trigger

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;
/

 CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given
name or overwrites an existing trigger with the same name.
 {BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the trigger get
fired. i.e for example: before or after updating a table. INSTEAD OF is used to create a trigger on
a view. before and after cannot be used to create a trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering event. More
than one triggering events can be used together separated by OR keyword. The trigger gets fired
at all the specified triggering event.
 [OF col_name] - This clause is used with update triggers. This clause is used when you want to
trigger an event only when a specific column is updated.
 CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given
name or overwrites an existing trigger with the same name.
 [ON table_name] - This clause identifies the name of the table or view to which the trigger is
associated.
 [REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and new values
of the data being changed. By default, you reference the values as :old.column_name or
:new.column_name. The reference names can also be changed from old (or new) to any other
user-defined name. You cannot reference old values when inserting a record, or new values
when deleting a record, because they do not exist.
 [FOR EACH ROW] - This clause is used to determine whether a trigger must fire when each row
gets affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is
executed(i.e.statement level Trigger).
 WHEN (condition) - This clause is valid only for row level triggers. The trigger is fired only for
rows that satisfy the condition specified.
PL/SQL NOTES Page 11 of 11

1. Create a trigger to find username of person performing INSERT into table emp.

create table ins_emp (cuser varchar2(12),cdate date);

CREATE OR REPLACE TRIGGER emp_before_insert


BEFORE INSERT
ON emp
FOR EACH ROW
DECLARE
v_username varchar2(10);
BEGIN
SELECT user INTO v_username FROM dual;
insert into ins_emp(cuser,cdate) values (v_username,sysdate);
END;
/

SQL> select * from ins_emp;

CUSER CDATE
------------ ---------
SCOTT 28-AUG-16
SCOTT 28-AUG-16

2. Example: Enter a log record each time an update is made to employees

CREATE TABLE Emp_log


( Log_date DATE,
Action CHAR(30)
);

CREATE OR REPLACE TRIGGER Log_emp_update


AFTER UPDATE ON emp
BEGIN
INSERT INTO Emp_log (Log_date, Action)
VALUES (SYSDATE, 'Employee Table Updated');
END;

UPDATE emp
SET sal=sal+100
WHERE deptno=10;

SQL> select * from emp_log;

LOG_DATE ACTION
--------- ------------------------------
28-AUG-16 Employee Table Updated

Вам также может понравиться