Professional Documents
Culture Documents
advantages:
-------------
1.programming capability
2.conditional checking capability
3.improved performance(network traffic reduces)
4.tight integration with SQL(all the feature of the sql can be used)
5.portability
6.It has the features of exception handling
7.Using plsql we can write 2 type of prgs:
---------------------------------------------
1.Ananymous blocks
These are not stored in database, they are stored in o/s files. they are
not named blocks,not reusable,they are standalone.
2.Stored prg or stored units
these are stored in db. so they can be referred from db.
eg: procedures,functions,packages,triggers
These are used in front end applications.
structure of Plsql prg:
-----------------------
declare
//declaration section
begin
//executable stmts;
exception;
//exception handling section
end;
Variable declaration:
----------------------
syntax: var_name data_type(size);
eg: n number(3);
name varchar2(10);
constant declaration:
-----------------------
syntax: var_name constant data_type(size);
eg: PI constant number(5,3);
Initializing the values:
-----------------------
syntax: var_name data_type(size):=value;
eg: course varchar2(20):='java';
Accepting values:
-------------------
syntax: var_name data_type(size):=&var_name;
eg: salary number(7,2):=&salary;
Output statement: dbms_output.put_line(variable||'msg');
To see the output : set serveroutput on;
1.sample prg:
cl scr;
begin
dbms_output.put_line('welcome to pl/sql');
end;
press '/' to execute the program
type: set serveroutput on;
2.%rowtype
-------------
A single variable is declared which will be adjustED to different datatypes OF A
LL COLS.
//WAP TO ACCEPT EMPNO DISPLAY ENAME,JOB,SAL,COMM,HIREDATE
declare
empr emp%rowtype;
eno emp.empno%type:=&eno;
begin
select * into empr from emp where empno=eno;
dbms_output.put_line(empr.ename||empr.sal||empr.comm||empr.hiredate);
end;
/
3.record type:
----------------
Collection of different types of variables.
syntax: type record_name is record(variable tablename%rowtype,-------------);
record_variable record_name;
//WAP A BLOCK TO DISPLAY ENAME, SALARY, JOB.
declare
type emprec is record(name emp.ename%type, vjob emp.job%type, salary emp
.sal%type);
e1 emprec;
begin
select ename,job,sal into e1 from emp where empno=&empno;
dbms_output.put_line(e1.name||e1.vjob||e1.salary);
end;
/
Control statements:
1.if
---
syntax:
if conditon then
statements;
end if;
2.if..else
---------
syntax:
if <condition> then
statement1;
else
statement2;
end if;
3.elsif...statement.
--------------------
syantax:
if <condition1> then
statement;
elsif <condition2> then
statements;
elsif <condition3> then
statements;
------------;
else
statements;
end if;
//WAP TO TEST FOR +VE NO.
declare
no number:=&no;
begin
if no>0 then
dbms_output.put_line('it is positive ');
end if;
end;
//WAP TO TEST FOR EVEN OR ODD NO.
declare
n number :=&n;
begin
if mod(n,2)=0 then
dbms_output.put_line('even');
else
dbms_output.put_line('odd');
end if;
end;
//WAP TO TEST FOR LEAP YEAR OR NOT.
declare
year number:=&year;
begin
if mod(year,4)=0 and mod(year,100)!=0 or mod(year,400)=0 then
dbms_output.put_line('leap year');
else
dbms_output.put_line('not leap year ');
end if;
end;
//WAP TO ACCEPT EMPNO AND INCREMENT SAL BY 500 IF COMM IS NULL ELSE 200.
declare
salary emp.sal%type;
com emp.comm%type;
begin
select sal,comm into salary,com from emp where empno=&empno;
if com is null then
salary:=salary+500;
else
salary:=salary+200;
end if;
dbms_output.put_line(salary||' '||com);
end;
//WAP TO ACCEPT EMPNO AND BASED ON JOB INCREMENT SAL AS FOLLOWS.
CLERK 500
SALESMAN 700
ANALYST 1000
MANAGER 1500
OTHERS 200
declare
salary emp.sal%type;
sal1 emp.sal%type;
vjob emp.job%type;
begin
select sal,job into sal1,vjob from emp where empno=&empno;
salary:=sal1;
if vjob like 'clerk'then
salary:=salary+500;
elsif vjob like 'salesman' then
salary:=salary+700;
elsif vjob like 'analyst' then
salary:=salary+1000;
elsif vjob like 'manager' then
salary:=salary+1500;
else
salary:=salary+200;
end if;
dbms_output.put_line(vjob||' '||sal1);
dbms_output.put_line('incremented salary '||salary);
end;
EXCEPTION HANDLING
-------------------------
Abnormal termination of normal flow of program.Its a run time error.exceptions a
re also raised due to hardware problems.
Exceptions are 2 types:
-------------------------
1.predefined exceptions
2.User defined exceptions
1.predefined exceptions:
---------------------------
These are supplied by system, stored in standard package available to all progra
ms. Handled automatically by system.
eg:
no_data_found;
zero_divide,cursor_already_open,invalid_cursor,
prog_error: It occurs when function created without return stmt;
value_error: too many rows
storage_error: no data found
invalid_number: attempting to convert from string to number
others:
--------
Its a exception handler. It must be the last stmt in the prg.
syntax:
declare
-----------;
begin
exe stmts;
exception
when <exp_name1> then exp_handler1;
when <exp_name2> then exp_handler2;
--------------------------------------------;
when others then stmts;
end;
prg without exception handler
declare
a number:=&a;
b number:=&b;
c number;
begin
c:=a/b;
dbms_output.put_line(c);
dbms_output.put_line('end of program');
end;
/
Above prg :HANDLING ZERO_DIVIDE.
declare
a number:=&a;
b number:=&b;
c number;
begin
c:=a/b;
dbms_output.put_line(c);
exception
when zero_divide then
dbms_output.put_line('division by zero not possible');
end;
//HANDLING NO_DATA_FOUND
declare
emprec emp%rowtype;
begin
select * into emprec from emp where empno=&empno;
dbms_output.put_line(emprec.ename);
exception
when no_data_found then
dbms_output.put_line('no such employee');
end;
--demonstrate To Too_many_rows Exception
Declare
Z Emp%rowtype;
Begin
Select * Into Z From Emp Where Deptno = 20;
Dbms_output.put_line(z.empno||z.ename||z.deptno);
Exception
When Too_many_rows Then
Dbms_output.put_line('too Many Rows In Row Type Variable');
End;
/
--cursor_already_open
Declare
Cursor S Is Select Ename From Emp;
Ena Emp.ename%type;
Begin
Open S;
Loop
Fetch S Into Ena;
Exit When S%notfound;
Dbms_output.put_line(ena);
End Loop;
Open S;--opened Again
Exception
When Cursor_already_open Then
Dbms_output.put_line('cursor Should Not Open More Than One Time');
End;
/
--value_error
Declare
N Number(3);--3digits
Begin
N:=&number;
Dbms_output.put_line('sqr Value Is ' ||(n*n));
Exception
When Value_error Then
Dbms_output.put_line('value Is Larger Than Given Width');
End;
/
Stored Programs:
-------------------
adv:
-supports reusability and modularity
-easy maintainance
-reducing coding
-performance is improved
eg: procedures,functions,packages ,triggers
Procedures and functions are a series of executable statements and are present i
n data base. These are more useful while developing the applications
A function can return a value but a procedure cannot return a value technically,
but returns more than 1 value using out parameter.
Procedure :syntax:
-----------
create or replace procedure p_name(parameters in/out/in out datatype) is/as loca
l declaration;
begin
executable stmts;
exception
exception handling section
end pro_name;
//SAMPLE PROCEDURE.
create or replace procedure pro1
as
begin
dbms_output.put_line('welcome to procedures... ');
end pro1;
/
Procedure can be executed in 2 ways using
1.execute command
syntax:
execute <procedure_name>(args);
eg:
execute pro1; or
exec pro1;
2.client program.
FUNCTIONS:
--------------
They return a value to the called environment. Every function can have default a
rguments and function can accept parameters.
syntax:
create or replace function fun_name(parameters in/out/in out data_type) return d
atatype
is/as
variable var_name;
begin
executable stmt;
return var;
exception
exception handling section;
end [fun_name];
//FUNCTION WITHOUT PARAMETERS:
//WAP TO DISPLAY THE NO. OF EMPS IN A DEPARTMENT.
create or replace function f1 return number
is
deptnum emp.deptno%type:=&deptnum;
n number;
begin
select count(*) into n from emp where deptno=deptnum;
return n;
end;
EXECUTION:
@ file
var n number
exec :n:=f1;
print n;
//FUNCTION WITH PARAMETERS:
//WRITE THE ABOVE PRG BY PASSING DEPTNO.
create or replace function f3(deptno1 in number default 10) return number
is
n number;
begin
select count(*) into n from emp where deptno=deptno1;
return n;
end;
execution:
@ file_name;
var n number;
exec :n:=f3(20);
print n;
Q: Find the area of rectanlge.
create or replace function rect(l in number,b in number) return number
as
area number;
begin
area:= l*b;
return area;
end;
/
execution
var n number
exec :n:=rectanlge(10,5);
print n;
--wap which accepts the job and returns no of employs in that job
create or replace function f2(vjob in emp.job%type)
return number
as
cnt number;
begin
select count(*) into cnt from emp where job=vjob;
return cnt;
end f2;
Functions are executed in 3 ways
1.by execute command
2.by selecting function from dual
3.by writing client prg
--execution
--1.
var n number;
--execute :n:=f2('MANAGER') ;
--print n;
--2.select f2('MANAGER') from dual;
--3.client prg
declare
m number;
vjob emp.job%type:='&vjob';
begin
m:=f2(vjob);
dbms_output.put_line('the no of emp s '||m);
end;
/
//WAP to ACCEPT EMPNO AND RETURN HIS EXPERIENCE.
create or replace function fexp(eno in emp.empno%type) return number
is
n number;
begin
select (months_between(sysdate,hiredate)/12) into n from emp where empno=eno;
return n;
end;
EXECUTION:
1.var x number;
exec :x:=fexp(7876);
print x;
2.select fexp(7839) from dual;
3.declare
no number:=&no;
begin
no:=fexp(no);
dbms_output.put_line('the experience '||no);
end;
confirm procedures,functions:
select name,type from user_source;
confirm procedures:
select * from user_procedures
To drop procedure:
drop procedure <pro_name>
To drop function:
drop function <fun_name>
PACKAGES:
-------------
It is a database object which contains procedures, functions,cursors,exceptions
etc;
-->packages are not executed but the things in packages
-->packages does not have parameters.
Creation of packages in 2 steps:
----------------------------------
1. Specification of package
2. Body of package.
Specification sepcifies things to be excuted. These are available to dif
ferent users.
Body provides definitions for the things specified in Specification.
Specification syntax:
----------------------
create or replace package pkg_name
as
procedure pro_name1(parameter in/out/in out dt);
procedure pro_name2(parameter in/out/in out dt);
function fun_name1(parameter) return dt;
function fun_name2(parameter) return dt;
end pkg_name;
Body syntax:
--------------
create or replace package body pkg_name
as
//Define procedures
//Define functions etc.
end pkg_name;
Q: wap to create a pkg consisting of 2 functions
1.package specification
create or replace package pak_fun as
function sqr( m in number) return number;
function cube(n in number) return number;
end;
/
2.package body
create or replace package body pak_fun as
function sqr(m in number) return number is
begin
return m*m;
end sqr;
function cube(n in number) return number is
begin
return n*n*n;
end cube;
end pak_fun;
/
3.client prg for above:
declare
x number(4);
begin
x:=&number;
dbms_output.put_line('square value '||pak_fun.sqr(x));
dbms_output.put_line('cube value '||pak_fun.cube(x));
end;
/
--create a package which contains a function to check deptno exists or not and p
rocedure to retrieve rows.
create or replace package emp_trans as
function dcheck(dno in number) return number;
procedure eprint(dno in number);
end;
/
create or replace package body emp_trans as
function dcheck(dno in number) return number is
d emp.deptno%type;
begin
select distinct deptno into d from emp where deptno=dno;
return 0;
exception
when no_data_found then
return 1;
end dcheck;
procedure eprint(dno in number) as
cursor s is select * from emp where deptno=dno;
z emp%rowtype;
begin
open s;
loop
fetch s into z;
exit when s%notfound;
dbms_output.put_line(z.ename||z.deptno);
end loop;
end eprint;
end emp_trans;
/
client prg for above:
declare
dno emp.deptno%type;
begin
dno:=&deptno;
if(emp_trans.dcheck(dno)=0) then
emp_trans.eprint(dno);
else
dbms_output.put_line('deptno not exist');
end if;
end;
/
drop package:
drop package pkg_name;
TRIGGERS:
--------------
It is a PL/SQL object which executes on its own, when an event occurs. An event
may be DML or DDL operation.
Adv:
-----
1.A trigger can audit the information(who made the changes)
2.High level security can be imposed.
3.Complex business rules can be imposed(high level restriction)
4.Trigger can permit accessibility on a table for a particular time.
5. Triggers does not need user interaction, as these are individual objects.
Elements of trigger:
----------------------
1. trigger event
2. trigger restriction
3. trigger body:-PL/SQL block
syntax:
create or replace trigger trg_name before/after/insteadof
dml event (insert/update/delete)
ddl event on table_name;
for each row when condition;
begin
--executable stmt
end;
Two levels of triggers:
------------------------
1. Row level triggers: fires on each row.
2. Statement level triggers: fires automatically once on all the rows in a trans
action.
Types of triggers:
-------------------
1. DML triggers: fires when DML operation is performed.
2. System Triggers: fires when a change occurs in schema.
Trigger predicates:
---------------------
1. insert
2. delete
3. update
These identify the action performed on the table.
pseudo columns/correlation name:
1. :old
It indicates the value present before update/delete
2. :new
It indicates the value after insert.
These are useful to track the changes made to the table.
//1.WAT BEFORE INSERTING DATA INTO TABLE.
create or replace trigger trg1
before insert on emp1 for each row
begin
dbms_output.put_line('one rec inserted ..orbit');
end;
/
//2.WAT BEFORE DELETING DATA INTO TABLE.
//3.WAT BEFORE UPDATING DATA INTO TABLE.
//4.WAT BEFORE INSERT/DELETE/UPDATE'ING A TABLE
create or replace trigger trg4
before insert or update or delete on emp1 for each row
begin
if inserting then
dbms_output.put_line('1 record inserted...ramesh');
elsif updating then
dbms_output.put_line('record(s) updated..ramesh');
else
dbms_output.put_line('record(s) deleted... ramesh');
end if;
end;
/
//5.WAT, ACCEPTING DOJ. IF DOJ !=SYSDATE, REPLACE DOJ WITH SYSDATE.
create or replace trigger trg5
before insert or update on emp2 for each row
when(new.hiredate<>sysdate)
begin
if :new.hiredate<>sysdate then
:new.hiredate:=sysdate;
end if;
dbms_output.put_line('doj recovered....');
end;
/
//6.
create or replace trigger t7 before insert or update on emp2 for each row
begin
if :new.sal>3000 then
:new.sal:=5000;
elsif :new.sal>2000 then
:new.sal:=2000;
end if;
end;
/
//7. Resctriction on time
create or replace trigger t9
before insert or update or delete on emp2 for each row
begin
if(to_number(to_char(sysdate,'hh24')) between 10 and 20) then
raise_application_error(-2002,'sorry....transaction not allowed between 10 and 2
0..');
end if;
end;
/
//8.Restriction on week days
create or replace trigger t10
before insert or update or delete on emp2 for each row
begin
if to_char(sysdate,'dy') in('fri','sat','wed') then
raise_application_error(-2001,'sorry....!. transactions are not allowed on week
ends...');
end if;
end;
/
confirm triggers:
select trigger_name,table_name from user_triggers;
Drop trigger:
drop trigger <trg_name>;
Enable/disable triggers:
alter trigger trg_name enable/disable;
* for a table any no of triggers can be written.
CODD RULES
-------------------
12 CODD RULES were proposed by EF.codd
1.The information rule:
specifies that the info. must be logically represented in exactly at one place i
n a systamatic way in rows and cols.