Oracle PS SQL嵌套循环:
Table 1
key_col start_year End_year
1000 2008 2010
1002 2009 2012
对于每个key_col
值,我想通过循环start_year
和end_yea
r来插入行key_col
。
例如,对于key_col = 1000
,我想将以下内容插入目标表
key_col year
1000 2008
1000 2009
1000 2010
如何在PL SQL中执行此操作?
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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;