WBAR
WBAR

Reputation: 4984

Oracle 11g: INSERT SELECT with WITH statement

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

Upvotes: 1

Views: 8172

Answers (2)

planben
planben

Reputation: 700

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);

Upvotes: 3

Kirill Leontev
Kirill Leontev

Reputation: 10931

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

Upvotes: 1

Related Questions