引用匿名块中的游标

时间:2012-02-24 20:31:57

标签: sql oracle cursor

如果返回多个值,如何引用游标的特定值?

DECLARE
  X INTEGER;
  CURSOR c1 IS SELECT col1, col2, col3.....;
BEGIN
  OPEN c1;
  LOOP
    EXIT WHEN c1%NOTFOUND;
    FETCH (col2 from c1) INTO X;
  END LOOP;
END;

1 个答案:

答案 0 :(得分:13)

你为什么要这样?据推测,如果您在游标声明中选择了三列,则需要在代码中使用所有三列,因此您需要将所有三列提取到三个单独的局部变量中,即

DECLARE
  x      integer;
  y      integer;
  z      integer;
  CURSOR c1
      IS SELECT column1, column2, column3
           FROM some_table;
BEGIN
  OPEN c1;
  LOOP
    FETCH c1 
     INTO x, y, z;
    EXIT WHEN c1%NOTFOUND;
  END LOOP;
  CLOSE c1;
END;

或者,您可以根据游标声明声明记录类型并获取

DECLARE
  CURSOR c1
      IS SELECT column1, column2, column3
           FROM some_table;
  c1_rec c1%ROWTYPE;
BEGIN
  OPEN c1;
  LOOP
    FETCH c1 
     INTO c1_rec;
    dbms_output.put_line( c1_rec.column2 );
    EXIT WHEN c1%NOTFOUND;
  END LOOP;
  CLOSE c1;
END;

您还可以完全摆脱显式循环,这通常是首选方法,因为您不必担心游标泄漏和(在现代版本中)Oracle可以自动为您进行批量收集

DECLARE
  CURSOR c1
      IS SELECT column1, column2, column3
           FROM some_table;
BEGIN
  FOR c1_rec IN c1
  LOOP
    dbms_output.put_line( c1_rec.column2 );
  END LOOP;
END;