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

The DL/SQL programs :-

EMBEDDED SQL




We are writing Java script and we can call in oracle through ODBC drivers
and hr VB script also
Any SQL which is already integrated in the language known as embedded
SQL
DL/SQL allows DML,DRL and TCL commands
The above all commands syntaxes are same except select statement
Select statement syntax :-
Select <col1>,<col2>,..into <var1>,<var2> from <tab1>,<tab2>..where
<condition>;
Q) Write a program accept employee number and display his details along with
annual salary and experience
Declare
v_ empno number(5):= & empno
v _ e name varchar 2(20);
v _ job varchar 2(20);
v _ sal number (8,2);
v _ hiredate date;
v _ deptno number(4);
v_ann_sal number (10,2);
v_exp number (6,2);
Begin
Select ename, job, sal, hiredate , depno - no.of cols
Into v_ename,v_job,v_sal,v_hiredate,v_deptno no.of variables
From emp
Where empno = v_empno;
V_ann_sal:= v_sal*12;
V_exp:=maths_between (sysidate,v_hiredate)/12;
dopl(empno=!! v_empno);
,, (ename=!! v_ename);
,, (job= !! v_job);
,, (hiredate=!! v_hiredate);
,, (salary=!! v-sal);
,, (Annual salary=!! v_ann_sal);
,, (experience =!! v_exp);
End;
Note:-
1) No.of columns should be equal to no.of variables
2) Always write condition on p.k with that DL SQL statement returns at a
time
For example, 1 created some variables, present 1 want to change that
length of variables with help of alter modification . for that using
ATTRIBUTE DATE TYPES
ATTRIBUTE DATE TYPES :-
1) It is a column date type.
2) It is a pointer,points to same address of the existing database column
3) It is a pointer it inherits the specification of one or more database columns
or entire table specifications or cursor specification
4) Attribute datatype is completely depend on dynamic on dynamic memory
management concept
5) The main concept of attribute datatype is to reduce maintenance cost
6) It is classified into 2types
1) %type
2) %rowtype
%type :- It is used for to declare scalar variable, it inherits the specification of
only one database column.
Syntax :- <variable name> <table name> . <col name> % type;
Example:- v_dname dept.dname %type;
% rowtype:- It is used for to declare structure variable (also known as record
type variable), it inherits the specification of entire database table.
Syntax :- <variable name> <table name>%rowtype;
Example:- x emp %rowtype;
X variable contains (or) inherits all columns of emp table.
To read the x variable X.empno
X.ename
X.sal
Example for % type:
Declare
v_empno emp.empno%type;= &empno;
v_ename emp.ename %type;
v_job emp.job % type; emp.table datatype
v_ sal emp.sal%type; declarations
v_hiredate emp.hiredate%type;
v_ann_sal number(20,2) my own datatype
v_exp number(6,2) declarations
Example for % rowtype
Declare
e emp%rowtype
begin
e.empno:= &empno
select * into e from emp
e e inherits all colmns of emp table
where empno= e.empno; ex- 7369
dopl (empno =!! e.empno);
,, (ename=!!e.ename);
,, (job =!!e.job);
,, (hiredate=!!e.hiredate);
,, (deptno.=!!e.deptno);
end;
1) Example:- Write a program accept a employee number and calculate
bonus and insert into bonus table based on the following conditions
Salaray bonus_amt add_amt
>=5000 20% on ann_sal 1500
>=3000&& <5000 15%on ann_sal 1200
>=1500&& <3000 12% ,, ,, 1000
<1500 10% ,, ,, 800
Q ) Create table bonus (empno number(5) reference emp(empno)
Bonus_amt number(10,2)
Add_amt number(8,2)
Iss_dt date);
Declare
V_empno emp.empno % type:= &empno;
V_sal emp.sal % type;
V_ann_Sal number(10,2);
b bonus % rowtype;
Begin
Select sal into v_Sal from emp
Where empno = v_empno;
V_ann_Sal: = v_Sal *12;
If v_Sal >=5000
b.bonus_amt := v_ann_sal*20/100
b.add_amt:= 1500
else if v_Sal>=3000 then
b.bonus _amt:= v_ann_sal*15/100;
b.add_amt:= 1200;
else if v_sal >= 1500 then
b.bonus_amt := v_ann_sal*12/100;
b.add_amt := 1000;
else

