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

pl/sql

Programming language using sql. plsql block: a set of instructions runs in the database. to enhance capabilities of sql oracle introduced pl/sql in early 1990s. a pl/sql is a combination of sql statements and as well programming constructs like Variables, if conditions, loop, control instructions etc. Features of pl-sql : Modular programming Security Exception handing pl-sql block : a block is a set of sql and plsql constructs which is executed as single unit. These are two types of blocks 1. Unnamed plsql block 2. Named plsql block. Unnamed plsql block: it is a plsql code which is not saved in the database but can be saved in client machine. Named blocks: stored in the database. ex: functions, procedures, packages, triggers. Declare (optional) Variable section Begin Executable section Exception (optional) End; Variable: a variable is a name gives to the memory location where a value is stored. syn:<variable><data type>[notnull :=value]

note: when it is not null give a value mandatory. ex: declare a number (3):=1000; b number (3):=1000; c number (3); c:= a+b; dbms_output.put_line(the sum of two numbers is||c); end; / constant variable: syn: <variable> constant<data type>:=value; ex: pi constant number (4, 2) =3.14; select into: it must and should return only one row .if it returns more than one row or zero rows it is error. To retrieve row or string variables syn: select <column(s)> into <variables> from <table_name> [where <condition>]; ex: declare v_empno number (4):=&v_empno; v_ename varchar2 (10); begin select ename into v_ename from emp where empno=v_empno; dbms_output.put_line(employee name is|| v_ename);

end; / declaring variables with existing columns data types <variable> <table.column>%type; v_ename emp.ename%type; v_job scott.emp.job%type; (if they are in different schema then). declare v_deptno dept.deptno%type; v_dname dept.dname%type; v_loc dept.loc%type; begin select * into v_deptno , v_dname ,v_loc from dept where deptno=&deptno; dbms_output.put_line(department number:||v_deptno); end; record type: it is a collection of individual variables .it is a composite data type defined by user, also called as user defined data type. type <type_name > is record (variable 1 data type, variable2 data type,); ex:- type emp_rec is record(ename varchar2(10), job varchar2(20),sal number(7,2)); to use a composite data type we should declare a variable and use it syn: <variable> <composite_data_type>; r emp_rec; r1 emp_rec; declare v_empno number (4):=v_empno; type emp_rec is record (ename varchar2 (10), job varchar2 (10), sal number (7, 2)); r emp_rec; begin

select ename,job,sal into r.ename,r.job,r.sal from emp where empno=v_empno; dbms_output.put_line(employee name:||r.ename); dbms_output.put_line(employeejob:||r.job); dbms_output.put_line(empsal:||r.sal); end; / note: - above select into statement using record variable can also be written as select ename,job,sal into r from emp where empno=v_empno; example 2 declare type dept_rec is record(deptno dept.deptno%type,dname dept.dname%type,loc dept.loc%typte); r dept_rec; begin select * into r from dept where deptno=&deptno; dbms_output.put_line(deptno:||r.deptno); dbms_output.put_line(dname:||r.dname); dbms_output.put_line(location at:||r.loc); end; / declaring record variable based on existing table:syn:-<record_variable><table>%rowtype; declare r dept%rowtype; begin select * into r from dept where deptno=&deptno; dbms_output.put_line(deptno:||r.deptno);

dbms_output.put_line(dname:||r.dname); dbms_output.put_line(location at:||r.loc); end; / ex2:declare type emp_rec is record(ename varchar2(20),dname varchar2(10)); r emp_rec; v_empno number(4):=&v_empno; begin select e.ename,d.dname into r from emp e,dept d where e.deptno=d.deptno and e.empno=v_empno; dbms_output.put_line(employee||r.ename||is working in|| r.dname||department); end; / do it: create a block which will accept department name and display no.of employees working in it control instructions: 1.decision control instructions 2.loop control instructions decision control instructions: used to execute a set of statements based on a condition(variable). like if,ifelse,nested if ,ifelsif. if:- executes a set of statements if given condition is true. syn: if<condtion> then statements;

