Oracle之数组

本文介绍了Oracle数据库中处理数组的方法,包括固定长度数组、可变长度数组和自定义结果集。强调了使用%BULK COLLECT%进行批量操作的高效性,以及%ROWTYPE变量在简化代码和提高可维护性方面的优势。还提到了在某些情况下,通过ROWID处理批处理可能更为高效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

固定长度数组:

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;

 

转载于:https://www.cnblogs.com/xiaozhuanfeng/p/10755189.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值