end if
insert into bonus (empno, bonus_amt,add_amt,iss_dat)
values (v_empno,b.bonus_amt,b.add_amt,sysda)
commit;
dopl(Bonus calculated and inserted into bonus table)
end;
CURSOR
1) It is a private Sq1 Area
2) It is classified into 2 types
1) Implicit cursor
2) Explicit cursor
1) Implicit cursor :- It involves automatically for insert , update & delete
statements and it also involves for select statement if it returns only one row
2) Explicit cursor:- It is require to retrieve multiple records from database table
using select statement
To create explicit cursor the following steps are requires
1) Memory allocation (1) cursor declaration
2) Retrieval process (2) Open cursor
3) Fetch process (3) Fetch cursor
4) Memory allocation (4)close cursor
Oracle database server







1) Cursor declaration :-
Syntax :- cursor <cursor name> is select.;
Example:- cursor ec is select * from emp;
How to create cursor variable:-
<cursor variable> <cursor name> % rowtype;
Example:- v_ec ec % rowtype;
2) Open cursor:-
Open <cursor name>;
Eg: open ec;
3) fetch cursor :-
fetch <cursor name> into <cursor variable>;
eg:- Fetch ec into v_ec;
4) close cursor :-
close <cursor name>;

CURSOR ATTRIBUTES
1) % isopen :- It returns TRUE if the cursor is already open <cursor
name> % is open
2) %found:- It returns TRUE if the record is found to fetch
<cursor name>%found
3) % not found:- It returns true if the record is not found to fetch it is
opposite of % found
<cursor name>% not found
4) % row count:- It returns no. of records fetched from active set
<cursor name> % row count
1) Write a programme to display all employee details
Declare
Cursor ec is select * from emp;
V_ec ec% rowtype;
Begin
Open ec;
Loop
Fetch ec into v_ec;
Exit when ec% not found;
dopl(empno=//v_ec.empno);
,, (ename=//v_ec.ename);
,, (job=//v_ec.job);
,, (salary=//v_ec.sal);
,, (deptno.=//v_ec.deptno);
,, (___________________);
End loop;
Close ec;
End;
Hence, exit is a keyword to terminate the loop
NOTE:- if u want execute single statement then go with WHEN structure
Syntax:- S1 when <condition>
______ T
Q) write a programme display dept.no wise
Declare
Cursor dc is select distinct deptno from emo;
V_dc cd%row type;
Cursor ec is select * from emp where deptno=vc_dc.deptno;
Vc_ec ec%rowtype;
Deptno=10
-------------
-------------
Total:
Dept.no=20
------------
----------------
Total:


dc ec
10
20
30
-----------
-----------
-----------
Begin
Open dc;
Loop
Fetch dc into v_dc;
Exit when dc% not found;
Dopl(deptno= ||v_dc. Deptno);
Dopl(____________________);
Open ec;
Loop
Fetch ec into v_ec;
Exit when ec%not found;
Dopl( v_ec.empno|| ||v_e.ename|| ||v_ec.job
|| ||v_ec.sal|| ||v_ec.deptno);
End loop;
Dopl(total no.of employees:||ec%row(a int);
Close.ec;
End loop;
Close dc;
End;
Q) write a program display empno ,ename,job,salary,deptno,dname,loc and
grade of all employees.?
Note:- we can write any query in cursor like join,subquery etc
Declare
Cursor ec is select
e.empno,e.ename,e.job,e.sal,e.deptno,d.dname,d.loc,s.grade
From emp e,dept d,salegrade S
Where e.deptno=d.deptno
And e.sal between s.losal and s.hisal;
rc_ec ec%rowtype;
begin
open ec;
loop fetch ec into v_ec;
exit when ec%not found;
dopl (empno=||v_ec.empno);
dopl(job=||v_ec.job);
dopl(salary=||v_ec.sal);
dopl(deptno=||v_ec.deptno);
dopl(dname=||v_ec.dname);
dopl(location=||v_ec.loc);
dopl(grade=||v_ec.grade);
dopl(________________);
end loop;
close ec;
end;
CURSOR FOR LOOP
If any for loop using cursor variable then it is called cursor for loop
Syntax:- for <cursor variable> in <cursor name>
Loop
________
________
End loop
________
________
For control structure is a good one in using cursor variable
Any for loop is operated by using cursor known as cursor for loop
The cursor for loop require only declaration of the cursor and remaining 3
steps (open,fetch, & close) are automatically performed by for loop itself
The cursor for loop variable automatically declared by cursor for loop
itself
The acope of the cursor for loop variable is within the loop
q) Write a programme to display all department details.?
Declare
Cursor dc is select * from depy;
Begin
For v_dc in dc
Loop
dopl(deptno=||v_dc.deptno);
dopl(dname=||v_dc.dname);
dopl(location=||v_dc.location);
end loop;
end;
Using for loop we can reduce writing no.of statements
q) write a program calculate bonus fro all employees and insert into bonus table
(20% of annual salary)
declare
cursor ec is select empno,sal from emp;
v_ann_sal number (10,2);
v_bonus_Amt bonus.bonus_amt%type;
begin
for v_ec in ec
loop
v_ann_sal:=v_ec.sal*12;
Emp no sal
--------- --------
---------- --------
v_bonus_amt:=v_ann_sal*20/100;
insert into bonus(empno,bonus_amt,add_amt,iss_dt) in buffer
values(v_ec.empno,v_bonus_amt,1000,sysdate);
end loop;
commit;
dopl(Bonus calculate for all employee);
end;
CURSOR PARAMETERS :-
Cursor <cursor name> (arg1 datatype (width),_ _ _ _) is
Select _ _ _ _ ;
Eg:- cursor ec(pdeptno number(4)) is select * from emp
Where deptno=pdeptno;
How to open cursor parameter :-
Open <cursor name> (val1,val2,_ _ _ _);
Eg:- open ec (10);
1
st
example for without parameters:-
Write a program accept deptno an d display details of employee who are working
in given department
Declare
30
V_deptno emp.deptno%type:=&deptno;
Where deptno=v_depno; static substitution
S * & emp w deptno=30
Begin
For v_Ec in ec
Loop
dopl(empno=||v_ec.empno);
dopl(ename=||v_ec.ename);
dopl(job=||v_Ec.job);
dopl(salary=||v_ec.sal);
dopl(deptno=||v_ec deptno);
dopl(__________________);
end loop;
end;
2
nd
example for using parameter
Declare
30
V_deptno emp.deptno%type:=&deptno
Cursor ec(pdeptno number (5)) is select from emp
Where deptno=pdeptno;
30
S * & e w d = pdeptno
begin
for v_ec in ec(v_deptno)
loop
dopl(empno=||v_ec.empno);
dopl(ename=||v_ec.ename);
dopl(job=||v_ec.job);
dopl(salary=||v_ec.sal);
end loop;
For v_ec in ec(10)
end;
open ec(20);
Instead of creating cursors just pass the parameters
It is dynamic
Ref cursor :-
1. Static Ref cursor (strong ref cursor)
2. Dynamic Ref cursor ( weak ref cursor)
Static ref cursor:-
Syntax:- type<type name> is ref cursor return <return type>;
Eg:- type src is ref cursor return emp%rowtype;
Type keyword , src<typename>
Eg:-
Declare
type src is ref cursor return emp%rowtype;
xc src;
begin
open xc for select * from emp;
loop
fetch xc into v_ec;
exit when xc%not found;
dop(empno=||v_ec.empno);
dopl(ename=||v_ec.ename);
dopl(job=||v_Ec.job);
dopl(salary=||v_ec.sal);
dopl(deptno=||v_ec deptno);
dopl(__________________);
end loop;
close xc;
end;
DYNAMIC REF CURSOR:-
SYNTAX:- type<type name> is ref cursor;
Eg:- type drc is ref cursor
Example:-
Declare
Type drc is ref cursor;
Xc drc;
V_ec emp%rowtype;
V_dc dept%rowtype;
V_sc salgrade%rowtype;
Begin
Open xc for select * from emp;
Loop
Fetch xc into v_ec;
Exit when xc%not found;
dopl(empno=||v_ec.empno);
dopl(ename=||v_ec.ename);
dopl(job=||v_Ec.job);
dopl(salary=||v_ec.sal);
end loop;
close xc;
open xc for select * from dept;
loop
fetch xc into v_dc;
exit when xc% not found;
dopl(deptno=||v_dc.deptno);
dopl(dname=||v_dc.dname);
dopl(location=||v_dc.location);
dopl(___________________);
end loop;
close xc;
open xc for select * from salgrade;
loop
fetch xc into v_sc;
exit when xc%not found;
dopl(grade=||v_sc.grade);
dopl(losal=||v_sc.losal);
dopl(hisal=||v_sc.hisal);
endloop;
close xc;
end;


PACKAGE
Package is a collection of variables,procedures ,function and cursors
the main concept of package is
1) To increase application performance
2) To reduce networl performance
3) To save memory
Example:- A super market having 4 modules i.e
employee ---- 500
customer --- 500
Bill ---1000
Stock ---500
Total ---2500
All 2500 created in database if user wants to retrieve any particular object then it
searches one object among 2500 object.so it will take time and decrease
performance
If ui calls b( ) function from
2500 it takes time &
Decrease performance







