Search This Blog

Showing posts with label oracle. Show all posts
Showing posts with label oracle. Show all posts

Saturday, September 24, 2022

PL/SQL - Collections

A collection is an ordered group of elements having the same data type. Each element is identified by a unique subscript that represents its position in the collection.

Oracle PL/SQL


PL/SQL provides three collection types −

  • Index-by tables or Associative array
  • Nested table
  • Variable-size array or Varray

Oracle documentation provides the following characteristics for each type of collections −

Collection TypeNumber of ElementsSubscript TypeDense or SparseWhere CreatedCan Be Object Type Attribute
Associative array (or index-by table)UnboundedString or integerEitherOnly in PL/SQL blockNo
Nested tableUnboundedIntegerStarts dense, can become sparseEither in PL/SQL block or at schema levelYes
Variablesize array (Varray)BoundedIntegerAlways denseEither in PL/SQL block or at schema levelYes

We have already discussed varray in the chapter 'PL/SQL arrays'. In this chapter, we will discuss the PL/SQL tables.

Both types of PL/SQL tables, i.e., the index-by tables and the nested tables have the same structure and their rows are accessed using the subscript notation. However, these two types of tables differ in one aspect; the nested tables can be stored in a database column and the index-by tables cannot.

Index-By Table

An index-by table (also called an associative array) is a set of key-value pairs. Each key is unique and is used to locate the corresponding value. The key can be either an integer or a string.

An index-by table is created using the following syntax. Here, we are creating an index-by table named table_name, the keys of which will be of the subscript_type and associated values will be of the element_type

TYPE type_name IS TABLE OF element_type [NOT NULL] INDEX BY subscript_type; 
 
table_name type_name;

Example

Following example shows how to create a table to store integer values along with names and later it prints the same list of names.

DECLARE 
   TYPE salary IS TABLE OF NUMBER INDEX BY VARCHAR2(20); 
   salary_list salary; 
   name   VARCHAR2(20); 
BEGIN 
   -- adding elements to the table 
   salary_list('Rajnish') := 62000; 
   salary_list('Minakshi') := 75000; 
   salary_list('Martin') := 100000; 
   salary_list('James') := 78000;  
   
   -- printing the table 
   name := salary_list.FIRST; 
   WHILE name IS NOT null LOOP 
      dbms_output.put_line 
      ('Salary of ' || name || ' is ' || TO_CHAR(salary_list(name))); 
      name := salary_list.NEXT(name); 
   END LOOP; 
END; 
/

When the above code is executed at the SQL prompt, it produces the following result −

Salary of James is 78000 
Salary of Martin is 100000 
Salary of Minakshi is 75000 
Salary of Rajnish is 62000  

PL/SQL procedure successfully completed.

Example

Elements of an index-by table could also be a %ROWTYPE of any database table or %TYPE of any database table field. The following example illustrates the concept. We will use the CUSTOMERS table stored in our database as −

Select * from customers;  

+----+----------+-----+-----------+----------+ 
| ID | NAME     | AGE | ADDRESS   | SALARY   | 
+----+----------+-----+-----------+----------+ 
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 | 
|  2 | Khilan   |  25 | Delhi     |  1500.00 | 
|  3 | kaushik  |  23 | Kota      |  2000.00 | 
|  4 | Chaitali |  25 | Mumbai    |  6500.00 | 
|  5 | Hardik   |  27 | Bhopal    |  8500.00 | 
|  6 | Komal    |  22 | MP        |  4500.00 | 
+----+----------+-----+-----------+----------+  

DECLARE 
   CURSOR c_customers is 
      select name from customers; 

   TYPE c_list IS TABLE of customers.Name%type INDEX BY binary_integer; 
   name_list c_list; 
   counter integer :=0; 
BEGIN 
   FOR n IN c_customers LOOP 
      counter := counter +1; 
      name_list(counter) := n.name; 
      dbms_output.put_line('Customer('||counter||'):'||name_lis t(counter)); 
   END LOOP; 
END; 
/ 

When the above code is executed at the SQL prompt, it produces the following result −

Customer(1): Ramesh  
Customer(2): Khilan  
Customer(3): kaushik     
Customer(4): Chaitali  
Customer(5): Hardik  
Customer(6): Komal  

