Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
288 views

PLSQL

PLSQL is the programming language extension for SQL and PL/SQL. It allows developers to write blocks of code that include conditional and iterative logic flow controls. Key features include supporting variables, conditional statements, loops, error handling, composite data types, and stored procedures. Cursors allow PLSQL blocks to retrieve multiple rows from a database into variables for processing. Common cursor operations include opening, fetching rows into variables, and closing the cursor.

Uploaded by

venuoracle9
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
288 views

PLSQL

PLSQL is the programming language extension for SQL and PL/SQL. It allows developers to write blocks of code that include conditional and iterative logic flow controls. Key features include supporting variables, conditional statements, loops, error handling, composite data types, and stored procedures. Cursors allow PLSQL blocks to retrieve multiple rows from a database into variables for processing. Common cursor operations include opening, fetching rows into variables, and closing the cursor.

Uploaded by

venuoracle9
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

PLSQL

Satya Manchigantis

PLSQL
Programming Language of Structure Query Language

Page 1 of 54

PLSQL

Satya Manchigantis

Features: Supports to execute a block of commands as a unit. Supports variables and constants. Supports conditional constructs. Supports iteration control statements. Supports error handling. Supports to define composite data types. Supports to execute the code automatically based on the event threw data base triggers. Supports to store and shared the code using subprograms. PLSQL Block: It is an collection of sql & program language statements. There are 2 types. 1. Anonymous block Name less block Temporary block Syntax:Declare <variable decl> Begin <exec stmts>; End;

2. Named Block Block with fixed name. Stored permanently in database Ex:- Subprograms. Variable declaration: All sql data types are supported. Boolean is supported. Declare Veno number(4):=7900; Vename varchar2(90); Vjob varchar2(90) NOTNULL :=CLERK; Doj date default sysdate; Flag Boolean:= TRUE; Pin constant number(6):=500038; := Assignment operator = Comparission operator

Executable Statements: DML and TCL are not valid. DDL and DCL are not allowed.
Page 2 of 54

PLSQL

Satya Manchigantis

Select ----- into statement.{ Used to retrieve data into Plsql variables.} Select <column list> into <variables> from <table name> Where <condition>; Used to print message & variables contents onto screen. DBMS_OUTPUT.PUT_LINE(message Text || Variables); Comments --Comment line /*Multi Line Comment*/ Activates the DBMS stmt output buffer. >set server output on;

Ex: Plsql Program retrieves the employ details and calculates the net salary and prints. Declare Veno number(4):=3400; or &employ; Vname varchar2(90); Vsal number(12,2); Vcomm number(12,2); Net number(12,2); Begin --Retrieve data from table. Select ename, sal, comm. Into vname, vsal, vcomm from emp Where empno=veno; --Calculated net salary Net:= vsal+nvl(comm., 0); Dbms_output.put_line(employ details are:||veno||||vename||||net); End; / To save to local system(.sql file) Save <filename> To display the file Get filename To open the file in editor Ed filename To execute the file Start filename or @filename

Page 3 of 54

PLSQL

Satya Manchigantis

Attribute Declaration: Used to define the Plsql variables dynamically according to the table structure. 1. %Type: Column type declaration. Used to define the variables according to the specific column structure. Syntax: variable <tablename>.<columnname>%type; Ex: Declare --using %type declaration Veno emp.empno%type := &employ; Vsal emp.sal%type; Vcomm emp.comm%type; Net emp.sal%type; 2. %Rowtype: Record type declaration Used to define the variables according to the complete table structure. Syntax: variable <tablename>%rowtype; Ex: declare --using %Rowtype declaration. I emp%rowtype; Net number(19,9); Begin i.empno :=&empno; select ename, sal, comm. Into i.ename, i.sal, i.comm from emp where empno = i.empno; net:= sal+nvl(comm., 0); dbms_output.put_line(Employ details are:||i.empno||||i.ename||||net); end; /

Page 4 of 54

PLSQL

Satya Manchigantis

Conditional Constructs: Used to check for multiple conditions while manipulating data in plasql 1. If 2. case(8i) 1. Simple If If <condition 1> then <exec stmts>; Elsif <cond 2> then <exec stmts>; --Else < exec stmts>; End if; Ex: Plsql block checks for existing new comm. And assign new comm.. Declare Veno emp.empno%type := &employ; Vname emp.ename%type; Vcomm emp.comm%type; Begin Select ename, comm. Into vname, vcomm from emp Where empno = veno; If vcomm is null then Vcomm :=3000; Elsif vcomm = 0 then Vcomm :=2500; Else vcomm := vcomm+vcomm*.25; Endif; Update emp set comm.= vcomm wehre empno = veno; Dbms_output.put_line(veno||||vname|||vcom); Commit; End; / 2. Case(8i) : o Used to check for multiple conditions easily. o It will check for equality condition. o It can be used in select statement Syntax: 1. Case <variable> When <value1> then <exec stmts>; When <value2> then <exec stmts>; --Page 5 of 54

PLSQL

Satya Manchigantis

-Else <exec stmts> End case; 2. Case When <cond1> then <value1> When <cond2> then <value2> Else <value> End case; Using case construct: Ex: Declare Grade char(1):=&grade; Begin Case grade When A then Dbms_output.put_line(Grade is A); When B then Dbms_output.put_line(Grade is B); When C then Dbms_output.put_line(Grade is C); Else Dbms_output.put_line(Grade is C); End case; End; / Case in select: select empno, ename, sal, job, case when job = CLERK then C when job = salesman then B when job in (Manager, Analyst) then B+ when job = President then A else D end Grade from emp; --It is used to generate reports.

Page 6 of 54

PLSQL

Satya Manchigantis

Iteration control statements: (LOOPS) Supports to execute a block of stmts until conditions are true. 4 types: 1. simple loop 2. while loop 3. numeric for loop 4. cursor for loop 1. Simple Loop: It is an infinite loop block. Syntax: Loop <exec stmts<; End loop; To break simple loop : o Exit when(cond); o If(cond) then Exit; End if; Ex: --Prints first 10 numbers onto screen Declare A number(3):= 1; Begin Dbms_output.put_line(The numbers are:); Loop Dbms_output.put_line(a); A := a+1; Exit when (a > 10); End loop; Dbms_output.put_line(End of numbers); End; / 2. While Loop: It is an pre-tested loop. Syntax: While (cond) Loop <exec stmts>; End loop; Ex: Declare A number(3):=1; Begin Dbms_output.put_line(The numbers are:); While (a<=10) loop Dbms_output.put_line(a);
Page 7 of 54

PLSQL

Satya Manchigantis

A := a+1; End loop; Dbms_output.put_line(End of numbers); End; / 3. Numeric For Loop: It increments the variable by 1 always. Variable cant be assigned with a value in for loop. Syntax: For <var> in [reverse] <value1>..<value2> Loop <Exec stmts>; End loop; <var> Automatically defined by for loop. Reverse(optional) Accepts values in reverse order .. Range operator Ex: Begin Dbms_output.put_line(The numbers are:); For n in 1..10 Loop Dbms_output.put_line(n); End loop; Dbms_output.put_line(end of numbers); End; Dbms_output.put : prints the results in same line. Dms_output.put_line : prints the result in new line. Put_line must be followed with put stmt to activate output buffer. 4. Cursor For loop: Used to perform cursor operations automatically Improves performances Syntax: For <var> in <cur name> Loop <exec stmts>; End loop; Advantages: No need to open cursor No need to fetch rows No need to check for end of rows No need to close cursor No need to declare variables Ex: Declare Cursor c2 is select * from dept; Begin For I in c2
Page 8 of 54

