在PL SQL中定义循环内的游标

时间:2016-04-15 22:07:37

标签: sql oracle plsql

我可以在循环内设置游标的值吗?我是SQL新手,所以如果这是一个基本问题我会道歉。有问题的变量是c2。

declare
  type NumberArray is array(100) of clock_in_out.pr_emp_id%Type;
  type DateArray is array(1000) of clock_in_out.time_in_out%TYPE;
  emps NumberArray;
  times DateArray;

  cursor c1 is select unique pr_emp_id from clock_in_out;
  cursor c2;

BEGIN
  open c1;
  fetch c1 bulk collect into emps;
  close c1;

  FOR i IN emps.FIRST .. emps.LAST
   LOOP

      c2 is select time_in_out from clock_in_out where pr_emp_id = emps(i) order by time_in_out;

      open c2;
      fetch c2 bulk collect into times;
      close c2;

    END LOOP;
END;

1 个答案:

答案 0 :(得分:1)

是的,您可以在定义光标时使用参数:

DECLARE
  TYPE NumberArray IS ARRAY(100)  OF clock_in_out.pr_emp_id%Type;
  TYPE DateArray   IS ARRAY(1000) OF clock_in_out.time_in_out%TYPE;
  emps NumberArray;
  times DateArray;

  CURSOR c2( emp_id clock_in_out.pr_emp_id%TYPE) IS
    select time_in_out
    from clock_in_out
    where pr_emp_id = emp_id
    order by time_in_out;
BEGIN
  SELECT UNIQUE pr_emp_id
  BULK COLLECT INTO emps
  FROM clock_in_out;

  FOR i IN emps.FIRST .. emps.LAST
  LOOP
    open c2 ( emps(i) );
    fetch c2 bulk collect into times;
    close c2;

    FOR j IN 1 .. times.COUNT LOOP
      DBMS_OUTPUT.PUT_LINE( times(i) );
    END LOOP;
  END LOOP;
END;
/

或者你可以根本不使用游标:

declare
  type NumberArray is array(100) of clock_in_out.pr_emp_id%Type;
  type DateArray is array(1000) of clock_in_out.time_in_out%TYPE;
  emps NumberArray;
  times DateArray;
BEGIN
  select unique pr_emp_id
  BULK COLLECT INTO emps
  from clock_in_out;

  FOR i IN emps.FIRST .. emps.LAST
  LOOP
    select time_in_out
    BULK COLLECT INTO times
    from clock_in_out
    where pr_emp_id = emps(i)
    order by time_in_out;

    FOR j IN 1 .. times.COUNT LOOP
      DBMS_OUTPUT.PUT_LINE( times(i) );
    END LOOP;
  END LOOP;
END;
/