in generally oracle executes one statements only
every procedure ,function and cursor are stand-alone abjects
To over come above drawback implemented package with the package save time
and increase performance

employee ---- 500
customer --- 50
Bill ---1000
Stock ---500

all the above funct ,cursor etc push into thr package
Then each module wise created in dbase instead of 2500 just 4 only







Any user call wnr . to any call it send request to dbase and get that function and
keep in its memory .if again need same function no need to search in dbase it is
available in its memory only by this save time and increase performace and
remaining users can also call same function
Packages are 2 types :-
Package specification Package body
1)it will declare package name
Syntax:- create or replace
Package<package name>
Is
Procedure <procedure
name>(arg1,datatype,..);

1)it defines package name
Syntax:- create [or replace]
Package body<package name>
Is
Procedure <procedure
name>(arg1,database,);




Function<function
name>(arg1,datatype,)return<return
Type>;


end*<package name>+;


Function<function
name>(arg1,datatype,)return<return
Type>;


end*<package name>+;

Both are same to identify use with body
Example:-
create or replace
package mypack
os
procedure multi_table(n in number);
function factorial(n number )return number;
function emp_exp(pempno number)return number;
function emp_exp(pename vachar2)return number;
function emp_exp(phdate date)return number;
end;
/*if u pass empno,ename,date to above 3 functions it displays experience of
employee
It is also called function overloading and it check no.of args*/
Create or replace
Package body mypack
Is
Procedure multi_table(n in number)
Is
i number(2):=1;
begin
for i in 1.10dbms_output.put_line(n||*||i||=||n*i);
end loop;
end multi_table;
function factorial(n number) return number
is
fact number(10):=1;
begin
for i in 1n
loop
fact:=fact*I;
end loop;
return fact;
end factorial;
function emp_exp (Pempno number)return number
is
v_hdate emp.hiredate%type ;
v_exp number(5,2);
begin
select hiredate into v_date from emp where empno=Pempno;
v_exp:= months_between (sysdate,v_hdate)/12;
return v_exp;
exception
when no_date_found then
return null;
when others the
return null;
end emp_exp;
function emp_exp (Pename varchar2)return number
is
v_hdate emp.hiredate% type;
v_exp number(5,2);
begin
select hiredate into v_hdate from emp where ename=Pename;
v_exp : = moths between (sysdate,v_hdate)/12;
return v_exp;
exception
when no_date_found the
return null;
end em_exp;

