How to declare and define function which returns associative array in Oracle PL/SQL?
And how to call the same function from procedure ?
>Solution :
Here’s an example on how to do it:
DECLARE
TYPE my_associative_array_type IS TABLE OF VARCHAR2(100) INDEX BY PLS_INTEGER;
FUNCTION return_associative_array RETURN my_associative_array_type IS
my_array my_associative_array_type;
BEGIN
-- Populate the associative array
my_array(1) := 'First Element';
my_array(2) := 'Second Element';
-- ... add more elements as needed
RETURN my_array;
END return_associative_array;
PROCEDURE use_associative_array IS
local_array my_associative_array_type;
BEGIN
-- Call the function
local_array := return_associative_array;
-- Use the array
DBMS_OUTPUT.PUT_LINE('First Element: ' || local_array(1));
DBMS_OUTPUT.PUT_LINE('Second Element: ' || local_array(2));
-- ... process other elements or iterate over them
END use_associative_array;
BEGIN
-- Call the procedure
use_associative_array;
END;
Or alternatively you can use a package:
CREATE OR REPLACE PACKAGE my_package IS
TYPE my_associative_array_type IS TABLE OF VARCHAR2(100) INDEX BY PLS_INTEGER;
FUNCTION return_associative_array RETURN my_associative_array_type;
PROCEDURE use_associative_array;
END my_package;
Package Body
CREATE OR REPLACE PACKAGE BODY my_package IS
FUNCTION return_associative_array RETURN my_associative_array_type IS
my_array my_associative_array_type;
BEGIN
my_array(1) := 'First Element';
my_array(2) := 'Second Element';
-- ... add more elements as needed
RETURN my_array;
END return_associative_array;
PROCEDURE use_associative_array IS
local_array my_associative_array_type;
BEGIN
local_array := return_associative_array;
DBMS_OUTPUT.PUT_LINE('First Element: ' || local_array(1));
DBMS_OUTPUT.PUT_LINE('Second Element: ' || local_array(2));
-- ... process other elements or iterate over them
END use_associative_array;
END my_package;
Using the Package
BEGIN
-- Call the procedure from the package
my_package.use_associative_array;
END;