end if; ex:declare v_empno number(4):=v_empno; v_sal number(7,2); v_grade char(1); begin select sal into v_sal from emp where empno=v_empno; if v_sal>=3000 then v_grade:=a; end if; if v_sal <3000 then v_grade:-=b; end if; dbms_output.put_line(employee grade is ||v_grade); end ; / declare v_empno number(4):=&v_empno; v_sal number(7,2); v_grade char(1):=b; begin select sal into v_sal from emp where empno:=v_empno; if v_sal >=3000 then v_grade:=a; end if ; dmbs_output.put_line(employee grade is ||v_grade);

end if; / -declare v_dept number(2):=&v_deptno; v_dname varchar2(10); v_loc varchar2(10); v_count number; begin select dname,loc into v_dname,v_loc from dept where deptno=v_deptno; select count(*) into v_count from emp where deptno=v_deptno; dbms_output.put_line(v_deptno||v_dname||v__loc||v_count): end; note: in plsql procedures are stored in server these are called client system. If all clients are called at a time these are stored in queue based upon the priority it will take. These are take care in oracle server. In sql the queries are stored client side only. Basically plsql is combination of sql statements and programming language so on that situation both engines will work on switching process . that is called context switching. nested if : using an if condition in another if is called nested if assign grade a to employees who are working as job analyst, president,manager sal>3000- grade a sal<3000- grade b job not in president manager sal>=3000 grade c sal<3000 grade d

declare v_empno number(4):=v_empno;

v_job varchar2(10); v_sal number(7,2); v_grade char; begin select job,sal from emp where empno=v_empno; if v_job in(president, manager) then if v_sal>=3000 then v_grade :=a; else v_grade :=b; end if; else if v_sal>=3000 then v_grade:=a; else v_grade :=b; end if; else if v_sal>=3000 then v_grade:=c; else v_grade:=d; end if; end if; dbms_output.put_line(gtade is||v_grade); end; /

ifelsif syn : if <condition > then action elsif <conditon> then ------------------else statements; endif; if sal>=5000 then grade:=a; elsif sal>=4000 then grade :=b; elsif sal>=3000 then grade:=c; else grade:=d; end if;

loop control insturctions 1.simple loop 2.while loop 3.for loop

1.simple loop: syn: loop statements; exit when<cond>; statements; end loop; note: if condition is true then statement will exit. Ex: declare 1 to n declare i number:=1; n number:=&n; begin loop dbms_output.put_line(i); exit when i=n; i:=i+1; end loop; end; / while: syx: while <conditon> loop statements;

end loop; ex:-declare i number:=1; n number:=&n; begin while i<=n; loop dbms_output.put_line (i); i: =i+1; end loop; end; FOR LOOP :

syn: for <vari> in <val1> <val2> loop statements; end loop; ex:- declare n number:=&n; begin for i in 1..n /* for i in reverse order*/ loop dbms_output.put_line(i); end loop; end;

CURSOR

A cursor is a pl/sql object which is capable of storing more than one row at a time. The number of rows hold by a cursor is called active set. I.e. a cursor is temporary work area which can hold more than one row even though a cursor is capable of holding more than one row, we can process only one row at a time. There are two types of cursors IMPLICIT CURSOR EXPLICIT CURSOR implicit cursor: An implicit cursor is the one which is raised by oracle when ever we perform dml operations when a select statement which returns only one row is executed using this implicit cursor we can know how many rows are effected by the dml operations to at least one row is effected or not attributes: sql%found true/false If it is true at least one row is affected by the dml operation. sql%notfound: it is quite opposite to previous. Returns true if no row affected by the dml operations. sql%row count: return count of rows effected by dml operations. sql%is open: always evaluates to false bcoz pl/sql closes implicit cursor immediately after they are executed. ex: declare v_deptno number(2):=&v_deptno; begin update emp set sal=sal*1.15 where deptno=v_deptno;

if sql%found then dbms_output.put_line(sql%rowcount||emplouees updated); elsif sql%notfound then dbms_output.put_line(no employees in dept); end if ; end; EXPLICIT CURSORS: An explicit cursor is the one which is created by user to hold more than one row .a cursor may hold more than one row but we can process only one row at a time. steps: 1 declare the cursor in the declaration session syx: cursor <cursor name> is <select statement>; 2.open the cursor syn: open <cursor name>; 3.fetch the records getting the rows from a cursor using fetch syn: fetch <cursor name> into <variable records>; 4.close the cursor syn: close<curosr name>; ex:declare cursor c is select * from dept ; v_deptno dept.deptno%type; v_dname dept.dname%type; v_loc dept.location%type; begin open c;