Function emp_exp(Phdate date)return number
Is
V_Exp number(5,2);
Begin
V_exp := months_between (sysdate,Phdate)\12;
return v_exp;
end emp_exp;
end mypack;
Sql @ pal
Package created
Package body created.
Sql> exec mypack . nultitable(9);
Sql>select mypack, factorial(5) from dual;
Sql>select empno,ename,hiredate,mypack.emp_exp(empno)
Sql> empno,ename,hiredate,mypack.emp_exp(ename) from emp;
Sql> ,, ,, ,, ,, (hiredate) ,, ,, ;


TRIGGERS
TIRGGER is also a dbase object ,it rises automatically whenever the user performs
any DML operation on the associated table
Syntax:- create [or replace] trigger<trigger name>
Before/after [insert] or [update] or [delete]
On <table name>
[for each row]
[when (<condition>)]
[declare
----------
----------
--------- ]
Begin
---------
---------
---------
[exception
---------
---------
---------]
end [<trigger name>];

Trigger is similar to stored procedure
When ever user calls to dbase then procedure executes
Trigger ,user performs any DML operations it automatically
Every constraint is a predefined trigger
If u want constraint other than5 constraint( p.k ,unique,not now,check.ref
etc) go with trigger
Generally update ,delete and indert operation performing then only
constraint raises
Similarly trigger also raises update ,delete and insert operations
Example:-
q) I want to resolve permissions to users on weekend i.e firday night onwards
Monday morning for security purpose
Instead of revoke permission manually go with the trigger
q) My business timing 9-5pm I want to revoke permissions after those hours
It means HH24
9-16 i.e (it works upti 4pm and 59min 59 sec
Because it starts 0-24 format)
Using with trigger we can revoke permission after business hours
q) I want to maintain unique case in my table.
Suppose If anyboday given small or capital or mixed but my table can
take only capital . using with trigger we can maintain unique case sensitive
q) I dont want to allow decrement of my sal it is possible with
mainly triggers are classified into 2 levels
trigger :- 1
st
type:-
row level 1) Before --- a) insert
b)update
c)delete
rowlevel 2) after a) insert
b)update
c)delete
2
nd
type:-
Column level1) Before --- a) insert
b)update
c)delete
2) after a) insert
b)update
c)delete
Even you write trigger using with after but it raises before only
Whenever press enter after writing program immediately it will check if any
trigger is in the program or not
Example:-
Write a database to stop transaction on emp table on Sundays
Sql>ed +1
Create or replace
Trigger stop_sun_emp
Before [insert] or [update] or [delete] on emp
Begin

