Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

oracle pl/sql arrays

i have some numbers which i want to store in an array. how will i declare array and assign value to it in oracle pl/sql??

like image 313
Andromeda Avatar asked Aug 23 '10 07:08

Andromeda


People also ask

Does Oracle SQL support arrays?

The oracle. sql. ARRAY class contains methods that return array elements as Java primitive types. These methods allow you to access collection elements more efficiently than accessing them as Datum instances and then converting each Datum instance to its Java primitive value.

How do you sort an array in PL SQL?

You can't sort an associative array by values, but you have to convert the data to some other data structure and make the sorting there. The easiest way would have been to convert to another associative array where keys and values swap places, but that requires your key values should be unique too.

Can we use array in SQL query?

The ARRAY function returns an ARRAY with one element for each row in a subquery. If subquery produces a SQL table, the table must have exactly one column. Each element in the output ARRAY is the value of the single column of a row in the table.

Can we create multi dimensional collection in PL SQL?

Description PL/SQL doesn't offer native support for multi-dimensional arrays, as you will find in other programming languages. You can, however, emulate these structures using nested collections.


1 Answers

There are array type in PL/SQL but we can create those ourselves using the table

declare 
  type NumberArray is table of number index by binary_integer;
  myArray NumberArray;
begin

   myArray(0) := 1
   myArray(1) := 2 
   --or use a for loop to fill
end;

The explanation article

EDIT :

or as Adam Musch said if we know the data size of data, that we are operating on, we can use VARRAYs that are length fixed, this is oracle environment, so subscripts start from 1,

Alternative is using VARRAY, where array subscript starts from 1 and the length of VARRAYs is fixed.

Semantic:

declare  type VarrayType is varray(size) of ElementType;

Example :

    declare
      type NumberVarray is varray(100) of NUMERIC(10);
      myArray NumberVarray;
    BEGIN
      myArray := NumberVarray(1,10,100,1000,10000);

      myArray(1) = 2;

      for i in myArray.first..myArray.last
      loop
        dbms_output.put_line('myArray(' || i || '): ' || myArray(i));
      end loop;  
    end;
END;

Output :

myArray(1) : 2
myArray(2) : 10
myArray(3) : 100
myArray(4) : 1000
myArray(5) : 10000
like image 82
Damian Leszczyński - Vash Avatar answered Oct 01 '22 11:10

Damian Leszczyński - Vash