根据Oracle中的字段值插入记录数

时间:2018-07-16 10:35:00

标签: sql oracle

我有以下脚本:-

SELECT
   quoteid,
   tariff_length,
   cost 
FROM
   tblquotesnew q 
   LEFT JOIN
      tbltariffsnew t 
      ON q.tariff_id = t.tariff

可能会返回以下内容:-

quoteid tariff_length cost
310     4             12
311     6             16

是否可以将行插入到单独的表中,其中插入的行数是基于riff_length?

因此,使用以上内容,插入表(tblcommnew)看起来像

commid quoteid cost
1      310     12
2      310     12
3      310     12
4      310     12
5      311     16
6      311     16
7      311     16
8      311     16
9      311     16
10     311     16

2 个答案:

答案 0 :(得分:2)

这里是一个选择:

SQL> with test (quoteid, tariff_length, cost) as
  2    (select 310, 4, 12 from dual union
  3     select 311, 6, 16 from dual
  4    )
  5  select rownum as commid, quoteid, cost
  6  from test,
  7       table(cast(multiset(select level from dual
  8                           connect by level <= tariff_length
  9                          ) as sys.odcinumberlist));

    COMMID    QUOTEID       COST
---------- ---------- ----------
         1        310         12
         2        310         12
         3        310         12
         4        310         12
         5        311         16
         6        311         16
         7        311         16
         8        311         16
         9        311         16
        10        311         16

10 rows selected.

SQL>

答案 1 :(得分:2)

@Littlefoot的方法略有不同,就是使用XMLTable生成组合:

with tblquotesnew (quoteid, tariff_length, cost) as (
            select 310, 4, 12 from dual
  union all select 311, 6, 16 from dual
)
select rownum as commid, quoteid, cost
from tblquotesnew
cross join xmltable ('1 to xs:integer($n)' passing tariff_length as "n");

    COMMID    QUOTEID       COST
---------- ---------- ----------
         1        310         12
         2        310         12
         3        310         12
         4        310         12
         5        311         16
         6        311         16
         7        311         16
         8        311         16
         9        311         16
        10        311         16

作为插入,您只需执行以下操作即可:

insert into tblcommnew (commid, quoteid, cost)
select rownum, quoteid, cost
from tblquotesnew
cross join xmltable ('1 to xs:integer($n)' passing tariff_length as "n");

10 rows inserted.