Then
Raise_application_error(-201--.sorry. the transactions are not allowed on
Sundays on emp.);
End if;
End;
/
Sql>@t1
Trigger created
Sql>insert into emp (empno.ename) values(4567,h4);

Example2:-
Create a dbase trigger to stop transactions on emp table on nonworking hours [9-
5pm]
Sql>ed +2
Create or replace
Trigger stop_non_work_emp
Before insert or update or delete
On emp
Begin
If to_char(sysdate,hh24)not
Between 10 to 16 then
Raise_application_error(-20200, sorry.the time is over);
end if;
end;
/
*SUB PROGRAMS*
Sub programs are divided into 2 types
1) Anonymous PL/SQL Block
2) Named PL/SQL Block
Difference between anonymous and named pl/sql blocks:-
Anonymous pl/sql block Named pl/sql block
1) It starts from declare keyword
2) This program will string in
operating system
3) It stores source code
4) It is open to all users (because it
is stored at o.s)
5) It doesnt support reusability
6) It is a clientside programming
7) Less usage of people
8) The maintenance cost is high
9) After compilation immediately it
will stores in o.s as source code
1) It start from create keyword
2) This program will storing in DATABASE
3) It stores complied code
4) It is not open to all users (because it is
at dbase)
5) It support reusability
6) It is a server side programming
7) Nearly 80% people using this
8) It reduces maintenance cost
9) After compliatiob immediately it will
stores at dbase as a complied code
10) Example:- procedures &
10) Example:- till now all
programs cursors start with
declare


functions



Named pl/sql :- block again divided into two types
procedues Functions
1) It is a group of statements to
perform specific task
2) It may or maynot return a
value
3) It returns one or more value
4) It allows to perform DML
operations
1) it is also a group of statements to perform
specific task
2) it must return a value
3) it returns only one value
4) it doesnt allow to perform DML operations