PLSQL

Satya Manchigantis

Loop Dbms_output.put_line(c2%rowcount||||i.deptno||||i.dname||||i.loc); End loop; --close cursor End; For I in c2 loop Declares I variable Open cursor Fetch 1 row into i Check end of rows Declare Cursor ecur Is Select empno, ename, sal, job, emp.deptno, dname, loc From Emp, dept Where emp.deptno = dept.deptno;

Page 9 of 54

PLSQL

Satya Manchigantis

CURSORS: It is a temporary buffer used to hold the transaction data for manipulation purpose. It is not stored in database. It is not re-usable. It is valid in Plsql block only. It is created in logical memory only. 2 types A. implicit cursors: Automatically defined by oracle whenever DML operations are performed by user. It has a fixed name SQL It gives the status of DML statements in Plsql block. It will not support cursor operations. It supports %found, %nofound, %rowcount, attributes. Ex: TO update only 5 employees Declare Vdno number(2) := &dno; Begin Update emp set sal = sal+1000 where deptno = vdno; If sql%notfound then Dbms_output.put_line(Unable to update rows No such dept exists); Elsif sql%rowcount > 5 then Dbms_output.put_line( Invalid operation Cant update more than 5 employees); Rollback; Else Dbms_output.put_line(sql%rowcount|| employees are updated successfully); Commit; End if; End; / B. Explicit cursors: Created by user in Plsql block used to retrieve multiple rows into Plsql block for manipulation purpose. 1. Declaring cursor: Syntax : cursor <cur name> is <select stmt>; 2. Cursor Operations: i. Open cursor: Open <cur name>; Used to open the cursor. Memory will be allocated to cursor after opening it.

Page 10 of 54

PLSQL

Satya Manchigantis

ii.Fetch Cursor: Fetch <cur name> into <vars>; Used to retrieve data from cursor to Plsql variables. At a time it can retrieve only one row into variables Generally fetch will be placed in loop iii.Close Cursor: close <cursor name>; Used to close the cursor. Memory allocated will be de-allocated. 3. Cursor Attributes: Gives the status of cursor <cur name>%<attribute> i. %isopen (Returns true/false) Returns True if cursor is opened successfully ii. %found (Returns true/false) Returns True if fetch stmt successfully retrieves the into Plsql vars. iii. %notfound (Returns true/false) Returns true if fetch stmt fails to retrieve the row into Plsql vars. iv. %rowcount (Returns true/false) Returns the no of rows successfully retrieved from cursor so far. Initially it holds 0. After every successful fetch it is incr by 1. Ex-1: Declaring cursor var with %Type Declare Cursor c1 Is Select empno, ename, comm. From emp Order by deptno; Veno emp.empno%type; Vname emp.ename%type; Vcomm emp.sal%type; Begin Open c1; If c%isopen then Dbms_output.put_line(EMP NEW COMM); LOOP Fetch c1 into veno, vname, vcomm; Exit when c1%notfound; If vcomm is null then Vcomm := 3000; Elsif vcomm = 0 then Vcomm := 2500; Else vcomm := vcomm+vcomm*.25; Endif; Update emp set comm.= vcomm where empno = veno;
Page 11 of 54

PLSQL

Satya Manchigantis

Dbms_output.put_line(veno||vname||vcomm); End loop; Dbms_output.put_line(c1%rowcount||Employees are updated with new comm); Close c1; Commit; Else dbms_output.put_line(Unable to open cursor); End if; End; / Declaring cursor var with rowtype. Ex-2: Declare Cursor c2 Is select * from dept; I c2%rowtype; Begin Open c2; Loop Fetch c2 into I; Exit when c2%notfound; Dbms_output.put_line(c2%rowcount||||i.deptno||||i.dname||||i.loc); End loop; Close c2; End; Cursor with Scalar query: Ex1: Declare Cursor c2 is select eno, ename, sal ,job, (select min(sal) from emp where job = e.job) lopay, (select max(sal) from emp where job = e.job) hipay, from emp E order by job; Begin For k in c2 Loop Dbms_output.put_line(k.eno||||k.job||||k.ename||||k.sal||||k.lopay||k.hipay); End loop; End; / Ex2: Calculate bonus for first 10 lowest employees. Declare Cursor c1 Is Select eno, ename, sal, sal+nvl(comm., 0) net, job from emp Order by sal; I c1%rowtype;
Page 12 of 54

PLSQL

Satya Manchigantis

Bonus emp.sal%type; Begin For I in c1 Loop If i.job = CLERK Then bonus:= round(i.net*.25); Elsif i.job = EXECUTIVE Then bonus := round(i.net*.50); Else then Bonus := round(i.net*.1); End if; Dbms_output.put_line( i.eno||||i.ename||||i.job||||bonus); Exit when(c1%rowcount >= 10); End loop; End; /

Cursor with Parameters(8.0): Used to accept the input dynamically while opening the cursor. Supports to define generalized cursor. Maximum 32 parameters can be passed to cursor. Ex-1: Calculates incr for employees depending on experience for particular dept only. Declare Cursor c1(dno number) Is Select * from emp Where deptno = dno; I c1%rowtype; Incr number(12); Expr number(2); Begin Open c1(&dno); Loop Fetch c1 into i; Exit when c%notfound; Net := i.sal + nvl(comm., 0); Expr := round(months_between(sysdate, i.hiredate))/12); If expr <=2 Then incr := net*.25; Elsif expr<=5 Then incr := net*.5; Else incr := net*.1; End if; Update emp set sal := sal+incr where eno = i.eno;
Page 13 of 54

PLSQL

Satya Manchigantis

Dbms_output.put_line(i.eno||||e.job||||expr||incr||i.deptno); End loop; Close c1; End; / EX-2 : Cursor c2(dno number, vjob varchar2) Is select * from emp Where deptno = dno and job = vjob; Open c2(30, clerk); For I in c2(20, salesman) loop Ex-3: Cursor c3(vcourse varchar2, vtime varchar2) Is select * from student where course = vcourse and timing = vtime; open c3(oracle 9i, 10AM); for I in c3(oracle 9i, 6PM); EX-4: Cursor c4 Is select * from student Where course = &course; It is valid in oracle sql environment. Cursor parameters are used to pass values from other application s/w tools.

Page 14 of 54

PLSQL

Satya Manchigantis