fetch c into v_deptno,v_dname,v_loc ; dbms_output.put_line(v_deptno|| ||v_dname|| ||v_loc); fetch c into v_deptno,v_dname,v_loc ; dbms_output.put_line(v_deptno|| ||v_dname|| ||v_loc); close c; end; / in oracle fetch statement will follow forward approach where as in other data bases they follow both forward and backward. note: consider if a table have four rows if i want to fetch the fifth row it will show null values. ex: declare cursor c is select * from dept; r dept%rowtype; begin open c; fetch c into r; dbms_output.put_line(r.deptno|| ||r.dname|| ||r.loc); fetch c into r; dbms_output.put_line(r.deptno|| ||r.dname|| ||r.loc); close c; end; / ex 2: declare cursor c is select ename,job,sal,dname from emp,dept where emp.deptno=dept.deptno;

r c%rowtype; begin open c; fetch c into r; dbms_output.put_lime(r.ename||r.job||r.sal||r.dname); close c; end; / attributes: these are actually start with cursor name <cursorname>%found: returns true if the fetch statement is successful. <cursorname>%not found: returns true if the fetch statement is not successful. <cursorname>%row count: returns count of rows fetched up to now. <cursorname>%is open: return true if cursor is already open.

cursor with simple loop: declare cursor c is select ename,job,sal from emp; r c%row type; begin open c; loop fetch c into r; exit when c%not found; dbms_output.put_line(r.ename|| ||r.job|| ||r.sal); end loop;

dbms_output.put_line(c%rowcount||rows fetching); close c; end; / 2.cursor with while loop: declare cursor c is select ename,job,sal from emp; r c%rowtype; begin open c; ferch c into r; while c%found; loop dbms_output.put_line(rpad(r.ename,10)||rpad(r.job,10)||lpad(r.sal,8)); fetch c into r; end loop; close c; end; / example 3: declare cursor c is select ename,job,sal from emp order by ename; grade char; begin dbms_output.put_line(sno || ||sname|| ||sal grade); for r in c

loop if r.sal>=5000 then grade:=a; elsif r.sal>=4000 then grade: =b; elsif r.sal>=3000 then grade: =c; else grade:=d; endif; dbms_output.put_line(rpad(c%rowcount,4)||rpad(r.ename,10)||rpad(r.job,10)|| lpad(r.sal,8)); end loop; end; ---------------------------------------------------------------------------------------------------------------------cursor with parameters (parameter cursor); A cursor can accept parameters and return rows based on the passed parameters. syn: cursor <name>(par1 datatype,par2 datatype);

declare v_deptno number:=&v_deptno; cursor c(x number) is select * from emp where deptno=x; r emp%rowtype; begin open c( v_deptno); loop fetch c into r; exit when c%notfound;

dbms_output.put_line(r.ename); end loop; close c; end;

ex 2: declare cursor c(x number) is select * from emp where deptno=x; r emp%rowtype; begin for i in (select * from dept); loop dbms_output.put_line('dept name'||i.dname); open c(i.deptno); loop fetch c into r; exit when c%notfound; dbms_output.put_line(r.ename); end loop; close c; end loop; end; -----------------------------------------

EXCEPTIONS: ----------An exception is raised if any statement violates RDBMS rules. An exception is a runtime error. I.e. an error occurred at runtime. They are two types of exceptions 1. Named exceptions 2.unnamed exceptions Named:-Each exception raised by oracle here an error number associated oracle have already named them such exceptions are called named exceptions. Having named exceptions

error no ora-01403

exception name no_data_found

DESC when select into statement returns no rows

ora-01422 ora-1001 ora_06511

too_many_ rows invalid_cursor cursor_ already_open

when select into statement returns more than one row when we fetch rows from a cursor when is not yet open when we open a cursor which is already open

ora-06502

value_error

when converting char data to number

