oracle 引用匿名块中的游标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9437613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 00:38:20  来源:igfitidea点击:

Referring to a cursor in an anonymous block

sqloraclecursor

提问by brendan

How can you refer to a cursor's specific value if there are multiple values returned?

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

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;

回答by Justin Cave

Why would you want to? Presumably, if you are selecting three columns in your cursor declaration, you need all three columns in your code, so you would need to fetch all three columns into three separate local variables, i.e.

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

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;

Alternately, you can declare a record type based on the cursor declaration and fetch into that

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

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;

You can also get rid of the explicit loop entirely which is generally the preferred approach since you don't have to worry about cursor leaks and (in modern versions) Oracle can automatically do bulk collects for you

您还可以完全摆脱显式循环,这通常是首选方法,因为您不必担心游标泄漏,并且(在现代版本中)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;