EXCEPTIONS: Errors in Plsql block are termed as exceptions. Error handling solutions are provided in exception block. 3 types 1. Pre defined exceptions Defined by oracle Activated by oracle automatically. Solution provided by user. No_data_found: Automatically activated whenever select stmt fails to retrieve data into variables. Too_many_rows: Automatically activated whenever select stmt retrieves more than one row into variables. Value_Error: Automatically activated whenever data types are not matching. Zero_divide: Automatically activated whenever invalid arithmetic operations is performed (no/zero). Dup_val_on_index: Automatically activated whenever duplicate values are inserted into unique index column. Storage_error: Automatically activated whenever there is lack of memory in server. Invalid_cursor: Automatically activated whenever user fetch the rows from cursor without opening the cursor. Time_out_on_resoursces: Automatically activated whenever user performs an infinite loo process. Transaction_backed_out: Automatically activated whenever there is an communication problem with server. Login_denied: Automatically activated whenever user name or pwd are not valid. Cursor_already_open: Automatically activated whenever user opends the cursor which is already in open state. Others: General exception Used to handle any pre-defined exception. It will not support non-predefined/user defined exceptions. Pseudo columns activated by other exception. It must be last exception in exception block. SQLCODE: Holds the currently raised error no. SQLERRM: Holds the currently raised error message.

Page 15 of 54

PLSQL

Satya Manchigantis

2. User defined exceptions Defined by user. Activated by using RAISE stmt. Solution provided by user. Ex: Plsql block handles diff types of errors. Declare Veno emp.eno%type := &employ; Vname emp.ename%type; Vsal emp.sal%type; Salary_missing exception; --Declaring user defined excep Begin Select ename, sal into vname, vsal from emp Where eno = veno; If vsal is null then Raise salary_missing; --Activating user defined excep Else vSal := vsal + vsal * .5 Update emp set sal = vsal where eno = veno; Dbms(salary updated for||veno||is||vsal); Commit; End if; When no_data_found then Dbms_output.put_line(No such emp found||veno); when too_many_rows then dbms_output.put_line(More than one emp found for||veno); when salary_missing then dbms_output.put_line(Emp has null salary providing default pay); update emp set sal=5000 where eno= veno; commit; when others then dbms_output.put_line(Error occurred); dbms_output.put_line(sqlcode||||sqlerrm); end; / 3. Non pre-defined exceptions (undefined exceptions) Defined by user. Activated automatically by constraints. Solution provided by user. Used to handle constraint violation of errors in Plsql. Ex: Handling foreign key constraint error. Declare Vdno number(2) := &dno; Employ_exists exception;
Page 16 of 54

PLSQL

Satya Manchigantis

Pragma exception_init(employ_exists, -2292); Begin Delete from dept where dno = vdno; Commit; Exception When employ_exists then Dbms_output.put_line( Emp are still working cant remove dept); End; / EXCEPTION_INIT(Exception_name, Error_no); Built-in sub-pgm used to provide exception name to the constraint violation error EXCEPTION PROPAGATION: Declare ------------Begin ------------Begin ------ERR ------------Exception ------------------Solution End; No Solution ------------Exception ------Sol No sol ------Quit with error ------- Quit with success End; /

Page 17 of 54

PLSQL

Satya Manchigantis

PRAGMA: It is an special instruction to Plsql to execute sub program in declaration section. DEPT EMP ----Deptno(PK) eno Deptno(FK) Constraint violation error nos: -00001 Unique -1400 Not null -2290 Check -2291 Parent not exists(ref) -2292 Child records exists(ref) EX-1: create table std_inf(roll number(4), name varchar2(90), course varchar2(20) check( course in (oracle 9i, unix, D2k)), fee number); Insert into std_inf values( 101, Sai, java, 2300); PLSQL block handling check constraint error Declare Invalid_course exception; Pragma exception_init(invalid_course, -2290); Begin Insert into std_inf values(101, Sai, java, 2300); Commit; Exception When invalid_course then Dbms_output.put_line( student course must be oracle 9i or unix or d2k); End; / EX-2: Using nested blocks, cursors with lock and exceptions. Create table itemmast(itno number(2), name varchar2(90), qoh number(4), rol number(5)); Insert into itemmast values(&1, &2, &3, &4); Create table ittran(itno number(4), tran_type char(1) [I-Issue(-), R-Receipts(+)], qty number(5), updt char(1)); Insert inot ittran values(&1, &2, &3, &4); Declare Cursor tran is select into, tran_type, qty from ittran where upper(updt) = N for update; --cursor with lock Cursor item is select * from itemmast; Vname varchar2(20); Vqoh number(4);
Page 18 of 54

PLSQL

Satya Manchigantis

Begin For I in tran loop Begin --nested loop Select name, qoh into vname, vqoh from itemmast Where itno = i.itno; Exception When no_data_found then Dbms_output.put_line(no such item exists with itno||itno); End; If i.tran_type = R then Vqoh := vqoh + i.qty; Elsif i.tran_type = I then Vqoh := vqoh i.qty; End if; Update itemmast set qoh = vqoh where itno = i.itno; Update ittran set updt= Y where CURRENT OF TRAN; End loop; Commit; Dbms_output.put_line(Stock Report); For k in item loop Dbms_output.put_line(k.itno||||k.name||||k.qty); End loop; Exception When others than Dbms_output.put_line(sqlcode||||sqlerrm); End; FOR UPDATE: Locks the rows retrieved into cursor WHERE CURRENT OF: Clause (8.0) Used to locate the current row manipulated by cursor To use this cursor must be locked

Page 19 of 54

PLSQL

Satya Manchigantis

Composite data types: [User defined data types] Defined by the user. Valid in Plsql block only. They are not stored in the database permanently. They will not hold data. They are not re-usable. This will improve performance of oracle while retrieving or manipulating huge loads of data into Plsql blocks. 2 types 1. PLSQL Records: It is an collection of elements of different data types stored at one location. It is similar to C Prog structures. Syntax: Type <record name> is record (element1 <datatype>, Element2 <datatype>, .. Elementn <datatype>);

EX: Declare --declaring Plsql record. Type erec is record(eid number(4), name emp.ename%type, basic emp.sal%type, da emp.sal%type, hra emp.sal%type, e.pf emp.sal%type, gross emp.sal%type); E erec; --record type variable Begin e.eid:= &employ; select ename, sal into e.name, e.basic from emp where empno = e.eid; e.da := e.basic*.24; e.hra:= e.basic*.15; e.pf:= e.basic*.15; e.gross := e.basic+e.da+e.hra-e.pf; dbms_output.put_line(e.eid||||e.name||||e.basic||||e.pf||||e.gross); end;

2. PLSQL Tables: It is an collection of elements of same datatype stored in continous memory locations. It is similar to C Prog arrays. It is supported with an index automatically. Syntax: Type <table_name> is table of <datatype> index by binary_integer;
Page 20 of 54

PLSQL

Satya Manchigantis

EX: Declare --declaring Plsql tables. TYPE names IS TABLE OF emp.ename%type INDEX BY BINARY_INTEGER; TYPE pays IS TABLE OF emp.sal%type INDEX BY BINARY_INTEGER; N names; P pays; Totsal number(12) := 0; Ctr number(9):=1; Begin --filling tables For I in (select ename, sal from emp) loop N(ctr):= i.ename; P(ctr):=i.sal; Ctr:= ctr+1; End loop; --printing table contents For k in 1..n.count loop Dbms_output.put_line(n(k)||||p(k)); Totsal:= totsal + p(k); End loop; Dbms_output.put_line(Total Salary is :||totsal); End; N.COUNT : Gives no of elements in Plsql table

