如何将%TYPE与Oracle关联数组一起使用?

时间:2016-11-23 08:51:31

标签: arrays oracle types associative-array

我在某些Oracle包标题中声明了一个关联数组类型,如:

TYPE ParamArray IS TABLE OF VARCHAR2(4096) INDEX BY VARCHAR2(512);

在我的包体中,我想迭代数组而不重复字符串大小,以避免在更新包头时出现不匹配。

我的尝试是:

PROCEDURE IterateArray( Params ParamArray )
AS
  v_ParamName ParamArray%TYPE;
BEGIN
  v_ParamName := Params.First;
  WHILE v_ParamName IS NOT NULL LOOP
    -- do something with the array entry
    v_ParamName := Params.Next(v_ParamName);
  END LOOP;
END;

但是这在我的Oracle 10g测试服务器上没有用。

1 个答案:

答案 0 :(得分:2)

您可以定义自己的类型来处理varchar2并使用您的类型,而无需重复大小。 例如:

CREATE OR REPLACE PACKAGE testpck AS
    SUBTYPE myType IS VARCHAR2(4096);     /* a type for the values */
    SUBTYPE myIndexType is VARCHAR2(512); /* a type for the index  */
    TYPE ParamArray IS TABLE OF myType
        INDEX BY myIndexType;
    PROCEDURE IterateArray(Params ParamArray);
END;

CREATE OR REPLACE PACKAGE BODY testpck AS
    PROCEDURE IterateArray(Params ParamArray) AS
        v_ParamName     myType; 
        v_index         myIndexType;
    BEGIN
        v_index    := Params.FIRST;

        WHILE v_index IS NOT NULL
        LOOP
            -- do something with the array entry
            v_ParamName := Params(v_index);
            dbms_output.put_line('value of ' || v_index || ' is ' || v_ParamName);
            v_index     := Params.NEXT(v_index);             
        END LOOP;
    END;
END;

电话:

declare
    myArray         testpck.ParamArray;
    myValue         testpck.myType;
    myIndex         testpck.myIndexType;     
begin    
    myIndex := 'ONE';
    myValue := 'VALUE OF ONE';
    myArray(myIndex) := myValue;     
    --
    myIndex := 'TWO';
    myValue := 'VALUE OF TWO';
    myArray(myIndex) := myValue;
    --
    testpck.IterateArray(myArray);
end;