Procedure:-
Syntax:- create [or replace]
Procedure <procedure name> (arg1 datat type,_ _ _ _)
Is/as
_______
_______
_______
Begin
_______
_______
_______
[exception

_______
_______
_______ ]
end[<procedure name>];
Q) create a procedure accept a integer number and print multiplication table?

Sql> ed pl
/*declare*/
Create or replace procedure
Multi_table(n number)
/*n number := &n it is giving as a parameter to input in procedure*/
/*remaining program like a simple program*/
Is
i number(2):=1;
begin
while i<=10
loop
dopl(n||*||i||=||n*i);
i:=i+1;
end loop;
end;
Sql> @ pl
If procedure created with compilation errors then

=>show errors
To execute program
Sql> exec multi_table(9)

Q) create a procedure accept a string and display string

Sql> ed p2
Create or replace
Procedure print (str varchar2)
Is
Begin
Dbms_output.put_line(str);
End;

Sql> @ p2
Sql> exec print (Hello good evening);

Q) create a procedure accept a string and find reverse of the given string

Create or replace procedure
rev str (str varchar2)
is
temp varchar 2(50);
ch char;
L number (2);
Begin
L: = length (str);
For i in 1..L
Loop
Ch=substr(str, -i, 1);
End loop;
Print(temp);
End;
Sql> @ p3
Sql> exec str rev (tecno)

Types of parameters
There are 3 types of parameters they are
1) IN 2) OUT 3) IN OUT
IN:- it receives value from calling place .BY default all ar in parameter are
constant parameters
Example:- P1 ( n in number) receives as ip --- P1 (10)
It is constant it cant change . if u want create out

OUT:- To send a value to calling place
Example:-
P1(n in number , m out number , k out number) p1(a,b,c)
m= n*
k=n*n*n
ex:- I want to give 2 variables as a i/p and with that I want to pprint
.sum,product,difference etc for that I need 5 parameters to
IN OUT:- To remove and send value to callin place
P1 ( n in out number)
n = n*n
1)example for in parameter :-

<sql> ed p1
Create or replace
Procedure factorial (n in number)
is
fact number(10):=1;
begin
for p .in 1..n
loop
fact := fact * i;
end loop;
print (Factorial =//fact);
end;
Sql > @ p1 <= / sql> exec factorial(5)

2)Example for OUT parameter:-

Sql> ed p2
Create or replace
Procedure factorial (\n in number , m out number)
is
fact number (10):= 1;
begin
loop
fact:= fact *I;
end loop;
m:= fact;
end;
Sql> @ p2
Sql> variable x number
Sql> exec factorial 2(5,:x)
Sql> print :x
Sql> ed x2
X bind variable to read & write
Bind proceed with :
Print it is a key word
Declare
a number (5):= &a;
b number (10);
begin
factorial 2(a.b);
print (Factorial =||b);
end;
Sql> @ x2
Enter value for a:5

3)Example for IN OUT parameter :-

Sql> ed p3
Create or replace
Procedure factorial3( n in out number)
is
fact number(10):=1;
for i in 1.n
loop
fact:= fact * I;
end loop;
n: = fact;
end;
Sql> @ p3

Sql> ed x3
Declare
a number (5):= &a;
begin
print ( Factorial of ||a||is:);
factorial 3(a);
print (a);
end;
Sql> @ x3
Enter a value for a:5

{before calling proce a values is 5 , after calling proce a value becomes 120)
An INPUT parameter lets you pass initial values to ther subprogram being
called and return upated values to the caller . Inside the subprogram , an
values to the caller . Inside the subprogram , an IN OUT parameter acts
like an initialized variable
The actual parameter that corresponds to an IN OUT formal parameter
must be a variable ; if cannot be a constant or
FUNCTIONS:-
A function is a subprogram that computes a value. Functions and
procedures are structured alike , except that functions have a RETURN
clause
Syntax:-
Function
Create [or replace]
Function <function name> (arg1 datatype ;_ _ _ )
Return <return type>

Is/as
_______
_______
_______
Begin
_______
_______
_______
[exception

_______
_______
_______ ]
end[<procedure name>];
Q) create a function similar to absolute function.?

