tags:

views:

52

answers:

2

Hi, I have to run a query in the loop in SQLPLUS. and the count of loop is coming from some other SQL query. So i have to declared a variable which will take the value of count. Now I want to use this variable in my query. How would i be able to do the same . Please suggest me Thanks in advance

A: 
BEGIN
   DECLARE
      count_loop           NUMBER DEFAULT 0; -- counter coming from some other SQL query...
      progressive_number   NUMBER DEFAULT 0;
      copy_count_loop      NUMBER DEFAULT 0;
   BEGIN
      -- calculus generating the COUNT_LOOP value > 0.
      copy_count_loop := count_loop;

      FOR progressive_number IN 1 .. count_loop
      LOOP
      -- do your operations using copy_count_loop
      END LOOP;
   END;
END;
/

It is not so clear what would you like to do with COUNT_LOOP. I have made a copy of the counter before entering in the FOR cycle, so you can use COPY_COUNT_LOOP inside the FOR cycle, without affecting neither progressive_number variable, nor count_loop variable.

The chicken in the kitchen
+1  A: 

If I understand the question correctly, you can use a SQL*Plus variable coupled with a selected column to accomplish this:

SQL> undefine loop_ctr
SQL> column loop_ctr new_value loop_ctr noprint
SQL> select 5 AS loop_ctr from dual;


SQL> set serveroutput on
SQL> begin
  2  for i in 1..&&loop_ctr
  3  loop
  4  dbms_output.put_line('i = ' || i);
  5  end loop;
  6  end;
  7  /
old   2: for i in 1..&&loop_ctr
new   2: for i in 1..         5
i = 1
i = 2
i = 3
i = 4
i = 5
SQL> 

Hope that helps

bhangm