0% found this document useful (0 votes)
20 views

UNIT-3-Ads

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

UNIT-3-Ads

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT-3

PL/SQL Part – II:


PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs
one or more specific tasks. It is just like procedures in other programming languages.

The procedure contains a header and a body.

o Header: The header contains the name of the procedure and the parameters
or variables passed to the procedure.
o Body: The body contains a declaration section, execution section and exception
section similar to a general PL/SQL block.

How to pass parameters in procedure:


When you want to create a procedure or function, you have to define parameters
.There is three ways to pass parameters in procedure:

1. IN parameters: The IN parameter can be referenced by the procedure or


function. The value of the parameter cannot be overwritten by the procedure
or the function.
2. OUT parameters: The OUT parameter cannot be referenced by the procedure
or function, but the value of the parameter can be overwritten by the procedure
or function.
3. INOUT parameters: The INOUT parameter can be referenced by the procedure
or function and the value of the parameter can be overwritten by the procedure
or function.

NOTE: A procedure may or may not return any


value.
PL/SQL Create Procedure
Syntax for creating procedure:

1. CREATE [OR REPLACE] PROCEDURE procedure_name


2. [ (parameter [,parameter]) ]
3. IS
4. [declaration_section]
5. BEGIN
6. executable_section
7. [EXCEPTION
8. exception_section]
9. END [procedure_name];

Create procedure example


In this example, we are going to insert record in user table. So you need to create user
table first.

Table creation:

1. create table user(id number(10) primary key,name varchar2(100));

Now write the procedure code to insert record in user table.

Procedure Code:

1. create or replace procedure "INSERTUSER"


2. (id IN NUMBER,
3. name IN VARCHAR2)
4. is
5. begin
6. insert into user values(id,name);
7. end;
8. /

Output:

Procedure created.
PL/SQL program to call procedure
Let's see the code to call above created procedure.

1. BEGIN
2. insertuser(101,'Rahul');
3. dbms_output.put_line('record inserted successfully');
4. END;
5. /

Now, see the "USER" table, you will see one record is inserted.

ID Name

101 Rahul

PL/SQL Drop Procedure


Syntax for drop procedure

1. DROP PROCEDURE procedure_name;

Example of drop procedure

1. DROP PROCEDURE pro1;

PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between
procedure and a function is, a function must always return a value, and on the other
hand a procedure may or may not return a value. Except this, all the other things of
PL/SQL procedure are true for PL/SQL function too.

Syntax to create a function:

1. CREATE [OR REPLACE] FUNCTION function_name [parameters]


2. [(parameter_name [IN | OUT | IN OUT] type [, ...])]
3. RETURN return_datatype
4. {IS | AS}
5. BEGIN
6. < function_body >
7. END [function_name];

Here:

o Function_name: specifies the name of the function.


o [OR REPLACE] option allows modifying an existing function.
o The optional parameter list contains name, mode and types of the parameters.
o IN represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.

The function must contain a return statement.


o RETURN clause specifies that data type you are going to return from the function.
o Function_body contains the executable part.
o The AS keyword is used instead of the IS keyword for creating a standalone function.

PL/SQL Function Example


Let's see a simple example to create a function.

1. create or replace function adder(n1 in number, n2 in number)


2. return number
3. is
4. n3 number(8);
5. begin
6. n3 :=n1+n2;
7. return n3;
8. end;
9. /

Now write another program to call the function.

1. DECLARE
2. n3 number(2);
3. BEGIN
4. n3 := adder(11,22);
5. dbms_output.put_line('Addition is: ' || n3);
6. END;
7. /

Output:

Addition is: 33
Statement processed.
0.05 seconds

Another PL/SQL Function Example


Let's take an example to demonstrate Declaring, Defining and Invoking a simple
PL/SQL function which will compute and return the maximum of two values.

1. DECLARE
2. a number;
3. b number;
4. c number;
5. FUNCTION findMax(x IN number, y IN number)
6. RETURN number
7. IS
8. z number;
9. BEGIN
10. IF x > y THEN
11. z:= x;
12. ELSE
13. Z:= y;
14. END IF;
15.
16. RETURN z;
17. END;
18. BEGIN
19. a:= 23;
20. b:= 45;
21.
22. c := findMax(a, b);
23. dbms_output.put_line(' Maximum of (23,45): ' || c);
24. END;
25. /

Output:

Maximum of (23,45): 45
Statement processed.
0.02 seconds

