Sub programs in pl/sql
• subprograms are named pl/sql blocks that can take Parameters and be invoked.
• pl/sql has two types of subprograms called procedure and Function
• pl/sql programs can be stored in the database as stored Procedure and can be invoked whenever required.
• like unnamed or anonymous pl/sql block , subprograms Have a declarative part, an executable part, and an optional
Exception handling part.
Procedure
A procedure is a subprogram that perform a specific action
A procedure can be called from any pl/sql program
Procedures can also be invoked from the sql prompt
A procedure has two parts:
1 specification.
2 body.
Procedure specification begins with the key word procedure
Followed by the procedure name and an optional list of arguments,
Enclosed within parenthesis.procedure that take no parameters are
Written without paranthesis
Procedure body begins with the keyword is or as and ends with an
End followed by an optional procedure name.
The procedure body has three parts:
1.declarative part.
2.executable part.
3.exception handling part.
1.declarative part contains local declaration.
2.executable part contains statements, which are placed between
The keyword begin and exception (or end).
3exception handling part contains exception handlers, which are placed between the keyword exception and end. This part is optional.
Syntax
Create [ or replace] procedure
( [mode] ,….)
Is as
[local declaration]
Begin
Pl/sql executable statements
[exception
Exception handlers]
End [procedure_name];
Where mode indicates the type of the argument (such as in,out or In out) and pl/sql executable statements represents the pl/sql Code, enclosed within begin and end.
The or replace option is used in case the user wants to modify
A previously stored procedure or function.
Example: procedure
The employee number and the amount to be incremented is
Passed as parameter
Create or replace procedure incr_proc (pempno number, amt number) is
Vsalary number;
Salary_miss exception;
Begin
Select sal into vsalary from emp where empno= pempno;
If vsalary is null then
Raise salary_miss;
Else
Update emp set sal = sal + amt
Where empno= pempno;
End if;
Exception
When salary_miss then
Dbms_output.put_line (pempno' has salary as null');
When no_data_found then
Dbms_output.put_line(pempno' no such employee number');
End incr_proc;
/
Calling a procedure
A procedure is called as a pl/sql statement. A procedure
Can be called from any pl/sql program by giving their name
Followed by the parameters.
To call the procedure named “incr_proc” from a block , the command is
Incr_proc (v_empno, v_amount);
V_empno : local variable storing the employee number to be incremented.
V_amount : local variable storing the amount to be incremented.
Procedure can also be invoked from the sql prompt using the
Execute command
Sql> execute incr_proc(,);
Functions
A function is a subprogram that returns a value.
A function must have a return clause.
Functions and procedures have a similar structure , except that
The function have a return clause.
Create [ or replace] function
([mode],……..)
Return datatype is
[local declaration]
Begin
Pl/sql executable statements
[exception
Exception handler]
End [funcation_name];
Like a procedure , a function has two parts:
• the specification and the body.
• the function specification begins with the keyword function And ends with the return clause, which specifies the datatype Of the result value.
• the function body is exactly same as procedure body. Return statement.
• return statement immediately returns control to the caller Environment. Execution then resumes with the statement
Following the subprogram call.
• a subprogram can contain several return statements. Executing Any of them terminates the subprogram immediately. The return Statement used in functions must contain an expression, which is Evaluated when the return statement is executed . The resulting Value is assigned to the function identifier. Therefore a function must contain At least one return statement.
• note: return statement can also be used in procedures. But it should not Contain any expression. The statement simply returns control to the caller Before normal end of the procedure is reached.
Example: function
Create or replace function review_func (pempno number)
Return number is
Vincr emp.sal%type;
Vnet emp.sal%type;
Vsal emp.sal%type;
Vcomm emp.comm%type;
Vempno emp.empno%type;
Begin
Select empno,sal ,nvl(comm,0) into vempno,vsal,vcomm from emp
Where empno =pempno;
Vnet:=vsal+vcomm;
If vsal<=3000 then vincr:=0.20* vnet; elsif vsal>3000 and vsal<=6000 then vincr:=0.40* vnet ; end if; return (vincr); end review_func ; / calling of function named “review_func” from a pl/sql block. Declare incr_sal number; begin incr_sal:= review_func(7698); dbms_output.put_line (incr_sal); end; /
Actual versus formal parameters
• the variables or expressions referenced in the parameter list of a Subprogram call are actual parameters.
• the variables declared in a subprogram specification and referenced In the subprogram body are formal parameters
• the following procedure call has two actual parameters pempno and amt. Incr_proc (pempno, amt)
• the following procedure declaration has two formal parameters Named p_empno and amount
Create or replace procedure increment (p_empno number ,amount number) is
----
--
Begin
--
--
End increment;
Argument modes
Argument modes are used to define the behavior of formal parameters There are 3 argument modes to be used with any subprograms
1. In: the in parameter lets the user pass values to the called Subprogram. Inside the subprogram, the in parameter acts Like a constant, therefore, it cannot be modified.
2 out: the out mode parameter lets the user return values to the Calling block. Inside the subprogram, the out parameter acts like An uninitialized variable.
3 in out : the in out parameter lets the user pass initial values To the called subprogram and returns updated value to the Calling block. The three parameters modes in (the
default), out, and in out, can be usedWith any subprograms. A procedure or function can change the value of the Argument, which could be used for further processing.
Stored packages
• a package is a database object that groups logically related Pl/sql objects.
• packages encapsulate related procedures, functions, associated Cursors and variables together as logical unit in the database.
• packages are made of two components: the specifications and The body.
• the specification is the interface to applications and has Declarative statements.
• the body of a package contains different procedures and Functions.
• packages are groups of procedures, functions, variables and Sql statements grouped into a single unit.
• the entire package is loaded into the memory when a procedure, Within the package is called for the first time. This reduces the Unnecessary disk i/o and network traffic.
Packages usually have two parts, a specification and a body.
Package specification
• the specification is the interface to the applications, it declares the Types, variables, constants, exceptions, cursors and subprograms.
• the specification holds public declarations, which are visible to theApplications.
• the scope of these declarations is local to your database schema and Global to the package.so, the declared objects are accessible from Your application and from anywhere in the package.
The package body
• the body fully defines cursors and subprograms, and so implements
• the body holds implementation details and private declarations, which Are hidden from the application.
• the scope of these declarations is local to the package body.
• unlike a package specification, the declarative part of a package body Can contain subprogram bodies.
Main advantages of packages
• better performance
• overloading
A package is created interactively with sql*plus Using the create package and create package body
Commands.
The syntax is:
Package specification syntax
Create[or replace] package as
/*
Declarations of global variables and cursors (if any);
Procedures and functions;
*/
End [];
Package body syntax
Create [or replace] package body as
/*
Private type and object declaration,
Subprogram bodies;
*/
[begin
--action statements;]
End [pkg-name];
Example of package
Create or replace package emp_pack as
Procedure emp_proc (pempno in emp.empno%type);
Function incr_func (peid number, amt number)
Return number;
End emp_pack;
/
Create or replace package body emp_pack
As
Procedure emp_proc (pempno in emp. Empno%type)
Is
Vtempname emp.ename%type;
Vtesal emp.sal%type;
Begin
Select ename,sal into vtempname,vtesal from emp where
Empno=pempno;
Dbms_output.put_line (pempno vtempnamevtesal);
Exception
When no_data_found then
Dbms_output.put_line (pempno 'not found');
End emp_proc;
Function incr_func (peid number, amt number)
Return number is
Vsalary number;
Salary_miss exception;
Vtemp number;
Begin
Select sal into vsalary from emp where empno=peid;
If vsalary is null then
Raise salary_miss;
/*if the vsalary is null an exception salary_miss is raised*/
Else
Update emp set sal = sal+ amt where empno =peid;
Vtemp:=vsalary + amt;
Return (vtemp);
End if;
Exception
When salary_miss then
Dbms_output.put_line (peid ' has salary as null');
/* if the employee number is not found the exception no_data found
Is raised*/
When no_data_found then
Dbms_output.put_line (peid 'no such number');
End incr_func;
End emp_pack;
/
Calling a procedure and function of a package
• calling a procedure of a package
Execute emp_pack.emp_proc(7499);
• calling a function of a package
Declare
Vsalary number;
Begin
Vsalary:=emp_pack.incr_func(7499,100);
Dbms_output.put_line (vsalary);
End;
/
Database triggers
• a database trigger is a stored pl/sql program unit associated with a specific database table
• unlike the stored procedures or functions Which have to be explicitly invoked, these triggers implicitly Gets fired (executed) whenever the table is affected by any Sql operation
Parts of trigger
--trigger event
--trigger constraints (optional)
--trigger action
Trigger events a triggering event or statement is the sql statement that Causes a trigger to be fired. A triggering event can be insert, update or delete Statement for a specific table
Trigger restriction
Trigger restriction specifies a boolean expression that must be true for a trigger
To fire. The trigger action is not executed if the trigger restriction evaluates to
False. A trigger restriction is an option available for trigger that are fired for each
Row. Its function is to conditionally control the execution of the trigger
A trigger restriction is specified using a when clause.
Trigger action
A trigger action is the procedure (pl/sql block) that contain the sql statements
And plsql code to be executed when a triggering statement is issued and the
Trigger restriction evaluates to true
Syntax
Create [or replace] trigger
Before after instead of
Delete [or] insert [or] update [ of [, …]]
On
[referencing [old [as] ] [new [as] ]]
[for each row [ when ]]
Begin
---
/* pl/sql block */
----
End;
Description of syntax of database trigger
Before option
Oracle fires the trigger before modifying each row affected by The triggering statement
After option
Oracle fires the trigger after modifying each row affected By the triggering statement
Instead of option
Oracle fires the trigger for each row , to do something else Instead of performing the action that executed the trigger. When specifies the trigger restriction . This condition has to be satisfied to Fire trigger. The condition can be specified for the row trigger.
Statement level trigger:
Statement level trigger executes once for each transaction. For example if a single transaction inserted 1000 rows into the
Emp table, then a statement level trigger on that table Would only be executed once.
Example:
To create a trigger for the emp table,
Which makes the entry in the ename column in upper case
Create or replace trigger upper_trig1
Before insert or update of ename on emp for each row
Begin
:new.ename:=upper(:new.ename);
End;
/
Raise_application_error
The raise application error is a built in oracle procedure which lets user issue the
User defined error messages
Range varies from (-20000 to -20999)
Create or replace trigger test_trig before insert on emp for each row
Begin
If inserting then
If :new.sal=1500 then
Raise_application_error(-20231,'insertion not allowed');
End if;
End if;
End;
/
Instead of trigger tells oracle what to do instead of performing The action that executed the trigger
• except instead of trigger , all trigger can be used only on tables. Instead of triggers can be used only on view
Example
• view create
Create or replace view v_instead1 as
Select empno,ename,emp.deptno,job,sal,dname,loc from emp,dept
Where emp.deptno= dept.deptno
• trigger create
Create or replace trigger tv_instead1 instead of delete on v_instead1 for each row begin
Delete from emp where deptno=:old.deptno;
Delete from dept where deptno=:old.deptno;
End;
Pl/sql file i/o (input/output)
File i/o is done through the supplied package utl_file.
• the oracle 8i server adds file input/output capabilities to pl/sql.
• this is done through the supplied package utl_file.
• this package has some procedures and functions which add power to Interact with a file.
• the file i/o capabilities are similar to those of the standard operating System stream file i/o (open,get,put,close), similar to the c Programming file functions with some limitations.
• for example, you call the fopen function to return a file handle, Which you then use in subsequent calls to get_line or put to Perform stream i/o to a file.
•after performing i/o on the file fclose can be used to close the file.
Syntax and use of the UTL_FILE package Functions and Procedures:
1. FUNCTION FOPEN
FUNCTION FOPEN (LOCATION, FILENAME, OPEN_MODE)
RETURN UTL_FILE.FILE_TYPE;
LOCATION is the operating system-specific string that specifies the
Directory or area in which to open the file
FILENAME is the name of the file, including extension, without any
Directory information.
OPEN_MODE is a string that specifies how the file is to be opened.
Options allowed are “R” for Read, “W” for Write and “A” for Append.
Function FOPEN returns a file handle that is used in subsequent file
Operations.
Example:
V_FILENAME:=UTL_FILE.FOPEN(P_FILEDIR, P_FILENAME, ‘R’);
2. FUNCTION IS_OPEN
FUNCTION IS_OPEN (FILE)
RETURN BOOLEAN;
Where
FILE is the value returned by FOPEN.
Function IS_OPEN tests a file handle to determine if it identifies an open
File.
Example:
BEGIN
IF UTL_FILE.IS_OPEN (‘P_FILE’) THEN
….
….
END IF;
END;
3. PROCEDURE FCLOSE
PROCEDURE FCLOSE (FILE)
Where
FILE is the value returned by an FOPEN operation.
PROCEDURE FCLOSE closes the open file identified by FILE.
Example:
UTL_FILE.FCLOSE(V_FILEHANDLE);
4. PROCEDURE GET_LINE
PROCEDURE GET_LINE (FILE, BUFFER);
Where
FILE is the value returned by an FOPEN operation.
BUFFER holds the read text.
5. PROCEDURE GET_LINE reads a line of text from the open file
Identified by FILE and places the text in the output BUFFER.
Example:
UTL_FILE.GET_LINE (V_FILEHANDLE, V_NEWLINE);
6. PROCEDURE PUT_LINE
PROCEDURE PUT_LINE (FILE, BUFFER);
Where
FILE is the value returned by an FOPEN operation.
BUFFER is the text to write.
PROCEDURE PUT_LINE writes text string BUFFER to the file
Identified by FILE, then writes a line terminator
Example:
UTL_FILE.PUT_LINE (V_FILEHANDLE, ‘ROLLNO NAME SUBJECT ’);
UTL_FILE.PUT_LINE (V_FILEHANDLE, ‘--------- ----- ------ ’);
The file will be written with the following format:
ROLLNO NAME SUBJECT
--------- ---- ------
Collections
• Nested Tables
• VARYING Arrays (VARRAY)
Nested Tables
A nested tables is useful for data models requiring referential integrity
And is suitable for master-detail and one to many relationships.
A nested table is a database table which stores data in it, that cannot be
A Nested Table can be included in a table definition as one of the
Columns. That is why, they are known as Nested Tables.
Nested Tables can be manipulated directly using SQL.
To create a nested table the syntax is as follows:
CREATE TYPE TABLE_NAME IS TABLE OF TABLE_TYPE [NOT NULL];
Where:
TABLE_NAME The name of new type
TABLE_TYPE The type of each element in a nested table. It can be
Built-in type, a user defined type or a reference to
Object type.
Example:
CREATE TYPE BOOKS_TYPE AS OBJECT
(BOOK_NO NUMBER (4),
BOOK_TITLE VARCHAR (20),
AUTHOR VARCHAR2(20));
/
Type created.
CREATE TYPE BOOKS AS TABLE OF BOOKS_TYPE;
/
Type created.
Example:
CREATE TABLE STUDENT (
STUDENT_NO NUMBER(4) NOT NULL,
STUDENT_NAME VARCHAR2(25),
BOOKS_ISSUED BOOKS )
NESTED TABLE BOOKS_ISSUED STORE AS BOOK_TABLE;
Table created.
Inserting Records
INSERT INTO STUDENT VALUES
(1001, 'AMIT KUMAR',
BOOKS (BOOKS_TYPE(3211, 'ORACLE 8 UNLEASHED', 'KAIT'),
BOOKS_TYPE(3922, 'PL/SQL PROG','J J')));
Accessed directly.
Update is used to modify the store table
• The Operator allows nested tables to be manipulated using DML when it is stored in a table
• The table takes the sub query as argument and returns the Nested table to be used in DML.
• The Sub Query must return single nested columns
Example:
UPDATE THE (SELECT BOOKS_ISSUED FROM STUDENT WHERE
STUDENT_NO=1001)
SET BOOK_TITLE = 'ORACLE UNLEASHED'
WHERE BOOK_NO=3211;
Inserting records in nested Table
Example:
Insert into the (select books_issued from student where student_no=1001)
Values (books_type(5111, 'Visual Basic', 'Ken'));
Selecting a records from the Nested Table
Example:
Select * FROM THE (SELECT BOOKS_ISSUED FROM STUDENT WHERE
STUDENT_NO=1001) WHERE BOOK_NO=3211
/
Deleting a records from the Nested Table
For deleting a row from the nested table using the condition from the
Nested table
DELETE FROM THE (SELECT BOOKS_ISSUED FROM STUDENT WHERE
STUDENT_NO=1001) WHERE BOOK_NO=3211;
VARRAYS
Varray is a datatype similar to an array in C or PASCAL. Elements are
Inserted into a VARRAY, starting at index 1 up to the maximum length
Declared in the VARRAY type.
A VARRAY has the following:
• COUNT Current Number of elements
• LIMIT Maximum number of elements the VARRAY can Contain. The LIMIT is user defined. Each element of the array has the position indicated by an index which Can range from one to the COUNT value. A VARRAY can be stored in a database column. A VARRAY can only Be manipulated as a whole. Individual elements of stored VARRAYS Cannot be modified.
Creating varrays
Example:
CREATE TYPE BOOKS_TYPE1 AS OBJECT
(BOOK_NO NUMBER (4),
BOOK_TITLE VARCHAR (20),
AUTHOR VARCHAR2(20));
/
Type created.
CREATE OR REPLACE TYPE BOOKS_ARRAY AS VARRAY(10)
OF BOOKS_TYPE1;
/
Type created.
CREATE TABLE STUDENTS1(
STUDENT_NO NUMBER(4),
BOOKS_ISSUED BOOKS_ARRAY);
Table created.
Inserting Rows
The values can be inserted in a VARRAY as a whole, we can insert rows Into the table using
The constructor as follows:
INSERT INTO STUDENTS1
VALUES
(2355, BOOKS_ARRAY(
BOOKS_TYPE1(1020,'ORACLE BEGINNERS', 'ORACLE PRESS'),
BOOKS_TYPE1(1111,'TUNING ORACLE','CONEY')));
This row contains a VARRAY BOOKS_ARRAY having two elements
Updating Rows
The varrays can be updated as a whole. Individual elements cannot
Be accessed.
UPDATE STUDENTS1
SET BOOKS_ISSUED=BOOKS_ARRAY(
BOOKS_TYPE1(1020,'ORACLE BEGINNERS','ORACLE PRESS'))
WHERE STUDENT_NO=2355;
The row for STUDENT_NO 2355, will have only one element in the
VARRAY column.
To modify a stored VARRY, it has to be selected into a PLSQL variable and then inserted back into the table .
The Technique is as below:
Note:
LIST_OF_BOOKS.COUNT gives the number of elements in the VARRAY
LIST_OF_BOOK.EXTEND appends one element ot the array i.e increase the array limit by 1
Example
DECLARE
LIST_OF_BOOKS BOOKS_ARRAY;
BEGIN
SELECT BOOKS_ISSUED INTO LIST_OF_BOOKS
FROM STUDENTS1 WHERE STUDENT_NO=2355;
DBMS_OUTPUT.PUT_LINE('NO OF BOOKS ISSUED' TO_CHAR(LIST_OF_BOOKS.COUNT));
DBMS_OUTPUT.PUT_LINE('ARRAY LIMIT' LIST_OF_BOOKS.LIMIT);
LIST_OF_BOOKS.EXTEND;
LIST_OF_BOOKS(LIST_OF_BOOKS.COUNT):=BOOKS_TYPE(2334,'DBA HANDBOOK','KEVIN');
UPDATE STUDENTS1 SET BOOKS_ISSUED=LIST_OF_BOOKS WHERE STUDENT_NO=2355;
COMMIT;
END;
/
Autonomous Transactions
An Autonomous Transaction (AT) is an independent transaction started by another
Transaction, The main transaction (MT). At the time of execution it lets you
Suspend the main transaction, do SQL Operation, Commit, or
Rollback those operation , then resume the main transaction. It always
Executes with in an autonomous scope.
An autonomous Block is a routine marked with the
PRAGMA AUTONOMOUS_TRANSACTION
Example of Autonomous Transaction
Main Transaction
CREATE OR REPLACE Procedure PROC1_TRAN is
EMP_ID NUMBER:=7499;
BEGIN
UPDATE EMP SET SAL =SAL+100
WHERE EMPNO=EMP_ID;
PROC2_TRAN(EMP_ID);
DELETE FROM EMP
WHERE EMPNO=EMP_ID;
ROLLBACK;
END;
/
Autonomous Transaction
CREATE OR REPLACE Procedure PROC2_TRAN(P_EMP_ID NUMBER) is
PRAGMA AUTONOMOUS_TRANSACTION;
DEPT_ID NUMBER;
BEGIN
SELECT DEPTNO INTO DEPT_ID FROM EMP WHERE EMPNO=P_EMP_ID;
UPDATE DEPT SET DNAME='ACCOUNTING1'
WHERE DEPTNO=30;
COMMIT;
END;
/
SQL loader
This tool is used to move the data from Non –oracle standard source into the oracle
Database Using sql loader a user can
Load data from multiple data files
Two types on input have to be provided to SQL*Loader.
The data file containing the actual data
The control file containing the specification which drive the sql*loader session
SQL Loader generates three files
The log file (Summary of the execution of the Load)
The bad File (Rejected by Oracle)
The discard File (Doesn't meet the condition)
Create a Data File EMPLOYEE.TXT with following contents :
3000,HARPREET,ENGG,10000
3001,PREET1, ,20000
Create a Control File TEST.CTL with following contents :
LOAD DATA
INFILE 'EMPLOYEE.TXT'
APPEND
INTO TABLE EMP
WHEN JOB != ' '
Fields Terminated By ","
(
EMPNO
,ENAME
,JOB
,SAL
)
Calling a Control File TEST.CTL which in turn refers to EMPLOYEE.TXT file for Data are:
SQLLDR CONTROL=TEST.CTLSub programs in pl/sql
• subprograms are named pl/sql blocks that can take Parameters and be invoked.
• pl/sql has two types of subprograms called procedure and Function
• pl/sql programs can be stored in the database as stored Procedure and can be invoked whenever required.
• like unnamed or anonymous pl/sql block , subprograms Have a declarative part, an executable part, and an optional
Exception handling part.
Procedure
A procedure is a subprogram that perform a specific action
A procedure can be called from any pl/sql program
Procedures can also be invoked from the sql prompt
A procedure has two parts:
1 specification.
2 body.
Procedure specification begins with the key word procedure
Followed by the procedure name and an optional list of arguments,
Enclosed within parenthesis.procedure that take no parameters are
Written without paranthesis
Procedure body begins with the keyword is or as and ends with an
End followed by an optional procedure name.
The procedure body has three parts:
1.declarative part.
2.executable part.
3.exception handling part.
1.declarative part contains local declaration.
2.executable part contains statements, which are placed between
The keyword begin and exception (or end).
3exception handling part contains exception handlers, which are placed between the keyword exception and end. This part is optional.
Syntax
Create [ or replace] procedure
( [mode] ,….)
Is as
[local declaration]
Begin
Pl/sql executable statements
[exception
Exception handlers]
End [procedure_name];
Where mode indicates the type of the argument (such as in,out or In out) and pl/sql executable statements represents the pl/sql Code, enclosed within begin and end.
The or replace option is used in case the user wants to modify
A previously stored procedure or function.
Example: procedure
The employee number and the amount to be incremented is
Passed as parameter
Create or replace procedure incr_proc (pempno number, amt number) is
Vsalary number;
Salary_miss exception;
Begin
Select sal into vsalary from emp where empno= pempno;
If vsalary is null then
Raise salary_miss;
Else
Update emp set sal = sal + amt
Where empno= pempno;
End if;
Exception
When salary_miss then
Dbms_output.put_line (pempno' has salary as null');
When no_data_found then
Dbms_output.put_line(pempno' no such employee number');
End incr_proc;
/
Calling a procedure
A procedure is called as a pl/sql statement. A procedure
Can be called from any pl/sql program by giving their name
Followed by the parameters.
To call the procedure named “incr_proc” from a block , the command is
Incr_proc (v_empno, v_amount);
V_empno : local variable storing the employee number to be incremented.
V_amount : local variable storing the amount to be incremented.
Procedure can also be invoked from the sql prompt using the
Execute command
Sql> execute incr_proc(,);
Functions
A function is a subprogram that returns a value.
A function must have a return clause.
Functions and procedures have a similar structure , except that
The function have a return clause.
Create [ or replace] function
([mode],……..)
Return datatype is
[local declaration]
Begin
Pl/sql executable statements
[exception
Exception handler]
End [funcation_name];
Like a procedure , a function has two parts:
• the specification and the body.
• the function specification begins with the keyword function And ends with the return clause, which specifies the datatype Of the result value.
• the function body is exactly same as procedure body. Return statement.
• return statement immediately returns control to the caller Environment. Execution then resumes with the statement
Following the subprogram call.
• a subprogram can contain several return statements. Executing Any of them terminates the subprogram immediately. The return Statement used in functions must contain an expression, which is Evaluated when the return statement is executed . The resulting Value is assigned to the function identifier. Therefore a function must contain At least one return statement.
• note: return statement can also be used in procedures. But it should not Contain any expression. The statement simply returns control to the caller Before normal end of the procedure is reached.
Example: function
Create or replace function review_func (pempno number)
Return number is
Vincr emp.sal%type;
Vnet emp.sal%type;
Vsal emp.sal%type;
Vcomm emp.comm%type;
Vempno emp.empno%type;
Begin
Select empno,sal ,nvl(comm,0) into vempno,vsal,vcomm from emp
Where empno =pempno;
Vnet:=vsal+vcomm;
If vsal<=3000 then vincr:=0.20* vnet; elsif vsal>3000 and vsal<=6000 then vincr:=0.40* vnet ; end if; return (vincr); end review_func ; / calling of function named “review_func” from a pl/sql block. Declare incr_sal number; begin incr_sal:= review_func(7698); dbms_output.put_line (incr_sal); end; /
Actual versus formal parameters
• the variables or expressions referenced in the parameter list of a Subprogram call are actual parameters.
• the variables declared in a subprogram specification and referenced In the subprogram body are formal parameters
• the following procedure call has two actual parameters pempno and amt. Incr_proc (pempno, amt)
• the following procedure declaration has two formal parameters Named p_empno and amount
Create or replace procedure increment (p_empno number ,amount number) is
----
--
Begin
--
--
End increment;
Argument modes
Argument modes are used to define the behavior of formal parameters There are 3 argument modes to be used with any subprograms
1. In: the in parameter lets the user pass values to the called Subprogram. Inside the subprogram, the in parameter acts Like a constant, therefore, it cannot be modified.
2 out: the out mode parameter lets the user return values to the Calling block. Inside the subprogram, the out parameter acts like An uninitialized variable.
3 in out : the in out parameter lets the user pass initial values To the called subprogram and returns updated value to the Calling block. The three parameters modes in (the
default), out, and in out, can be usedWith any subprograms. A procedure or function can change the value of the Argument, which could be used for further processing.
Stored packages
• a package is a database object that groups logically related Pl/sql objects.
• packages encapsulate related procedures, functions, associated Cursors and variables together as logical unit in the database.
• packages are made of two components: the specifications and The body.
• the specification is the interface to applications and has Declarative statements.
• the body of a package contains different procedures and Functions.
• packages are groups of procedures, functions, variables and Sql statements grouped into a single unit.
• the entire package is loaded into the memory when a procedure, Within the package is called for the first time. This reduces the Unnecessary disk i/o and network traffic.
Packages usually have two parts, a specification and a body.
Package specification
• the specification is the interface to the applications, it declares the Types, variables, constants, exceptions, cursors and subprograms.
• the specification holds public declarations, which are visible to theApplications.
• the scope of these declarations is local to your database schema and Global to the package.so, the declared objects are accessible from Your application and from anywhere in the package.
The package body
• the body fully defines cursors and subprograms, and so implements
• the body holds implementation details and private declarations, which Are hidden from the application.
• the scope of these declarations is local to the package body.
• unlike a package specification, the declarative part of a package body Can contain subprogram bodies.
Main advantages of packages
• better performance
• overloading
A package is created interactively with sql*plus Using the create package and create package body
Commands.
The syntax is:
Package specification syntax
Create[or replace] package as
/*
Declarations of global variables and cursors (if any);
Procedures and functions;
*/
End [];
Package body syntax
Create [or replace] package body as
/*
Private type and object declaration,
Subprogram bodies;
*/
[begin
--action statements;]
End [pkg-name];
Example of package
Create or replace package emp_pack as
Procedure emp_proc (pempno in emp.empno%type);
Function incr_func (peid number, amt number)
Return number;
End emp_pack;
/
Create or replace package body emp_pack
As
Procedure emp_proc (pempno in emp. Empno%type)
Is
Vtempname emp.ename%type;
Vtesal emp.sal%type;
Begin
Select ename,sal into vtempname,vtesal from emp where
Empno=pempno;
Dbms_output.put_line (pempno vtempnamevtesal);
Exception
When no_data_found then
Dbms_output.put_line (pempno 'not found');
End emp_proc;
Function incr_func (peid number, amt number)
Return number is
Vsalary number;
Salary_miss exception;
Vtemp number;
Begin
Select sal into vsalary from emp where empno=peid;
If vsalary is null then
Raise salary_miss;
/*if the vsalary is null an exception salary_miss is raised*/
Else
Update emp set sal = sal+ amt where empno =peid;
Vtemp:=vsalary + amt;
Return (vtemp);
End if;
Exception
When salary_miss then
Dbms_output.put_line (peid ' has salary as null');
/* if the employee number is not found the exception no_data found
Is raised*/
When no_data_found then
Dbms_output.put_line (peid 'no such number');
End incr_func;
End emp_pack;
/
Calling a procedure and function of a package
• calling a procedure of a package
Execute emp_pack.emp_proc(7499);
• calling a function of a package
Declare
Vsalary number;
Begin
Vsalary:=emp_pack.incr_func(7499,100);
Dbms_output.put_line (vsalary);
End;
/
Database triggers
• a database trigger is a stored pl/sql program unit associated with a specific database table
• unlike the stored procedures or functions Which have to be explicitly invoked, these triggers implicitly Gets fired (executed) whenever the table is affected by any Sql operation
Parts of trigger
--trigger event
--trigger constraints (optional)
--trigger action
Trigger events a triggering event or statement is the sql statement that Causes a trigger to be fired. A triggering event can be insert, update or delete Statement for a specific table
Trigger restriction
Trigger restriction specifies a boolean expression that must be true for a trigger
To fire. The trigger action is not executed if the trigger restriction evaluates to
False. A trigger restriction is an option available for trigger that are fired for each
Row. Its function is to conditionally control the execution of the trigger
A trigger restriction is specified using a when clause.
Trigger action
A trigger action is the procedure (pl/sql block) that contain the sql statements
And plsql code to be executed when a triggering statement is issued and the
Trigger restriction evaluates to true
Syntax
Create [or replace] trigger
Before after instead of
Delete [or] insert [or] update [ of [, …]]
On
[referencing [old [as] ] [new [as] ]]
[for each row [ when ]]
Begin
---
/* pl/sql block */
----
End;
Description of syntax of database trigger
Before option
Oracle fires the trigger before modifying each row affected by The triggering statement
After option
Oracle fires the trigger after modifying each row affected By the triggering statement
Instead of option
Oracle fires the trigger for each row , to do something else Instead of performing the action that executed the trigger. When specifies the trigger restriction . This condition has to be satisfied to Fire trigger. The condition can be specified for the row trigger.
Statement level trigger:
Statement level trigger executes once for each transaction. For example if a single transaction inserted 1000 rows into the
Emp table, then a statement level trigger on that table Would only be executed once.
Example:
To create a trigger for the emp table,
Which makes the entry in the ename column in upper case
Create or replace trigger upper_trig1
Before insert or update of ename on emp for each row
Begin
:new.ename:=upper(:new.ename);
End;
/
Raise_application_error
The raise application error is a built in oracle procedure which lets user issue the
User defined error messages
Range varies from (-20000 to -20999)
Create or replace trigger test_trig before insert on emp for each row
Begin
If inserting then
If :new.sal=1500 then
Raise_application_error(-20231,'insertion not allowed');
End if;
End if;
End;
/
Instead of trigger tells oracle what to do instead of performing The action that executed the trigger
• except instead of trigger , all trigger can be used only on tables. Instead of triggers can be used only on view
Example
• view create
Create or replace view v_instead1 as
Select empno,ename,emp.deptno,job,sal,dname,loc from emp,dept
Where emp.deptno= dept.deptno
• trigger create
Create or replace trigger tv_instead1 instead of delete on v_instead1 for each row begin
Delete from emp where deptno=:old.deptno;
Delete from dept where deptno=:old.deptno;
End;
Pl/sql file i/o (input/output)
File i/o is done through the supplied package utl_file.
• the oracle 8i server adds file input/output capabilities to pl/sql.
• this is done through the supplied package utl_file.
• this package has some procedures and functions which add power to Interact with a file.
• the file i/o capabilities are similar to those of the standard operating System stream file i/o (open,get,put,close), similar to the c Programming file functions with some limitations.
• for example, you call the fopen function to return a file handle, Which you then use in subsequent calls to get_line or put to Perform stream i/o to a file.
•after performing i/o on the file fclose can be used to close the file.
Syntax and use of the UTL_FILE package Functions and Procedures:
1. FUNCTION FOPEN
FUNCTION FOPEN (LOCATION, FILENAME, OPEN_MODE)
RETURN UTL_FILE.FILE_TYPE;
LOCATION is the operating system-specific string that specifies the
Directory or area in which to open the file
FILENAME is the name of the file, including extension, without any
Directory information.
OPEN_MODE is a string that specifies how the file is to be opened.
Options allowed are “R” for Read, “W” for Write and “A” for Append.
Function FOPEN returns a file handle that is used in subsequent file
Operations.
Example:
V_FILENAME:=UTL_FILE.FOPEN(P_FILEDIR, P_FILENAME, ‘R’);
2. FUNCTION IS_OPEN
FUNCTION IS_OPEN (FILE)
RETURN BOOLEAN;
Where
FILE is the value returned by FOPEN.
Function IS_OPEN tests a file handle to determine if it identifies an open
File.
Example:
BEGIN
IF UTL_FILE.IS_OPEN (‘P_FILE’) THEN
….
….
END IF;
END;
3. PROCEDURE FCLOSE
PROCEDURE FCLOSE (FILE)
Where
FILE is the value returned by an FOPEN operation.
PROCEDURE FCLOSE closes the open file identified by FILE.
Example:
UTL_FILE.FCLOSE(V_FILEHANDLE);
4. PROCEDURE GET_LINE
PROCEDURE GET_LINE (FILE, BUFFER);
Where
FILE is the value returned by an FOPEN operation.
BUFFER holds the read text.
5. PROCEDURE GET_LINE reads a line of text from the open file
Identified by FILE and places the text in the output BUFFER.
Example:
UTL_FILE.GET_LINE (V_FILEHANDLE, V_NEWLINE);
6. PROCEDURE PUT_LINE
PROCEDURE PUT_LINE (FILE, BUFFER);
Where
FILE is the value returned by an FOPEN operation.
BUFFER is the text to write.
PROCEDURE PUT_LINE writes text string BUFFER to the file
Identified by FILE, then writes a line terminator
Example:
UTL_FILE.PUT_LINE (V_FILEHANDLE, ‘ROLLNO NAME SUBJECT ’);
UTL_FILE.PUT_LINE (V_FILEHANDLE, ‘--------- ----- ------ ’);
The file will be written with the following format:
ROLLNO NAME SUBJECT
--------- ---- ------
Collections
• Nested Tables
• VARYING Arrays (VARRAY)
Nested Tables
A nested tables is useful for data models requiring referential integrity
And is suitable for master-detail and one to many relationships.
A nested table is a database table which stores data in it, that cannot be
A Nested Table can be included in a table definition as one of the
Columns. That is why, they are known as Nested Tables.
Nested Tables can be manipulated directly using SQL.
To create a nested table the syntax is as follows:
CREATE TYPE TABLE_NAME IS TABLE OF TABLE_TYPE [NOT NULL];
Where:
TABLE_NAME The name of new type
TABLE_TYPE The type of each element in a nested table. It can be
Built-in type, a user defined type or a reference to
Object type.
Example:
CREATE TYPE BOOKS_TYPE AS OBJECT
(BOOK_NO NUMBER (4),
BOOK_TITLE VARCHAR (20),
AUTHOR VARCHAR2(20));
/
Type created.
CREATE TYPE BOOKS AS TABLE OF BOOKS_TYPE;
/
Type created.
Example:
CREATE TABLE STUDENT (
STUDENT_NO NUMBER(4) NOT NULL,
STUDENT_NAME VARCHAR2(25),
BOOKS_ISSUED BOOKS )
NESTED TABLE BOOKS_ISSUED STORE AS BOOK_TABLE;
Table created.
Inserting Records
INSERT INTO STUDENT VALUES
(1001, 'AMIT KUMAR',
BOOKS (BOOKS_TYPE(3211, 'ORACLE 8 UNLEASHED', 'KAIT'),
BOOKS_TYPE(3922, 'PL/SQL PROG','J J')));
Accessed directly.
Update is used to modify the store table
• The Operator allows nested tables to be manipulated using DML when it is stored in a table
• The table takes the sub query as argument and returns the Nested table to be used in DML.
• The Sub Query must return single nested columns
Example:
UPDATE THE (SELECT BOOKS_ISSUED FROM STUDENT WHERE
STUDENT_NO=1001)
SET BOOK_TITLE = 'ORACLE UNLEASHED'
WHERE BOOK_NO=3211;
Inserting records in nested Table
Example:
Insert into the (select books_issued from student where student_no=1001)
Values (books_type(5111, 'Visual Basic', 'Ken'));
Selecting a records from the Nested Table
Example:
Select * FROM THE (SELECT BOOKS_ISSUED FROM STUDENT WHERE
STUDENT_NO=1001) WHERE BOOK_NO=3211
/
Deleting a records from the Nested Table
For deleting a row from the nested table using the condition from the
Nested table
DELETE FROM THE (SELECT BOOKS_ISSUED FROM STUDENT WHERE
STUDENT_NO=1001) WHERE BOOK_NO=3211;
VARRAYS
Varray is a datatype similar to an array in C or PASCAL. Elements are
Inserted into a VARRAY, starting at index 1 up to the maximum length
Declared in the VARRAY type.
A VARRAY has the following:
• COUNT Current Number of elements
• LIMIT Maximum number of elements the VARRAY can Contain. The LIMIT is user defined. Each element of the array has the position indicated by an index which Can range from one to the COUNT value. A VARRAY can be stored in a database column. A VARRAY can only Be manipulated as a whole. Individual elements of stored VARRAYS Cannot be modified.
Creating varrays
Example:
CREATE TYPE BOOKS_TYPE1 AS OBJECT
(BOOK_NO NUMBER (4),
BOOK_TITLE VARCHAR (20),
AUTHOR VARCHAR2(20));
/
Type created.
CREATE OR REPLACE TYPE BOOKS_ARRAY AS VARRAY(10)
OF BOOKS_TYPE1;
/
Type created.
CREATE TABLE STUDENTS1(
STUDENT_NO NUMBER(4),
BOOKS_ISSUED BOOKS_ARRAY);
Table created.
Inserting Rows
The values can be inserted in a VARRAY as a whole, we can insert rows Into the table using
The constructor as follows:
INSERT INTO STUDENTS1
VALUES
(2355, BOOKS_ARRAY(
BOOKS_TYPE1(1020,'ORACLE BEGINNERS', 'ORACLE PRESS'),
BOOKS_TYPE1(1111,'TUNING ORACLE','CONEY')));
This row contains a VARRAY BOOKS_ARRAY having two elements
Updating Rows
The varrays can be updated as a whole. Individual elements cannot
Be accessed.
UPDATE STUDENTS1
SET BOOKS_ISSUED=BOOKS_ARRAY(
BOOKS_TYPE1(1020,'ORACLE BEGINNERS','ORACLE PRESS'))
WHERE STUDENT_NO=2355;
The row for STUDENT_NO 2355, will have only one element in the
VARRAY column.
To modify a stored VARRY, it has to be selected into a PLSQL variable and then inserted back into the table .
The Technique is as below:
Note:
LIST_OF_BOOKS.COUNT gives the number of elements in the VARRAY
LIST_OF_BOOK.EXTEND appends one element ot the array i.e increase the array limit by 1
Example
DECLARE
LIST_OF_BOOKS BOOKS_ARRAY;
BEGIN
SELECT BOOKS_ISSUED INTO LIST_OF_BOOKS
FROM STUDENTS1 WHERE STUDENT_NO=2355;
DBMS_OUTPUT.PUT_LINE('NO OF BOOKS ISSUED' TO_CHAR(LIST_OF_BOOKS.COUNT));
DBMS_OUTPUT.PUT_LINE('ARRAY LIMIT' LIST_OF_BOOKS.LIMIT);
LIST_OF_BOOKS.EXTEND;
LIST_OF_BOOKS(LIST_OF_BOOKS.COUNT):=BOOKS_TYPE(2334,'DBA HANDBOOK','KEVIN');
UPDATE STUDENTS1 SET BOOKS_ISSUED=LIST_OF_BOOKS WHERE STUDENT_NO=2355;
COMMIT;
END;
/
Autonomous Transactions
An Autonomous Transaction (AT) is an independent transaction started by another
Transaction, The main transaction (MT). At the time of execution it lets you
Suspend the main transaction, do SQL Operation, Commit, or
Rollback those operation , then resume the main transaction. It always
Executes with in an autonomous scope.
An autonomous Block is a routine marked with the
PRAGMA AUTONOMOUS_TRANSACTION
Example of Autonomous Transaction
Main Transaction
CREATE OR REPLACE Procedure PROC1_TRAN is
EMP_ID NUMBER:=7499;
BEGIN
UPDATE EMP SET SAL =SAL+100
WHERE EMPNO=EMP_ID;
PROC2_TRAN(EMP_ID);
DELETE FROM EMP
WHERE EMPNO=EMP_ID;
ROLLBACK;
END;
/
Autonomous Transaction
CREATE OR REPLACE Procedure PROC2_TRAN(P_EMP_ID NUMBER) is
PRAGMA AUTONOMOUS_TRANSACTION;
DEPT_ID NUMBER;
BEGIN
SELECT DEPTNO INTO DEPT_ID FROM EMP WHERE EMPNO=P_EMP_ID;
UPDATE DEPT SET DNAME='ACCOUNTING1'
WHERE DEPTNO=30;
COMMIT;
END;
/
SQL loader
This tool is used to move the data from Non –oracle standard source into the oracle
Database Using sql loader a user can
Load data from multiple data files
Two types on input have to be provided to SQL*Loader.
The data file containing the actual data
The control file containing the specification which drive the sql*loader session
SQL Loader generates three files
The log file (Summary of the execution of the Load)
The bad File (Rejected by Oracle)
The discard File (Doesn't meet the condition)
Create a Data File EMPLOYEE.TXT with following contents :
3000,HARPREET,ENGG,10000
3001,PREET1, ,20000
Create a Control File TEST.CTL with following contents :
LOAD DATA
INFILE 'EMPLOYEE.TXT'
APPEND
INTO TABLE EMP
WHEN JOB != ' '
Fields Terminated By ","
(
EMPNO
,ENAME
,JOB
,SAL
)
Calling a Control File TEST.CTL which in turn refers to EMPLOYEE.TXT file for Data are:
SQLLDR CONTROL=TEST.CTL
No comments:
Post a Comment