; syn declare ----------------------begin statements; exception when <exception_name> then --------------when <exception_name> then --------end;

ex: Declare a number; b number; c number; zero_devide exception; Begin a:=&a; b:=&b; c:=a/b;

dbms_output.put_line('result is='||c); Exception when zero_devide then dbms_output.put_line('cannot divide a value by zero'); end; /

Declare v_ename varchar2 (100); v_job varchar2 (10); Begin Select ename,job into v_ename,v_job from emp where empno='&empno'; dbms_output.put_line('emp name:'||v_ename); dbms_output.put_line('emp job:'||v_job); Exception When no_data_found then dbms_output.put_line('emp doesnot exist'); When invalid_number then dbms_output.put_line('number should be number farmate'); End; / Note: dbms_output.put_line(sql errm); It will show the error message and sql code-> display error code

3) Declare C number;

Begin C: ='&a'+'&b'; dbms_output.put_line('sum='||C); Exception When value_error then dbms_output.put_line('give number'); When others then dbms_output.put_line('un known errors occurred'); End; /

Note: - check built in fun for error message of error code

Handling UN named exceptions: -------------------------To handle unnamed exceptions which is not named by oracle we should associate a name to the specific exception and handle we can associate a name to exception using 'pragma exception_init'

Steps 1. Create an exception name syn:<exception_name> exception; 2. Associate the created name to error number; syn : pragma exception_init(<exception_name,<error_number>); 3. Now we can handle exception with the name associated;

Ex:-

Declare v_deptno number:=&v_deptno; child_data_found exception; pragma exception_init(child_data_found,-2292); Begin Delete from dept where deptno=v_deptno; If sql%found then dbms_output.put_line('department deleted'); Else dbms_output.put_line('dept does not found'); End if; Exception When child_data_found then dbms_output.put_line('employees exist in this deparment'); End; /

---Exception propagation: ---------------------If we write exceptions for one condition but there was raised exception Regarding to another condition.

User defined exceptions:

