如何在pl / sql中编写循环数字的循环

时间:2010-07-09 16:55:51

标签: sql oracle plsql

我想写一个迭代数字105 102 19 17 101 16 106 107

的循环

对于每次迭代,我想在查询中插入数字并将其插入表中。

伪:

LOOP (105 102 19 17 101 16 106 107)
   FETCH select * from some_table where value=current_iteration_index --105..etc.
   INTO my_rec_type

END LOOP;

4 个答案:

答案 0 :(得分:12)

另一种方法:

declare
 type numListType is table of number;
 numList numListType;
begin
numList := numListType(
 105,102,19,17,101,16,106,107 
);
for i in numList.FIRST..numList.LAST loop
 -- your usage of element goes here
 dbms_output.put_line(numList(i));
end loop;
end;
/

答案 1 :(得分:4)

这里有一个更简洁,尽管不那么丑陋的替代方案:

DECLARE 
CURSOR C IS
SELECT val 
  FROM (SELECT LEVEL val FROM dual CONNECT BY LEVEL < 1000)
 WHERE val IN (105,102,19,17,101,16,106,107);
BEGIN
  FOR R IN C LOOP
    select * 
     INTO my_rec_type
     from some_table
    where value=R.val; --105..etc.
    ... more stuff
  END LOOP;
END;

此处的优势(IMO)是您只需要修改IN列表以及CONNECT BY子句的限制来更改结果。

答案 2 :(得分:3)

虽然您的问题有几个解决方案,但根据您的处理方式我会告诉您我认为您接近这个错误的方式 - 您没有利用数据库的功能

你能解释原因吗

select * from some_table where value in (105, 102, 19, 17, 101, 16, 106, 107)

不能做你想做的事吗?

答案 3 :(得分:1)

这是一个选项,使用Cursor FOR LOOP%ROWTYPE attribute

DECLARE

  my_rec_type SOME_TABLE%ROWTYPE;

  CURSOR c IS 
    SELECT 105 AS c_index FROM DUAL
    UNION ALL
    SELECT 102 AS c_index FROM DUAL 
    UNION ALL
    SELECT 19 AS c_index FROM DUAL 
    UNION ALL
    SELECT 17 AS c_index FROM DUAL 
    UNION ALL
    SELECT 101 AS c_index FROM DUAL
    UNION ALL
    SELECT 16 AS c_index FROM DUAL 
    UNION ALL
    SELECT 106 AS c_index FROM DUAL
    UNION ALL
    SELECT 107 AS c_index FROM DUAL

BEGIN

  FOR cursor_rec IN c
  LOOP

     SELECT * 
       INTO my_rec_type
       FROM some_table 
       WHERE value = cursor_rec.c_index;

  END LOOP;

END;