Oracle 11g: INSERT SELECT with WITH statement

怎甘沉沦 提交于 2019-12-24 16:00:07

问题


I've written this simple example DML with WITH statement:

WITH seq AS
 (SELECT to_char(LEVEL - 1) p FROM dual CONNECT BY LEVEL <= 10)
SELECT old_value,
       new_value
  FROM (SELECT to_char(t1.p) old_value,
               to_char(t2.p) new_value
          FROM (SELECT row_number() over(ORDER BY p) rn,
                       p
                  FROM seq) t1,
               (SELECT row_number() over(ORDER BY dbms_random.random) rn,
                       p
                  FROM seq) t2
         WHERE t1.rn = t2.rn);

Is there any way to use WITH statement in INSERT statement?

FIDDLE


回答1:


as mentioned here : https://forums.oracle.com/thread/696477 and here : insert statement with with clause invalid identifier oracle

the WITH clause is part of the select statemant , so just try to wrap it all with an INSERT statement as below :

INSERT INTO SOME_TABLE    
WITH seq AS
     (SELECT to_char(LEVEL - 1) p FROM dual CONNECT BY LEVEL <= 10)
    SELECT old_value,
           new_value
      FROM (SELECT to_char(t1.p) old_value,
                   to_char(t2.p) new_value
              FROM (SELECT row_number() over(ORDER BY p) rn,
                           p
                      FROM seq) t1,
                   (SELECT row_number() over(ORDER BY dbms_random.random) rn,
                           p
                      FROM seq) t2
             WHERE t1.rn = t2.rn);



回答2:


Just put insert on the top.

18:04:23 HR@sandbox> create table t (k number, v number);

Table created.

Elapsed: 00:00:00.84
23:00:22 HR@sandbox> insert into t
23:00:34   2  with tt as (
23:00:39   3  select rownum, rownum*10 from dual
23:00:47   4  connect by rownum < 10
23:00:54   5  )
23:00:55   6  select * from tt
23:00:58   7  /

9 rows created.

Elapsed: 00:00:00.24


来源:https://stackoverflow.com/questions/17837750/oracle-11g-insert-select-with-with-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!