PL/SQL function example PL/SQL function example


using table
Let's take a customer table. This example illustrates creating and calling a standalone
function. This function will return the total number of CUSTOMERS in the customers
table.

Create customers table and have records in it.

Customers

Id Name Department Salary

1 Alex web developer 35000

2 Ricky program developer 45000

3 Mohan web designer 35000

4 Dilshad database manager 44000

Create Function:

1. CREATE OR REPLACE FUNCTION totalCustomers


2. RETURN number IS
3. total number(2) := 0;
4. BEGIN
5. SELECT count(*) into total
6. FROM customers;
7. RETURN total;
8. END;
9. /

After the execution of above code, you will get the following result.

Function created.

Calling PL/SQL Function:

While creating a function, you have to give a definition of what the function has to do.
To use a function, you will have to call that function to perform the defined task. Once
the function is called, the program control is transferred to the called function.

After the successful completion of the defined task, the call function returns program
control back to the main program.

To call a function you have to pass the required parameters along with function name
and if function returns a value then you can store returned value. Following program
calls the function totalCustomers from an anonymous block:

1. DECLARE
2. c number(2);
3. BEGIN
4. c := totalCustomers();
5. dbms_output.put_line('Total no. of Customers: ' || c);
6. END;
7. /

After the execution of above code in SQL prompt, you will get the following result.

Total no. of Customers: 4


PL/SQL procedure successfully completed.

PL/SQL Recursive Function


You already know that a program or a subprogram can call another subprogram. When
a subprogram calls itself, it is called recursive call and the process is known as
recursion.

Example to calculate the factorial of a number


Let's take an example to calculate the factorial of a number. This example calculates
the factorial of a given number by calling itself recursively.

1. DECLARE
2. num number;
3. factorial number;
4.
5. FUNCTION fact(x number)
6. RETURN number
7. IS
8. f number;
9. BEGIN
10. IF x=0 THEN
11. f := 1;
12. ELSE
13. f := x * fact(x-1);
14. END IF;
15. RETURN f;
16. END;
17.
18. BEGIN
19. num:= 6;
20. factorial := fact(num);
21. dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
22. END;
23. /

After the execution of above code at SQL prompt, it produces the following result.

Factorial 6 is 720
PL/SQL procedure successfully completed.

PL/SQL Drop Function


Syntax for removing your created function:
If you want to remove your created function from the database, you should use the
following syntax.

1. DROP FUNCTION function_name;

PL/SQL Packages
PL/SQL Packages is schema object and collection of related data type (variables,
constants), cursors, procedures, functions are defining within a single context.
Package are divide into two part,

1. Package Specification
2. Package Body

Package specification block you can define variables, constants, exceptions and
package body you can create procedure, function, subprogram.

PL/SQL Package Advantages

1. You can create package to store all related functions and procedures are grouped
together into single unit called packages.
2. Package are reliable to granting a privileges.
3. All function and procedure within a package can share variable among them.
4. Package are support overloading to overload functions and procedures.
5. Package are improve the performance to loading the multiple object into
memory at once, therefore, subsequent calls to related program doesn't required
to calling physically I/O.
6. Package are reduce the traffic because all block execute all at once.

Syntax of package specification:


CREATE PACKAGE package_name AS
PROCEDURE procedure_name;
END ;
/
Example:

CREATE or REPLACE PACKAGE pkg1


IS | AS
PROCEDURE pro1
(no in number, name out varchar2);
FUNCTION fun1
(no in number)
RETURN varchar2;
END;
/

Syntax of body or definition:

CREATE OR REPLACE PACKAGE BODY package_name AS


PROCEDURE procedure_name IS
//procedure body
END procedure_name;
END package_name;
/

Example:
CREATE or REPLACE PACKAGE BODY pkg1
IS
PROCEDURE pro1(no in number,info our varchar2)
IS
BEGIN
SELECT * INTO temp FROM emp1 WHERE eno = no;
END;

FUNCTION fun1(no in number) return varchar2


IS
name varchar2(20);
BEGIN
SELECT ename INTO name FROM emp1 WHERE eno = no;
RETURN name;
END;
END;
/

Pl/SQL Program calling Package


