You are on page 1of 40

Pl/sql Procedural language structured query language Select username from dba_users; A pl/sql is associated with a block which

is divided into 3 parts 1. Declaration block 2. Executable block 3. Exceptional block Declaration block: declaration block is used to declare temporary variables which can be defined or can be accepted at run time. Example: <var> <datatype>(size); Or <var> <datatype>(size):=&var; Executable block: it contains output statement, conditional statements etc., (process) (outputs) Example: Dbms_output.put_line(<message>); Exceptional block: errors raised by pl/sql block is handled by using exceptional block. Example: When no_data_found then <statements>; Declaration block Executable block Exceptional block Declaration block begins with declare Executable block begins with being Exceptional block begins with exception Block is completed with end Example for pl/sql block with minimum inputs

Begin dbms_output.put_line(hello world); End; / Practical approach to create a block Step 1 Sql> host notepad b1.sql The above statement activates b1.sql Type the following code Begin dbms_output.put_line(hello world); End; / Save and exit from notepad Step 2 Execution of pl/sql block sql>@b1.sql Note: if results are not displayed give the following statement as sql prompt Sql> set serveroutput on And re-execute the pl/sql block Sql>/ Interactive pl/sql block Declare Sno number(4):=6000; Sname varchar2(20):=&name; S1 number(3):=&s1; S2 number(3):=&s2; S3 number(3):=&s3; Total number(4); Begin total:=s1+s2+s3;

Dbms_output.put_line(sno :||sno); Dbms_output.put_line(sname:||name); Dbms_output.put_line(total:||total); End; / Importance of pl/sql block It helps in performing operatons based on condition Example Select * from emp where job=manager; Update emp set sal=sal+100 where Job=manager; Pl/sql block contains a pre-defined set of instructions they can be repeatedly called any number of time which saves time. Pl/sql block is of two types 1. Anonymous block 2. Named block Anonymous block A block without any name is called anonymous block Name block A block with a name is called name block which is stored along with database and is uniquely identified with a name. Note: normal blocks are stored in local harddisk with the name and file extension (b1.sql) Sql>save c:\deepak\s.sql Working with 3 blocks in pl-sql Declare a number(4):=&a; b number(4):=&b; c number(4); Begin C:=a/b; Dbms_output.put_line(c);

Exception When zero_divide then Dbms_output.put_line('ziro divide'); End; / User defined exceptions with if conditon Declare a number(4):=&a; b number(4):=&b; err1 exception; err2 exception; Begin if (a>b) then raise err1; else raise err2; end if; Exception When err1 then Dbms_output.put_line('a is big'); When err2 then Dbms_output.put_line('b is big'); End; / Assignment 1. Interchange values without using 3rd variable 2. Accept a string and a character to find no. Of characters in accepted string Select length('apple')-length(replace('apple','p')) from dual Solution : 1 Declare A number(4):=&a; B number(4):=&b; Begin Dbms_output.put_line('before swap'); Dbms_output.put_line(a); Dbms_output.put_line(b); A:=a+b; B:=a-b; A:=a-b; Dbms_output.put_line('after swap'); Dbms_output.put_line(a);

Dbms_output.put_line(b); End; / Solution 2 Declare str varchar2(20):='&string'; chr char:='&character'; res number(4); Begin Res:=length(str)-length(replace(str,chr)); Dbms_output.put_line(res); End; / Limitation of pl/sql block Pl-sql block is capable of perfroming task on single record extracted from a database table. Example: Positive Select * from emp where ename=smith 1 output Negative Select * from emp; Multiple output Example

Declare tempno number(4); tname varchar2(20); Begin Select empno,ename into tempno,tname from emp where ename=smith; Dbms_output.put_line(empno =||tempno); Dbms_output.put_line(name =|| tname); End; /

Sql statement with exception Declare Tempno number(4); Tname varchar2(20); Begin Select empno,ename into tempno,tname from emp where empno=&empno; Dbms_output.put_line('empno ='||tempno); Dbms_output.put_line('name ='|| tname); Exception When no_data_found then Dbms_output.put_line('no record found ....'); End; / 2.5.05 Working with sql statements in pl/sql with attributes (%type and %rowtype) %type attribute : it is used to declare a variable in pl-sql block with a reference to a column of a table. Ename varchar2 10 Syntax: <var> <tname>.<col name>%type; Example: Tname emp.ename%type; Declare Tname emp.ename%type; Begin Select ename into tname from emp Where empno=&empno; Dbms_output.put_line('name of employee : '||tname); End; / Assignment

