天天看點

在ORACLE存儲過程中使用數組

在PL/SQL中是沒有數組(Array)概念的。但是如果程式員想用Array的話,就得變通一下,用TYPE 和Table of Record來代替多元數組,一樣挺好用的。

emp_type 就好象一個table 中的一條record 一樣,裡面有id, name,gender等。emp_type_array 象個table, 裡面含有一條條這樣的record (emp_type),就象多元數組一樣。

--單維數組

DECLARE

TYPE emp_ssn_array IS TABLE OF NUMBER

INDEX BY BINARY_INTEGER;

best_employees emp_ssn_array;

worst_employees emp_ssn_array;

BEGIN

best_employees(1) := '123456';

best_employees(2) := '888888';

worst_employees(1) := '222222';

worst_employees(2) := '666666';

FOR i IN 1..best_employees.count LOOP

DBMS_OUTPUT.PUT_LINE('i='|| i || ', best_employees= ' ||best_employees(i)

|| ', worst_employees= ' ||worst_employees(i));

END LOOP;

END;

--多元數組

DECLARE

TYPE emp_type IS RECORD

( emp_id employee_table.emp_id%TYPE,

emp_name employee_table.emp_name%TYPE,

emp_gender employee_table.emp_gender%TYPE );

TYPE emp_type_array IS TABLE OF emp_type INDEX BY BINARY_INTEGER;

emp_rec_array emp_type_array;

emp_rec emp_type;

BEGIN

emp_rec.emp_id := 300000000;

emp_rec.emp_name := 'Barbara';

emp_rec.emp_gender := 'Female';

emp_rec_array(1) := emp_rec;

emp_rec.emp_id := 300000008;

emp_rec.emp_name := 'Rick';

emp_rec.emp_gender := 'Male';

emp_rec_array(2) := emp_rec;

FOR i IN 1..emp_rec_array.count LOOP

DBMS_OUTPUT.PUT_LINE('i='||i

||', emp_id ='||emp_rec_array(i).emp_id

||', emp_name ='||emp_rec_array(i).emp_name

||', emp_gender = '||emp_rec_array(i).emp_gender);

END LOOP;

END;

用下面語句聲明數組類型

type intarray is varry(30) of integer;

用下面語句聲明一個數組變量

declare

A intarray;用下面語句聲明數組類型

type intarray is varry(30) of integer;

用下面語句聲明一個數組變量

declare

A intarray;用下面語句聲明數組類型

type intarray is varry(30) of integer;

用下面語句聲明一個數組變量

declare

A intarray; ======================================================  oracle 存儲過程傳回數組的方法:

  1.建立包

  create or replace package test is

  TYPE filename_array IS TABLE OF varchar2(1);

  filename filename_array;

  end test;

  2. 建立存儲過程

  create or replace procedure test_array(v_cfjg out test.filename_array ) is

  begin DECLARE i number;

  D_cfjg dic_cfjg%rowTYPE;

  -- D_nr dic_cfjg%rowTYPE;

  cursor c1 is SELECT * FROM dic_cfjg;

  BEGIN

  i:=0;

  v_cfjg := test.filename_array(); --數組初始化

  open c1;

  LOOP fetch c1 into D_cfjg;

  EXIT WHEN c1%NOTFOUND ;

  i:=i+1;

  v_cfjg.EXTEND;

  -- DBMS_OUTPUT.PUT_LINE(TO_CHAR(D_cfjg.dm));

  v_cfjg(v_cfjg.count):=D_cfjg.dm;

  DBMS_OUTPUT.PUT_LINE(v_cfjg(v_cfjg.count));

  -- 測試

  -- FETCH C1 INTO D_cfjg;

  -- EXIT WHEN c1%NOTFOUND ;

  END LOOP;

  end;

  EXCEPTION

  WHEN TOO_MANY_ROWS THEN

  DBMS_OUTPUT.PUT_LINE('TOO_MANY_ROWS');

  WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(sqlerrm);

  end test_array;