Now we have a one package pkg1, to call package defined function, procedures also
pass the parameter and get the return result.
pkg_prg.sql
DECLARE
no number := &no;
name varchar2(20);
BEGIN
pkg1.pro1(no,info);
dbms_output.put_line('Procedure Result');
dbms_output.put_line(info.eno||' '||
info.ename||' '||
info.edept||' '||
info.esalary||' '||);
dbms_output.put_line('Function Result');
name := pkg1.fun1(no);
dbms_output.put_line(name);
END;
/

PL/SQL Package Alter


You can update package code you just recompile the package body,

Syntax
ALTER PACKAGE package_name COMPILE BODY;

Recompile the already created/executed package code,


Example
SQL>ALTER PACKAGE pkg1 COMPILE BODY;

Package body Altered.

PL/SQL Package Drop


You can drop package using package DROP statement,

Syntax
DROP PACKAGE package_name;

Example
SQL>DROP PACKAGE pkg1;

Package dropped.

Trigger in SQL

A Trigger in Structured Query Language is a set of procedural statements which are


executed automatically when there is any response to certain events on the particular
table in the database. Triggers are used to protect the data integrity in the database.

In SQL, this concept is the same as the trigger in real life. For example, when we pull
the gun trigger, the bullet is fired.

To understand the concept of trigger in SQL, let's take the below hypothetical
situation:

Suppose Rishabh is the human resource manager in a multinational company. When


the record of a new employee is entered into the database, he has to send the
'Congrats' message to each new employee. If there are four or five employees, Rishabh
can do it manually, but if the number of new Employees is more than the thousand,
then in such condition, he has to use the trigger in the database.

Thus, now Rishabh has to create the trigger in the table, which will automatically send
a 'Congrats' message to the new employees once their record is inserted into the
database.

The trigger is always executed with the specific table in the database. If we remove the
table, all the triggers associated with that table are also deleted automatically.
In Structured Query Language, triggers are called only either before or after the
below events:

1. INSERT Event: This event is called when the new row is entered in the table.
2. UPDATE Event: This event is called when the existing record is changed or
modified in the table.
3. DELETE Event: This event is called when the existing record is removed from
the table.

Types of Triggers in SQL


Following are the six types of triggers in SQL:

1. AFTER INSERT Trigger


This trigger is invoked after the insertion of data in the table.
2. AFTER UPDATE Trigger
This trigger is invoked in SQL after the modification of the data in the table.
3. AFTER DELETE Trigger
This trigger is invoked after deleting the data from the table.
4. BEFORE INSERT Trigger
This trigger is invoked before the inserting the record in the table.
5. BEFORE UPDATE Trigger
This trigger is invoked before the updating the record in the table.
6. BEFORE DELETE Trigger
This trigger is invoked before deleting the record from the table.

Syntax of Trigger in SQL


1. CREATE TRIGGER Trigger_Name
2. [ BEFORE | AFTER ] [ Insert | Update | Delete]
3. ON [Table_Name]
4. [ FOR EACH ROW | FOR EACH COLUMN ]
5. AS
6. Set of SQL Statement

In the trigger syntax, firstly, we have to define the name of the trigger after the CREATE
TRIGGER keyword. After that, we have to define the BEFORE or AFTER keyword with
anyone event.
Then, we define the name of that table on which trigger is to occur.

After the table name, we have to define the row-level or statement-level trigger.

And, at last, we have to write the SQL statements which perform actions on the
occurring of event.

Example of Trigger in SQL


To understand the concept of trigger in SQL, first, we have to create the table on which
trigger is to be executed.

The following query creates the Student_Trigger table in the SQL database:

1. CREATE TABLE Student_Trigger


2. (
3. Student_RollNo INT NOT NULL PRIMARY KEY,
4. Student_FirstName Varchar (100),
5. Student_EnglishMarks INT,
6. Student_PhysicsMarks INT,
7. Student_ChemistryMarks INT,
8. Student_MathsMarks INT,
9. Student_TotalMarks INT,
10. Student_Percentage );

The following query shows the structure of theStudent_Trigger table:

1. DESC Student_Trigger;

Output:

Field Type NULL Key Default Extra

Student_RollNo INT NO PRI NULL

Student_FirstName Varchar(100) YES NULL

Student_EnglishMarks INT YES NULL

Student_PhysicsMarks INT YES NULL

Student_ChemistryMarks INT YES NULL


Student_MathsMarks INT YES NULL

Student_TotalMarks INT YES NULL

Student_Percentage INT YES NULL

The following query fires a trigger before the insertion of the student record in the
table:

1. CREATE TRIGGER Student_Table_Marks


