Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Cursor fetch with multiple rows

Catfive LanderJan 8 2013 — edited Jan 10 2013
I have been given code which, effectively, looks like this:
declare
  cursor cTest is select * from (select 'one' from dual union all select 'two' from dual);
  lvText varchar2(10);
begin
  open cTest;
  fetch cTest into lvText;
  close cTest;
  dbms_output.put_line(lvText);
end;
/
That consistently returns just the result "one", even though there are two rows in the cursor.

If I re-write the code like this:
declare
  lvText varchar2(10);
begin
  select thecol into lvText from (select 'one' as thecol from dual union all select 'two' from dual);
  dbms_output.put_line(lvText);
end;
/
...then I get the error I expected (ORA-01422: exact fetch returns more than requested number of rows).

I guess I am a bit surprised the "fetch into" syntax (which I haven't used before) works at all. Why doesn't it spot that multiple rows are being loaded into a single variable and explode? I am guessing that which row 'wins' the competition to be assigned to the variable is completely indeterminate? Any doco on this behaviour you can point me at, please? The bit I read (http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/fetch_statement.htm) simply says that "You must use either a cursor FOR loop or the FETCH statement to process a multiple-row query", but it doesn't say "the code will silent grab one of the rows at random if you use the FETCH statement on a multiple-row resultset".

(tested on 11.2.0.3, if it makes a difference)
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 7 2013
Added on Jan 8 2013
36 comments
27,981 views