0% found this document useful (0 votes)
5 views11 pages

Unit 3 SQL

The document explains PL/SQL exception handling, detailing what exceptions are, their types (system-defined and user-defined), and how to handle them using specific syntax. It provides examples of exception handling, including raising exceptions and using implicit and explicit cursors. Additionally, it covers predefined exceptions and the structure of PL/SQL procedures.

Uploaded by

vavemos441
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)
5 views11 pages

Unit 3 SQL

The document explains PL/SQL exception handling, detailing what exceptions are, their types (system-defined and user-defined), and how to handle them using specific syntax. It provides examples of exception handling, including raising exceptions and using implicit and explicit cursors. Additionally, it covers predefined exceptions and the structure of PL/SQL procedures.

Uploaded by

vavemos441
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/ 11

PL/SQL Exception Handling

What is Exception

An exception is a PL/SQL error that is raised during program execution, either implicitly by Times or
explicitly by your program. Handle an exception by trapping it with a handler or propagating it to the calling
environment.

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

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;

17. /

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

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;

1. DECLARE
2. c_id ID%type := 8;
3. c_name NAME%type;
4. c_addr 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;

3.

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.

PL/SQL Cursor

When an SQL statement is processed, Oracle creates a memory area known as context area. A cursor is a
pointer to this context area. It contains all information needed for processing the statement. In PL/SQL, the
context area is controlled by Cursor. A cursor contains information on a select statement and the rows of
data accessed by it.

A cursor is used to referred to a program to fetch and process the rows returned by the SQL statement, one at
a time. There are two types of cursors:

o Implicit Cursors
o Explicit Cursors

1) PL/SQL Implicit Cursors

The implicit cursors are automatically generated by Oracle while an SQL statement is executed, if you don't
use an explicit cursor for the statement.

These are created by default to process the statements when DML statements like INSERT, UPDATE,
DELETE etc. are executed.

Orcale provides some attributes known as Implicit cursor's attributes to check the status of DML operations.
Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.

For example: When you execute the SQL statements like INSERT, UPDATE, DELETE then the cursor
attributes tell whether any rows are affected and how many have been affected. If you run a SELECT INTO
statement in PL/SQL block, the implicit cursor attribute can be used to find out whether any row has been
returned by the SELECT statement. It will return an error if there no data is selected.
The following table specifies the status of the cursor with each of its attribute.

Attribute Description

%FOUND Its return value is TRUE if DML statements like INSERT, DELETE and
UPDATE affect at least one row or more rows or a SELECT INTO statement
returned one or more rows. Otherwise it returns FALSE.

%NOTFOUND Its return value is TRUE if DML statements like INSERT, DELETE and
UPDATE affect no row, or a SELECT INTO statement return no rows.
Otherwise it returns FALSE. It is a just opposite of %FOUND.

%ISOPEN It always returns FALSE for implicit cursors, because the SQL cursor is
automatically closed after executing its associated SQL statements.

%ROWCOUNT It returns the number of rows affected by DML statements like INSERT,
DELETE, and UPDATE or returned by a SELECT INTO statement.

PL/SQL Implicit Cursor Example

Create customers table and have records:

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

Let's execute the following program to update the table and increase salary of each customer by 5000. Here,
SQL%ROWCOUNT attribute is used to determine the number of rows affected:

1. DECLARE
2. total_rows number(2);
3. BEGIN
4. UPDATE customers
5. SET salary = salary + 5000;
6. IF sql%notfound THEN
7. dbms_output.put_line('no customers updated');
8. ELSIF sql%found THEN
9. total_rows := sql%rowcount;
10. dbms_output.put_line( total_rows || ' customers updated ');
11. END IF;
12. END;
13. /

Output:

6 customers updated
PL/SQL procedure successfully completed.

Now, if you check the records in customer table, you will find that the rows are updated.

1. select * from customers;

ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 25000

2 Suresh 22 Kanpur 27000

3 Mahesh 24 Ghaziabad 29000

4 Chandan 25 Noida 31000

5 Alex 21 Paris 33000

6 Sunita 20 Delhi 35000

2) PL/SQL Explicit Cursors

The Explicit cursors are defined by the programmers to gain more control over the context area. These
cursors should be defined in the declaration section of the PL/SQL block. It is created on a SELECT
statement which returns more than one row.

Following is the syntax to create an explicit cursor:

Syntax of explicit cursor

Following is the syntax to create an explicit cursor:

1. CURSOR cursor_name IS select_statement;;

Steps:

You must follow these steps while working with an explicit cursor.

1. Declare the cursor to initialize in the memory.


2. Open the cursor to allocate memory.
3. Fetch the cursor to retrieve data.
4. Close the cursor to release allocated memory.
1) Declare the cursor:

It defines the cursor with a name and the associated SELECT statement.

Syntax for explicit cursor decleration

1. CURSOR name IS
2. SELECT statement;

2) Open the cursor:

It is used to allocate memory for the cursor and make it easy to fetch the rows returned by the SQL
statements into it.

Syntax for cursor open:

1. OPEN cursor_name;

3) Fetch the cursor:

It is used to access one row at a time. You can fetch rows from the above-opened cursor as follows:

Syntax for cursor fetch:

1. FETCH cursor_name INTO variable_list;

4) Close the cursor:

It is used to release the allocated memory. The following syntax is used to close the above-opened cursors.

Syntax for cursor close:

1. Close cursor_name;

PL/SQL Explicit Cursor Example

Explicit cursors are defined by programmers to gain more control over the context area. It is defined in the
declaration section of the PL/SQL block. It is created on a SELECT statement which returns more than one
row.

Let's take an example to demonstrate the use of explicit cursor. In this example, we are using the already
created CUSTOMERS table.

Create customers table and have records:

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

Execute the following program to retrieve the customer name and address.

1. DECLARE
18. c_id ID%type := 8;
19. c_name NAME%type;
20. c_addr ADDRESS%type;
2. CURSOR c_customers is
3. SELECT id, name, address FROM customers;
4. BEGIN
5. OPEN c_customers;
6. LOOP
7. FETCH c_customers into c_id, c_name, c_addr;
8. EXIT WHEN c_customers%notfound;
9. dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
10. END LOOP;
11. CLOSE c_customers;
12. END;
13. /

Output:

1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL procedure successfully completed.

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 function 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.

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 INSERTUSER;

You might also like