2. BEFORE INSERT
3. ON
4. Student_Trigger
5. FOR EACH ROW
6. SET new.Student_TotalMarks = new.Student_EnglishMarks + new.Student_Phy
sicsMarks + new.Student_ChemistryMarks + new.Student_MathsMarks,
7. new.Student_Percentage = ( new.Student_TotalMarks / 400) * 100;

The following query inserts the record into Student_Trigger table:

1. INSERT INTO Student_Trigger (Student_RollNo, Student_FirstName, Student_


EnglishMarks, Student_PhysicsMarks, Student_ChemistryMarks, Student_Maths
Marks, Student_TotalMarks, Student_Percentage) VALUES ( 201, Sorya, 88, 75,
69, 92, 0, 0);

To check the output of the above INSERT statement, you have to type the following
SELECT statement:

1. SELECT * FROM Student_Trigger;


Output:

Student_RollNo Student_FirstName Student_EnglishMarks Student_PhysicsMarks Student_ch

201 Sorya 88 75 69

Advantages of Triggers
These are the following advantages of Triggers:

o Trigger generates some derived column values automatically


o Enforces referential integrity
o Event logging and storing information on table access
o Auditing
o Synchronous replication of tables
o Imposing security authorizations
o Preventing invalid transactions

Creating a trigger:
Syntax for creating trigger:

1. CREATE [OR REPLACE ] TRIGGER trigger_name


2. {BEFORE | AFTER | INSTEAD OF }
3. {INSERT [OR] | UPDATE [OR] | DELETE}
4. [OF col_name]
5. ON table_name
6. [REFERENCING OLD AS o NEW AS n]
7. [FOR EACH ROW]
8. WHEN (condition)
9. DECLARE
10. Declaration-statements
11. BEGIN
12. Executable-statements
13. EXCEPTION
14. Exception-handling-statements
15. END;

Here,

o CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existing trigger


