Oracle动态游标的使用

 Oracle动态游标的使用

----定义 
TYPE cursor_type IS REF CURSOR;
c1 cursor_type;
----使用 
--打开动态游标,再往下就都一样了 
OPEN c1 FOR sql2;
LOOP
  FETCH c1
    INTO r_c1;
  EXIT WHEN c1%NOTFOUND;
END LOOP;

实例

1、SQL语句为单条查询结果

DECLARE
  TYPE cursor_type IS REF CURSOR;
  c1      cursor_type;
  l_count NUMBER;
BEGIN
  OPEN c1 FOR
    SELECT COUNT(*) FROM cux_gl_je_headers h;
  LOOP
    FETCH c1
      INTO l_count;
    EXIT WHEN c1%NOTFOUND;
  END LOOP;
  dbms_output.put_line('l_count = ' || l_count);
END;

2、SQL语句为多条查询结果

使用fetch bulk collect into批量读取数据

DECLARE
  TYPE type_record_rec IS RECORD(
    je_header_id NUMBER,
    org_id       NUMBER,
    je_category  VARCHAR2(240),
    je_source    VARCHAR2(240)); --定义记录组
  TYPE type_record_tb1 IS TABLE OF type_record_rec INDEX BY PLS_INTEGER;
  l_type_record_tb1 type_record_tb1;

  TYPE cursor_type IS REF CURSOR; --动态游标定义
  c1      cursor_type;
  l_count NUMBER;
BEGIN
  OPEN c1 FOR
    SELECT h.je_header_id, h.org_id, h.je_category, h.je_source
      FROM cux_gl_je_headers h; --打开游标
  LOOP
    EXIT WHEN c1%NOTFOUND; --游标没有数据退出
    FETCH c1 BULK COLLECT
      INTO l_type_record_tb1 LIMIT 10000; --批量取数
  END LOOP;

  FOR i IN 1 .. l_type_record_tb1.count LOOP
    dbms_output.put_line('=====================================================');
    dbms_output.put_line('l_type_record_tb1(' || i || ').je_header_id = ' || l_type_record_tb1(i)
                         .je_header_id);
    dbms_output.put_line('l_type_record_tb1(' || i || ').org_id = ' || l_type_record_tb1(i)
                         .org_id);
    dbms_output.put_line('l_type_record_tb1(' || i || ').je_category = ' || l_type_record_tb1(i)
                         .je_category);
    dbms_output.put_line('l_type_record_tb1(' || i || ').je_source = ' || l_type_record_tb1(i)
                         .je_source);
  END LOOP;
END;

你可能感兴趣的:(oracle,sql,Cursor,select,动态游标)