Sql> ed f1
Create or replace function absolute ( n number) return number
is
begin
if n >= 0 then
return n;
else
return (n);
end if
end
note:- n number should be same at both sides

Q) How to test function.?

Sql> selct absolute (-18) from dual;

2) Display words takes input as s number

Sql > ed f2
Create or replace
Function my_sign ( n number) return varchar2
is
x varchar 2(20);
begin
if n>0 then
x: = positive number
return x;
else if n<0 then
x: = negative number;
return x;
else
x: = zero;
return x;
end if;
end;
sql> @ f2
sql> select my_sign (18) from dual;

q) create a function accept employee number and return his experience

sql> ed f3
create or replace
abs (-18)
o/p 18
sign (18)=1
(-18)=1
(0)=0
function emp_exp (Pempno emp.empno % type) return number
is
v_hiredate emp hiredate%type:
v_exp number(8,12);
begin
select hiredate into v_hiredate
from emp where empno = Pempno;
v_exp:=trunc ( months _between (sysdate , v_hiredate)/12,3)
returns v_exp;
exception
when no_data_found then
return null;
when others then
return null;
end;
sql> @ f3

Q) How to execute

Sql > select empno , upper (ename) hiredate from emp_exp
Sql > select emp_exp (&empno) from emp;

Note:- upper is a predefined function
Emp_exp is a user defined function

Q) Create a function accept empno and return is gross salary

Sql> ed f4
Create or replace
Function gross_sal (Pempno emp_empno % type)return number
is
v_sal emp.sal%type;
v_ta number (8,12);
v_da number (8,2);
v_hra number(8,2);
v_tot_allow nmber(10,2);
v_gross_sal number (10,2);
Begin
Select sal into v_sal from emp where empno=pempno
V_ta := v_sal * 30/100;
V_da:=v_sal* 40/100;
V_hra:=v_sal * 50/100;
V_tot_all:= v_ta + v_da + v_hra ;
V_gross_sal : = v_sal + v_tot _allow;
Return v_gross_sal;
Exception
When no_data_found then
return null;
When others then
return null;
end;
TIRGGERS
Q) create a database trigger to stop updation whonever a salary is decremented

Sql> Ed t3
Create or replace
Trigger stop_updation_sal_dcr
Before update
On emp
For each row
Begin
If:new.sal < : old_sal then
raise_application_error (-22000,sorry.salary cannot be decremented);
end if
end;
sql> update emp set sal=sal-4000 where empno=7060
sql>update emp set sal=sal-3000 where empno=7698

note:- without for we cant write when condition
without when we can write for condition
Pseudo columns in triggers :-
:new.<col name>
:old.<col name>

Q) how to see all the created triggers in our system:

Sql> select <trigger name> from user_tirggers
1) Statement level /row level trigger
2) Table level trigger

Q) How can see a particular code of trigger

Sql> select trigger_body from user_triggers
Where trigger_name = STOP_SUN_EMP

Q)How to drop trigger

Drop trigger <trigger name>

Q) I want tp give permissions on a particular table only one Sunday & next Sunday
onwards it permissions should be continued
-> Instead of drop and recreating trigger go with disable / enable ;
Sql > alter trigger <trigger name > disable / enable ;

Q) I want to disable all triggers on my emp table?

Sql> alter table <table name> disable / enable all triggers

Oracle 10g
Line size will be increased 24 lines before it is 14 lines
Set page size 20 ;
SPOOL:- If you want to save any table data from oracle to another environment
with spool
Sql > spol c;\ sample.txt
Sql> select * from emp;
Sql> select * from dept;
Sql> spool off

If you open c:\sample.txt , it contains two tables i.e emp & dept
We can load any tables from aracle to another environment up tp 9i but
we cannot append the existed files but append can allowed 10g onwards

Example:-
Sql> spool c:\sample.txt append
Sql> select * from sal grade;
Sql> spool off;

Up to 9i no space allowed in characters
Ex:- c:\emp details.ext
But log onwards above is works
Ex:- spool c:\emp details.txt
Sql> select * from emp;
Sql>spool off
Check emp details in OS