with the trigger_name.
o {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed.
The INSTEAD OF clause is used for creating trigger on a view.
o {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
o [OF col_name]: This specifies the column name that would be updated.
o [ON table_name]: This specifies the name of the table associated with the trigger.
o [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for
various DML statements, like INSERT, UPDATE, and DELETE.
o [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed
for each row being affected. Otherwise the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
o WHEN (condition): This provides a condition for rows for which the trigger would fire.
This clause is valid only for row level triggers.

Create trigger:

Let's take a program to create a row level trigger for the CUSTOMERS table that would
fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table.
This trigger will display the salary difference between the old values and new values:

1. CREATE OR REPLACE TRIGGER display_salary_changes


2. BEFORE DELETE OR INSERT OR UPDATE ON customers
3. FOR EACH ROW
4. WHEN (NEW.ID > 0)
5. DECLARE
6. sal_diff number;
7. BEGIN
8. sal_diff := :NEW.salary - :OLD.salary;
9. dbms_output.put_line('Old salary: ' || :OLD.salary);
10. dbms_output.put_line('New salary: ' || :NEW.salary);
11. dbms_output.put_line('Salary difference: ' || sal_diff);
12. END;
13. /
PL/SQL Exception Handling
What is Exception
An error occurs during the program execution is called Exception in PL/SQL.

PL/SQL facilitates programmers to catch such conditions using exception block in the
program and an appropriate action is taken against the error condition.

There are two type of exceptions:

o System-defined Exceptions
o User-defined Exceptions

PL/SQL Exception Handling


Syntax for exception handling:

Following is a general syntax for exception handling:

1. DECLARE
2. <declarations section>
3. BEGIN
4. <executable command(s)>
5. EXCEPTION
6. <exception handling goes here >
7. WHEN exception1 THEN
8. exception1-handling-statements
9. WHEN exception2 THEN
10. exception2-handling-statements
11. WHEN exception3 THEN
12. exception3-handling-statements
13. ........
14. WHEN others THEN
15. exception3-handling-statements
16. END;

Example of exception handling


Let's take a simple example to demonstrate the concept of exception handling. Here
we are using the already created CUSTOMERS table.

SELECT* FROM COUSTOMERS;

ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 20000

2 Suresh 22 Kanpur 22000

3 Mahesh 24 Ghaziabad 24000

4 Chandan 25 Noida 26000

5 Alex 21 Paris 28000

6 Sunita 20 Delhi 30000

1. DECLARE
2. c_id customers.id%type := 8;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. BEGIN
6. SELECT name, address INTO c_name, c_addr
7. FROM customers
8. WHERE id = c_id;
9. DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
10. DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
11. EXCEPTION
12. WHEN no_data_found THEN
13. dbms_output.put_line('No such customer!');
14. WHEN others THEN
15. dbms_output.put_line('Error!');
16. END;
17. /

After the execution of above code at SQL Prompt, it produces the following result:

No such customer!
PL/SQL procedure successfully completed.

The above program should show the name and address of a customer as result whose
ID is given. But there is no customer with ID value 8 in our database, so the program
raises the run-time exception NO_DATA_FOUND, which is captured in EXCEPTION
block.

Note: You get the result "No such customer" because the customer_id used in the
above example is 8 and there is no cutomer having id value 8 in that table.

If you use the id defined in the above table (i.e. 1 to 6), you will get a certain result. For
a demo example: here, we are using the id 5.

1. DECLARE
2. c_id customers.id%type := 5;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. BEGIN
6. SELECT name, address INTO c_name, c_addr
7. FROM customers
8. WHERE id = c_id;
9. DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
10. DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
11. EXCEPTION
12. WHEN no_data_found THEN
13. dbms_output.put_line('No such customer!');
14. WHEN others THEN
15. dbms_output.put_line('Error!');
16. END;
17. /

After the execution of above code at SQL prompt, you will get the following result:

Name: alex
Address: paris
PL/SQL procedure successfully completed.

Raising Exceptions
In the case of any internal database error, exceptions are raised by the database server
automatically. But it can also be raised explicitly by programmer by using command
RAISE.

Syntax for raising an exception:

1. DECLARE
2. exception_name EXCEPTION;
3. BEGIN
4. IF condition THEN
5. RAISE exception_name;
6. END IF;
7. EXCEPTION
8. WHEN exception_name THEN
9. statement;
10. END;

PL/SQL User-defined Exceptions


PL/SQL facilitates their users to define their own exceptions according to the need of
the program. A user-defined exception can be raised explicitly, using either a RAISE
statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.

Syntax for user define exceptions

1. DECLARE
2. my-exception EXCEPTION;

PL/SQL Pre-defined Exceptions


There are many pre-defined exception in PL/SQL which are executed when any
database rule is violated by the programs.

For example: NO_DATA_FOUND is a pre-defined exception which is raised when a


SELECT INTO statement returns no rows.

Following is a list of some important pre-defined exceptions:


Exception Oracle SQL Description
Error Code

ACCESS_INTO_NULL 06530 -6530 It is raised when a NULL object is automatically assigned


a value.

CASE_NOT_FOUND 06592 -6592 It is raised when none of the choices in the "WHEN"
clauses of a CASE statement is selected, and there is no
else clause.

COLLECTION_IS_NULL 06531 -6531 It is raised when a program attempts to apply collection


methods other than exists to an uninitialized nested table
or varray, or the program attempts to assign values to the
elements of an uninitialized nested table or varray.

DUP_VAL_ON_INDEX 00001 -1 It is raised when duplicate values are attempted to be


stored in a column with unique index.

INVALID_CURSOR 01001 -1001 It is raised when attempts are made to make a cursor
operation that is not allowed, such as closing an
unopened cursor.

INVALID_NUMBER 01722 -1722 It is raised when the conversion of a character string into
a number fails because the string does not represent a
valid number.

LOGIN_DENIED 01017 -1017 It is raised when s program attempts to log on to the


database with an invalid username or password.

NO_DATA_FOUND 01403 +100 It is raised when a select into statement returns no rows.

NOT_LOGGED_ON 01012 -1012 It is raised when a database call is issued without being
connected to the database.

PROGRAM_ERROR 06501 -6501 It is raised when PL/SQL has an internal problem.

ROWTYPE_MISMATCH 06504 -6504 It is raised when a cursor fetches value in a variable having
incompatible data type.
SELF_IS_NULL 30625 -30625 It is raised when a member method is invoked, but the
instance of the object type was not initialized.

STORAGE_ERROR 06500 -6500 It is raised when PL/SQL ran out of memory or memory
was corrupted.

TOO_MANY_ROWS 01422 -1422 It is raised when a SELECT INTO statement returns more
than one row.

VALUE_ERROR 06502 -6502 It is raised when an arithmetic, conversion, truncation, or


size-constraint error occurs.

ZERO_DIVIDE 01476 1476 It is raised when an attempt is made to divide a number


by zero.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy