Fork me on GitHub

Oracle之数组

记忆力不好,提供样例套路:

固定长度数组:

declare
  type t_test is varray(5) of varchar2(9);
  test t_test := t_test('a', 'b', 'c', 'd', 'e');
begin
  --遍历
  for i in 1 .. test.count loop
    dbms_output.put_line(test(i));
  end loop;
end;

可变长度数组:

declare
  type t_test is table of varchar2(9);
  test t_test := t_test('a', 'b', 'c', 'd', 'e');
begin
  --遍历
  for i in 1 .. test.count loop
    dbms_output.put_line(test(i));
  end loop;
end;

自定义结果集:

如当前有表,表结构如图:

declare
  type stu_record is record(
    v_sname    l_student_info_tbl.sname%type,
    v_sage     l_student_info_tbl.sage%type,
    v_sgender  l_student_info_tbl.sgender%type,
    v_sclassno l_student_info_tbl.sclassno%type);

  TYPE stu_rec IS TABLE OF stu_record INDEX BY BINARY_INTEGER;

  v_stu_rec stu_rec;

begin
  select t.sname, t.sage, t.sgender, t.sclassno
    bulk collect
    into v_stu_rec
    from l_student_info_tbl t;

  for i in 1 .. v_stu_rec.count loop
    dbms_output.put_line(v_stu_rec(i).v_sname);
  end loop;
end;

结果:注意:bulk collect 可以在select into ,fetch into ,returning into ,需要大量内存,但比游标高效。

 

%rowtype表示一行记录的变量,比分别使用%TYPE来定义表示表中各个列的变量要简洁得多,并且不容易遗漏、出错。这样会增加程序的可维护性。

declare
  TYPE t_user IS TABLE OF l_student_info_tbl%ROWTYPE INDEX BY BINARY_INTEGER;
  v_arry_user t_user;

begin
  select t.* bulk collect into v_arry_user from l_student_info_tbl t;

  for i in 1 .. v_arry_user.count loop
    dbms_output.put_line(v_arry_user(i).sname);
  end loop;
end;

 

有时批处理,用rowid处理更快高效。

declare
  type t_rowid is table of rowid index by pls_integer;
  v_rowid t_rowid;

begin
  select rowid
    bulk collect
    into v_rowid
    from l_student_info_tbl t
   where rownum <= 2;

  for i in 1 .. v_rowid.count loop
    dbms_output.put_line(v_rowid(i));
  end loop;

 forall i in 1.. v_rowid.last
 --dml语句(insert update delete)

end;

 

posted @ 2019-04-23 11:04  小传风  阅读(295)  评论(0编辑  收藏  举报