Page 21 of 54

PLSQL

Satya Manchigantis

Nested records and Plsql tables using records: Declare Type pf_rec is record(pfno number(9), amt number(12,2)); --Nested record Type erec is record(eid number(9), name emp.ename%type, basic emp.sal%type, job emp.job%types, pf pf_rec); --plsql table using nested records. Type etab is table of erec Index by binary_integer; Ctr number(3):=1; E etab; Begin For I in (select empno, ename, sal, job from emp) pf.rec Loop E(ctr).eid := i.empno; erec E(ctr).name := i.ename; E(ctr).job := i.job; etab E(ctr).pf.pfno := i.empno+1000; E(ctr).pf.amt := round(i.sal * .15); Ctr := ctr + 1; End loop; --printing table contents Dbms_output.put_line(employee pay details are:); For k in 1..e.count Loop Dbms_output.put_line(e(k).eid|||| e(k).name|||| e(k).basic|||| e(k).job|||| e(k).pf.pfno|||| e(k).pf.amt); End loop; End; /

Page 22 of 54

PLSQL

Satya Manchigantis

DATABASE TRIGGERS: A set of Plsql stmts stored permanently in database and automatically activated whenever an event raising stmt (DML) is preformed. They are stored in user_triggers system table. They are use to impose business rules/user defined restrictions on table. They are also activated when tables are manipulated by either users or by other application s/w tools. They provide high security on tables. TCL commands are not allowed in triggers. Trigger parts: 1. Triggering even: Indicates when to activate the trigger. Before insert/update/delete After insert/update/delete 2. Trigger types: a. Row trigger: Activates the trigger for every row manipulated by DML stmt. b. Stmt trigger: Activates the trigger for only once for 1 DML stmt (Default type). 3. Trigger restriction: Used to stop the activation of trigger based on condition. If condition is true trigger is active. 4. Trigger Body: A set of Plsql stmts. Syntax: Create or replace TRIGGER <trigger_name> Before/after insert or update or delete [of <columns>] on <table_name> [for each row When (<condition>) Declare <var declaration>; ] Begin <exec stmts>; [Exception <exec stmts>;] End;

(1) (2) (3)

If condition is true trigger is activated

Page 23 of 54

PLSQL

Satya Manchigantis

EX:

Trigger converts student name to upper case automatically. Create ore replace trigger up_con before insert on stu_info For each row Begin NEW & OLD (pseudo columns): :new.sname := upper(:new.sname); End; Used to retrieve data from DML stmt tempory buffer. Valid with ROW triggers only. INSERT NEW valid OLD invalid UPDATE valid valid DELETE invalid valid

Triggering Events: 12 Events per table are allowed. Before insert row Before insert stmt After insert row After insert stmt before update row before update stmt After update row After update stmt before delete row before delete stmt After delete row After delete stmt

EX: Trigger checks fro valid increment.