These are the exceptions which are raised by the user based on company or project requirement. We can raise an exception using the statement like 'raise'. raise<exception_name>; Exception name be user defined or pre defined We may raise predefined exception name or user defined exception name Ex: Declare v_empno number(4):=&v_deptno; new_sal number(7,2):=&new_sal; v_sal number(7,2); invalid_salary exception; Begin Select Sal into v_sal from emp where empno=&v_empno; if new_sal>v_sal*1.2 then raise invalid_salary; end if; update emp set sal=new_sal where empno=v_empno; exception when invalid_salary then dbms_output.put_line('can't increase salary more than 20%'); end; /

Modular programming: means the entire block should be placed in another begin block so we can handle exceptions in declare block.

procedures

procedures:-- a procedure is a named pl/sql block which is saved in the database for later usage. note: dont write substitution variables in procedures b'coz if we give the value for first from second time onwards it will store the same value. syn: create or replace procedure < par name, p2 dtype,...> is --------begin ------exception ------end; /

create or replace procedure get_emp_data is cursor c is select ename,job,sal from emp; r c%rowtype; begin open c; loop fetch c into r; exit when c%not found; dbms_output.put_line(r.ename||r.job||r.sal); end loop; close c; end; /

Execution process: syn: exec get_emp_data;

show error: to view errors in named block sql:show err note: procedure will not return a value.

2. Create or replace procedure get_emp_data(v_deptno number) is Cursor c is select ename,job,sal from emp where deptno=v_deptno; r c%rowtype;

begin open c; loop fetch c into r; exit when c%not found; dbms_output.put_line(r.ename||r.job||r.sal); end loop; close c; end; /

3. create or replace procedure job_desc(v_job varchar2(20)) is v_count number; v_sum number; v_max number; begin select count(*),sum(sal),max(sal) into v_count,v_sum,v_max from emp where upper(job)=upper(v_job); dbms_output.put_line('no.of employees working as '||v_job||v_count); dbms_output.put_line('total salaries paid||v_sum);

Type of parameters 1.In parameters 2.out parameters 3.inout parameters Procedure xyz(a number,b number)

These are in parameters

Out parameters: these are used to get output from a procedure Create or replace procedure get_deptdata(v_deptno in number, v_dname out varchar2, v_loc out varchar2); is begin select dname,loc into v_dname,v_loc from dept where deptno=v_deptno; exception when no_data_found then null; end;

how to call procedure in pl/sql declare x number(2):=&x; y varchar2(10); z varchar2(10); begin get_deptdata(x,y,z); dbms_output.put_line('dept name'||y); dbms_output.put_line('dept loc:'||z); end; / call procedure using bind variables sql> variable x varchar2(10) sql> variable y varchar2(20) sql> exec get_deptdata(30,:x,:y)

sql> print :x

sql> print :y

sql>select :x,:y from dual;

inout argument: can be used for both input as well as output. This variable can be used for both ex Create or replace procedure get_emp_count(v_deptno inout number) Is Begin Select count (*) into v_deptno from emp where deptno=v_deptno; End; /

Ways to pass parameters in procedure: Positional Conventional Combinational

ex:Create or replace procedure insert_dapt(v_deptno number,v_dname varchar2,v_loc varchar2:='newyark') is

begin insert into dept values(c_deptno,v_dname,v_loc); end; / positional: insert_dept(50,'marketing','boston'); conventional: (v_loc=>'boston',v_deptno=>50,v_dname=>'marketing'); combinational (50,v_loc=>'boston',v_dname=>'marketing');

Functions:A function is also a named pl/sql block like a procedure, the difference is fun returns a values where as procedure can't returns a value. we can use these functions in a select statement also just like 'pre defined functions'

Create or replace function <function_name>[(<parameters>)] return <return_type> is -----begin ---

----return<value>; exception ------end; /

ex:create or replace function concat2(s1 varchar2,s2 varchar2) return varchar2 is begin return s1||'||s2; end; /

select concat(ename,job) from emp;

2. Accept empno and return ename Create or replace function emp_ename(v_empno number) return varchar2 is v_ename varchar2(20); Begin Select ename into v_ename from emp where empno=v_empno; Return v_ename;

exception when no_data_found then return 'none'; end; /

select get_name(7902) from dual; select get_name(empno) from emp;

create or replace function get_count(v_deptno number) return number is v_count number; begin select count(*) into v_count from emp where deptno=v_deptno; retunn v_count; end; /

select count(10) from dual; select deptno,dname,get_count(deptno) from dept;

Packages:A package is a group of individual pl/sql constrains like variables, constants, record types Other collection types, cursors, procedures and functions.

Package creation is involved in two steps Create package specification Create package body Package specification consists of variables ,constants ,cursors ,functions ,procedures, record types And other collections types declared. A package body which consists of cursor, procedures and function definitions.

syn:- create or replace package<pack_name> is||as variable(s)||constants|| record type; collection type(s); cursor(s) return<return type>; end <pack_name>; /

body:

Create or replace body<pack_name> is||as Cursor <cursor_name>returns <return_type> is Select statement; Procedure <procedure_name>[arguments] is ----

------begin --exception ------end <proc_name>; function <function_name>[(arguments)] return <return_type> is ------begin -------exception ------end <fun_name>; end <pack_name>; /

ex: create or replace package pack1

is procedure emp_data; procedure dept_data; end pack1;

Execute this

Now create the body of the pack

Create or replace package body pack1 is procedure emp_data is cursor c is select * from emp; begin for r in c loop dbms_output(r.ename||r.job||r.sal); end loop; end emp_data; procedure dept_data is cursor c is select * from dept; begin for r in c loop

dbms_output.put_line(r.deptno||r.dname||r.loc); end loop; end dept_data; end pack1; /

2. Create or replace package emp_pack is r emp%rowtype; v_manager varchar2(10); procedure get_emp(v_empno number); procedure get_all_emp(v_deptno number); end emp_pack; / create or replace package body emp_pack is function get_name(v_empno number) return varchar2; procedure get_emp(v_empno number) is begin select * into r from emp where empno=v_empno; v_manager:=get_name(r.mgr); dbms_output.put_line(r.ename); dbms_output.put_line(v.manager); exception when no_data_found then

dbms_output.put_line('emp does not support'); end get_emp; procedure get_all_emp(v_deptno number) is cursor c is select * from emp where deptno=v_deptno; begin open c; loop fetch c into r; exit when c%notfound; v_manager:=get_name(r.mgr); dbms_output.put_line(r.ename||v_manager); end loop; close c; end get_all_emp; function get_name(v_empno number) return varchar2 is v_ename varchar2(10); begin select ename into v_ename from emp where empno=v_empno; return v_ename; exception when no_data_found then return 'none'; end get_ename; end emp_pack;

Triggers A trigger is also a pl/sql block used to implement data integrity on tables. I.e. it can be Used to validate the data. a trigger get fires when ever an associated dml operation is Performed on a table. A trigger can be used to validate data and as well as to keep track Of existing data. In trigger there are in two formats 1. before 2.after Create or replace trigger<trigger_name> Before || after|| instead of Insert or update or delete of columns on <table_name> [referenceing old as o new as n] [for each row] [when <cond>] Declare Begin ------End;

raise_application_error(): to rise user defined errors.

syx: raise_application_error(-errorno,'message');

the number should be -20000 to -20999 if it is Sunday no need to do any transactions CREATE OR REPLACE TRIGGER NO_TRANS_ON_SUN BEFORE INSERT OR UPDATE OR DELETE ON EMP BEGIN IF TO_CHAR(SYSDATE,'DY')='SUN' THEN RAISE_APPLICATION_ERROR(-2000,'CAN''T PERFORM ANY DML OPERATIONS ON SUNDAY'); END IF; END;

Levels of triggers 1. Statement level trigger and 2. Row level trigger First one is execute only for entire table Second one will execute for every row.

to drop: drop trigger<trigger_name> Trigger will not allow commit and rollback statements;

1. Statement level trigger: it is a trigger when executed only once whenever DML operations per formed Create table emp_track(uname varchar2(10),tdate date,ttime varchar2(20)); CREATE OR REPLACE TRIGGER EMP_TRACK_TRIGGER

AFTER INSERT OR UPDAT OR DELETE ON EMP BEGIN INSERT INTO EMP_TRACK VALUES (USER, SYSDATE, TO_CHAR (SYSDATE,'HH:MM')); END; /

Row Level Triggers: it is a trigger which is executed for each row affected DML operation. A row level trigger is used to validate data in each row. We can validate data using the Qualifier old and new old contains old data and new contains new specification by adding For each row in trigger creation

CREATE OR REPLACE TRIGGER TO_UPPDER BEFORE INSERT OR UPDATE ON EMP FOR EACH ROW BEGIN :NEW.ENAME:=UPPER(:NEW.ENAME); :NEW.JOB:=UPPER(:NEW.JOB); END; /

Order of trigger execution

before statement level before row level after row level after statement level trigger.

TRIGGER MUTATION : A trigger is said to be mutating when ever we try to perform dml operations or select operation in trigger body of the same table an exception is raised which is called trigger mutation error.b'coz we can't perform DML or select on the same table in trigger body. To overcome this trigger mutating error we can implement the 'pragma autonomous_transaction'.

Alter trigger <trigger_name> enable or disable;

note : the trigger ,procedure, functions or packages are stored in data dictionary user_procedures If you want to know code the user_sources

trigger cascade: one trigger should not call another trigger

NOTE: Instead of is used when you are going for VIEWS

COLLECTIONS plsql tables: A table type is used to show more then one row of values . a plsql table is one of the collection type. So the use plsql table we should declare a variable to it and use it. syn:- type <type_name> is table of <datatype>

ex: type <type_name> is table of <datatype> [index by binary_integer/pls_integer];

if we not declare index by option and data type then it follow linked list ex: type< name> is table of varchar2(10) index by binary_integer; n number;

ex: type names is table of varchar2(10) index by binary_integer; cursor c is select ename from emp; v_ename varchar2(10); n names; idx number:=0; begin open c; loop fetch c into v_ename; exit when c%notfound; idx:=idx+1; n(idx):=v_ename;

end loop; for i in 1..idx loop dbms_output.put_line(n(i)); end loop; end; table type attributes: first : returns first index number of a table ex: data.first last: return the last index number. next: next index number of a specified index data.next(5)->after the 5th what we have. prior: privious index count: to know number of indexes present in a table delete to delete all indexes or specified index data.delete -all the indexes deleted present in table. data.delete(idxno) delete specified ex data.delete(5); data.prior(6); o/p:4 b.coz 5th is deleted. exists:returns true if specific index exists data.exists(5)- false b'coz it is already deleted. Extend: to extend an index of a non indexed table here it is extend one place for one time.

Nested tables: while creating a table in sql if we take any of the column data type has a pl/sql table type then it is called nested tables sql> create type members is table of varchar2(15); sql> create table family_details(family_head varchar2(20),dependents members) Nested table dependents store as dept_tbl / Note: dept_tbl is new table which stores family_head insert into family_details values('babu',member('swati','kavya','bujji')); sql> select * from family_details; sql> select * from table(select dependent from family_details where family_head='babu')

insertion : insert into table(select dependent from family_details where family_head='babu') values ('ramesh'); delete from table(select dependent from family_details where family_head='babu') where column_value='bujji'; NOTE: Here dept_tbl is storage table if we want to access data by original table

note: oracle do not follow pointers thats only we are using dependents store concept

Refcursor: it is basically a data type. A ref cursor is used to associate a Select statement .at runtime rather than at compile time. i.e we can associate a select statement to refcursor while opening the cursor. syn: type <type_name> is ref cursor; type ref_cur is ref_cursor; c ref_cur;

here c is called cursor variable open c for select * from emp; ------close c; open c for select * from dept; ------close c; ex: DECLARE TYPE REF_CUR IS REF CURSOR; C REF_CUR; R1 EMP%ROWTYPE; R2 DEPT%ROWTYPE; BEGIN OPEN C FOR SELECT * FROM EMP; LOOP FETCH C INTO R1; EXIT WHEN C%NOTFOUND; DBMS_OUTPUT.PUT_LINE(R1.ENAME); END LOOP; CLOSE C; OPEN C FOR SELECT * FROM DEPT;

LOOP FETCH C INTO R2; EXIT WHEN C%NOTFOUND; DBMS_OUTPUT.PUT_LINE(R2.DNAME); END LOOP; CLOSE C; END; Dynamic sql: It is a string which contains any DDL or DML command with variables Such string should be executed as a command. It can be done in two ways 1. Using dbms_sql package 2. Using native dynamic sql [execute immediate] Ex:Begin Create table sample (name varchar2 (10)); End; Error because we cant execute DDL cmd is a plsql block. To perform DDL cmd we can use dynamic sql. Begin Execute immediate create table sample(name varchar2(10)); End; / EX2:-

Create or replace procedure del_rows(tname varchar2)

is str varchar2(100); begin str:='delete from'||tname; execute immediate str; dbms_output.put_line('rows deleted'||sql%rowcount); end; / bulk binding: binding reefers to executing an sql command in plsql block where there are may transactions to be performed from a plsql block. For each transaction a context switch occurs between plsql and sql engine for more transactions more switches occur which will increase the cpu time usage. bulk binding is used to perform more transactions in a single switch to reduce cpu time usage which will increase the speed of execution there are two types of bulk binding. 1.bulk insert: can be implemented using 'forall' 2.bulk delete: can be implemented using 'bulk collection into'. Create table sample(sno number,name varchar2(10)); set timing on; declare type sam_tbl is table of sample%rowtype index by binary_integer; s sum_tbl; begin for i in 1..1000 loop s(i).sno:=1; s(i).name:='madhu'; end loop;

for i in 1..1000 loop insert into sample values(s(i).sno,s(i).name); end loop; end; /

here no.of switches occurred to insert rows can be reduced to one switch using 'forall' as follows forall i in 1..1000 insert into sample values s(i);

example2:

declare type sam_tbl is table of sample%rowtype index by binary_integer; s sam_tbl; r sample%rowtype; cursor c is select * from sample; idx number:=0; begin open c; loop fetch c into r; exit when c%notfound; idx:=idx+1;

s(idx):=r; end loop; close c; end c;

using 'bulk collection into ' to reduce no of switches declare type sam_tbl is table of sample%rowtype; index by binary_integer; s sam_tbl; begin select * bulk collection into s from sample; end; /

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