1

Oracle PS SQL 嵌套循环:

Table 1

key_col start_year End_year
1000    2008       2010
1002    2009       2012

对于每个key_col值,我想通过循环start_yearend_year来插入行key_col。例如key_col = 1000,我想将以下内容插入到我的目标表中

key_col year
1000    2008
1000    2009
1000    2010

如何在 PL SQL 中执行此操作?

4

3 回答 3

1

这是其中一种方法,其中 CTE(公用表表达式)Years用于生成从 min(在本例中)2008 到 max 2012 的年份,然后将结果与原始数据右外连接。

   with years(yr) as(
      select min_year + (level - 1)
        from ( select min(start_year) as min_year
                    , max(end_year)   as max_year
                 from your_table) t
              connect by min_year + (level - 1) <= t.max_year
             )
    select s.key_col
         , s.yr
      from ( select *
               from your_table yt
              right join years y
                 on (y.yr >= yt.start_year and 
                     y.yr <= yt.end_year)
            ) s
     order by key_col
            , yr

结果:

   KEY_COL         YR
---------- ----------
      1000       2008
      1000       2009
      1000       2010
      1002       2009
      1002       2010
      1002       2011
      1002       2012

SQLFiddle 演示

于 2013-09-09T15:22:27.543 回答
0
select key_col, start_year+rn as year 
from table1,
(select level-1 as rn from dual connect by level<100) a
 where rn <= end_year - start_year
 order by 1,2

结果

KEY_COL     YEAR
1000        2008
1000        2009
1000        2010
1002        2009
1002        2010
1002        2011
1002        2012
于 2013-09-10T11:26:29.427 回答
0

您可以尝试使用以下代码:

BEGIN
   FOR RECORD IN (SELECT KEY_COL,START_YEAR,END_YEAR FROM TABLE1)--Loop records in table 1
   LOOP
      FOR YEAR IN RECORD.START_YEAR .. RECORD.END_YEAR --Loop from start to end years
      LOOP
         DBMS_OUTPUT.PUT_LINE(RECORD.KEY_COL||' - '||YEAR);--Show values for testing
         INSERT INTO TARGET_TABLE (KEY_COL,YEAR) VALUES (RECORD.KEY_COL,YEAR);-- Insert
      END LOOP;
   END LOOP;
END;
于 2013-09-10T21:09:30.580 回答