Oracle 4
Oracle 4
SQL PL/SQL
SQL statements are passed to the PL/SQL sends an entire block of SQL
Oracle Engine one at a time. Each time statements to the Oracle engine all in one
an SQL statement is executed, a call is go. Since the Oracle engine got the SQL
made to the engine’s resources, which statements as a single block, it processes
increases network traffic. this code much faster than one sentence
at a time.
SQL does not have any procedural PL/SQL is development tool that supports
capabilities like Conditional checking using facilities of conditional checking, branching
conditional statement, looping and and looping, declaration and use of
branching, declaration and use of variable variable to store intermediate result.
to store intermediate result.
SQL has no facility for programmed PL/SQL also permits dealing with errors as
handling of errors and so if an error required, and facilitates displaying user-
occurs, the Oracle engine displays its own friendly messages, when errors are
error messages. encountered.
In SQL it is not possible to perform PL/SQL facilitates all sorts of calculations
calculations without the use of the Oracle can be done quickly and efficiently without
Engine. the use of the Oracle engine.
Structured query language. Procedural language structure query
language.
DECLARE
BEGIN
EXCEPTION
SQL or PL/SQL code to handle errors that may arise during the execution of the
code block between BEGIN and EXCEPTION section
· In simple loop, the keyword loop should be placed before the first
statement in the sequence and the keyword end loop should be
written at the end of the sequence to end the loop.
Syntax:
Loop
Sequence of statements;
End loop;
declare
num number := 0;
begin
loop
num:=num + 2;
exit when num > 10;
end loop;
dbms_output.put_line(‘Loop exited when the value of num has reached’
to_char(i));
end;
The WHILE loop
Syntax:
WHILE condition
LOOP
Action;
END LOOP;
declare
PI number (4, 2):= 3.14;
radius number(5);
area number(14,2);
begin
radius := 3;
while radius <=
7 loop
area := PI * power(radius,2);
insert into areas values(radius, area);
radius := radius + 1;
end loop;
end;
The FOR Loop
Syntax:
FOR variable IN [REVERSE] start..end
LOOP
Action;
END LOOP;
· Note: The variable in the FOR loop need not be declared. Also the
increment value cannot be specified. By default the for loop
variable is always incremented by 1.
Example:
declare
strval varchar(10);
str_length number(2);
reverse_str varchar(10);
begin
strval:=’&strval’;
str_length := length(strval);
for i in reverse 1..str_length
loop
reverse_str := reverse_str || substr(strval,i,1);
end loop;
dbms_output.put_line(‘Original String is : ‘ || strval);
dbms_output.put_line(‘Reverse String is : ‘ || reverse_str);
end;
EXPLAIN %TYPE AND %ROWTYPE WITH EXAMPLE.
DETAILING:
%TYPE
Syntax:
Tablename.columnname%TYPE;
Example:
declare
/*data type of mempno and msal is similar to the data type
and size of empno and salary column of emp table.*/
mempno emp.empno%TYPE;
msal emp.sal%TYPE;
incre_amt number(4);
finalsal number(10,2);
begin
mempno:=&mempno;
incre_amt:=&incre_amt;
select sal into msal from emp where empno=mempno;
finalsal:=msal+incre_amt;
update emp set sal=finalsal where empno=mempno;
insert into oldsal values(mempno,msal,sysdate);
end;
%ROWTYPE
Syntax:
tablename%ROWTYPE
WHAT IS
CURSOR?
DETAILING:-
· The Oracle Engine uses a work area for its internal processing in order to
execute an SQL statement.
· This work area is called a Cursor. A cursor is opened at the client end.
· The data is stored in the cursor is called the Active Data Set.
· The size of the cursor in memory is the size required to hold the number of rows
in the Active Data Set.
Example:
When a user fires a select statement as:
SELECT empno, ename, sal FROM emp WHERE deptno=10;
CURSOR
E1 Ivan 8500
SERVER E4 Peter 5700
E5 Robert 9000
E8 Julie 6500
Types of Cursors
Cursors are classified into two types.
1. Implicit Cursor
2. Explicit Cursor
A cursor that is created, opened and managed by Oracle Engine for its
internal processing is known as Implicit Cursor.
A cursor that is created, opened and managed through PL/SQL block by the
user is known as Explicit Cursor.
Cursor Attributes:
· Cursor Attributes are a set of four system variables, which keep track of the
Current status of a cursor.
· Both Implicit and Explicit cursors have four attributes.
· A cursor that is created, opened and managed by Oracle Engine for its internal
processing is known as Implicit Cursor.
· Since the implicit cursor is opened and managed by the Oracle engine internally,
the function of reserving an area in memory, filling this area with appropriate
data, processing the data in the memory area, releasing the memory area when
the processing is completed, is taken care of by the Oracle engine.
· The name of implicit cursor is always SQL.
begin
update emp set sal=sal+(sal*0.15) where empno = &mempno;
if sql%found then
dbms_output.put_line('Employee exists…Increment done successfully')
end if;
if sql%notfound then
dbms_output.put_line('Employee does not exist…Try another number
end if;
end;
The implicit cursor has following attribute.
· Cursor Declaration
Syntax:
CURSOR CursorName IS SELECT statement;
Initialization and Opening of a cursor takes place via the Open statement. Open
Statement will:
Executes a query associated with the cursor.
Creates the Active Data Set that contains all rows, which meet the query search
criteria
Sets the row pointer in the Active Data Set to the first record.
Syntax:
Open <cursorname>;
o A fetch statement then moves the data held in the Active Data Set into
memory variables.
o Data held in the memory variables can be processed as desired.
o The fetch statement is placed inside a Loop…End Loop construct, which
causes the
data to be fetched into the memory variables and processed until all the
rows in
the Active Data Set are processed.
o The fetch loop then exits.
Syntax:
FETCH CursorName INTO Variable1, Variable2,…;
Closing a Cursor
The Close Statement will release the memory occupied by the cursor and its Data
Set both on the Client and on the Server.
declare
/*data type of mempno,mdept and msal is similar to the data type and size
of empno, dept and salary column of emp table.*/
/*Defining Cursor*/
cursor c_emp is select empno,sal from emp where dept=’HR’;
mempno emp.empno%type;
msal emp.sal%type;
incre_amt number(4);
finalsal emp.sal%type;
begin
/*Open Cursor*/
open c_emp; /* Fetching of rows from
cursor*/ loop
fetch c_emp into mempno,msal;
if c_emp%found then
incre_amt:=(msal*15)/100;
finalsal:=msal+incre_amt;
update emp set sal=finalsal where empno=mempno;
insert into hroldsal values(mempno,msal,sysdate);
else
exit;
end
if; end loop;
ONE WORD QUESTION AND ANSWER
SR.NO QUESTION ANSWER
1. EXPLICIT MEANS USER
÷ A declarative part
÷ An executable part
÷ An optional exception-handling part
Declarative Part
÷ The declarative part may contain the declarations of cursors, constants,
variables, exceptions and subprograms. These objects are local to the
procedure or function.
Executable Part
÷ The executable part is a PL/SQL block consisting of SQL and PL/SQL
statements that assign values, control execution and manipulate data.
÷ The data that is to be returned back to the calling environment is also
returned from here. The variables declared are put to use within this
block.
÷ This part contains code that deals with exceptions that may be
raised during the execution of code in the executable part.
÷ An Oracle exception handler can be redirected to the exception
handling section of the procedure or function where the procedure
or function determines the actual action that must be carried out
by Oracle's exception handler.
Note: The compilation process does not display the errors. These errors can be viewed by
giving
“show err” command at sql prompt or by using “SELECT * FROM USER_ERRORS”
statement. The status of a procedure or function is shown by the use of a select
statement as
follows:
O
R
Syntax:
CREATE OR REPLACE FUNCTION <Function Name> (Argument IN Data type...)
RETURN <Data type> {IS, AS}
Variable declarations;
Constant declarations;
BEGIN
PL/SQL subprogram body;
EXCEPTION
Exception PL/SQL blocks;
END;
Function also needs pl/sql block to call it.
Declare
Variable declaration
Begin
Variable=call function
(); Subprogram body;
End;
Keywords and Parameters
The keywords and the parameters used for creating database functions are
explained below:
REPLACE Recreates the function if it already exists. This option is used to change
the definition of an existing function without dropping, recreating and
re- granting object privileges previously granted on it. If a function is
redefined, Oracle recompiles it.
Function Is the name of the function to be created?
Argument Is the name of an argument to the function? Parentheses can be omitted
if no arguments are present.
IN Indicates that the parameter will accept a value from the user.
RETURN data type Is the data type of the function's return value? Because every function
must return a value, this clause is required. It supports any data type
supported by PL/SQL.
PL/SQL Is the definition of function consisting of PL/SQL statements.
subprogram body
declare
meno number(3);
dnm varchar2(10);
begin
meno:=&meno;
dnm:=get_deptnm(meno);
dbms_output.put_line(‘Employee No. : ‘ || meno || ‘ Department Name : ‘ || dnm);
end;
DELETING A STORED PROCEDURE OR FUNCTION
Syntax:
DROP FUNCTION <Function Name>;
Syntax:
CREATE OR REPLACE PROCEDURE <Procedure Name>
(Argument {IN, OUT, IN OUT) Data Type ...) {IS, AS}
Variable declarations;
Constant declarations;
BEGIN
PL/SQL subprogram body;
EXCEPTION
Exception PL/SQL blocks;
END;
Syntax:
Execute procedure name;
declare
mename emp.ename%type;
mjob emp.job%type;
mempno number := 101;
begin
search_employee(mempno,mename,mjob);
dbms_output.put_line('Employee # : ' || mempno);
dbms_output.put_line('Name : ' || mename || ' Job ' ||
end; mjob);
÷ In the above example, value of employee number is passing to
search_employee procedure through PL/SQL block and value of two OUT
parameters vename and vjob will return back to the calling block and stored in
mename and mjob respectively.
Syntax:
DROP PROCEDURE <Procedure Name>;
Example:
Create or replace package pck_employee is
Function get_deptnm (vempno in number) return number is;
Procedure search_employee (vempno in number, vename out
varchar2, vjob out varchar2) is;
End pck_employee;
Execution of Package:
When a package is invoked, the Oracle engine performs three steps to execute it:
Use of Trigger:
Note: The PL/SQL block cannot contain transaction control SQL statements like COMMIT,
ROLLBACK, and SAVEPOINT in trigger
Trigger Restriction
÷ A trigger restriction specifies a Boolean (logical) expression that must be
TRUE for the trigger to fire.
÷ A trigger restriction is specified using a WHEN clause.
÷ In short, when the expression given with WHEN true then only
trigger action becomes executes for triggering event.
÷ If the triggering statement affects no rows, the trigger is not executed at all.
÷ Row triggers should be used when some processing is required whenever
a triggering statement affects a single row in a table.
Statement Triggers
÷ A statement trigger is fired once on behalf of the triggering statement,
independent of the number of rows the triggering statement affects.
÷ Even if no rows are affected, trigger fired.
÷ Statement triggers should be used when a triggering statement affects rows in a
table but the processing required is completely independent of the number of rows
affected.
Syntax:
CREATE OR REPLACE TRIGGER <trigger name>
BEFORE, AFTER
{DELETE, INSERT, UPDATE [OF Column ...]}
ON <table name>
[REFERENCING {OLD AS old, NEW AS new}]
[FOR EACH ROW [WHEN Condition] ]
The keywords and the parameters used for creating database triggers are
explained below:
OR REPLACE Recreates the trigger if it already exists. This option can be used to cha
the definition of an existing trigger without requiring the user to drop
trigger first.
Trigger Name Is the name of the trigger to be created?
BEFORE Indicates that the Oracle engine fires the trigger before executing
triggering statement.
AFTER Indicates that the Oracle engine fires the trigger after executing
triggering statement.
DELETE Indicates that the Oracle engine fires the trigger whenever a DEL
statement deletes any row of table.
INSERT Indicates that the Oracle engine fires the trigger whenever an INS
statement inserts any row in table. ow
ON Specifies the name of the table, which the trigger is to be created. A trigand
cannot be created on a table in the schema use
SYS.
SQL
ew
FOR EACH Designates the trigger to be a row trigger. The Oracle engine fires a r
ROW trigger once for each row that is affected by the triggering statement
meets the optional trigger constraint defined in the WHEN clause. If this ry.
cla
e
REFERENCING is omitted the trigger is a statement trigger.
Specifies correlation names. Correlation names can be used in the PL/
block and WHEN clause of a row triggers to refer specifically to old and
n values of the current row.
WHEN Specifies the trigger restriction. The trigger restriction contains a SQL
condition that must be satisfied for the Oracle engine to fire the trigger.
This condition must contain correlation names and cannot contain a qu
Syntax:
DROP TRIGGER <trigger name>;
declare
oper varchar2(8);
begin
if updating then
oper := 'update';
end if;
if deleting then
oper := 'delete';
end if;
/*insert the old values in the audit_client table. */
insert into aO
data type.
Syntax:
Create type <type name> as
object (
Name Data type (size),
Name Data type (size),
…,
…
);
Example:
Create type add_type as
object (
street varchar2(50),
city varchar2(20), state
varchar2(20), pin
number(6)
);
You can also use the user defined data type in creation of other user define
data type.
Example:
Create type person_type as
object (
name varchar2(20),
add1 add_type
);
Example:
Create table
customer (
cust_id number(3),
person
person_type
);
Inserting records in table contain user define data type:
Example:
Create table borrower
(
name varchar2(25),
tool varchar2(25)
);
Syntax: Create or replace type <type name> as varray (size) of data type (size)
Example:
Create table borrower
(
name varchar2(25),
tool tools_va );
Inserting records into Varray (
):
÷ When a data type is created, the database automatically creates a
method called a constructor method for the data type.
÷ Since a varying array is an abstract data type, we need to use
constructor method to insert records into tables that use varying arrays.
Example:
÷ ThisIinsert into bfiorsrrtoswp ecrifviaelsutehse(‘vNaelueel’,otof
othlse_vna(m‘heamcomluemr’n,’.ax’,’sledge’,null,null));
÷ Because the name column is not a part of abstract data type.
÷ The maximum number of entries per row, called its LIMIT, and the current
number of entries per row, called its COUNT.
÷ This query cannot be performed directly vie a SQL select statement.
÷ To retrieve the COUNT AND LIMIT from varray you need to use PL/SQL.
ur
Os NE WORD QUESTION AND ANSWER
SR.NO QUESTION ANSWER
1. VARRAY MEANS - COLLECTOR
2 HOW MANY TYPES OF 255
ATTRIBUTE ARE STORE
IN ONE LINE
3 VARRAY MEANS VARRIYING ARRAY.
DETAILING:
>;
÷ Varray have a limited number of entries, a second type of collector is
“Nested Table”.
÷ Nested Table has no limit on the number of entries per row.
÷ A nested table is, as its name implies, a table within a table.
÷ It is a table that is represented as a column within another table.
÷ You can have multiple rows in the nested table for each row in the
main table.
Syntax :
Create or replace type < table name> as table of <user define type>
Create table <table name>
(
columnname datatype(size),
columnname nested table
)
nested table <column name contain nested table data type> store as <table name
Example:
Create or replace type stud_ty as
object (
name varchar2(15),
add1 varchar(30),
city varchar2(15)
);
create type stud_nt as table of stud_ty;
create table studrec
(
stream varchar2(15),
studdet stud_nt
)
nested table studdet store as stud_tab;
Inserting record into nested table:
Insert into studrec values (‘BCA4’,stud_nt(stud_ty(‘xyz’,’jagnath
plot’,’rajkot’),
stud_ty(‘abc’,’kalawad
road’,’rajkot’),
stud_ty(‘pqr’,’university
road’,’rajkot’)
));
EXAMPLE:
Select name from the (select studdet from studrec where stream
like 'BCA4')