Oracle - PL/SQL Associative Array
-- The code below initialize the array values to 0. Based on 
-- the random value generated by the DBMS_RANDOM.value(0,1)
-- function, the array value is switched to 1 when the 
-- random value is greater than 0.5.

DECLARE
 TYPE   tab_bin IS TABLE OF NUMBER INDEX BY PLS_INTEGER; 
 v_bin  tab_bin;

BEGIN
 -- Initialize array values to 0
 FOR idx IN 1..20 LOOP
  v_bin(idx) := 0;
 END LOOP;

  -- Display The basic array
 FOR idx IN 1..v_bin.COUNT LOOP
   IF idx < v_bin.COUNT THEN
     DBMS_OUTPUT.PUT(v_bin(idx)||', ');
   ELSE
     DBMS_OUTPUT.PUT_lINE(v_bin(idx));
   END IF;
 END LOOP;

  -- Switch the value to 1 if > 0.5
 FOR idx IN 1..v_bin.COUNT LOOP
   IF DBMS_RANDOM.value(0,1) > 0.5 THEN
      v_bin(idx) := 1;
   END IF;
 END LOOP;

  -- Display The final array
 FOR idx IN 1..v_bin.COUNT LOOP
   IF idx < v_bin.COUNT THEN
     DBMS_OUTPUT.PUT(v_bin(idx)||', ');
   ELSE
     DBMS_OUTPUT.PUT_lINE(v_bin(idx));
   END IF;
 END LOOP;
 
END;
/

=> Above PL/SQL Code Output (also shown below)

=> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
=> 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1


Oracle registered trademark of Oracle Corporation.

Last Revised On: January 12th, 2014

  54902