PL/SQL procedure successfully completed

Nested Tables

A nested table is like a one-dimensional array with an arbitrary number of elements. However, a nested table differs from an array in the following aspects −

  • An array has a declared number of elements, but a nested table does not. The size of a nested table can increase dynamically.

  • An array is always dense, i.e., it always has consecutive subscripts. A nested array is dense initially, but it can become sparse when elements are deleted from it.

A nested table is created using the following syntax −

TYPE type_name IS TABLE OF element_type [NOT NULL]; 
 
table_name type_name; 

This declaration is similar to the declaration of an index-by table, but there is no INDEX BY clause.

A nested table can be stored in a database column. It can further be used for simplifying SQL operations where you join a single-column table with a larger table. An associative array cannot be stored in the database.

Example

The following examples illustrate the use of nested table −

DECLARE 
   TYPE names_table IS TABLE OF VARCHAR2(10); 
   TYPE grades IS TABLE OF INTEGER;  
   names names_table; 
   marks grades; 
   total integer; 
BEGIN 
   names := names_table('Kavita', 'Pritam', 'Ayan', 'Rishav', 'Aziz'); 
   marks:= grades(98, 97, 78, 87, 92); 
   total := names.count; 
   dbms_output.put_line('Total '|| total || ' Students'); 
   FOR i IN 1 .. total LOOP 
      dbms_output.put_line('Student:'||names(i)||', Marks:' || marks(i)); 
   end loop; 
END; 
/  

When the above code is executed at the SQL prompt, it produces the following result −

Total 5 Students 
Student:Kavita, Marks:98 
Student:Pritam, Marks:97 
Student:Ayan, Marks:78 
Student:Rishav, Marks:87 
Student:Aziz, Marks:92  

PL/SQL procedure successfully completed. 

Example

Elements of a nested table can also be a %ROWTYPE of any database table or %TYPE of any database table field. The following example illustrates the concept. We will use the CUSTOMERS table stored in our database as −

Select * from customers;  

+----+----------+-----+-----------+----------+ 
| ID | NAME     | AGE | ADDRESS   | SALARY   | 
+----+----------+-----+-----------+----------+ 
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 | 
|  2 | Khilan   |  25 | Delhi     |  1500.00 | 
|  3 | kaushik  |  23 | Kota      |  2000.00 | 
|  4 | Chaitali |  25 | Mumbai    |  6500.00 | 
|  5 | Hardik   |  27 | Bhopal    |  8500.00 | 
|  6 | Komal    |  22 | MP        |  4500.00 | 
+----+----------+-----+-----------+----------+ 

DECLARE 
   CURSOR c_customers is  
      SELECT  name FROM customers;  
   TYPE c_list IS TABLE of customerS.No.ame%type; 
   name_list c_list := c_list(); 
   counter integer :=0; 
BEGIN 
   FOR n IN c_customers LOOP 
      counter := counter +1; 
      name_list.extend; 
      name_list(counter)  := n.name; 
      dbms_output.put_line('Customer('||counter||'):'||name_list(counter)); 
   END LOOP; 
END; 
/ 

When the above code is executed at the SQL prompt, it produces the following result −

Customer(1): Ramesh  
Customer(2): Khilan  
Customer(3): kaushik     
Customer(4): Chaitali  
Customer(5): Hardik  
Customer(6): Komal  

PL/SQL procedure successfully completed. 

Collection Methods

PL/SQL provides the built-in collection methods that make collections easier to use. The following table lists the methods and their purpose −

S.NoMethod Name & Purpose
1

EXISTS(n)

Returns TRUE if the nth element in a collection exists; otherwise returns FALSE.

2

COUNT

Returns the number of elements that a collection currently contains.

3

LIMIT

Checks the maximum size of a collection.

4

FIRST

Returns the first (smallest) index numbers in a collection that uses the integer subscripts.

5

LAST

Returns the last (largest) index numbers in a collection that uses the integer subscripts.

6

PRIOR(n)

Returns the index number that precedes index n in a collection.

7

NEXT(n)

Returns the index number that succeeds index n.

8

EXTEND

Appends one null element to a collection.

9

