关联数组问题

时间:2018-02-16 01:10:55

标签: oracle plsql user-defined-types

我已经创建了一个关联数组,我知道它可以使用不同的写作方式,但是只需要提示如何使这项工作。目前,当我编译这个块时,我没有收到任何数据。谢谢!

    DECLARE
        TYPE type_state IS TABLE OF VARCHAR(50)
        INDEX BY VARCHAR2(50);
        tbl_state type_state;
        lv_statecity1_txt VARCHAR2(30):= 'TAMPA';
        lv_statecity2_txt VARCHAR2(30):= 'ATLANTA';
        lv_statecity3_txt VARCHAR2(30):= 'NYC';
        lv_cnt_num NUMBER(5) := 0;
    BEGIN
        tbl_state('FLORIDA') := lv_statecity1_txt;
        tbl_state('GEORGIA') := lv_statecity2_txt;
        tbl_state('New_York') := lv_statecity3_txt;
        FOR i IN 1..tbl_state.count loop
            IF tbl_state(i) IS NOT NULL THEN
              LV_CNT_NUM := LV_CNT_NUM + 1;
              dbms_output.put_line(tbl_state(i));
            END IF;
        END LOOP;
        dbms_output.put_line('That''s it folks');
    END;

1 个答案:

答案 0 :(得分:3)

tbl_state是由字符串索引的字符串表 - 传入索引值1,2,3(数字)将无效。

确实,数组对仍然是有序的(第一,第二等),但是在循环中访问它们有点复杂。您将需要一个WHILE循环,并且索引(我保持名称i以尽可能地匹配您的代码)必须声明为与数组中的键相同的数据类型和长度。

DECLARE
        TYPE type_state IS TABLE OF VARCHAR(50)
        INDEX BY VARCHAR2(50);
        tbl_state type_state;
        lv_statecity1_txt VARCHAR2(30):= 'TAMPA';
        lv_statecity2_txt VARCHAR2(30):= 'ATLANTA';
        lv_statecity3_txt VARCHAR2(30):= 'NYC';
        lv_cnt_num NUMBER(5) := 0;                 --  WHAT IS THIS FOR? NEEDED??
        i varchar2(50);                            --  Notice this line
    BEGIN
        tbl_state('FLORIDA') := lv_statecity1_txt;
        tbl_state('GEORGIA') := lv_statecity2_txt;
        tbl_state('New_York') := lv_statecity3_txt;
        i := tbl_state.first;                      --  And this line
        while (i is not null) loop                 --  And this one
              LV_CNT_NUM := LV_CNT_NUM + 1;
              dbms_output.put_line(tbl_state(i));
              i := tbl_state.next(i);              --  And this one
        END LOOP;
        dbms_output.put_line('That''s it folks');
    END;
/