合并插入语句

时间:2018-03-01 00:09:17

标签: sql oracle

我如何将多个插入语句放在一起?我要插入8种不同的描述。例如:

insert into table (
    p_number, description, period
)
select  p.p_number, g.description, g.period, 
from    other_table p
        ,('desc1' as description
                ,2015 + Level as period
        from dual connect by 2015 + Level <=2050) g
where   p.flag = 'Y';


insert into table (
    p_number, description, period
)
select  p.p_number, g.description, g.period, 
from    other_table p
        ,('desc2' as description
                ,2015 + Level as period
        from dual connect by 2015 + Level <=2050) g
where   p.flag = 'Y';

3 个答案:

答案 0 :(得分:2)

您可以使用 union all

insert into table (
    p_number, description, period
)
select  p.p_number, g.description, g.period, 
from    other_table p
        ,('desc1' as description
                ,2015 + Level as period
        from dual connect by 2015 + Level <=2050) g
where   p.flag = 'Y'
union all
select  p.p_number, g.description, g.period, 
from    other_table p
        ,('desc2' as description
                ,2015 + Level as period
        from dual connect by 2015 + Level <=2050) g
where   p.flag = 'Y';

答案 1 :(得分:1)

您可以使用CTE生成描述和句点,并将它们交叉连接到真实源表:

insert into target_table (
    p_number, description, period
)
with descriptions (description) as (
            select 'desc1' from dual
  union all select 'desc2' from dual
  -- etc.
),
periods (period) as (
  select 2015 + level
  from dual
  connect by level <= 35
)
select s.p_number, d.description, p.period, 
from source_table s
cross join descriptions d
cross join periods p
where s.flag = 'Y';

未经测试,当然......

答案 2 :(得分:-1)

使用交叉联接(和联合):

insert into table (
    p_number, description, period
)
select  p.p_number, d.description, g.period
from    other_table p cross join (
    select 'desc1' description from dual  union 
    select 'desc2' from dual  union 
    ...
    select 'desc1' from dual 
) d cross join ( 
    select 2015 + Level as period
        from dual connect by 2015 + Level <=2050
) g