Column specification is supported with Create or replace trigger valid_incr update event only. Not valid with insert Before update of sal on emp and delete. operations(Row level For each row operations) Begin If :new.sal <= :old.sal then Raise_application_error(-20300, Incr must be more than existing salary; End if; End; /

Raise_application_error(error no, error message); Built in subprogram stops DML stmt execution and displays the error message. Error_NO range: -20002 to -20990 Oracle Reserved error nos: -20000 to +20000

Page 24 of 54

PLSQL

Satya Manchigantis

Constraints vs Triggers: Constraint provide standard error message. Triggers provide user friendly error message. Constraints will for existing errors. Triggers will not check for existing errors. If constraint & trigger are defined on table, one time only trigger will be activated. Ex: Trigger checks for valid salary according to the job. Create table job_pays(job varchar2(20), losal number(10), hisal number(10)); Create or replace trigger chk_sal Before insert on emp for each row When(new.job<>PRESIDENT) --If true trigger is activated Declare Minsal number(10); Maxsal number(10); Begin Select losal, hisal into minsal, maxsal from job_pays Where job =:new.job; If :new.sal>maxsal and :new.sal<minsal then Raise_application_error(-20201, salary must be between||maxsal||and||minsal||for job||:new.job); End if; Exception When no_data_found then Raise_application_error(-20202, No data found for dept||:new.job); End; / EX: Trigger adds the fee installment amt automatically into fee installments table Create fee_installments(roll number(9), prev_fee number(9), curr_fee number(9), dop date);
Keywords: Inserting, updating, deleting Represents insert, update, delete operations. Valid in triggers only

Create or replace trigger add_fee Before update or insert on student For each row Begin If inserting then Insert into fee_installments values(:new.roll, :new.fee, :new.fee, sysdate); Elsif updating then Insert into fee_installments values(:old.rol, :old.fee, :new.fee - :old.fee, sysdate); End if; End; /

Page 25 of 54

PLSQL

Satya Manchigantis

Statement level triggers: Trigger locks the table for DML operations to provide security. Trigger checks for o Valid timings o Weekends o Public holidays Ex: Create or replace trigger security_chk Before insert or update or delete on bankmaster Declare A number; Begin --check for valid timings. If to_char(sysdate, hh24) not in (10,11,12,13,14,15,16,17,18) then Raise_application_error(-20111, No operations allowed invalid timings); End if; --check for week ends. If to_char(sysdate, dy) in (sat,sun) then Raise_applicaiton_error(-20112, No operations allowed week ends); End if; --check for public holidays Select count(*) into a from holiday where to_date(hdate) = to_date(sysdate); If a>0 then Raise_application_error(-20113, No operations allowed public holidays); End if; End; / Instead of triggers: Triggers supported only on views Used to perform DML operations on join views Instead of ----insert, update, delete EX: Create view edept As Select empno, ename, job, sal, emp.dtno, dept.dtno dno, dname, loc from emp, dept Where emp.dno = dept.dno; Create trigger T1 instead of insert on edept For each row Begin Insert into dept values(:new.dno, :new.dname, :new.loc); Insert into emp(empno, ename, sal, job, dtno) values(:new.empno, :new.ename, :new.sal, :new.job, :new.dtno); End;

Page 26 of 54

PLSQL

Satya Manchigantis

Disabling triggers: Alter table <table_name> disable all triggers; Enabling triggers: Alter table <table_name> enable all triggers; Removing triggers: Drop trigger <trigger_name>;

Checking for existing triggers: Desc user_triggers; Select trigger_name, trigger_event from user_triggers Where table_name = emp; Select * from user_triggers Where trigger_name = chk_sal Create trigger T2 Before insert on temp for each row Begin Update temp set c2 = HARI; End; --It will not perform update in trigger body because 2 DML operations cant be performed on table at once --It leads to a trigger mutation error while working in other s/w tools.

Page 27 of 54

PLSQL

Satya Manchigantis

SUBPROGRAMS: A set of Plsql stmts stored permanently database and used to perform a task. They can accept input from user as arguments dynamically. They are stored in user_source system table. They are reusable components. They can be shared with other users. They can be used n other application s/2 tools. They are faster in execution stored n compiled formed. They support modularity. A huge task divided into N no of sub tasks. Easy to manage the logic easy to debug errors. 2 types 1. Procedures 2. Functions 1. Procedures:

A sub prg type performs a task and will return a value. Generally procedures are used to perform DML operations on database. They cant be called in SELECT stmt. Procedure can be used in sql, other application s/w tools, Plsql triggers procedures, functions, packages, D6i.

Syntax: Create or replace procedure <p_name> [(arguments MODE <datatype>)] Is [<var_declaration>] Begin <exec stmts>; End; Calling a procedure: procedure_name(arguments); EX: Create or replace procedure Sim_ins(p number, n number, r number) Is Si number(12); Begin Si := (p*n*r)/100; Dbms_output.put_line(simple interest:||si); End; / SQL: Desc sim_ins Exec sim_ins(2,3,4); PLSQL: begin sim_ins(123,12,8.5); End;

Page 28 of 54

PLSQL

Satya Manchigantis

2. Functions: A sub prog type performs a task and will return the value (Return only one value). Generally functions are used for reporting purpose or for calculating purpose. They can be called in SELECT stmt. Function can be used in sql, select, other application tools, Plsql, triggers, procedures, functions, packages. Syntax: Create or replace function <function_name> [(args MODE <datatype>)] Return <datatype> Is [<var declaration>]; Begin <exec stmts>; Return (variable); [Exception <exec stmts>;] End; Calling a function: var := fun_name(args); EX: Create or replace function si(p number, n number, r number) Return number Is Si number(9); Begin Si := (p*n*r)/100; Return(round(si)); End; SQL: i. Desc si Select si(1200,8,7) from dual; ii. Variable result number exec:result:=si(5400, 10, 9.5); print result; PLSQL: Declare result number(12); begin result:=si(1200,9,7); dbms_output.put_line(result); end;

Create table loan_master(cust_id number(4), cname varchare(9), amount number(12), duration number(3), irate number(5,2)); Insert into loan_master values(&1, &2, &3, &4, &5); Select cust_id, upper(cname), si(amount, duration, irate) interest from loan_master;

Page 29 of 54

PLSQL

Satya Manchigantis

EX-1: Function checks for leap year Create or replace function chk_year(y number) Return varchar2 Is Begin If mod(y,4) = 0 then Return(leap year); Else Return ( Not leap year); End if; End; Select chk_year(2008), chk_year(2010) from dual; Variable result varchar2(90); Exec:result:=chk_year(2012); Print result;

SET AUTOPRINT ON

Automatically prints the variable, No need to use print stmt.

EX-2: Procedure cal the new comm. For all emp of particular dept. Create or replace procedure call_comm(vdept number) Is Cursor c1 Is Select empno, ename, comm. From emp Where deptno = vdept; I c1%rowtype; Begin For I in c1 Loop If i.comm is null Then i.comm :=3000; elseif i.comm = 0 then i.comm:=2500; else i.comm = i.comm+i.comm*.25; end if; update emp set comm. = i.comm where empno = i.empno; dbms_output.put_line(i.empno||has been updated comm. For||i.comm); end loop; commit; end;
Page 30 of 54

PLSQL

Satya Manchigantis

Desc user_source Select name from user_source; To Remove sub progs: Drop procedure <proc_name>; Drop function <fun_name>; Create sequence s1 increment by 1 start with 11; EX-3: Procedure adds a dept into Dept table Create or replace procedure add_dept (vname varchar2 default unknown, vloc varchar2 default hyderabad) Is Begin Insert into dept values(s1.nextval, vname, loc); Commit; End; Desc add_dept Exec add_dept; Exec add_dept(sales, mumbai); Exec add_dept(export); Exec add_dept(vloc => chennai); Exec add_dept(vloc=> pune, vname => software); Named notation: Arguments are passed based on their name.

Sharing Sub-Programs: Scott: Grant execute on add_dept to user1; User1: Desc scott.add_dept Exec scott.add_dept(Testing); Insert into scott.dept values(22, HR, sec);

--Error

User can manipulate the table only through procedure but not directly. Parameter modes in sub-programs: MODE indicates the behaviour of argument in sub program 3 types. 1. IN: (default mode) IN parameter is used to carry the input into subprogram. It cant be assigned with a value in subprogram.

Page 31 of 54

PLSQL

Satya Manchigantis

2. OUT: OUT parameter is used to return the results from sub program. It cant be assigned with a value in sub program 3. IN OUT: INOUT parameter is used to carry the input and return the results from subprogram. It can be assigned with a value in subprogram.

EX-1: Create or replace procedure P1(a in out number) Is Begin A:= A*A*A; End; SQL: Desc p1 Var x2 number; Exec :x2 := 5; Exec p3(:x2); Print x2

--intialising variable at sql

EX-2: Calculate factorial for given number and checks for odd/even number. Create or replace function call_fact( n in number, f out number); Return Boolean Is Fac number(9) :=1; Begin -- cal factorial 5! = 5*4*3*2*1 =120 For I in 1..n Loop Fac := fac * I; End loop; F:= fac; -- storing result in out parameter If mod(n,2) = 0 Then Function returning Return(TRUE); Boolean value (or) with Else OUT parameter cant be Return(false); End if; used in sql or select stmt. End; Using CALL_FACT function: Declare A number(9) := &num; Fact number(90); Begin
Page 32 of 54

PLSQL

Satya Manchigantis

If call_fact(a, fact) Then Dbms_output.put_line(Given number is even); Else Dbms_output.put_line(Given number is odd); End if; Dbms_output.put_line(Factorial of given number is:||fact); End; Triggers vs Programs: Triggers are automatically activated by DML statements. Procedures & functions has to be explicitly activated by user. Advantages: Code reusability. Faster execution of code. Easy to manage code. Executed in the oracle server memory even if it is activated from other application software tools.

Page 33 of 54

PLSQL

Satya Manchigantis

PACKAGES: It is a collection of related vars, cursors, procedures and functions. It is stored in user_source system table. It can be shared with other users. They will improve performance of oracle while accessing sub programs from client environment. They support oops features live encapsulation, data hiding, and function over loading. 2 parts i. package specification: It holds the declaration of variables, cursors, procedures and functions. Syntax: Create or replace package Package_name As <Var dec>; Procedure <proc_name>(args datatype); Functions <fun_name>(args datatype) return datatype; End <pack_name>; ii. Package body: it holds the code of sub program. Syntax: Create or replace package body Package_name As Procedure <proc_name>(args datatype) Is <exec stmts>; End <proc_name>; Functions <fun_name>(args datatype) return datatype Is <exe stmts>; End <fun_name>; End <pack_name>; Ex-1: Create or replace package pack1 as result number(12) procedure add_num( a number, b number); function mul_num(x number, y number); end pack1; create or replace package body pack1 as procedure add_num(a number, b number) is begin result := a+b;
Page 34 of 54

PLSQL

Satya Manchigantis

dbms_output.put_line(sum of numbers is:||result); end add_num; function mul_num(x number, y number) return number is begin result := x*y; return (round(result)); end mul_num; end pack1; / Using package elements: Exec pack1.add_num(2099, 8908); Select pack1.mul_num(200,22) from dual; Select ename, job, pack1.mul_num(sal,.15) pf, pack1.mul_num(sal, 2) bonus from emp; EX-2: LOCAL sub program are valid in package body only. Create or replace package epack As Function gross(vsal number) return number; Sub-program not Function experience(doj date) return number; defined in End epack; specification are local sub programs. We Create or replace package epack cant call this pgms As from outside of Function pf(vbasic number) return number is package. Begin Return( round(vbasic*.15)); End if; Function gross(vsal number) return number is Epf number(12); Begin Epf := pf(vsal); Return (round(vsal+vsal * .25 + vsal*.35 epf)); End gross; Function experience (doj date) return number is Begin Return (round(months_between(sysdate, doj))/12); End experience; End epack; / Select empno, ename, job, round(epack.experience(hiredate) experience, epack.gross(sal) Gross pay from emp; Select ename, epack.pf(sal) PF from emp;
Page 35 of 54

PLSQL

Satya Manchigantis

--ERROR, you cant call local subprogram.

Package with function overloading feature: Create or replace package load_pack As Function add_data(a number, b number) return number; Function add_data(a varchar2, b varchar2) return varchar2; End load pack; / Create or replace package load_pack body As Function add_data(a number, b number) return number Is Begin Return (a+b); End add_data; Function add_data(a varchar2, b varchar2) return number Is Begin Return(a|| ||b); End add_data; End load_pack; / Desc load_pack; Select load_pack.add_data(5,6) total, load_pack.add_data(Satya, M) name from dual; Removing Pack: Drop package <pack_name>; Sharing Pack: Grant execute on load_pack to user1; To view existing package body: Select text from user_source wehre name = pack1;

Page 36 of 54

PLSQL

Satya Manchigantis

8.0 Features: Returning into clause: o Used to return the values through DML stms. o Used with update and delete stmts. Ex: Var a varchar2(20) Var b number Update emp set sal = sal+3000 where empno = 7900 Returning ename, sal, into :a, :b; Print a b Delete from emp where mepno= 7920 Returning ename, sal into :a, :b; Print a b Bulk Collect: o o o o

Used to return bulk data into Plsql variables Variables must be of Plsql table type only Improves performance while retrieving data. Used with select, update, delete, fetch stmts.

Examples: Using in select stmt: Declare Type names table of emp.ename%type Index by binary_integer; Type pays table of emp.sal%type Index by bindary_integer; N names; P pays; Begin --Retrieving all emps in 1 transaction Select ename, sal bulk collect into N, P from emp; --Printing table contents Dbms_output.put_line(Employ details are); For I in 1..n loop Dbms_output.put_line(n(i)||||p(i)); End loop; End; Using in update stmt: Update emp set sal=sal+3000 where deptno = 30 Returning ename, sal bulk colleck into n,p; Using in delete stmt: Delete form emp where job = CLERK Returning ename, sal bulk collect into n,p;

Page 37 of 54

PLSQL

Satya Manchigantis

Using in fetch stmt: Declare Type names is table of emp.ename%type Index by binary_integer; Type names is table of emp.sal%type Index by binary_integer; N names; P pays; Cursor c1 is Select ename, sal into n, p from emp; Begin Open c1; Fetch c1 bulk collect into n,p; --printing table contents For I in 1..n count Loop Dbms_output.put_line(n(i)||||p(i)); End loop; End; / Dynamic SQL: o Supports to execute DDL commands in Plsql block. Execute immediate(DDL stmt); EX: Begin Execute immediate(create table employ(ecode number, ename varchar2(90), sal number)); End; Begin Execute immediate(drop table employ1); End;

NOTE: Table cant be manipulated in same Plsql block.

Using Long and Raw data types: Long: o Used to represent numbers or character values o Maximum limit is 2GB. o But only once it can be used in table. Raw(n): o Used to represent images o Max limit is 256 bytes(7.0)/2000 bytes (8.0) Long Raw: o Used to represent images upto 2 GB. o Raw and long raw can be manipulated by GUI tools only
Page 38 of 54

PLSQL

Satya Manchigantis

Ex: Create table emp(ecode number(3), ename varchar2(20), sal number(12,2), description long, deptno number(2)); Create table ephoto(ecode number(4), photo long raw); Create table customer(cust_id number(4), cname varchar2(20), addr varchar2(50), photo longraw);

File input & output (8.0): Used to transfer oracle table contents to OS file and OS file content to oracle table. Standard package holds all functions (arthematic, date, general); UTL_FILE Built in package supports file operations. Sub-Programs in UTL_FILE pkg: Fopen: Used to open the file in the specified mode and returns the address of the file. Mode R Read, W Write, A Append Fclose: Get_line: Put: Put_line: Fflush: Used to close the file Used to read a line from file to Plsql variable. Used to write a line into file but in New line. Used to write a line into file but in new line. Writes the file content from temporary buffer to physical memory (saving file into OS) File_type: Data type Used to define the variable to hold the address of file. Invalid_file_handle, Read_error: Pre-defined exception automatically activated while working with files. Plsql block transfers data from oracle table to OS file.

Ex: Plsql procedure transfer data from OS file to database table. Create or replace procedure load_student(pdir varchar2, pfile varchar2) Is Vfile utl_file.file_type; Vtext varchar2(200); Vname varchar2(20); Vcourse varchar2(20); Vfee number(5); Fcomma number(3); Scomma number(4); Begin Vfile:= utl_file.fopen(pdir, pfile, R);

Page 39 of 54

PLSQL

Satya Manchigantis

Loop Begin Utl_file.get_line(vfile, vtext); Exception When no_data_found then Exit; End; Fcomma := instr(vtext, ,,1,1); Scomma := instr(vtext, ,, 1,2); Vname := substr(vtext,1,fcomma,-1); Vcourse:=substr(vtext, fcomma+1, soma-fcomma); Vfee := substr(vtext, scomma+1); Insert into student values(s1.nextval, vname, vcourse, vfee); End loop; Commit; Exception When utl_fjile.read_error then Dbms_output.put_line(unable to read the file.); End; Exec load_student(c:\, student.txt): Note: Provide the below parameter in init.ora file (open in notepad) UTL_FILE_DIR = C:\Oracle\ora92\Bin Init.ora --system parameter file. Holds the parameter defined for oracle server.

Page 40 of 54

PLSQL

Satya Manchigantis

Object Technology(8.0): Object is a collection of different datatypes stored at one location. It will not hold data It can have methods (functions) defined in it. They are stored permanently in user_types system table They support inheritance feature. They can be shared with other users. They are reusable components. CDT: (composite data type) Object C structure Object with methods C++ class Nested tables Varying arrays EX: Plsql records Plsql tables Syntax: Create type <obj name> as object (element1 <datatype>, ele 2 <datatype>, -----Element N <datatype>); Object types: 2 types 1. Column object: Only few columns of table represent objects. 2. Row Object: Entire table structure depends on object. Create type etype as object( eid number(9), ename varchar2(90), sal number, deptno number(9)); Create table etab of etype; Row object Desc etab = desc etype Insert into etab values(1001, RAM, 210,10); Select * rom etab; Select eid, ename, sal from etab; Create table employ(einfo etype, job varchar2(90), hiredate date); Column object Ex: Create type addr_type as object (hno varchar2(90), street varchar2(90), city varchar2(90), pin number(6)); Create type Pf_type as object (pfno number(5), amt number(4)); Desc addr_type; Desc pf_type; Select * form user_types;

Page 41 of 54

PLSQL

Satya Manchigantis

Naming object: Create table student(roll number(3), sname varchar2(20), address addr_type, course varchar2(90), fee number(5)); Desc student; Insert into student values(101, SAI, addr_type(12-A, ameerpet, Hyd, 500038), oracle 9i, 2500); Select * from student; Select sname, address from student; Select sname, s.address.city, s.address.pin from student s; Update student s set s.address.hno = 308A where roll=101; Delete from student s where s.address.city = hyd;

Objects will not support constraints. Trigger check for null values in city.

Create trigger city_chk before insert on emp for each row begin if :new.address.hno is null then Raise_aplication_error(-20100, Student hno cant be null); End if; End; Sharing object: Scott: Grant execute on addr_type to user1; User1: Create table supplier(sid number, sname varchar2(90), saddr scott.addr_type); Select sname s.saddr.city from supplier s

Nested objects: [Max 32 levels] Create type person_type as object(pname vachar2(20), paddr addr_type); Desc person_type; Create table customer(cid number, cinfo person_type); Select cid, c.cinfo.paddr.city, c.cinfo.paddr.pin from customer c; Desc customer; Drop type <obj_name>; Drop type addr_type; Drop type pf_type; Purity level test: Checks for member functions are having DML stmts or not. DML are not valid in member functions.

Page 42 of 54

PLSQL

Satya Manchigantis

Restrict_references: Built-in sub program used to check for DML stmts in methods WNDS: Write no database state Pragma: Instruction to Plsql supports to execute sub program in declaration section Object with methods: Create or replace type etype as object(ecode number, name varchar2(90), basic number(90), job varchar2(4), hiredate date, member function gross(vbasic number) return number, pragma restrict_references(gross, WNDS), member function experience(doj date) return number, Pragma restrict_references(experience, WNDS)); Create or replace type body etype as Member function gross(vbasic number) return number Is Begin Return(round(vbasic+vbasic*.25+vbasic*.35-vbasic*.15)); End; Member function experience(doj date) return number Is Begin Return(round(months_between(sysdate, doj))/12); End; End; Create table etab of etype; Row object Insert into etab values(1001, RAM 3000, Analyst, 10-dec-01); Select ecode, name, job, basic, e.gross(basic) gross, e.experience(hiredate) exp in years from etab e;

Page 43 of 54

PLSQL

Satya Manchigantis

Collections(8.0): A group of similar rows stored at one location. 2 types 1. Nested table: Table with in a table A column holds a table of contents in it. Ex: Create type book_type as object (bookid number(4), title varchar2(90), doi date, dor datae); Object representing table of books Create type books is table of book_type; Create table stu_lib(roll number, name varchar2(90), course varchar2(90), binfo books) nested table binfo store as book_table; Desc book_type; Desc books; Desc stu_lib; Insert into stu_lib values(101, RAM, Oracle 9i, books(book_type(11, sql, sysdate, sysdate+10), book_type(12, plsql, sysdate, sysdate+11), book_type(13, dba, sysdate, sysdate+15))); Select * from stu_lib; Select name, binfo from stu_lib; Roll 101 102 Book id 11 12 13 2. Varrying arrays examples: It is an array of elements stored in a column. EX: i. ii. iii. iv. Create type blist is varray(5) of varchar2(25); --Object representing array of books. Create table items(itno number, name varchar2(90), brands blist); Insert into items values(102, Micro-oven, blist(LG, ONIDA, IFB)); desc blist desc items Title Doi Dor Name Course Binfo

Page 44 of 54

PLSQL

Satya Manchigantis

v. vi.

update items set brands = blist(LG, ONIDA, IFB, KENSTAR, SAMSUNG) where itno = 102; select name, brands from items; BINFO Title Doi

Roll 101

Name

Course 11 12 13

Bid

dor

102 Nested table Stored outside the table DML is allowed Stores unlimited data Varray Stored with in the table DML is not allowed stores limited data. Note: Collections will not support constraints Long, raw, lob data types are not valid in collections. Collections will not support dev-6i, VB (GUI tools) Java supports collections.

DML on nested tables: THE: Operator is used to perform DML on nested table. EX: Inserting a book(only 1 book allowed) Insert into THE(select binfo from stud_lib where roll=101) Values(book_type(15, DBA, sysdate, sysdate+10)); Changing a book details Update THE(select binfo from stu_lib where roll = 101) Set dor=sysdate+3 where book_id = 12; Update THE(select binfo from stu_lib where roll=101) Set title=Tuning where book_id = 15; Removing a book info Delete from THE(select binfo from stu_lib where roll=101) Where book_id =12;

Page 45 of 54

PLSQL

Satya Manchigantis

LOBS Large Objects(8.0): Used to represent huge loads of fdata Max limit is 4 GB N columns allowed per table 4 types 1. CLOB Char Large Object Used to represent char information upto 4 GB. 2. NCLOB Native char large object Used to represent other language text. *Nchar, Nvarchar2 -- Represents other language test. 3. BLOB Binary large object Used to represent images upto 4GB. 4. BFILE Binary File Used to hold the address of OS file. Representing Null values: CLOB Empty_CLOB( ) NCLOBEmpty_NCLOB( ) BLOB Empty_BLOB( ) BFILE Skip the column while inserting EX: Create table emp_lob(ecode number, name varchar(90), description CLOB, sal number, photo BLOB, edocs BFILE);

Making logical dir to insert Bfile value: DBA > Grant create any directory to scott; SCOTT > Create directory emp_dir as C:\employ\bonds; > Insert into emp_lob values (101, ;RAM, , 2100, empty_BLOB( ), Bfilename(emp_dir, e101.doc));
Built in subprogram used to represent OS file details into bfile column.

> Select ecode, ename, sal, description from emp_lob;

Page 46 of 54

PLSQL

Satya Manchigantis

Temparary Tables(8i): Used to hold the information in logical memory but not in physical memory. They hold the data for a particular period of time but not permanently. EX-1: EX-2: Create global temporary table(c1 date) on commit preserve rows; Insert into temp values(sysdate); Select * from temp; --28-Mar-2012 Commit; Select * from temp; --28-Mar-2012 Exit; Select * from temp; --No rows. Create global temporary table temp(c1 date) on commit delete rows; Insert into temp values(sysdate); Select * from temp; --28-Mar-2012 Commit; Select * from temp; -- No rows.

Autonomous Transactions: Defines the trigger as an independent transaction Allows TCL commands in triggers. Syntax: Create trigger add-incr before insert on incr For each row Declare Pragma autonomous transaction; Update emp set sal = sal+ :new.amt Where empno = :new.empno; Commit; End; Select empno, sal from emp; Insert into incr values(7900, 4000); Select empno, sal from emp; Select empno, amt from incr; Rollback; Select empno, amt from incr; Select empno, sal from emp;

--7900 8000 --7900 12000 --7900 4000 --No rows --7900 12000

Page 47 of 54

PLSQL

Satya Manchigantis

REF CURSORS: Dynamic Cursors: Supports to define the cursor without select stmt. Select stmt will be provided while opening cursor. Used to send cursor as an parameter in sub programs. Made easy to transfer huge data through sub programs. Syntax: Type <ref cursor name> is ref cursor; Create Package pack1 as Type rear is ref cursor; End pack1; Procedure returning multiple rows through OUT parameter. Create or replace procedure get_rows(vdept in number, vcur out pack1.rear) Is Begin Open vcur for select empno, ename, sal, job from emp where deptno = vdept; End; Using Procedure: Declare scur pack1.rear; vroll number(9); vname varchar2(90); vfee number; Begin Open scur for select roll, name, fee from student Where course = &course; Loop Fetch when scur%not found; DOPL(vroll||||vname||||vfee); End loop; Close scur; End;

Page 48 of 54

PLSQL

Satya Manchigantis

9i Features: 9i Joins: Supports ANSI/ISO standard sql 1999 syntax. Modularity for application sw tools to understand sql queries. 1. 2. 3. 4. 5. 6. 7. 8. Natural Join Join with using Equi Join (giving same output) Join with ON Inner Join Left Outer Join Right Outer Join Full Outer Join Left outer join union right outer join Cross Join

Select empno, ename, sal, deptno, dname, loc from emp Natural join dept; Select empno, ename, sal, job, deptno, dname, loc from emp join dept using (deptno); Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e join dept d on (e.deptno = d.deptno); Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e Inner join dept d on (e.deptno = d.deptno); Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e left outer join dept d on (e.deptno = d.deptno); Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e right outer join dept d on (e.deptno = d.depno); Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e full outer join dept don (e.deptno = d.deptno); Select empno, ename, sal, job, deptno, dname, loc from emp cross join dept;

Date functions: Systimestamp: Gives date and time including rational seconds in SERVER time zone. Current_timestamp: Gives date and time including fractional seconds in CLIENT time zone. Sysdate: Gives only date in server time zone. Current_date: Gives only date in client time zone. Extract: Used to retrieve a particular value from the given date (day/month/year) To_timestamp(d): Converts given date into date and time info with am/pm. Dbtimezone: Gives server time zone value Timestamp: Datatype Automatically stores date and time information with am/pm
Page 49 of 54

PLSQL

Satya Manchigantis

Select systimestamp, current_timestamp from dual; Select sysdate, current_date from dual; Select dbtimezone from dual; 28-Mar-12 6:50:23 PM Select extract(day from sysdate), Extract(month from sysdate), Extract(year from sysdate) from dual Create table temp(c1 timestamp); Insert into temp values(sysdate); Select * from temp; 28-Mar-12 6:55:29 PM NVL: 1. NVL(exp1, exp2): NVL is used to fill Null value with known value. If exp1 is NULL value then it will take exp2 If(exp1 = null) Then expr2 Else Expr1; Endif; 2. NVL2(exp1, exp2, exp3): If expr1 is null it manipulates exp3, if exp1 is not null it manipulates expr2 If(exp1 = null) Then Expr3 Else Expr2 Endif;

Page 50 of 54

PLSQL

Satya Manchigantis

MULTIPLE INSERTS: Supports to insert into more than 1 table at a time but input must be retrieved from existing table. EX: Make 3 empty tables same as dept table. create table D1 as select * from dept where rownum is null; create table D2 as select * from dept where rownum is null; create table D3 as select * from dept where rownum is null; insert all into D1 values(deptno, dname, loc) into D2 values(deptno, dname, loc) into D3 values(deptno, dname, loc) Select * from dept; Conditional Insert: EX-1: Insert all When (deptno <40) then Into D1 values(deptno, dname, loc) When (deptno<90) then Into D2 values(deptno, dname, loc) Else Into D3 values(deptno, dname, loc) Select * from dept; EX-2: Insert all When course = oracle 9i then Into Stu_ora(roll, name, fee) When course = java then Into stu_java(roll, name, fee) When course = unix then Into stu_unix values(roll, name, fee) Select * from student;

MERGE: Used to compare the 2 table contents them equal. It supports only update & insert operations. Ex: Merge Into temp t Using emp e On (t.tno = e.empno) When matched then Update set t.sal = e.sal, t.comm = e.comm, t.mgr = e.mgr, t.deptno = e.deptno
Page 51 of 54

PLSQL

Satya Manchigantis

when not matched then insert values(e.empno, e.ename, e.sal, e.com, Clauses: Into --Target Using --Source On --join condition

Emp --1 crore rows Temp --copy of emp -1 crore rows Emp --5000 inserts & 1000 performed.

Partition Tables: Supports to divide the huge tables into multiple partitions logically. This will improve the performance while retrieving or updating the data. Ex: Create table emp(empno number(4) primary key,------------) Partition by range(empno) (partition p1 values less than (101), Partition p2 values less than (201), Partition p3 values less than (maxvalue)); Insert into emp values(10, .); (110.); (210.); (310,); P1 P2 P3 P3 P1 P2 P3 -- 1-100 -- 101-200 -- 201 N

Select * from emp; Update emp partition p2 set sal = sal+3000; Select * from emp partition p3 where sal > 10000; Alter table emp merge partitions (p1, p2); Alter table emp drop partition p3; Alter table emp add partition p3 values less than (401); Alter table emp add partition p4 values less than <maxvalue);

Page 52 of 54

PLSQL

Satya Manchigantis

Oracle Utilities: Performed by the DBA on the dos-Prompt of Server. 3 utilitites. 1. Export: Used to translate information from database format to OS file format. EX: CD:\> EXP Enter username & pwd : scott/tiger Enter export buffer size(default): Press enter key. Enter export file name: mydata.dmp Export user(u), table(t) database : T Export table data : Y Compress the contents while exporting : Y Enter table1:emp Enter table 2:dept Enter table3: Press enter key

2. Import: Used to translate information from OS file format to database format. EX: CD:\> IMP Enter username & pwd : scott/tiger Enter import buffer size(default): Press enter key. Enter import file name: mydata.dmp Export entire file : Y Export table data : Y List the contents while exporting : N Ignore error due to object existence : N 3. Sql Loader: Used to transfer data from OS file to database table. Step-1: Abc.txt 10, sales, Hyd 20, import, Pune 30, export, Chennai 40, researc, Bgr

Page 53 of 54

PLSQL

Satya Manchigantis

Step-2: abc.ctl (control file) Load data infile abc.txt insert into table dept fields terminated by , (deptno, dname, loc)

Step-3: C:\>SQLLDR Userid = scott/Tiger control = abc.ctl NOTE: Insert (Default option): Supports only if table is empty. Append: Allows to add the rows to existing table with data. To avoid the abc.ctl.txt(.txt). we need to put file in . Oracle 10g: [ G Grid] Supports Grid technology It is an DBA version It supports to store EJB components directly into database without translation. It supports with regular exprs to search character data. It provides high performance compared to other versions.

<<<<<<<<<<<<<<<<<<<<<<<<<<<<< All the Best >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Dont Judge a book, by its cover

Page 54 of 54

You might also like