简体   繁体   中英

Oracle Cursor with conditional Select statement

I am new to this group. I was trying to think of having a cursor with condition select statement. Some how like this pseudo code--

[B]cursor test_cursor is
  if condition == 't11'
  then 
    select * from test1;
  else 
    select * from test1;
  end if;[/B]
begin

  for cursorVal in test_cursor loop
    //Doing the actual task on cursor data.
  end loop;

commit;
end;

Actually, i came across with a scenario where need to work on two different tables with same DDL. Based on some user input, need to fetch data from either of the table and further manipulate in procedure. As i said both table are of same DDL so don't want to create two different cursor. The reason for this same business logic will be applied on both tables data. Its just the user input which decide which table need to fetch data. Some how one can think of this as latest data and historical data and the way DB is designed.

Hope i am clear with my scenario.

Thanks, Arfeen.

The cursor can be declared as a union as described below. Depending on the content of variable condition , the cursor will either be based on Test1 or Test2.

SELECT * FROM Test1 WHERE condition = 't1'
UNION ALL
SELECT * FROM Test2 WHERE condition = 't2'

What you are trying to achieve looks like it could either be achieved by better table or view design or by using a BULK COLLECT. If you can - always consider database design first over code.

BEGIN

if condition == 't11' then
 SELECT XXXXXX
 BULK COLLECT INTO bulk_collect_ids
 FROM your_table1;
else
 SELECT XXXXXX
 BULK COLLECT INTO bulk_collect_ids
 FROM your_table2;
end if;

FOR indx IN 1 .. bulk_collect_ids.COUNT
LOOP
 .
 //Doing the actual task on bulk_collect_ids data.
 .
END LOOP;

END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM