Oracle Notes
Oracle Notes
Oracle Notes
? Introduction to PLSQL
Level 1 - Blocks
? Named Blocks
? Un Named Blocks (Anonymous Blocks)
Level 2 - Data Types
? % Type
? % Row Type
? PL/SQL Record
? PL/SQL Table
? Index By Table
Level 3 - Control Statements
? If
? If Else
? Elsif
? CASE
Level 4 - Loops
? Simple Loop
? While Loop
? For Loop
Level 5 - Cursors
? Implicit Cursor
? Explicit Cursor
? Parameter Cursor
? Ref Cursor
Level 6 - Exceptions
? Pre Defined Exceptions
? User Defined Exceptions
? Non Predefined Exceptions
Level 7 - Procedures
? Normal Procedures
? Procedure with Parameters
? Procedure Overloading
Level 8 - Functions
? Normal Funtions
? Function with Parameters
? Function Overloading
Level 9 - Packages
? Package Body
? Package Specification
Level 10 - Triggers
? Data Base Triggers
? DML Triggers
Level 11 - Collections
? Varrays
? Nested Tables
? Plsql Tables
*************************************************************************
-----Block
------->It is one of the area which is used to write a Programming logic.
-->Block has 3 sections:
1. Declaration Section:
** It is one of the section which is used to declare variables, cursors and exce
ptions and so on.
** It is Optional Section.
2. Executable Section
** It is one of the Section which is used to write a Program Coding.
** It is Mandatory Section.
3. Exception Section
** It is one of the Section which is used to handle the errors at runtime.
** It is Optional Section.
There are Two Types of blocks Supported by PL/SQL
1. Anonymous Block:
** These blocks do not have a name and also not stored in the Database.
Ex1: DECLARE
_______________
BEGIN
------------END;
Ex2: BEGIN
DBMS_OUTPUT.PUT_LINE("Welcome to E Busin
ess Solutions");
END;
2. Named Block:
** These blocks are having a name and also s
tored in database.
Examples : Procedures , Functions, Packages and Triggers etc..
Variable
-->It is one of the memory location which is used to store the d
ata.
-->Generally we declare the variables in declaration section.
-->Variables Support default and not null.
Syntax :Variable_Name
Datatype ( Size );
Ex : Declare
A
Number (5);
B
Number (5) not null :=10;
C
Number (5) default 10;
Ex-1 :
Declare
A Varchar2(20);
Begin
A := Hello EBS ;
Dbms_Output.Put_Line( A );
End;
=>Storing a value into variable:
Using assignment operator ( := ) we storing a value into
variable.
Syntax : Variable_Name := value;
Ex : a :=50;
=>Display Message ( or ) Varaible Value:
We have one pre defined package which is used display th
e message or value in a program.
Syntax : dbms_output.put_line ( message );
dbms_output.put_line ( variable_name );
=>Select ------ Into ------ Clause:
This clause is used to retrieve the data from table & st
oring into pl/sql variables.
Syntax : select col1, col2 into var1, var2;
*************************************************************************
---------DataTypes
---------1. % Type
2. % RowType
3. RecordType ( or ) Pl/sql Record
4. IndexBy Table ( or ) Pl/sql Table (COLLECTIONS) VVIP *******
%Type:
-->It is one of thedatatype which is used to assign the column datatype to a var
iable.
-->It is used to storeone value at a time.
-->It is not possibleto hold more than one column values or row values.
Syntax : variable_name table_name.column_name%type; Ex-1 :
Declare
Vno
emp.empno%type:=&n;
Vname emp.ename%type;
Begin
Select
ename into vname from emp where empno=vno;
Dbms_output.put_line (
employee name is :
End;
||
|| vname );
% RowType
-->It is one of the datatype which is used assign all the column datatypes of ta
ble to a variable.
-->It holds entire record of the same table.
-->Each of the time it override only one record.
-->It is not possible to capture more than one table data.
Syntax :variable_name table_name%rowtype;
Ex-1 :
Declare
Vrow
emp%rowtype;
Vno
emp.empno%type:=&n;
Begin
Select * into vrow from emp where empno=vno;
Dbms_output.put_line ( vrow.ename ||
|| vrow.sal );
End;
Record Type ( or ) Pl/Sql Record
-->Is is one of the user defined temporary data type which is used to store more
than one table data ( or ) to assign more than one column datatypes.
-->They must at least contain one element.
-->Pinpoint of data is not possible.
Syntax : Type Typename is Record ( Val-1 Datatype, Val-2 Datatype, ..);
Var Typename
Ex : Declare
Type Rec is record ( vname emp.ename%type,
Vsal emp.sal%type,
VLoc dept.loc%type);
Vrec Rec;
Vno emp.empno%type:=&n;
Begin
Select ename,sal,loc into vrec from emp,dept where emp.deptno=dept.deptno and em
p.empno=vno;
Dbms_output.put_line(vrec.vname|| , ||vrec.vsal|| , ||vrec.vloc);
End;
*************************************************************************
----------------------Conditional Statements
----------------------1.
2.
3.
4.
If Condition
If Else Condition
Elsif Condition
Case Condition
=>If Condition:
Syntax :
If condition then
Statements;
End if;
Ex-1 :
Declare
A Number ( 4 ) :=&n;
B
Char ( 1 );
Begin
If a<20 then
B:= Yes ;
End if;
Dbms_output.put_line ( B );
End;
=>If Else Condition:
Syntax :
If condition then
Statements ;
Else
Statements ;
End if;
Ex-1 :
Declare A Number ( 4 ) :=&n;
B Char ( 10 );
Begin
If a<20 then
B:= TRUE ;
Else
B:= FALSE ;
End if;
Dbms_output.put_line ( B );
End;
=>Elsif Condition
Syntax :
If condition-1 then
Statements;
Elsif condition-2 then
Statements;
Elsif condition-3 then
Statements;
Else
Statements;
End if;
Ex-1 :
Declare A Number ( 4 ) :=&n;
B
Char ( 15 );
Begin
If a<20 then
B:= Low Value ;
Elsif a>20 and a<100 then
B:= High Value ;
Else
Loop
Simple Loop
While Loop
For Loop
=>Simple Loop:
Syntax :
Loop
Statements;
End loop;
Syntax :
Loop
Code;
Exit when condition;
End loop;
Ex-1 :
Begin
Loop
Dbms_output.put_line (
Welcome to k-onlines.com' );
End loop;
End;
Ex-2 :
Declare
N
number(5):=1;
Begin
Loop
Dbms_output.put_line ( n );
Exit when n>=10;
N:=n+1;
End loop;
End;
Ex-3 :
Declare
N number(5):=1;
Begin
Loop
Dbms_output.put_line ( n );
If n>=10 then
Exit;
End if;
N:=N+1;
End loop;
End;
=>While Loop:
Syntax :
While ( Condition )
Loop
Statements;
End loop;
Ex-1:
Declare
N Number(4):=1;
Begin
While n>=10
Loop
Dbms_output.put_line ( N );
N:=N+1;
End loop;
End;
=>For Loop:
Syntax :
For variable_name in
Loop
Statements;
End loop;
Ex-1:
Declare
N number(5);
Begin
lowerbound..outerbound
For
n in 1..10
Loop
Dbms_output.put_line ( N );
End loop;
End;
Ex-2
Declare
N number(5);
Begin
For
n in reverse 1..10
Loop
Dbms_output.put_line ( N );
End loop;
End;
*************************************************************************
------------------------BIND VARIABLE/SESSION VARIABLE/HOST VARIABLE---------------------------------------------------------------------------------------------------------->These Variables are Session Variables
Syntax: Variable a Number;
Ex-1 :
Variable V Number;
DECLARE
A Number(5):=500;
BEGIN
:v:=a/2;
END;
*************************************************************************
-------CURSOR
--------->Cursor is a buffer area which is used to process Multiple records and also re
cord by record process
There are Two Types of Cursors:
1. Implicit Cursor
2. Explicit Cursor
=> IMPLICIT CURSOR :
1. SQL Statements return a single record
is called implicit cursor
2. Implicit cursor operations done by Sy
stem
3. Open by the system.
4. Fetch the records by the system.
5. Close the cursor by the system.
Eg:
DECLARE
X EMP%ROWTYPE;
BEGIN
SELECT * INTO X FROM EMP WHERE EMPNO=736
9;
DBMS_OUTPUT.PUT_LINE(X.EMPNO||','||X.ENA
ME);
END;
=> EXPLICIT CURSOR :
1. SQL Statements return a multiple reco
rd is called Explicit cursor
2. Explicit cursor operations done by th
e user.
3.
4.
5.
6.
Declare by user.
Open by the user.
Fetch the records by the user.
Close the cursor by the user.
Eg1:
DECLARE
CURSOR C1 IS SELECT ENAME, SAL FROM EMP;
V_NAME VARCHAR2(10);
V_SAL NUMBER(10);
BEGIN
OPEN C1;
FETCH C1 INTO V_NAME,V_SAL;
DBMS_OUTPUT.PUT_LINE(V_NAME||','||V_SAL)
;
CLOSE C1;
END;
//will print only one record, 1st record.
Eg2:
DECLARE
CURSOR C1 IS SELECT ENAME, SAL FROM EMP;
V_NAME VARCHAR2(10);
V_SAL NUMBER(10);
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO V_NAME,V_SAL;
DBMS_OUTPUT.PUT_LINE(V_NAME||','||V_SAL)
;
END LOOP;
CLOSE C1;
END;
//Will print all records
, but finaly record will go on infinite loop until buffer overflow as we have no
t specified exit loop considtion. We use Cursor attributes to specify the exit l
oop condition while using cursor.
Eg3:
DECLARE
CURSOR C1 IS SELECT ENAME, SAL FROM EMP;
V_NAME VARCHAR2(10);
V_SAL NUMBER(10);
BEGIN
OPEN C1;
FETCH C1 INTO V_NAME,V_SAL;
DBMS_OUTPUT.PUT_LINE(V_NAME||','||V_SAL)
;
FETCH C1 INTO V_NAME,V_SAL;
DBMS_OUTPUT.PUT_LINE(V_NAME||','||V_SAL)
;
CLOSE C1;
// Will print 2 records, as we have fetched twice without using loop.
END;
%NotFound
%Found
%IsOpen
%RowCount
INVALID_CURSOR if cu
NULL if cursor is OP
FALSE if a successfu
TRUE if no row was r
Eg:
DECLARE
CURSOR C1 IS SELECT ENAME, SAL FROM EMP;
V_NAME VARCHAR2(10);
V_SAL NUMBER(10);
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO V_NAME,V_SAL;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(V_NAME||','||V_SAL)
;
END LOOP;
CLOSE C1;
END;
Eg2:
DECLARE
CURSOR C1 IS SELECT ENAME, SAL FROM EMP;
VROW EMP%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO VROW.ENAME,VROW.SAL;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(VROW.ENAME||','||VR
OW.SAL);
END LOOP;
CLOSE C1;
END;
//same as above program, but here we are using single variable of rowtype datayp
e.
B) %FOUND:
----------> Returns
rsor is declared, but not open or if cursor is closed.
--> Returns
EN, but fetch has not been executed
--> Returns
l fetch has been executed
--> Returns
returned
INVALID_CURSOR if cu
NULL if cursor is OP
TRUE if a successful
FALSE if no row was
Eg1:
DECLARE
CURSOR C1 IS SELECT * FROM EMP;
VROW EMP%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO VROW.EMPNO, VROW.ENAME, VR
OW.SAL;
IF C1%FOUND
THEN
DBMS_OUTPUT.PUT_LINE(VROW.ENAME||','||VR
OW.ENAME||','||VROW.SAL);
ELSE
EXIT;
END IF;
END LOOP;
CLOSE C1;
END;
C) %IsOpen:
D) %ROWCOUNT:
----------> Returns INVALID_CURSOR if cu
rsor declared but not open or if cursor is closed.
--> Returns the number of rows f
etched by the cursor.
Eg1:
DECLARE
CURSOR C1 IS SELECT * FROM EMP;
VROW EMP%ROWTYPE;
BEGIN
OPEN C1;
IF C1%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE("CUROSR IS OPEN");
LOOP
FETCH C1 INTO VROW;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(VROW.ENAME||','||VR
OW.ENAME||','||VROW.SAL);
END LOOP;
END IF;
DBMS_OUTPUT.PUT_LINE("Total Number of Em
ployees:" || C1%ROWCOUNT);
CLOSE C1;
IF NOT C1%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE("CUROSR IS CLOSED")
;
END IF;
END;
Eg2:
DECLARE
CURSOR C1 IS SELECT * FROM EMP;
VROW EMP%ROWTYPE;
BEGIN
OPEN C1;
IF C1%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE("CUROSR IS OPEN");
LOOP
FETCH C1 INTO VROW;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(C1%ROWCOUNT||','||V
ROW.ENAME||','||VROW.ENAME||','||VROW.SAL);
END LOOP;
END IF;
DBMS_OUTPUT.PUT_LINE("Total Number of Em
ployees:" || C1%ROWCOUNT);
CLOSE C1;
IF NOT C1%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE("CUROSR IS CLOSED")
;
END IF;
END;
Ex2:
DECLARE
Cursor c1(p_job varchar2) is select * from emp w
here job=p_job;
I emp%rowtype;
BEGIN
Open c1('MANAGER');
LOOP
Fetch c1 into i;
Exit when c1%notfound;
DBMS_OUTPUT.PU_LINE(i.empno||','||i.ename||','||
i.job);
End LOOP;
Close c1;
Open c1('CLERK');
LOOP
Fetch c1 into i;
exit when c1%notfound;
dbms_output.put_line(i.empno||','||i.ename||','|
|i.job);
end loop;
close c1;
end;
Ex3:
DECLARE
Cursor c1(p_job varchar2,p_deptno number) is sel
ect * from emp where job=p_job and deptno=p_deptno;
I emp%rowtype;
BEGIN
Open c1(&p_job , &p_deptno);
LOOP
Fetch c1 into i;
Exit when c1%notfound;
DBMS_OUTPUT.PUT_LINE(i.empno||','||i.ename||','|
|i.job);
End LOOP;
Close c1;
Open c1(&p_job , &p_deptno);
LOOP
Fetch c1 into i;
exit when c1%notfound;
dbms_output.put_line(i.empno||','||i.ename||','|
|i.job);
end loop;
close c1;
end;
--> CURSOR WITH FOR LOOP:
---------------------- In cursor for Loop no need to opne, fetch and
close cursor. For loop will automatically do all of these operations.
Eg1:
DECLARE
VALUES(I.ENAME,I.SAL);
END LOOP;
END;
Eg2:
DECLARE
CURSOR C1 IS SELECT * FROM CURSOR_TABLE;
BEGIN
FOR I IN C1
LOOP
DELETE FROM CURSOR_TABLE WHERE EMPNO BET
WEEN 7900 AND 8000;
END LOOP;
END;
Eg3:
DECLARE
CURSOR C1 IS SELECT * FROM EMPLOYEES;
BEGIN
FOR I IN C1
LOOP
IF I.JOB='CLERK'
THEN
UPDATE EMPLOYEES SET SAL=SAL+1111 WHERE
EMPNO=I.EMPNO;
ELSIF I.JOB='MANAGER'
THEN
UPDATE EMPLOYEES SET SAL=SAL+2222 WHERE
EMPNO=I.EMPNO;
END IF;
END LOOP;
END;
s one of the ref cursor which does not have Return type.
--Normal cursor would keep data in buffer area f
or every Select statement.
--Ref cursor is used because is it saves the buf
fer area. It frees buffer area automatically and hence improves performance.
--In ref cursor we are executing select statemen
ts using open ... for statement.
Eg1:
DECLARE
TYPE T1 IS REF CURSOR;
v_t T1;
I EMP%ROWTYPE;
BEGIN
OPEN v_t FOR SELECT * FROM EMP WHERE SAL>2000;
LOOP
FETCH v_t INTO I;
EXIT WHEN v_t%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.EMPNO||','||I.ENAME||','|
|I.SAL);
END LOOP;
CLOSE V_T;
END;
Eg2:
SET SERVEROUTPUT ON SIZE 30000;
DECLARE
TYPE T1 IS REF CURSOR;
v_t T1;
I EMP%ROWTYPE;
J DEPT%ROWTYPE;
V_NO NUMBER(5):=&NO;
BEGIN
IF V_NO=1 THEN
OPEN v_t FOR SELECT * FROM EMP;
LOOP
FETCH v_t INTO I;
EXIT WHEN v_t%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.EMPNO||','||I.ENAME||','|
|I.SAL);
END LOOP;
CLOSE V_T;
ELSIF V_NO=2 THEN
OPEN v_t FOR SELECT * FROM DEPT;
LOOP
FETCH v_t INTO J;
EXIT WHEN v_t%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(J.DEPTNO||','||J.DEPNAME);
END LOOP;
CLOSE V_T;
ELSE
DBMS_OUTPUT.PUT_LINE('INPUT A VALID VALUE 1 OR 2
');
END IF;
END;
COMMIT;
END;
//We can achieve above functionality by using where current of feature,
But We must use FOR UPDATE clause in cursor if we are using WHERE CURRENT OF.
DECLARE
CURSOR C1 IS SELECT * FROM EMP FOR UPDATE;
I EMP%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
IF I.JOB='CLERK' THEN
UPDATE K SET SAL=I.SAL+1000 WHERE CURRENT OF C1;
END IF;
END LOOP;
COMMIT;
END;
*************************************************************************
---------EXCEPTIONS
----------->Exception is one of the
errors at runtime.
Types of Exceptions:
1.
2.
3.
5. invalid_number
6. value_error
7. zero_divide
8. others
etc etc etc
1. NO_DATA_FOUND:
---------------* When a PL/SQL block contains "Select into" cla
use and if requested data not available in the table, Oracle Server returns an e
rror.
* ERROR is ORA-01403:no data found
* To handle this error we are using NO_DATA_FOUN
D exception.
Eg:
DECLARE
I EMP%ROWTYPE;
BEGIN
SELECT * INTO I FROM EMP
WHERE EMPNO=1111;
DBMS_OUTPUT.PUT_LINE(I.E
MPNO||','||I.ENAME);
END;
--Above program will throw no data found exception, we w
ill catch the exception in below program
DECLARE
I EMP%ROWTYPE;
BEGIN
SELECT * INTO I FROM EMP
WHERE EMPNO=1111;
DBMS_OUTPUT.PUT_LINE(I.E
MPNO||','||I.ENAME);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE("Em
ployee Does not exist");
END;
2. TOO_MANY_ROWS:
---------------* When a Select into clause try to return more
than one recor or more than one value then oracle server return error.
* ERROR is ORA-01422:Exact fetch returns more th
an requested number of rows.
* To handle this error we are using TOO_MANY_ROW
S exception.
Eg:
DECLARE
I EMP%ROWTYPE;
BEGIN
3. INVALID_CURSOR:
-----------------* Whenever we are performing invalid operations
on a cursor, server returns an error.
For eg: If we try to close a cursor without op
ening the cursor then Oracle server returns an error.
* ERROR is ORA-01001: Invalid Cursor
* To handle this error we are using INVALID_CURS
OR exception.
Eg:
DECLARE
CURSOR C1 IS SELECT * FR
OM EMP;
I EMP%ROWTYPE;
BEGIN
--> Note here we have not opened the cursor
LOOP
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.E
NAME||','||I.SAL);
END LOOP;
CLOSE C1;
END;
--Above program will throw Invalid Cursor exception, we
will catch the exception in below program
DECLARE
CURSOR C1 IS SELECT * FR
OM EMP;
I EMP%ROWTYPE;
BEGIN
--> Note here we have not opened the cursor
LOOP
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.E
NAME||','||I.SAL);
END LOOP;
CLOSE C1;
EXCEPTION
WHEN INVALID_CURSOR THEN
DBMS_OUTPUT.PUT_LINE("Op
en The Cursor Properly before closing");
END;
4. CURSOR_ALREADY_OPEN:
----------------------* Whenever we try to RE-OPEN the cursor without
closing the cursor, Oracle server returns an error.
* ERROR is ORA-06511: CURSOR ALREADY OPEN
* To handle this error we are using CURSOR_ALREA
DY_OPEN exception.
Eg:
DECLARE
CURSOR C1 IS SELECT * FR
OM EMP;
I EMP%ROWTYPE;
BEGIN
OPEN C1
--> Note here we have opened the cursor
LOOP
OPEN C1
--> Note here we are again opening an already open cursor
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.E
NAME||','||I.SAL);
END LOOP;
CLOSE C1;
END;
;
C NUMBER(10):=&C
;
BEGIN
A:=B/C;
DBMS_OUTPUT.PUT_
LINE(A);
EXCEPTION
WHEN ZERO_DIVIDE
THEN
DBMS_OUTPUT.PUT_
LINE('VALUE OF C MUST BE GREATER THAN ZERO)
END;
**-->EXCEPTION PROPAGATION
-->Exceptions are also raised in
1. Exception Sec
tion
2. Executable Se
ction
3. Exception Sec
tion
--> If the Exceptions are raised in Exec
utable section those exceptions are handled using either inner block or an outer
block.
--> Where as If the Exception are raised
in declaration section or in exception section those exceptions are handled usi
ng outer blocks only.
Ex:
BEGIN
DECLARE
Z VARCHA
R2(3):='ABCD';
BEGIN
Z:='ABCD
';
DBMS_OUT
PUT.PUT_LINE(Z);
EXCEPTIO
N
WHEN VAL
UE_ERROR THEN
DBMS_OUT
PUT.PUT_LINE("INVALID STRING LENGTH");
END;
EXCEPTIO
N
WHEN VAL
UE_ERROR THEN
DBMS_OUT
PUT.PUT_LINE("THE LENGTH IS MORE");
END;
exception;
Ex:
DECLARE
A EXCEPTION;
-->Raise Excepti
on:
--> Whenever it is required to raise user defined exception either in executable
section or exception section,
in this case we are using raise keyword.
Syntax:
raise
userdefinedexception_name
Ex:
DECLARE
A EXCEPTION;
BEGIN
RAISE A;
END;
-->Handle Except
ion:
--> We can also handle user defined exceptions same as predefined exception usin
g predefined handler.
Syntax:
when userdefinedexception_name1 then
statements;
when userdefinedexception_name2 then
statements;
------when others then
statements;
EX1:
DECLARE
A EXCEPTION;
BEGIN
IF TO_CHAR(SYSDATE,'DY')='SUN' THEN
RAISE A;
END IF;
EXCEPTION
WHEN A THEN
DBMS_OUTPUT.PUT_LINE("MY EXCEPTION RAISED TODAY");
END;
EX2:
DECLARE
X NUMBER(2):=&X;
Y NUMBER(2):=&Y;
Z NUMBER(2);
A EXCEPTION;
BEGIN
Z:=X+Y;
DBMS_OUTPUT.PUT_LINE(Z);
IF Z>99 THEN
RAISE A;
END IF;
EXCEPTION
WHEN A THEN
DBMS_OUTPUT.PUT_LINE("MY USER DEFINED EXCEPTION RAISED");
END;
END LOOP;
CLOSE C1;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE("YOUR JOB NOT AVAILABLE");
END;
--> Exceptions can be called inside another Exception
***IMP***
-->
ERROR Trapping Functions:
------------------------------> There are two error Trapping functions supported by Oracle.
1. SQL Code
2. SQL Errm
1. SQL CODE:
--> It Returns error Numbers
2. SQL Errm:
--> It returns error number with
error message.
Ex:
DECLARE
V_SAL NUMBER(10);
BEGIN
SELECT SAL INTO V_SAL FROM EMP W
HERE EMPNO=7369;
DBMS_OUTPUT.PUT_LINE(SQLCODE);
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
***IMP***
-->
RAISE APPLICATION ERROR:
-----------------------------> If you want to display your own user defined exception numbe
r and exception message then we can use this raise application error.
Syntax:
raise_application_error (error_number,error_mess
age);
Error_Number: Is given between -20000 to -20999
Error_message: Is given message upto 512 charac
ters.
Ex:
DECLARE
A EXCEPTION;
I EMPLOYEES%ROWTYPE;
BEGIN
*************************************************************************
---------SUB PROGRAMS
--------------> Sub Programs are named pl/sql blocks which is used to solve
particular task.
--> There are two types of sub programs supported by Oracle.
1. Procedures
2. Functions
:-->PROCEDURES:
----------------> Procedures may or may not return a value.
--> Procedure return more than one value while using the
out parameter.
--> Procedure can execute in only 3 ways
1. Anonymous block
2. EXEC
3. CALL
--> Procedure can not execute in select statement.
--> Procedure internally has one time compilation proces
s.
--> Procedure are used to improve the performance of bus
iness applications.
--> Every Procedure is having two parts
a) Procedure Specification
-->In procedure
Specification we are specifying name of the procedure and types of the parameter
s.
b) Procedure Body
--> In procedure
body we are solving actual task.
EX:
CREATE OR REPLACE PROCEDURE P1(P_EMPNO NUMBER) I
S
V EMP%ROWTYPE;
BEGIN
SELECT * INTO V FROM EMP WHERE EMPNO=P_EMPNO;
DBMS_OUTPUT.PUT_LINE(V.EMPNO||','||V.ENAME);
END P1;
Ex2:
CREATE OR REPLACE PROCEDURE PROC_NAME(p_EMPLOYEE
_ID NUMBER)
IS
TYPE REC IS RECORD ( P_EMP_ID EMPLOYEES.EMPLOYE
E_ID%TYPE,
P_EMP_NAME EMPLOYEES.FIRST_NAME%TYPE,
P_EMP_START_DATE JOB_HISTORY.START_DATE%TYPE,
P_EMP_END_DATE JOB_HISTORY.END_DATE%TYPE,
P_EMP_JOB_ID JOB_HISTORY.JOB_ID%TYPE,
P_EMP_DEP_NAME DEPARTMENTS.DEPARTMENT_NAME%TYPE);
P_REC REC;
BEGIN
SELECT A.EMPLOYEE_ID,A.FIRST_NAME,B.START_DATE,B
.END_DATE,B.JOB_ID,C.DEPARTMENT_NAME INTO P_REC
FROM EMPLOYEES A,JOB_HISTORY B, DEPARTMENTS C
WHERE A.EMPLOYEE_ID=B.EMPLOYEE_ID
AND A.DEPARTMENT_ID=C.DEPARTMENT_ID
AND A.DEPARTMENT_ID=B.DEPARTMENT_ID
AND A.EMPLOYEE_ID=P_EMPLOYEE_ID;
DBMS_OUTPUT.PUT_LINE(P_REC.P_EMP_ID||','||P_REC.
P_EMP_NAME||','||P_REC.P_EMP_START_DATE||'.'||P_REC.P_EMP_END_DATE||','||P_REC.P
_EMP_JOB_ID||','||P_REC.P_EMP_DEP_NAME);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('We did not find any data f
or given Employee_id: '|| P_REC.P_EMP_ID);
END PROC_NAME;
-------> SHOW ERROR
function can be used to check errors while compiling database objects
--------> All database objects are recorded in ALL_OBJECTS table.
we can check them
DESC ALL_OBJECTS;
-->to check columns in t
hat table
select OBJECT_NAME,OBJECT_TYPE FROM ALL_OBJECTS WHERE OB
JECT_NAME='P1';
--> To find the count of procedures.
select count(1) FROM ALL_OBJECTS WHERE OBJECT_NAME='PROCEDURE';
--> To find who created a Particular Table
select OWNER, OBJECT_NAME from ALL_OBJECTS where OBJECT_NAME='EM
PLOYEE';
--> To find how many database Objects created by each user
select OWNER, count(OBJECT_NAME) from ALL_OBJECTS group by OWNER
;
--> Executing the PROCEDURE:
----------------------------Method 1 :
EXEC P11(7902);
Method 2 : Begin
P11(7902);
end;
Method 3: CALL P11(7902);
Ex2:
LOOP
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.ENAME||',
'||I.SAL||','||I.DEPTNO);
END LOOP;
CLOSE C1;
END P111;
--> Parameters in PROCEDURE:
------------------------------> Parameters are used to pass the value into Procedures and al
so return values from the PROCEDURE.
--> In this case we must use two types of parameters:
1. FORMAL PARAMETERS
2. ACTUAL PARAMETERS
--> Formal Parameters:
--> Formal Parameters are defined in Pro
cedure specification.
--> In formal Parameters we are defining
parameter name & mode of the parameter.
--> There are three types of modes suppo
rted by oracle.
1. IN mode
2. OUT mode
3. INOUT mode
1) IN MODE:
--> By Default Procedure paramet
ers is IN mode.
--> IN Mode is used to pass the
values into the Procedure body
--> This mode behaves like a con
stant in Procedure body , through this IN mode we can also pass default values u
sing default or ":=" operator.
EX:
CREATE OR REPLACE PROCEDURE P1(P
_DEPTNO IN NUMBER,
P_DNAME IN VARCHAR2,
P_LOC IN VARCHAR2)
IS
BEGIN
INSERT INTO DEPT VALUES(P_DEPTNO
,P_DNAME,P_LOC);
DBMS_OUTPUT.PUT_LINE("RECORD IS
INSERTED THROUGH PROCEDURE");
END;
--> There are 3 types of EXECUTION METHO
DS supported by IN parameter.
1. Positional Notations
2. Named Notations
3. Mixed Notations
1. Positional Notations:
Ex: EXEC P1(1,'a','b');
2. Named Notations:
Ex: EXEC P1(p_dname=>'x'
,p_loc=>'y',p_deptno=>2);
3. Mixed Notations:
Ex: EXEC p1(1,p_dname=>'
m',p_loc=>'n');
2) OUT MODE:
--> This Mode is used to return
values from procedure body.
--> OUT mode internally behaves
like a uninitialized variable in PROCEDURE body.
Ex1:
create or replace procedure p1(a
IN number, b OUT number) is
begin
b:=a*a;
dbms_output.put_line(b);
end;
NOTE:
In Oracle if a subprogram contains OUT o
r INOUT parameters those subprograms are executed using 2 Methods:
METHOD 1: USING BIND VARIABLE
METHOD 2: USING ANONYMOUS BLOCK
BIND VARIABLE:
--> These variab
les are session variables
--> These variab
les are created at host environment that's why these variables are also called a
s HOST VARIABLES.
--> These variab
les are not a PL/SQL variables, but we can also use these variables in PL/SQL to
execute subprograms having out parameters.
METHOD 1: Bind variable:
Ex:
VARIABLE B NUMBER;
EXEC P1(10,:b);
3) INOUT MODE:
--> This Mode is used to pass th
e values into Sub program and return the values from subprogram.
// WE CANNOT EXECUTE ABOVE PROGRAM LIKE
THIS P1(10); AS IT IS AN INOUT VARIABLE.
Ex1:
CREATE OR REPLAC
E PROCEDURE P1(A IN OUT NUMBER) Is
BEGIN
A:=A*A;
DBMS_OUTPUT.PUT_
LINE(A);
END;
METHOD 1: BIND VARIABLE
VARIABLE A NUMBE
R;
EXEC :A:=10;
--Assigning value 10 to variable A.
EXEC P1(:A);
METHOD 2 : ANONYMOUS BLO
CK
DECLARE
A NUMBER(10):=&N
;
BEGIN
P1(A);
DBMS_OUTPUT.PUT_
LINE(A);
END;
EX2:
CREATE OR REPLACE PROCED
URE P4(A IN OUT NUMBER) IS
BEGIN
SELECT SAL INTO A FROM E
MPLOYEE WHERE EMPNO=A;
DBMS_OUTPUT.PUT_LINE(A);
END;
:-->FUNCTIONS:
----------------> Function is a named PL/SQL block which is used to So
lve Particular task and by default functions return a single Value.
--> Function allows to return Multiple Return Statements
but it Execute only First return statement
--> Function can execute in 4 ways:
1. Anonymous Block
2. Select Statement
3. Bind Variable
4. EXEC
--> Like PROCEDURE Function is also having 2 Parts.
1. Function Specification
2. Function Body
--> In function specification we are specifying name of
the function and type of the parameters where as in function body we are solving
the actual task.
Ex:
CREATE OR REPLACE FUNCTION F1( A VARCHAR2)
RETURN VARCHAR2
IS
BEGIN
RETURN A;
END;
EXECUTING Function:
1. ANONYMOUS Block:
DECLARE
A VARCHA
R2(10):='WELCOME';
BEGIN
A:=F1('W
elcome');
DBMS_OUT
PUT.PUT_LINE(A);
END;
2. BIND Variable:
VARIABLE A Varch
ar2(10);
Begin
:A:=F1('WELCOME'
);
END;
3. EXEC:
EXEC DBMS_OUTPUT.PUT_LIN
E(F1('Welcome'));
4. SELECT:
SELECT F1('WELCOME TO AP
PS') FROM DUAL;
as parameter
> 10000 then
> 20000 then
> 50000 then
*************************************************************************
--------PACKAGES
----------> Package is a Database Object which is used to encapsulate variables,
constants, procedures, cursors, functions, types in to Single Unit.
--> Package does not accept Parameters, cannot be nested , cannot be Inv
oked.
--> Generally Packages are used to Improve performance of the Applicatio
n
because when we are calling packaged subprogram first time total
package is automatically loaded into memory area.
--> Whenever we are calling Subsequent sub program calls pl/sql run time
EX1:
CREATE OR REPLACE PACKAGE P1
IS
PROCEDURE P1;
PROCEDURE P2;
END;
CREATE OR REPLACE PACKAGE BODY PACK1
IS
PROCEDURE P1
BEGIN
DBMS_OUTPUT.PUT_LINE("PROCEDURE P1");
END P1;
PROCEDURE P2
BEGIN
DBMS_OUTPUT.PUT_LINE("PROCEDURE P2")
END P2;
END PACK1;
--> We can execute only one object from a Package at a time.
--> To execute one object from Package we have to execute in the
way mentioned below.
EXEC PACK1.P1;
(PACKAGE NAME.PROCEDURE NAME)
EX2:
CREATE OR REPLACE PACKAGE PACK1
IS
PROCEDURE P1(A NUMBER, B NUMBER, C OUT NUMBER);
PROCEDURE P2(X NUMBER, Y NUMBER);
END;
CREATE OR REPLACE PACKAGE BODY PACK1
IS
PROCEDURE P1(A NUMBER, B NUMBER, C OUT NUMBER)
IS
BEGIN
C:=A+B;
END P1;
PROCEDURE P2(X NUMBER, Y NUMBER)
IS
Z NUMBER(5);
BEGIN
Z:=X-Y;
DBMS_OUTPUT.PUT_LINE(Z);
END P2;
END PACK1;
SET SERVEROUTPUT ON;
DECLARE
C NUMBER(5);
BEGIN
PACK1.P1(10,20,C);
DBMS_OUTPUT.PUT_LINE(C);
END;
SET SERVEROUTPUT ON;
exec PACK1.P2(20,10);
*************************************************************************
-------TRIGGERS
---------> Triggers are also same as Stored Procedures, Triggers are au
tomatically invoked whenever DML operations are performed against table or a vie
w.
--> There are Two Types of Triggers Supported by PL/SQL
1. Statement Level Trigger:
** In Statement Level Trigger , Trigger
Body is executed only once for DML statements.
2. Row Level Trigger
** In Row Level Trigger, Trigger body is
executed for each and every DML statements.
Syntax:
CREATE {OR REPLACE} TRIGGER TRIGGER_NAME
BEFORE/AFTER TRIGGER_EVENT
INSERT or UPDATE or DELETE ON TABLE_NAME
{for each row}
{where condition}
{DECLARE}
variable declarations, cursors
BEGIN
-----END
EXECUTION ORDER IN
1.
2.
3.
4.
TRIGGER:
Before Statement Level
Before Row Level
After Row Level
After Statement Level
(or) :n
ew.column_name
-->When We are Using These Qualifiers in when cl
ause we are not allowed to use colon in front of the Qualifers.
BEFORE VS AFTER TRIGGER:-----------------------> In Before Trigger , Trigger body is
executed before DML statements are effected into database.
--> In After Triggers, Trigger body is e
xecuted after DML statements are effected into database.
--> Generally if we want to restrict inv
alid data entry always we are using before triggers,
where as if we are performing op
eration on the one table those operations are effected in another table then we
are using after Trigger.
--> Whenever we are Inserting values int
o new Qualifiers we must use before Trigger otherwise Oracle Server returns an e
rror.
Q: Write a PL/SQL Row Level Trigger on EMP Table whenever user inserting
data into a emp table salary should be more than 5000.
-->
CREATE OR REPLACE TRIGGER T90 BEFORE INS
ERT ON EMP
FOR EACH ROW
BEGIN
IF :NEW.SAL<5000 THEN
RAISE_APPLICATION_ERROR(-20123,'SALARY S
HOULD BE MORE THAN 5000');
END IF;
END;
ON DELETE CASCADE:
------------------While deleting a record, if there is dependency of that record in any other tabl
e.
Those records also will be deleted if ON DELETE CASCASE is set ON.
Q: Write a PL/SQL Row Level Trigger on EMP, DEPT Tables for implementing
on delete cascade concept, without using On DELETE cascade Clause.
CREATE OR REPLACE TRIGGER T91
AFTER DELETE ON DEPT
FOR EACH ROW
BEGIN
DELETE FROM EMP WHERE DEPTNO=:OLD.DEPTNO
;
END;
Q: Write a PL/SQL Row Level Trigger on DEPT table whenever updating dept
no's in DEPT table automatically those deptno's modified into emp table.
CREATE OR REPLACE TRIGGER T19
AFTER UPDATE ON DEPT
FOR EACH ROW
BEGIN
UPDATE EMP SET DEPTNO=:NEW.DEPTNO WHERE
DEPTNO=:OLD.DEPTNO;
END;
Q: Write a PL/SQL Row Level Trigger Whenever user inserting data into en
ame column after inserting data must be converted into uppercase.
CREATE OR REPLACE TRIGGER T20
BEFORE INSERT ON EMPLOYEE
FOR EACH ROW
BEGIN
:NEW.ENAME=UPPER(:NEW.ENAME);
END;
Q: Write a PL/SQL Row Level Trigger on EMP table by using below Conditio
n?
1. Whenever user Inserting data those values stored in a
nother table.
2. Whenever user Updating data those values stored in an
other table.
3. Whenever user Deleting data those values stored in an
other table?
create table employee as EMP;
similar table
create or replace trigger t1 after insert or delete or u
pdate on emp
for each row
begin
if inserting then
insert into employee(empno,ename) values(:new.empno,:new
.ename);
elseif updating then
insert into employee(empno,ename) values(:old.empno,:old
.ename);
elseif deleting then
insert into employee(empno,ename) values(:old.empno,:old
.ename);
end if;
end;
Q: Write a PL/SQL Row Level Trigger on EMP table, whenever a record is d
eleted display the number of records available in the Table after the delete.
CREATE OR REPLACE TRIGGER T1 AFTER DELETE ON EMP
FOR EACH ROW
DECLARE
CNT INT;
BEGIN
SELECT COUNT(*) INTO CNT FROM EMP;
DBMS_OUTPUT.PUT_LINE("No of records now availabl
e in EMP table : "||CNT);
END;
MUTATING TRIGGER:
-----------------
*************************************************************************
VVIP
-----------COLLECTIONS
-----------1. PL/SQL Record (or) Record Type
2. Index by Table (or) PL/SQL table (or) Associative Arrays
3. Nested Tables
4. Varrays
5. Ref Cursors
SYNTAX:
TYPE type_name IS TABLE
(binary_integer,
variable_name type_name;
////INDEX OF TABLE for NUMBER.
Eg1:
DECLARE
TYPE T1 IS TABLE
OF NUMBER(10) INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
V_T(1):=10;
V_T(2):=20;
V_T(3):=30;
V_T(4):=40;
V_T(5):=50;
DBMS_OUTPUT.PUT_
LINE(V_T(3));
DBMS_OUTPUT.PUT_
LINE(V_T.first);
DBMS_OUTPUT.PUT_
LINE(V_T.last);
DBMS_OUTPUT.PUT_
LINE(V_T.prior(3));
DBMS_OUTPUT.PUT_
LINE(V_T.next(4));
DBMS_OUTPUT.PUT_
LINE(V_T.count);
DBMS_OUTPUT.PUT_
LINE(V_T(5));
END;
Eg2:
DECLARE
TYPE T1 IS TABLE
OF NUMBER(10) INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
V_T(1):=10;
V_T(2):=20;
V_T(3):=30;
V_T(4):=40;
V_T(5):=50;
DBMS_OUTPUT.PUT_
LINE(V_T.count);
V_T.DELETE(2,3);
//Will Delete 2nd to 3rd Record.
DBMS_OUTPUT.PUT_
LINE(V_T.count);
V_T.DELETE;
//Will Delete all records, if index is not specified.
DBMS_OUTPUT.PUT_
LINE(V_T.count);
V_T.DELETE(1);
//Will Delete 1st record
DBMS_OUTPUT.PUT_
LINE(V_T.count);
V_T.DELETE(1,3);
//Will Delete 1st to third record
END;
//INDEX OF TABLE for VARCHAR.
WRITE A PL/SQL PROGRAM TO GET ALL EMPLOY
EE NAMES FROM EMP TABLE AND STORE IT INTO INDEX BY TABLE AND DISPLAY DATA FROM I
NDEX BY TABLE?
SOLUTION:
DECLARE
TYPE T1 IS TABLE OF VARC
HAR2(10) INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
FOR I IN 1..10
LOOP
FETCH C1 INTO V_T(N);
EXIT WHEN C1%NOTFOUND;
N:=N+1;
END LOOP;
CLOSE C1;
FOR I IN V_T.FIRST..V_T.
LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V_T
(1));
END LOOP;
END;
//Above same Programm can be Implemented Using FOR LOOP.
.!! We Use FOR LOOP because in FOR LOOP, we dont have to Open Cursor, close Curs
or or Initialise variable.
DECLARE
TYPE T1 IS TABLE OF VARC
HAR2(10) INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
SELECT ENAME BULK COLLEC
T INTO V1 FROM EMP;
FOR I IN V1.FIRST..V1.LA
ST
LOOP
DBMS_OUTPUT.PUT_LINE(V1(
I));
END LOOP;
END;
//INDEX OF TABLE for DATE.
DECLARE
TYPE T1 IS TABLE OF DATE
INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
FOR I IN 1..10
LOOP
V_T(I):=SYSDATE+i;
END LOOP;
FOR I IN V_T.FIRST..V_T.
LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V_T
(I));
END LOOP;
END;
DECLARE
TYPE T1 IS TABLE OF DATE
INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
SELECT HIREDATE BULK COL
LECT INTO V1 FROM EMP;
FOR I IN V_T.FIRST..V_T.
LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V_T
(I));
END LOOP;
END;
//INDEX BY VARCHAR2
DECLARE
TYPE T1 IS TABLE OF VARC
HAR2(10)
INDEX BY VARCHAR2(10);
V_T T1;
X VARCHAR2(10);
BEGIN
V_T('A') = 'ARUN';
V_T('B') = 'AJAY';
V_T('C') = 'ABHI';
X:='A'
LOOP
DBMS_OUTPUT.PUT_LINE(V_T
('X'));
X:=V_T.NEXT(X);
EXIT WHEN X IS NULL;
END LOOP;
END;
Eg of rowtype in index by table:
DECLARE
TYPE T1 IS TABLE OF emp%
rowtype
INDEX BY binary_integer;
V_T T1;
X NUMBER(5);
BEGIN
DECLARE
TYPE T1 IS TABLE OF emp%
rowtype
INDEX BY binary_integer;
V_T T1;
BEGIN
SELECT * BULK COLLECT IN
TO V_T FROM EMP;
FOR I IN V_T.FIRST..V_T.
.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V_T
(I).empno || ',' || V_T(I).ename);
END LOOP;
END;
-->NESTED TABLES:
--------------->
This is user defined type which
is used to store multiple data items in single unit
but before storing actual data w
e have to initialise the data while using Constructor
-->
Here constructor name is same as
Type name.
-->
Generally we are not allowed to
store Index By Table permanently in Database, to overcome this problem
they intodcued NESTED TABLES.
-->
These user defined types are per
manently stored in database.
-->
In Index by table we cannot add
or remove indexes, where as in NESTED TABLES we can add or remove indexes by usi
ng EXTEND, TRIM Collection methods.
-->
In NESTED TABLES we can allocate
memory explicitly while using EXTEND method.
SYNTAX:
TYPE type_name IS TABLE
of datatype(size);
:= TYPE_NAME();
-->VARRAYS:
variable_name type_name
--> Constructor
--------------->
This is user defined type which
is used to store multiple data items in single unit
but before storing actual data w
e have to initialise the data while using Constructor
-->
Here constructor name is same as
Type name.
-->
These user defined types are per
manently stored in database.
-->
Basically we are using the VARRA
YS for retrieveing HUGE DATA.
SYNTAX:
TYPE type_name IS VARRAY
(maxsize) of datatype(size);
variable_name type_name
:= TYPE_NAME();
Index ca
*************************************************************************
-->BULK MECHANISM:
---------------> Bulk is one of the method which is used to improve t
he performance of the applications.
--> Oracle introduced bulk bind processing collection i.
e in this process all sql statement related values into collections
and in this collection we are performing DML ope
ration like INSERT, UPDATE , DELETE using FOR ALL statement.
--> In this Bulk we have two options
1. BULK COLLECT
2. BULK BIND
EG:
DECLARE
TYPE T1 IS TABLE OF EMP%ROWTYPE INDEX BY BINARY INTEGER;
V T1;
BEGIN
SELECT * BULK COLLECT INTO V FROM EMP;
FOR I IN V.FIRST..V.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V(I).EMPNO||','|| V(I).ENAME||','||V(I).JOB);
END LOOP;
END;
--> Cursor Fetch
clauses
-----------------------SYNTAX:
FETCH CURSOR_NAME BULK COLLECT INTO COLLECTION_NAME;
Eg1:
SET SERVEROUTPUT ON
DECLARE
TYPE T1 IS TABLE OF EMP%ROWTYPE
INDEX BY BINARY_INTEGER;
V1 T1;
CURSOR C1 IS SELECT * FROM EMP;
BEGIN
OPEN C1;
FETCH C1 BULK COLLECT INTO V1;
CLOSE C!;
FOR i IN
V1.FIRST..V1.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V1(i).EMPNO||','||v1(i).ename||','||v1(i).job);
END LOOP
;
END;
Eg: TIME PROGRAM WITHOUT BULK FUNCTION.
declare
var1 varchar2(500) NULL;
n1 number(30);
n2 number(30);
ti number(30);
cursor c1 is select object_name from all_objects;
begin
n1:=DBMS_UTILITY.get_time();
open c1;
loop
fetch c1 into var1;
exit when c1%notfound;
end loop;
close c1;
n2:=DBMS_UTILITY.get_time();
dbms_output.put_line('Start Time: ' || n1);
dbms_output.put_line('End Time: ' || n2);
ti:=n2-n1;
dbms_output.put_line('Total Time Taken: ' || ti);
end;
OUTPUT:
Start Time: 2808071
End Time: 2808138
Total Time Taken: 67
end;
OUTPUT:
Start Time: 3824472
End Time: 3824514
Total Time Taken: 42
-->BULK
COLLECT used in DML Returning clauses.
----------------------------------------SYNTAX:
DML statement returning coloumn_name into variable_name;
Eg1:
VARIABLE A VARCHAR2(10);
UPDATE EMP SET SAL=SAL+1000 WHERE EMP_NAME='KING' RETURNING COLUMN_NAME BULK COL
LECT INTO :A;
PRINT A;
Eg2:
Write a
PLSQL Procedure to update salaries of clerk in Employee Table and also these upd
ates salries are
immediat
ely stored into INDEX BY TABLE by using DML Returning clause, and also display c
ontents from INDEX BY TABLE.
set serveroutput
on;
DECLARE
TYPE T1 IS TABLE
OF EMP%ROWTYPE INDEX BY BINARY_INTEGER;
V1 T1;
BEGIN
UPDATE EMP SET S
AL=SAL-1000 WHERE JOB='clerk' RETURNING EMPNO,ENAME,SAL, JOB,DEPTNO BULK COLLECT
INTO V1;
dbms_output.put_
line('Updated number of Clerks are :'|| sql%rowcount );
for i in v1.firs
t..v1.last
loop
dbms_output.put_
line(v1(i).EMPNO||','||v1(i).ENAME||','||v1(i).sal||','||v1(i).job||','||v1(i).d
eptno );
end loop;
END;
V1 T1;
BEGIN
for i in
1..100
loop
v1(i):=i
;
end loop
;
FORALL I
IN V1.FIRST..V1.LAST
insert i
nto bt
values(v
1(i));
END;
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------SQL
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------SQL->
? Introduction to SQL
Level 1 - Data Types
1. Number:
-->It allows only numeric values
--> Maximum Size is 38 digits
Syntax: X Number(P,(S));
P--> It allows how many digits to store.
S--> Size
Eg:
X Number(5,2);
2. Char
--> It allows alphanumeric characters (N
umbers + Characters)
--> Maximum size is 2000 bytes /characte
rs
Syntax: X Char(S);
S--> Size
3. Varchar
or VARCHAR2
--> It allows Alphanumeric characters
--> Max size 4000 bytes /characters
--> Memory Allocation is dynamic
Syntax: X VARCHAR2(50);
4. Date
--> It is used to store date values
--> Max size is 7 bytes
Syntax: X date;
5. Timestamp
--> It is used to store date along with
fraction of seconds.
Syntax: X Timestamp;
6. Long
--> It is used to store information
--> Max Size 2GB
--> Only once we have to use in Entire t
able
Syntax: X Long;
7. Raw
--> It is used to store images
--> Max size is 2000 Bytes
Syntax: X Raw;
8. LongRaw
--> It is used to store information as w
ell as images
--> Max size is 2GB
Syntax: X Longraw;
9. Lob ( CLob, Blob,BFile & NCLob )
1. CLOB:
--> It is used to store huge inf
ormation
--> Max size is 4GB
Syntax: X Clob;
2. BLOB:
--> It is used to store images b
ut in the binary format
--> Max size is 4GB
Syntax: X Blob;
3. BFILE:
--> It is used to store the file
s
--> Max size is 4GB
Syntax: X Bfile;
4. NCLOB:
--> It is used to store Multiple
Languages (Unicode format)
Level 2 - SQL Statements
? DDL
*Create
*Alter
*Drop
? DML
*Insert
*Update
*Delete
? DQL
*Select
? TCL
ly on the database.
1. IMPLICIT COMMIT: Automaticall
y executed by the system.
2. EXPLICIT COMMIT: Manually exe
cuted by user.
*Rollback--> It is executed to revert back the last chan
ges.
*Savepoint--> It is used to mark a specific ecord, It is
only for temporary purpose.
Eg: SAVEPOINT S1;
*Truncate--> It works like Delete + Commit, Syntax: TRUN
CATE TABLE Table_name;
? DCL
Level 3 - Clauses
?
?
?
?
?
?
?
Select
From
Where
Group By
Having
Order By
DISTINCT
Level 4 - Operators
? Arthemetic Operators
1. /
2. *
3. +
4. ? Logical Operators
1. And
2. Or
3. Not
? Relational Operators
1. =
2. <
3. >
4. <=
5. =>
6. !=
? Special Operators
1. Is
2. In
3. Not In
4. Between
5. Like
? Set Operators
1.
2.
3.
4.
Union
Union All
Intersect
Minus
Level 5 - Functions
? Number Functions
1. Power
2. Sqrt
3. Mod
4. Ascii
5. Ceil
6. Floor
7. Round
8. Trunc
? String Functions
1. Length
2. Reverse
3. Concat
4. Ltrim
5. Rtrim
6. Trim
7. Lpad
8. Rpad
9. Translate
10.Replace
11.Decode
? Date Functions
1. Sysdate
2. Current_Date
3. Add_Months
4. Months_Between
5. Next_Day
6. Last_Day
? Conversion Functions
1. To_Char
2. To_Date
3. To_Number
? General Functions
1. Greatest
2. Least
3. Nvl
4. Nvl2
5. Case
? Aggrigate Functions
1. Count (*)
2. Count ( Column )
3. Min
4. Max
5. Avg
6. Sum
Level 6 - Constraints
? Primary Key
? Composite Primary Key
? Unique
? Not Null
? Check
? Foreign Key
Level 7 - Joins
? Simple Join
? Equi Join
? Non Equi Join
? Outer Join
? Left Outer Join
? Right Outer Join
? Full Outer Join
? Self Join
Level 8 - Synonyms
--> It is used to hide the owner
of the table.
--> It works like a mirror image
of the table.
--> It does not have its own str
ucture.
--> It is dependent on the table
.
--> We can create synonym on tab
le, we never create synonym directly.
--> All synonyms are stored in U
SER_SYNONYMS table.
--> Synonysm fetch data from Tab
le, we can insert, update , delete on Synonym which will internally do same oper
ation on table.
--> Synonym can be created on an
other synonym,however source will be table.
? Public Synonym
--> It is used to create Public
Synonym in current schema but can be accessed through other schemas as well.
Syntax:
CREATE P
UBLIC SYNONYM synonym_name for table_name;
? Private Synonym
--> It is used to create Private
Synonym in current schema and can be accessed on through that schema and
cannot be accessed outsi
de that schame.
Syntax:
CREATE S
YNONYM synonym_name for table_name;
Level 9 - Views
--> It is advanced of Synonyms.
--> It is a Virtual table to hid
e the base table and it works like a mirror image of the table.
-->
? Simple View
? Complex View
? Force View
? Vertical View
? Horizantal View
? Functional View
? Partition View
? Inline View
? Materialized View
Level 10 - Indexes
? Simple Index
? Complex Index
? Unique Index
? Functional Index
? Bitmap Index
Level 11 - Sub Queries
? Simple Sub Query
? Co Related Sub Query
Level 12 - Clusters
Level 13 - Sequences
-------------SQL FUNCTIONS:
-------------1. Number Functions
2. String Functions
3. Date Functions
4. Conversion Functions
5. General Functions
6. Aggregate Functions
----------------Number Functions:
----------------1. POWER: POWER(a,b)
eg:
POWER(2,4)
= 8