1. Write a pl-sql block which accepts employee name and displays ename name,salary,designation and department location with a reference to %type attribute. Solution: Ename Salary Designation Department location emp.ename%type; emp.sal%type; emp.job%type; dept.loc%type;

Declare tname emp.ename%type; tsal emp.sal%type; tdes emp.job%type; tdloc dept.loc%type; Begin Select ename,sal,job,loc into tname,tsal,tdes,tdloc from emp,dept Where emp.deptno=dept.deptno and empno=&empno; Dbms_output.put_line(name =||tname);

Dbms_output.put_line(salary =||tsal); Dbms_output.put_line(designation=||tdes); Dbms_output.put_line(location=||tdloc); Exception When no_data_found then dbms_output.put_line(data not found); End; / Assignment 2 Write a pl-sql block which accepts employee name and displays number of employees working with the accepted employee name. Solution Declare Tname emp.ename%type:='&ename'; Tcount number(4); Begin Select count(*) into tcount from emp Where deptno=(select deptno from emp Where ename=tname); Dbms_output.put_line('no of employees --> '||tcount); End; / Assignemnt 3 Write a pl-sql block accepting grade and displaying number of employees working with the accepted grade. Solution Declare Tgrade salgrade.grade%type:='&grade'; Tcount number(4); Begin Select count(*) into tcount from emp,salgrade where sal between losal and hisal and grade=tgrade; Dbms_output.put_line('no of grade : '||tgrade|| ' employees are : '|| tcount); Exception When no_data_found then Dbms_output.put_line('no data'); End; /

Assignemnt 4 Write a pl-sql block which accepts department number and displays no. Of managers working in accepted department. Solution Declare Tdeptno emp.deptno%type:=&deptno; Tcount number(4); Begin Select count(*) into tcount from Emp where job='manager' and deptno=tdeptno; Dbms_output.put_line('no of employees with manager designation are : '||tcount); Exception When no_data_found then Dbms_output.put_line('no data found'); End; / Assignemen 5 Write a pl-sql block which accepts location and displays no. Of employees working in accepted location. Solution Declare Tloc dept.loc%type:='&location'; Tcount number(4); Begin Select count(*) into tcount from Emp,dept where emp.deptno=dept.deptno And dept.loc=tloc; Dbms_output.put_line('no of employees are : '||tcount); Exception When no_data_found then Dbms_output.put_line('no data found'); End; / Assignment 6 Write a pl-sql block which accepts character

And displays number of employees with the accepted character. Solution Declare Tcount emp.empno%type; Begin Select count(*) into tcount from Emp where ename like('%&tchar%'); Dbms_output.put_line('no of employees are : '||tcount); Exception When no_data_found then Dbms_output.put_line('no data found'); End; / Assignment 7 Accept employee number as input to pl-sql block to find number of employees with designation as clerk based on employee number > accepted number. Solution Declare Tempno emp.empno%type:=&empno; Tcount number(4); Begin Select count(*) into tcount from emp Where empno>tempno and job='clerk'; Dbms_output.put_line('no of clerks : '||tcount); End; / Assignment 8 Accept employee name to display employee name , his designation, location and grade Solution Declare Tname emp.ename%type:='&name'; Tdes emp.job%type; Tloc dept.loc%type; Tgrade salgrade.grade%type; Begin Select e.ename,e.job,d.loc,s.grade into tname,tdes,tloc,tgrade from

Emp e, dept d, salgrade s Where e.deptno=d.deptno and e.sal between s.losal and s.hisal and e.ename=tname; Dbms_output.put_line('name ='||tname); Dbms_output.put_line('job ='||tdes); Dbms_output.put_line('location ='||tloc); Dbms_output.put_line('grade ='||tgrade); Exception When no_data_found then Dbms_output.put_line('no such data found ..'); End; / Assignment 9 Write a pl-sql block which accepts designation and department number and displays number of employees with the same designation in the accepted department. Solution Declare Tdes emp.job%type:='&job'; Tdeptno emp.deptno%type:=&deptno; Tcount number(4); Begin Select count(*) into tcount from emp Where job=tdes and deptno=tdeptno; Dbms_output.put_line('no of employees with designation as '||tdes ||' are : '||tcount); Exception When no_data_found then Dbms_output.put_line('no such data found ..'); End; / Assignment 10 Write a pl-sql block which accepts location of employee and displays number of employees with the designation as manager and no. Of employees with the designation as clerk Solution Declare Tloc dept.loc%type:='&location'; Mcount number(4);

Ccount number(4); Begin Select count(*) into mcount from emp,dept Where job='manager' and emp.deptno=dept.deptno and dept.loc=tloc; Select count(*) into ccount from emp,dept Where job='clerk' and emp.deptno=dept.deptno and dept.loc=tloc; Dbms_output.put_line('no of managers : '||mcount); Dbms_output.put_line('no of clerks : '||ccount); Exception When no_data_found then Dbms_output.put_line('no such data found ..'); End; / Working with %rowtype attribute in pl/sql block %rowtype attribute is used in pl-sql block to reffer to a table complete record and assign a variable in decleration block Syntax <var> <tname>%rowtype; Example Rec emp%rowtype; Note: rec is a variable which can hold the completed record information. Explanation: Table contains the following two columns Table name: t1 A number(4); B number(4); Table data ----------------------------------a b ----------------------------------40 50 41 60

42 70 43 90 44 900 ----------------------------------Variable declared in pl-sql block Rec t1%rowtype; Extracting data into rec variable Select * into rec from t1 where a=42; Data extracted and stored as Rec a 42 b 70

Data can be displayed from pl-sql block with a reference to rec as Rec.a Or Rec.b Dbms_output.put_line(rec.a); Dbms_output.put_line(rec.b); Complete example Declare Rec emp%rowtype; Begin Select * into rec from emp Where empno=&empno; Dbms_output.put_line('employee number : '||rec.empno); Dbms_output.put_line('employee name : '||rec.ename); Dbms_output.put_line('employee salary : '||rec.sal); Dbms_output.put_line('employee comm : '||nvl(rec.comm,0)); Exception When no_data_found then Dbms_output.put_line('no data ....'); End; / Example of basic loop and for loop and while loop

Basic loop Declare I number(4):=1; Begin Loop dbms_output.put_line(i); exit when i>=10; i:=i+1; End loop; End; / Note: incrementation is required For loop Begin For i in 1..10 Loop Dbms_output.put_line(i); End loop; End; / Note: no incrementation is required While loop Declare I number(4):=1; Begin While i<=10 Loop Dbms_output.put_line(i); I:=i+1; End loop; End; / Assignment 11 Accept a number and display numbers from 1 to accepted number Solution Begin For i in 1..&i

Loop dbms_output.put_line(i); End loop; End; / Assignment 12 Accept a number and display math tables of it Solution Declare j number(4):=&j; p number(4); Begin For i in 1..10 Loop P:=i*j; Dbms_output.put_line(j||'x'||i||'='||p); End loop; End; / Assignment 13 Accept a string and a number to display the accepted name accepted number of times Solution Declare tstr varchar2(20):='&str'; tnum number(4):=&num; Begin For i in 1..tnum Loop Dbms_output.put_line(tstr||' - '||i); End loop; End; / Assignemnt 14 Accept a number and display sum of accepted number

Solution Declare Tnum number(4):=&num; P number(4):=0; Begin for i in 1..tnum loop p:=p+i; end loop; dbms_output.put_line(p); End; / Assignemnt 15 Accept a number to display numbers from accepted number to 1 Example 5 accepted Output 5,4,3,2,1 Solution Declare i number(4):=&num; Begin while i>=1 loop dbms_output.put_line(i); i:=i-1; end loop; End; / Working with cursors Pl-sql block is capable to process only one record. To enhance this features cursors are used.

Cursor is a work area which is to be declared and activated, records should be explicitly extreacted and displayed, cursors should be closed explicitely. Cursors are associated with cursor attributes (%is open -- %found -- %not found -- %rowcount) %is open it helps in analysis of cursor status %found it helps in analysis of records in cursor %not found it is used to analyze the negative impact of %found %rowcount it helps in analysis of records extracted in cursor area. Cursors are of two types 1. Implicit cursor (auto created and managed) 2. Explicit cursor (user defined) Syntax and keywords associated with cursors Cursor decleration Syntax Cursor <cursorname> is <sql query>; Example: Cursor c1 is select * from emp; Activate cursor Syntax Open <cursorname>; Example: Open c1; Extracting data into cursor Fetch <cursorname> into <var>; Example:

Fetch c1 into rec; Note: rec is a variable which is of %type or %rowtype. Closing of cursor Syntax Close <cursorname> Example: Close c1; Complete example of cursor with (%isopen) attribute Example (%isopen) Declare Cursor c1 is select * from emp where deptno=10; Err1 exception; Err2 exception; Begin Open c1; If c1%isopen then raise err1; Else raise err2; End if; Close c1; Exception When err1 then dbms_output.put_line('cursor open'); When err2 then dbms_output.put_line('cursor is closed'); End; / \ Example (%found) Declare Cursor c1 is select * from emp where ename='smith'; Rec emp%rowtype; Begin Open c1; Fetch c1 into rec;

If c1%found then Dbms_output.put_line('data found'); Else Dbms_output.put_line('data not found'); End if; Close c1; End; / Example (%notfound) Declare Cursor c1 is select * from emp where ename='smith'; Rec emp%rowtype; Begin Open c1; Fetch c1 into rec; If c1%found then Dbms_output.put_line('data found'); Else Dbms_output.put_line('data not found'); End if; Close c1; End; / Example (%rowcount) Declare Cursor c1 is select * from emp Where deptno=20; Rec emp%rowtype; N number(4); Begin Open c1; Loop fetch c1 into rec; exit when c1%notfound; End loop; N:=c1%rowcount; Dbms_output.put_line(n); End; / Displaying multiple outputs with cursor Declare Cursor c1 is select * from emp

Where deptno=20; Rec emp%rowtype; N number(4); Begin Open c1; Loop fetch c1 into rec; exit when c1%notfound; dbms_output.put_line(rec.ename); End loop; N:=c1%rowcount; Dbms_output.put_line('no of employees : '||n); End; / Assignment 16 Write a pl-sql block to display employee working with the employee who is least paid. Solution Declare Cursor c1 is select * from emp Where deptno=(select deptno from emp Where ename=(select ename from emp where sal=(select min(sal) from emp))); Rec emp%rowtype; Begin open c1; loop fetch c1 into rec; exit when c1%notfound; Dbms_output.put_line(rec.ename||' '||rec.deptno); end loop; close c1; End; /

Assignemnt 17 Write a pl-sql block which accepts department location and displays all the employees in the accepted location

Declare Cursor c1 is select * from emp where deptno=(select deptno from dept where loc='&loc'); Rec emp%rowtype; Begin open c1; loop fetch c1 into rec; exit when c1%notfound; dbms_output.put_line(rec.ename||' '|| rec.sal); end loop; close c1; End; / For loop with cursors Declare Cursor c1 is select * from dept; Begin For rec in c1 Loop Dbms_output.put_line(rec.dname||' '||rec.loc); End loop; End; / Dynamic cursor Declare Cursor c1 is &qry; Begin For rec in c1 Loop Dbms_output.put_line(&data); End loop; End; / Cursor extracting data from two tables Declare Cursor c1 is select e.ename,d.loc from emp e, Dept d where e.deptno=d.deptno; Begin For rec in c1 Loop

Dbms_output.put_line(rec.ename||' '||rec.loc); End loop; End; / Extracting indipendent column with cursors Declare Cursor c1 is select e.ename from emp e; Rec emp.ename%type; Begin Open c1; Loop Fetch c1 into rec; Dbms_output.put_line(rec); Exit when c1%notfound; End loop; Close c1; End; / Assignment 18 Display all the employees working with miller and jones with the designation as manager or clerk or analyst Assignment 19 Display all the employees only if they are maximum in count out of all the departments Assignement 20 Display the top three highly paid employees Assignment 21 Display all the employees only if the employee is highly paid when compared to his manager Assignment 22 Display all the employees only if the department is highly paid when compared with other departments

Assignment 24 Display all the employee information only if the departmant has more number of grade 1 or grade 3 Assignment 25 Write a pl-sql block todisplay all the employees name and manager name along with their salary,job, dname,loc,and grade only if the employee is designated as manager, clerk or analyst or president hired in the year 81 or 82 with th or ll or ending with 2nd last character as h

