Академический Документы
Профессиональный Документы
Культура Документы
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.
Begin
dbms_output.put_line ('Hello World');
end;
/
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
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;
/
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
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
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;
/
· <loop_body>
END 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
· <loop_body>
END 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;
/
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
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
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;
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
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;
/
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
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.
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
SQL> exec p2
3. --DELETION PROCEDURE
create or replace procedure myproc is
begin
delete from emp where empno=1000;
commit;
end;
/
RETURN total;
END;
/
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
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.
CUSER CDATE
------------ ---------
SCOTT 28-AUG-16
SCOTT 28-AUG-16
UPDATE emp
SET sal=sal+100
WHERE deptno=10;
LOG_DATE ACTION
--------- ------------------------------
28-AUG-16 Employee Table Updated