EXTEND(n)

Appends n null elements to a collection.

10

EXTEND(n,i)

Appends n copies of the ith element to a collection.

11

TRIM

Removes one element from the end of a collection.

12

TRIM(n)

Removes n elements from the end of a collection.

13

DELETE

Removes all elements from a collection, setting COUNT to 0.

14

DELETE(n)

Removes the nth element from an associative array with a numeric key or a nested table. If the associative array has a string key, the element corresponding to the key value is deleted. If n is null, DELETE(n) does nothing.

15

DELETE(m,n)

Removes all elements in the range m..n from an associative array or nested table. If m is larger than n or if m or n is null, DELETE(m,n) does nothing.

Collection Exceptions

The following table provides the collection exceptions and when they are raised −

Collection ExceptionRaised in Situations
COLLECTION_IS_NULLYou try to operate on an atomically null collection.
NO_DATA_FOUNDA subscript designates an element that was deleted, or a nonexistent element of an associative array.
SUBSCRIPT_BEYOND_COUNTA subscript exceeds the number of elements in a collection.
SUBSCRIPT_OUTSIDE_LIMITA subscript is outside the allowed range.
VALUE_ERRORA subscript is null or not convertible to the key type. This exception might occur if the key is defined as a PLS_INTEGER range, and the subscript is outside this range.

Friday, September 23, 2022

Oracle / PLSQL: ORA-00058 Error Message


Learn the cause and how to resolve the ORA-00058 error message in Oracle.

oracle pl/sql


Description

When you encounter an ORA-00058 error, the following error message will appear:

  • ORA-00058: DB_BLOCK_SIZE must be num to mount this database not num

Cause

You tried to start a database whose DB_BLOCK_SIZE parameter value in the initialization file does not match the value used when the database was created.

Resolution

The option(s) to resolve this Oracle error are:

Option #1

Make sure that you are mounting the correct database.

Option #2

Make sure that you are using the correct initialization file.

Option #3

You may need to change the DB_BLOCK_SIZE parameter in the initialization file.

Oracle / PLSQL: ORA-00057 Error Message


Learn the cause and how to resolve the ORA-00057 error message in Oracle.

oracle pl/sql


Description

When you encounter an ORA-00057 error, the following error message will appear:

  • ORA-00057: maximum number of temporary table locks exceeded

Cause

The number of temporary tables has reached or exceeded the number of temporary table locks allowed by Oracle.

Resolution

The option(s) to resolve this Oracle error are:

Option #1

This error is most commonly caused by a SQL statement that has performed a very large sort. The sort has created a number of temporary tables that has exceeded the limit specified in Oracle.

To correct this problem, increase the TEMPORARY_TABLE_LOCKS parameter in Oracle and perform a restart in Oracle.

Oracle / PLSQL: ORA-00054 Error Message


Learn the cause and how to resolve the ORA-00054 error message in Oracle.

Description

When you encounter an ORA-00054 error, the following error message will appear:

  • ORA-00054: resource busy and acquire with NOWAIT specified

Cause

You tried to execute a LOCK TABLE or SELECT FOR UPDATE command with the NOWAIT keyword but the resource was unavailable.

Or you tried to DROP a COLUMN using the ALTER TABLE command and received the error.

Resolution

The option(s) to resolve this Oracle error are:

Option #1

Wait and try the command again after a few minutes.

Option #2

Execute the command without the NOWAIT keyword.

Option #3

If the error occurred while trying to DROP a COLUMN, be sure to backup the data. Then TRUNCATE the table and execute the DROP COLUMN command again.

Oracle / PLSQL: ORA-00051 Error Message


Learn the cause and how to resolve the ORA-00051 error message in Oracle.

Description

When you encounter an ORA-00051 error, the following error message will appear:

  • ORA-00051: time-out occurred while waiting for resource

Cause

You were waiting for a resource and you timed out. This may have been caused by an Oracle instance abnormally terminating.

Resolution

The option(s) to resolve this Oracle error are:

Option #1

Restart the Oracle instance.

Oracle / PLSQL: ORA-00034 Error Message


Learn the cause and how to resolve the ORA-00034 error message in Oracle.

Description

