PLSQL Collections Notes 3
PLSQL Collections Notes 3
-------------------------
Syntax:
--------
DECLARE
TYPE t_array IS TABLE OF <datatype> INDEX BY PLS_INTEGER or VARCHAR2(n);
v_array t_array;
BEGIN
v_array(key) := value;
...
END;
name := marks.FIRST;
WHILE name IS NOT NULL LOOP
total := total + marks(name);
total_students := total_students + 1;
IF marks(name) > 75 THEN
count_above_75 := count_above_75 + 1;
END IF;
name := marks.NEXT(name);
END LOOP;
2. NESTED TABLES
-----------------
- One-dimensional collections.
- Can be sparse (gaps).
- Use EXTEND to add elements.
Syntax:
--------
DECLARE
TYPE t_table IS TABLE OF <datatype>;
v_table t_table := t_table();
BEGIN
v_table.EXTEND;
v_table(index) := value;
END;
numbers.DELETE(3);
Syntax:
--------
DECLARE
TYPE t_array IS VARRAY(n) OF <datatype>;
v_array t_array := t_array();
Comparison Summary
-------------------
| Collection Type | Index Type | Can Store in Table? | Gaps Allowed? | Use
Case |
|--------------------|----------------|----------------------|---------------|-----
------------------------------|
| Associative Array | Integer/String | ❌ | ✅ |
Lookups, temporary in-memory data |
| Nested Table | Integer | ✅ | ✅ |
Dynamic-sized lists |
| VARRAY | Integer | ✅ | ❌ |
Fixed-size ordered data |
Basic Syntax:
-------------
BEGIN
-- Code that might cause error
EXCEPTION
WHEN exception_name THEN
-- Error handling code
END;
Types of Exceptions:
---------------------
1. Predefined Exceptions: Built-in (e.g., ZERO_DIVIDE, NO_DATA_FOUND)
2. User-defined Exceptions: Declared by the programmer
3. Unnamed/Internal Exceptions: Caught using WHEN OTHERS
Example: ZERO_DIVIDE
---------------------
DECLARE
num1 NUMBER := 10;
num2 NUMBER := 0;
result NUMBER;
BEGIN
result := num1 / num2;
DBMS_OUTPUT.PUT_LINE('Result is: ' || result);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Cannot divide by zero!');
END;
Practice Task:
---------------
- Accept a number from user.
- Divide 100 by the number.
- Catch ZERO_DIVIDE and OTHERS.
(Solution can be added later.)
--- END OF EXCEPTION HANDLING SECTION ---