(Affiliated to Saurashtra University & Gujarat Technological University) 2 – Vaishalinagar 3 – Vaishalinagar Nr. Amrapali Railway Crossing Nr. Amrapali Railway Crossing Raiya Road Raiya Road Rajkot – 360001 Rajkot - 360001 Ph.No–(0281)2440478,2472590 Ph.No–(0281)2471645 ORACLE MATERIAL (B.CA. & B.SC.(I.T.) SEM-3) CH-4:- PL/SQL Difference between SQL and PL/SQL. DETAILING:- SQL PL/SQL SQL statements are passed to the Oracle Engine one at a time. Each time an SQL statement is executed, a call is made to the engine’s resources, which increases network traffic. PL/SQL sends an entire block of SQL statements to the Oracle engine all in one go. Since the Oracle engine got the SQL statements as a single block, it processes this code much faster than one sentence at a time. SQL does not have any procedural capabilities like Conditional checking using conditional statement, looping and branching, declaration and use of variable to store intermediate result. PL/SQL is development tool that supports facilities of conditional checking, branching and looping, declaration and use of variable to store intermediate result. SQL has no facility for programmed handling of errors and so if an error occurs, the Oracle engine displays its own error messages. PL/SQL also permits dealing with errors as required, and facilitates displaying user- friendly messages, when errors are encountered. In SQL it is not possible to perform calculations without the use of the Oracle Engine. PL/SQL facilitates all sorts of calculations can be done quickly and efficiently without the use of the Oracle engine.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
(Affiliated to Saurashtra University & Gujarat Technological University)
SQL statements are passed to the Oracle Engine one at a time. Each time an SQL statement is executed, a call is made to the engine’s resources, which increases network traffic.
PL/SQL sends an entire block of SQL statements to the Oracle engine all in one go. Since the Oracle engine got the SQL statements as a single block, it processes this code much faster than one sentence at a time.
SQL does not have any procedural capabilities like Conditional checking using conditional statement, looping and branching, declaration and use of variable to store intermediate result.
PL/SQL is development tool that supports facilities of conditional checking, branching and looping, declaration and use of variable to store intermediate result.
SQL has no facility for programmed handling of errors and so if an error occurs, the Oracle engine displays its own error messages.
PL/SQL also permits dealing with errors as required, and facilitates displaying user-friendly messages, when errors are encountered.
In SQL it is not possible to perform calculations without the use of the Oracle Engine.
PL/SQL facilitates all sorts of calculations can be done quickly and efficiently without the use of the Oracle engine.
(Affiliated to Saurashtra University & Gujarat Technological University)
A single PL/SQL code block consists of a set of SQL statements, clubbed together, and passed to the Oracle engine entirely.
A PL/SQL block has a definite structure, which can be divided into sections.
The sections of PL/SQL block are:
The Declare section.
The Begin Section.
The Exception section is optional.
The end section.
The Declare Section
PL/SQL block start with a declaration section, in which, memory variables and other Oracle objects can be declared and initialized.
The Begin Section
It consists of a set of SQL and PL/SQL statements.
Data manipulation statements, retrieval of data using SELECT, conditional statements, looping and branching statements are specified in this section.
The Exception Section
This section deals with handling of errors that arise during execution of the data manipulation statements and also user can generate its own user-defined error message.
The End Section
Declarations of memory variables, constants, cursors, etc. in PL/SQL
ONE WORD QUESTION AND ANSWER SR.NO QUESTION ANSWER
1. HOW MANY PART OF PL/SQL STRUCTURE
4
2 DECLARE MEANS___ DELCARE VARIABLE
3 BEGIN MEANS BODY
4 EXCEPTION IS OPTIONAL? YES
5 END MEANS PROGRAM IS OVER.
EXPLAIN DIFFERENTS TYPES OF LOOP IN PL/SQL. DETAILING:
Iterative control indicates the ability to repeat sections of a code block.
A loop marks a sequence of statements that has to be repeated.
The keyword loop has to be placed before the first statement in the sequence of statements to be repeated, while the keyword end loop is placed immediately after the last statement in the sequence.
PL/SQL supports the following structures for iterative control:
Simple Loop
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;
(Affiliated to Saurashtra University & Gujarat Technological University)
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;
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;
(Affiliated to Saurashtra University & Gujarat Technological University)
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.
Syntax: FOR variable IN [REVERSE] start..end LOOP
Action; END LOOP;
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;
(Affiliated to Saurashtra University & Gujarat Technological University)
PL/SQL uses the %TYPE attribute to declare variables based on definitions of columns in a table so user doesn’t need to remember data type and size of column of table.
If a column’s attributes change, the variable’s attributes will change as well.
This provides for data independence, reduces maintenance costs, and allows program to adapt to changes made to the table.
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;
(Affiliated to Saurashtra University & Gujarat Technological University)
PL/SQL uses the %ROWTYPE attribute to declare variables based on definitions of entire column in a table so user doesn’t need to remember data type and size of columns of table.
If a column’s attributes change, the variable’s attributes will change as well.
This provides for data independence, reduces maintenance costs, and allows program to adapt to changes made to the table.
ONE WORD QUESTION AND ANSWER SR.NO QUESTION ANSWER
1. TYPE AND ROW TYPE ARE ____
ATTRIBUTE.
2 TYPE MEANS ONE COLUMN
3 ROW TYPES MEANS ALL COLUMN
WHAT IS CURSOR? DETAILING:-
The Oracle Engine uses a work area for its internal processing in order to execute an SQL statement.
Syntax: tablename%ROWTYPE;
(Affiliated to Saurashtra University & Gujarat Technological University)
%ISOPEN Returns TRUE if cursor is open, FALSE otherwise.
%FOUND Returns TRUE if record was fetched successfully, FALSE otherwise.
%NOTFOUND Returns TRUE if record was not fetched successfully, FALSE otherwise.
%ROWCOUNT Returns number of records processed from the cursor.
ONE WORD QUESTION AND ANSWER SR.NO QUESTION ANSWER
1. CURSOR MEANS______ WORK AREA
2 IMPLICIT MEANS ORALCE ENGINE
3 EXPLICIT USER
4 HOW MANY TYPES OF ATTRIBUTE ARE IN CURSOR?
4
5 ADT MEANS ACTIVE DATA SET.
EXPLAIN IMPICIT CURSOR WITH EXAMPLE. DETAILING:- Implicit Cursor
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,
(Affiliated to Saurashtra University & Gujarat Technological University)
When individual records in a table have to be processed inside a PL/SQL code block, a cursor is used. This cursor will be declared and mapped to a SQL query in the Declare Section of the PL/SQL block and used within its Executable Section.
A cursor thus created and used is known as Explicit Cursor. The steps involved in using an explicit cursor and manipulating data in its active
set are:
Declare a cursor mapped to a SQL select statement that retrieves data for processing.
Open the cursor. Fetch data from the cursor one row at a time into memory variables. Process the data held in the memory variables as required using a loop. Exit from the loop after processing is complete. Close the cursor.
Cursor Declaration
A cursor is defined in the declarative part of a PL/SQL block. Naming the cursor and mapping it to a SELECT query is done at this
stage. When a cursor is declared, the Oracle engine is informed that a cursor
of the said name needs to be opened. The declaration is only information.
There is no memory allocation at this point in time.
The Functionality of Open, Fetch and Close Commands
Syntax:
CURSOR CursorName IS SELECT statement;
(Affiliated to Saurashtra University & Gujarat Technological University)
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.
Fetching Data from Cursor
A fetch statement then moves the data held in the Active Data Set into memory variables.
Data held in the memory variables can be processed as desired. 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.
The fetch loop then exits.
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.
Syntax: Open <cursorname>;
Syntax: FETCH CursorName INTO Variable1, Variable2,…;
Syntax: CLOSE <Cursor Name>;
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;
(Affiliated to Saurashtra University & Gujarat Technological University)
DETAILING: A Procedure or Function is a logically grouped set of SQL and PL/SQL statements
that perform a specific task. A stored procedure or function is a named PL/SQL code block that has been
compiled and stored in one of the Oracle engine's system tables.
Procedures and Functions are made up of:
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.
Exception Handling Part
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.
Procedures and Functions are stored in the Oracle database. Before a procedure or function is stored, the Oracle engine parses and compiles the procedure or function.
(Affiliated to Saurashtra University & Gujarat Technological University)
The Oracle engine while creating a procedure performs the following steps
automatically:
Compiles the procedure or function
Stores the procedure or function in the database
The status of a procedure or function is shown by the use of a select statement as follows:
ADVANTAGES OF USING A PROCEDURE OR FUNCTION 1. Security 2. Performance 3. Memory Allocation 4. Productivity 5. Integrity
ONE WORD QUESTION AND ANSWER SR.NO QUESTION ANSWER
1. PROCEDURE AND FUNCTION MEANS
SPECIAL SPACE THAT WORK ON SPECIAL PROGRAM
2 PROCEDURE AND FUNCTION ARE STORE IN_______
SYSTEM TABLE
3 PROCEDURE AND FUCNTION COMPILE AUTOMATICALLY
YES
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.
SELECT ObjectName, ObjectType, Status FROM User_Objects WHERE ObjectType = 'PROCEDURES';
OR
SELECT Object_Name, Object_Type, Status FROM User_Objects WHERE ObjectType = “FUNCTION”;
(Affiliated to Saurashtra University & Gujarat Technological University)
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
subprogram body
Is the definition of function consisting of PL/SQL statements.
EXAMPLE: create or replace function get_deptnm(vempno in
number) return number is mdeptnm varchar2(10);
begin select dept.deptnm into mdeptnm from emp,dept where dept.deptno=emp.deptno and emp_no=vempno; return(mdeptnm);
end;
(Affiliated to Saurashtra University & Gujarat Technological University)
Keywords and Parameters The keywords and the parameters used for creating database procedures are
explained below:
REPLACE Recreates the procedure if it already exists. This option is used to change the definition of an existing procedure without dropping, recreating and re-granting object privileges previously granted on it. If a procedure is redefined the Oracle engine recompiles it.
Procedure Is the name of the procedure to be created?
Argument Is the name of an argument to the procedure? Parentheses can be omitted if no arguments are present.
IN Indicates that the parameter will accept a value from the user.
OUT Indicates that the parameter will return a value to the user.
IN OUT Indicates that the parameter will either accept a value from the user or return a value to the user.
Data type Is the data type of an argument? It supports any data type supported by PL/SQL.
PL/SQL body Is the definition of procedure consisting of PL/SQL statements.
Procedures can be executed with EXECUTE statement.
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;
(Affiliated to Saurashtra University & Gujarat Technological University)
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.
DELETING A STORED PROCEDURE
A procedure can be deleted by using the following syntax
Syntax: Execute procedure name;
create or replace procedure search_employee(vempno in number, vename out varchar2, vjob out varchar2) is begin
select ename,job into vename,vjob from emp where emp_no=vempno; end;
declare mename emp.ename%type; mjob emp.job%type; mempno number := 101;
Checks with the data dictionary to determine whether the procedure and functions used in package are valid or not.
3. Execute: The package subprograms are executed.
ONE WORD QUESTION AND ANSWER SR.NO QUESTION ANSWER
1. PACKAGE MEANS? ORACLE OBJECT
2 CAN PACKAGE HOLD OTHER OBJECT WITH IN IT?
YES
3 HOW MANY TYPES OFPACKAGE
2
WHAT IS TRIGGER? EXPLAIN TYPES OF TRIGGER. DETAILING-
Database triggers are database objects created via the SQL* Plus tool on the client and stored on the Server in the Oracle engine's system table.
These database objects consist of the following distinct sections: A named database event A PL/SQL block that will execute when the event occurs
The Oracle engine allows the procedures that are implicitly executed by the user when an insert, update or delete is issued against a table.
These procedures are called database triggers.
The major issues that make these triggers standalone are that, they are fired implicitly (i.e. internally) by the Oracle engine itself and not explicitly called by the user.
Use of Trigger:
A trigger can permit DML statements against a table only if they are issued, during regular business hours or on predetermined weekdays
A trigger can also be used to keep an audit trail of a table (i.e. to store the modified and deleted records of the table) along with the operation performed and the time on which the operation was performed
It can be used to prevent invalid transactions.
Syntax:
Packagename.subprogram name;
(Affiliated to Saurashtra University & Gujarat Technological University)
For example, if an UPDATE statement updates 5 rows of a table, a row trigger is fired once for each row means it fires 5 times.
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.
Row Trigger and Statement Triggers are further classified into
1. Before Trigger 2. After Trigger.
Before Triggers BEFORE triggers execute the trigger action before the triggering statement. These types of triggers are commonly used in the following situations:
BEFORE triggers are used when the trigger action should determine whether or not the triggering statement should be allowed to complete.
By using a BEFORE trigger, user can eliminate unnecessary processing of the triggering statement.
BEFORE triggers are used to derive specific column values before completing a triggering INSERT or UPDATE statement.
After Triggers AFTER trigger executes the trigger action after the triggering statement is executed. These types of triggers are commonly used in the following situations:
AFTER triggers are used when the triggering statement should complete before executing the trigger action.
If a BEFORE trigger is already present, an AFTER trigger can perform different actions on the same triggering statement
BEFORE statement trigger
(Affiliated to Saurashtra University & Gujarat Technological University)
Before executing the triggering statement, the trigger action is executed.
BEFORE row trigger Before modifying each row affected by the triggering statement and before applying appropriate integrity constraints, the trigger is executed.
AFTER Statement Trigger
After executing the triggering statement and applying any deferred integrity constraints, the trigger action is executed.
AFTER Row Trigger After modifying each row affected by the triggering statement and applying appropriate integrity constraints, the trigger action is executed for the current row. Unlike BEFORE row triggers, AFTER row triggers have rows locked.
ONE WORD QUESTION AND ANSWER SR.NO QUESTION ANSWER
1. WHICH TOOL USE IN CREATE TORGGER
SQL*PLUS
2 HOW MANY TYPES OF TIRGGER
2
3 WHATIS TIRGGER? WE CAN CREATE SEQURITY PURPOSE.
EXPLAIN TRIGGER WITH EXAMPLE. DETAILING:-
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] ]
(Affiliated to Saurashtra University & Gujarat Technological University)
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 change the definition of an existing trigger without requiring the user to drop the trigger first. Trigger Name
Is the name of the trigger to be created? BEFORE
Indicates that the Oracle engine fires the trigger before executing the triggering statement. AFTER
Indicates that the Oracle engine fires the trigger after executing the triggering statement. DELETE
Indicates that the Oracle engine fires the trigger whenever a DELETE statement deletes any row of table.
INSERT
Indicates that the Oracle engine fires the trigger whenever an INSERT statement inserts any row in table. ON
Specifies the name of the table, which the trigger is to be created. A trigger cannot be created on a table in the schema SYS.
FOR EACH ROW
Designates the trigger to be a row trigger. The Oracle engine fires a row trigger once for each row that is affected by the triggering statement and meets the optional trigger constraint defined in the WHEN clause. If this clause is omitted the trigger is a statement trigger.
REFERENCING
Specifies correlation names. Correlation names can be used in the PL/SQL block and WHEN clause of a row triggers to refer specifically to old and new 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 query.
Syntax: DROP TRIGGER <trigger name>;
declare oper varchar2(8);
begin if updating then
oper := 'update'; end if;
(Affiliated to Saurashtra University & Gujarat Technological University)
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.
This insert into first specifies the value of the name column.
Because the name column is not a part of abstract data type.
Selecting data from varray ( )
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.
ONE WORD QUESTION AND ANSWER
Example: Insert into borrower values (‘Neel’,tools_va(‘hammer’,’ax’,’sledge’,null,null));
Example: Declare Cursor bor_cur is Select * from borrower; Begin For bor_rec in bor_cur Loop Dbms_output.put_line(‘Name’ || bor_rec.name); For I in 1..bor_rec.tools.count Loop Dbms_output.put_line(bor_rec.tools(i)); End loop; End loop; End;
(Affiliated to Saurashtra University & Gujarat Technological University)
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>;
(Affiliated to Saurashtra University & Gujarat Technological University)