When you encounter an ORA-00034 error, the following error message will appear:

  • ORA-00034: cannot COMMIT or ROLLBACK in current PL/SQL session

Cause

You tried to issue a COMMIT or ROLLBACK command from a PLSQL function, procedure, or package. However, COMMIT and ROLLBACK have been disabled with the following command:

ALTER SESSION DISABLE COMMIT IN PROCEDURE

Resolution

The option(s) to resolve this Oracle error are:

Option #1

Do not issue a COMMIT or ROLLBACK command from your PLSQL function, procedure, or package while disabled.

Option #2

Enable COMMIT or ROLLBACK for this PLSQL session.

Oracle / PLSQL: ORA-00028 Error Message


Learn the cause and how to resolve the ORA-00028 error message in Oracle.

Description

When you encounter an ORA-00028 error, the following error message will appear:

  • ORA-00028: your session has been killed

Cause

Your session has been killed by a privileged user (such as a DBA).

Resolution

The option(s) to resolve this Oracle error are:

Option #1

Check with your DBA. Your session may have been killed due to a scheduled outage or other activity.

Oracle / PLSQL: ORA-00023 Error Message

 Learn the cause and how to resolve the ORA-00023 error message in Oracle.

Description

When you encounter an ORA-00023 error, the following error message will appear:

  • ORA-00023: session references process' private memory; cannot detach session

Cause

You tried to detach a session but it contains references to the process memory (PGA) through any of: an open network connection, a very large context area, or operating system privileges.

Resolution

The option(s) to resolve this Oracle error are:

Option #1

If the session has an open network connection or a very large context area, you can try closing the session's database links and cursors.

Option #2

If the session has operating system privileges, you will not be able to detach the session.

Oracle / PLSQL: ORA-00020 Error Message

Learn the cause and how to resolve the ORA-00020 error message in Oracle.

Description

When you encounter an ORA-00020 error, the following error message will appear:

  • ORA-00020: maximum number of processes num exceeded

Cause

You tried to execute a statement that requested a resource. Since the maximum number of processes have been reached, Oracle will not process any new requests.

Resolution

The option(s) to resolve this Oracle error are:

Option #1

You can wait a few minutes and try to re-execute the statement(s).

Option #2

You can shut down Oracle, increase the PROCESSES parameter in the initialization parameter file, and restart Oracle.

Oracle / PLSQL: ORA-00018 Error Message

 Learn the cause and how to resolve the ORA-00018 error message in Oracle.

Description

When you encounter an ORA-00018 error, the following error message will appear:

  • ORA-00018: maximum number of sessions exceeded

Cause

You tried to execute a statement that requested a resource. Since the maximum number of sessions have been reached, Oracle will not process any new resource requests.

Resolution

The option(s) to resolve this Oracle error are:

Option #1

You can wait a few minutes and try to re-execute the statement(s).

Option #2

You can shut down Oracle, increase the SESSIONS parameter in the initialization parameter file, and restart Oracle.

Thursday, September 22, 2022

Oracle / PLSQL: ORA-00001 Error Message

Learn the cause and how to resolve the ORA-00001 error message in Oracle.

Description

When you encounter an ORA-00001 error, the following error message will appear:

  • ORA-00001: unique constraint (constraint_name) violated

Cause

You tried to execute an INSERT or UPDATE statement that has created a duplicate value in a field restricted by a unique index.

Resolution

The option(s) to resolve this Oracle error are:

Option #1

Drop the unique constraint.

Option #2

Change the constraint to allow duplicate values.

Option #3

Modify your SQL so that a duplicate value is not created.

Note

If you are not sure which unique constraint was violated, you can run the following SQL:

SELECT DISTINCT table_name
FROM all_indexes
WHERE index_name = 'CONSTRAINT_NAME';


Error 

ORA-00001: unique constraint(COLLECT.SYS_C00987) violated


In our example (see above error), our constraint name would be SYS_C00987 and we would execute the following SQL:

SELECT DISTINCT table_name
FROM all_indexes
WHERE index_name = 'SYS_C00987';

This would return the name of the table whose unique constraint we violated.

PL/SQL - Collections

A collection is an ordered group of elements having the same data type. Each element is identified by a unique subscript that represents its...