To save quiries into a file
Save
Sql>save al.txt
Or save c:\sampl1.txt
Sql> select * from emp;

FLASH BACK
Upto 9i no recover for drop tables but long onwards we can recollect
from recycle bin.

Q) how to read new and old columns given by oracle
Whenever update , insert & delete operation have done in the oracle it
stores immediately in buffer known as new value . Automatically the
previous value in the original tbale known as old value.
Update old ( correct)
new ( correct)

Whenever insert operation is happened it stores in buffer but not in table
Insert new (correct)
old ( wrong )
Whenever delete operation is happened it will load in buffer and deletes new
record but old is same in database
delete new (wrong)
old (correct )

Create a database trigger to table emp table back up:
Example:- If I will delete one row from buffer it want be delete it should be store
in another table
Create or replace trigger
Emp_backup_tr
After delete
For each row
Begin
Insert into
Emp_backup (emp no ename,job, mgr,hiredate,sal,comm.,deptno)
Values(:old.empno , :ol.ename ,:old.job , :ol.mgr , :old.sal , :old.comm,
:old.deptno)
End;

Steps:-
1)Create a backup table on emp
Sql> create table backup_emp on select * from emp;

2)Desc backup table
Sql> desc backup_emp;

3)Delete from emp where deptno=30;
Sql> delete from emp where deptno=30;
It automatically inserted into backup table

4)Select * enm backup_emp;
6 rows selected

Example:- drop table emp;
Table dropped
If you want see the dropped tables in recycle bin.
Sql> show recycle bin;
It will shows you the dropped tables.
You want recover dropped tables from recycle bin
Sql> flashback table emp to before drop rename to emp200;
i.e, it cant possible get back original name so assign like emp200 then
Sql>rename emp200 to emp;

Truncale is not possible even log for recollecting truncated tables
I want delets in recyclebin permanently
Sql> purge recyclebin;
Recycle purged;
Sql>show recycle bin
o/p nothing

TABLE PARTITIONING

TABLE PARTITIONING :-
Dividing table into samller parts for better performance
Types of partitions :-
1) Range partition
2) List partition
3) Hash partition
Range partition:-
Partitioning table based on range of values.
Sql> create table remp (empno number(5), ename varchar(10) ,
Sal number(5) , deptno number(5) );
Partitioning by range (deptno)
(partition rp1 values less than 10,
partition rp2 values less than 20,
partition rp3 values less than 30);
Sql> Insert into remp values (7369 , smith , 800,5);
Sql> Insert into remp values (7499, allen ,1600 , 15);
Sql> Insert into remp values (7521, Ward 2000,25);






Sql> Insert into remp values (7698 , KING ,5000,40);
Error since no partition for above data
Sql> select * from remp ;
Sql> select * from remp partition (rp1);

Adding new partition to the table :-
Sql> alter table remp add partition rp4
R1 <10
R2 >=10 <20
R3 >=20 < 30
Values less than (Max value);

Merging partition :-
Sql> alter table remp merge partitions rp1 , rp2 in to partition rp12:

Rename partition :-
Sql> alter table remp rename partition rp3 to rp33

Dropping partition :-
Sql> alter table remp drop partition rp4;

List partition :-
Partitioning table based on list of values
Sql> create table ( emp ( empno number (5),
ename varchar (10),
Job varchar (10)
Partition by list (job)
(partition L1 values (CLERK , Analyst),
Partition L2 values (PRESIDENT ,Manager);
Sql> insert into lemp values (7369 ,smith,CLERK);
Sql>insert into lemp values (7499,Allen,MANAGER);
Sql>select * from lemp;

Hash partition :-
This partition is completely Managed by ORACLE
If table is not suitable for range or list partition .We cab divide the table
based on Hash key values
Sql> create table hemp
(empno number(5),
ename varchar(10,
deptno number(5) );
Partition by hash (deptno)
(partition h1 , partition h2);
Sql> insert into hemp values (7369 ,smith,CLERK);
Sql>insert into hemp values (7499,Allen,MANAGER);
Sql> select * from hemp ;
Sql> select * from hemp partition (h1);
TOAD:-
TOAD is not a oracle software . it is a quest s/w

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