Query solution (1) and (2) Select w.ename,m.ename from emp w,emp m Where w.mgr=m.empno and w.ename=( Select e.ename from emp e Where (e.ename like('%th%') or e.ename like('%ll%') or e.ename like('%h_') ) and (e.hiredate like('%81') or e.hiredate like('%82')) and e.job in('manager','clerk','analyst')) / Select w.ename,m.ename from emp w,emp m Where w.mgr=m.empno and (w.ename like('%th%') or w.ename like('%ll%') or w.ename like('%h_') ) and (w.hiredate like('%81') or w.hiredate like('%82')) and w.job in('manager','clerk','analyst') / Example for having clause 1.display all the employees who are maximum in count A. Select * from emp where deptno=( Select deptno from emp Having count(*)=( Select max(count(*)) from emp Group by deptno) Group by deptno) / 2. Display all the employees who are min out of maximum count Select * from emp where deptno=( Select deptno from emp Having count(*)=(

Select min(count(*)) from emp Group by deptno) Group by deptno) / 3. Display all the employees working with the same department where there are more number of 'salesman' Select * from emp where deptno=( Select deptno from emp Where job='salesman' Having count(*)=( Select max(count(*)) from emp Where job='salesman' Group by deptno ) Group by deptno) and job='salesman' / Select <col/*> from <tablename> Where <cond> Having <cond> Group by <col> Order by <col>; Display all the employees only if the department contains more number of clerks Select * from emp where deptno=( Select deptno from emp Where job='clerk' Having count(*)=( Select max(count(*)) from emp Where job='clerk' Group by deptno) Group by deptno) /

Working with procedures Procedures are named block which are also referred as stored procedures as the exist in the database. Procedures accepts inputs, perform a process and display output. Procedures are identified by a unique name in database. Procedure should be written compiled without any errors so that it can be called any number of times from an anonymous block. Procedures are to be declared compiled and called explicitely. Syntax: Create or replace procedure <procedure name>(parameter list) is <variable> Begin <statements>; End; Example 1: Create or replace procedure p1(name varchar2) Is Begin dbms_output.put_line(hello :||name); End; / Note: execution of the above procedure should return procedure created statement at sql prompt Note: alter the code to analyze errors in procedure by typing the following code Create or replace procedure p1(name varchar2) Is Begin Dbms_output.put_line('hello :'|name); End;

/ Note: concatenation pipe missing it should return error message as: warning: procedure created with compilation errors. Type the following to get information about the error Sql> show errors Rectify the error and re-execute the procedural block till it returns procedure created Procedure call from anonymous block Declare n varchar2(20):=&name; Begin p1(n); End; / Or Begin p1('&n'); End; / Note: type at sql> prompt set serveroutput on to analyze results. Procedure 2 Procedure declaration Create or replace procedure findlength(name varchar2) Is Res number(4); Begin Res:=length(name); Dbms_output.put_line('length of name : '||name||' is : '||res); End; / Procedure call Begin findlength(&name);

End; / Drop a procedure Drop procedure <procedure name>; Select * from user_source where type='procedure' / Drop procedure findlength; Drop procedure p1; Execution of procedure at sql prompt Sql> execute findlength('deepak');

Assignment 1: Write a procedure which accepts employee name as input and displays number of employees working with him. Solution Procedure declaration Create or replace procedure numemp(name varchar2) is Tcount number(4); Begin select count(*) into tcount from emp where deptno=(select deptno from emp where ename=name); Dbms_output.put_line('no of employees :'||tcount); End; / Procedure call Begin Numemp('&name'); End; / Execution from sql prompt Execute numemp('smith');

Assignment 2: Write a procedure which accepts designation and displays total number of employees in emp table with same designation. Solution Procedure decleration Create or replace procedure findnumemp(des emp.job%type) is Res number(4); Begin select count(*) into res from emp where job=des; dbms_output.put_line(res); End; / Procedure call Declare d emp.job%type:='&designation'; Begin findnumemp(d); End; / Assignment 3: Write a pl-sql procedure which displays number of employees in the accepted department. \

Solution Procedure decleration Create or replace procedure numemp(dn emp.deptno%type) is Res number(4); Begin Select count(*) into res where deptno=dn; Dbms_output.put_line(res); End;

Procedure call Declare deptno emp.deptno%type:=&deptno; Begin numemp(deptno); End; / Assignment 4: Write a pl-sql procedure which accepts employee number and displays name of the employee with salary and designation including department name. Assignment 5: Accept designation and display all the employee with the same designation. Assignment 6: Accept code as input to perform deposit / withdraw operation on bank table with a reference to procedure. Bank Create table bank( Accno number(4) primary key, Ahname varchar2(20) not null, Balance number(8,2) not null)

Data Insert into bank values(1001,'dinesh',5000); Insert into bank values(1002,'dilip',4000); Insert into bank values(1003,'deepak',2000); Create or replace procedure transdeposit(amt number,acc number) is Begin Update bank set balance=balance+amt where accno=acc;

End; / Create or replace procedure transwithdraw(amt number,acc number) is Begin Update bank set balance=balance-amt where accno=acc; End; / Create or replace procedure trans(opt char,acc number,amt number) is Begin If opt='d' then Transdeposit(amt,acc); Else Transwithdraw(amt,acc); End if; End; / Execution of procedure Execute trans('d',1003,1000) Working with functions Functions are named blocks which exist in database with a unique name. Functions return values after completion of process assigned to it. Functions are equivalent to procedures but they differ only by sending restults to the place from where the call was being made. Functions are to be declared and called from anonymous block Syntax: Create or replace function <fname>(list of parameters) return <datatype> is <var> Begin <statement>; End; /

Function decleration Create or replace function f1(a number,b number) return number is Res number(4); Begin res:=a+b; return(res); End; / Function call from anonymous block Declare a number(4):=&a; b number(4):=&b; c number(4); Begin c:=f1(a,b); for i in 1..c loop dbms_output.put_line(i); end loop; End; / Execution of function from sql prompt Sql> var a number Sql> execute :a:=f1(&a,&b) Sql> select :a from dual; Or Sql>print :a Or Sql>print a Or Sql> select f1(&a,&b) from dual; Assignments 1: Write a function which accepts department location and displays number of employees in accepted department location Cerate or replace function Assignment 2

Write a function which accepts a name and displays numbers based on the length of accepted name Assignemnt 3 Write a function which calculates total salaries of each department Assignment 4 Write a function which accepts number inputs and displays the output based on procedure to add accepted inputs Assignemnt 5 Write a function which performs add / sub / mul / divide operation based on the input given by user with two inputs

03.05.2005 +++++++++++++++++++++++++++++++++++++++++++++++ 04.05.05 Working with packages Creating procedure p1 and p2 Procedure1.sql Create or replace procedure p1(a number,b number) Is Res number(4); Begin Res:=a+b; Dbms_output.put_line('result of add = '||res); End; / Procedure2.sql Create or replace procedure p2(a number,b number) Is Res number(4); Begin Res:=a-b; Dbms_output.put_line('result of subtract = '||res);

End; / Function1.sql Create or replace function f1(a number,b number) Return number is Res number(4); Begin res:=a*b; return(res); End; / Function2.sql Create or replace function f2(a number,b number) Return number is Res number(4); Begin res:=a/b; return(res); End; / Working with packages Packages are stored procedures with a combination of functions and procedures. Packages are divided into two parts 1. Packages specification 2. Package body
1.

2.

Package specification: it is used to define a unique package name and to specify the structure associated with procedures and functions, which are part of package. Package body: it is used to refer to a declared or defined package and to specify the actual process associated with procedures and functions (source code)

Creating a package with the name as: math No. Of procedures associated 2 : p1( ) and p2( ) No. Of functions associated 2 : f1( ) and f2( )

Package specification

Create or replace package math is Procedure p1(a number,b number); Procedure p2(a number,b number); Function f1(a number,b number) return number; Function f2(a number,b number) return number; End; / Package body Create or replace package body math is Procedure p1(a number,b number) Is Res number(4); Begin res:=a+b; dbms_output.put_line(res); End p1; Procedure p2(a number,b number) Is Res number(4); Begin res:=a-b; dbms_output.put_line(res); End p2; Function f1(a number,b number) return number Is Res number(4); Begin res:=a*b; return(res); End f1; Function f2(a number,b number) return number Is Res number(4); Begin res:=a/b; return(res); End f2; End math; / Execution of package from sql prompt Defining variable

Sql>var a number Sql>var b number Sql>execute math.p1(5,5); Sql> execute math.p2(5,5); Sql>execute :a:=math.f1(5,5); Sql>execute :b:=math.f2(5,5); Extracting function output from bind variables Sql>select :a,:b from dual; Execution of package from pl-sql anonymous block Declare a number(4):=&a; b number(4):=&b; c number(4); Begin -- procedure call math.p1(a,b); math.p2(a,b); -- function call c:=math.f1(a,b); dbms_output.put_line(c); c:=math.f2(a,b); End; / Problem 1: Create or replace function ff1(n number) return varchar2 is Ext varchar2(20); Cursor c1 is select ename from emp where deptno=n; Begin for i in c1 loop ext:=i.ename; return(ext); end loop; End; / Function returns more than one value Declare n emp.deptno%type:=&deptno; ex emp.ename%type; Begin

Ex:=ff1(10); End; Assignment 1: Create a package by name dep10 which allows to perform the following operations only on department 10 1. 2. 3. 4. Display contents of department 10 (p) Display contents of accepted designation (p) Display number of employees (f) Display total salary, average salary, minimum salary, maximum salary (f) 5. Insert data into table (p) 6. Update data in table (p) 7. Delete data in table (p) (p) procedure (f) function Assignment 2: Create a package by name bank Triggers Triggers are also referred as database triggers. They can be explicitly invoked based on event like (insert / update / delete) Trigger is associated with three parts Trigger based on time Trigger base on event Trigger based on action Trigger based on constraint Triggers are mainly used to implement business logic associated with the rules and regulations framed. Trigger can be associated with statement and row Positive 14 trigger combinations 1. Before insert statement 2. Before insert row

3. After insert statement 4. After insert row 5. Before update statement 6. Before update row 7. After update statement 8. After update row 9. Before delete statement 10.before delete row 11.after delete statement 12.after delete row 13. Instead of statement 14. Instead of row Firing sequence of trigger Before statement trigger (fires once) Before row trigger (fires once for each row) After row trigger (fires once for each row) After statement trigger (fires once) Creating statement trigger Example on before insert statement Create or replace trigger t1 Before insert on bank Begin dbms_output.put_line('started inserting '); End; / Example on after insert statement Create or replace trigger t2 After insert on bank Begin dbms_output.put_line('completed inserting'); End; / Drop trigger Sql> drop trigger t1; Example on before update statement Create or replace trigger t3 Before update on bank

Begin dbms_output.put_line('started updating'); End; / Example on after update statement Create or replace trigger t4 After update on bank Begin dbms_output.put_line('completed updating'); End; / Example on before delete statement Create or replace trigger t5 Before delete on bank Begin dbms_output.put_line('data will be deleted '); End; / Example on after delete statement Create or replace trigger t5 After delete on bank Begin dbms_output.put_line('data deleted successfully'); End; / Example on before (insert / update / delete) (conditional predicates) Inserting / updating / deleting Create or replace trigger mytrig Before insert or updte or delete on bank Begin If inserting then Dbms_output.put_line(insert performed); End if; If updating then Dbms_output.put_line(update performed); End if; If deleting then Dbms_output.put_line(deleting performed);

End if; Row trigger Create or replace trigger trig1 Before update on bank For each row Begin dbms_output.put_line('line updated'); End; / Perform the following trigger Sql>update bank set balance=balance+100; Example on row trigger Create or replace trigger trig1 Before insert on bank For each row Begin dbms_output.put_line('line inserted'); End; / Create or replace trigger trig1 Before insert or update or delete on bank For each row Begin Dbms_output.put_line('data altered'); End; / Inserting records from pl-sql block Begin For i in 1..50000 Loop Insert into bank values(i,'deepak '||i,i+1000); End loop; End; / Trigger based on update to insert into 2nd table

Create or replace trigger mytrig Before update on bank For each row Begin If updating then Insert into bankback values(:old.accno,sysdate); End if; End; / Insert :old can not be reffered if insert is performed Update :old and :new can be reffered at the time of performing update operation on a table. Delete Only :old can be reffered while performing delete operation on a table. Working with instead of trigger Creating view based on join Create view emp10 as select e.empno,e.ename,e.sal,d.deptno,d.dname,d.loc From emp e,dept d Where e.deptno=d.deptno and e.deptno=10; Extracting data from a view Select * from emp10; Instead of trigger is used to specify what has to be done instead of performing a specific operation like (instead of delete) Create trigger mytrig Instead of delete on emp10 For each row Delete from emp where deptno=:old.deptno; Delete from dept where Deptno=:old.deptno; End;/

You might also like