Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL insert into with With clause

I'm new to sql, so maybe it is a dumb question, but is there any possibility to use With clause with Insert Into? Or are there any common workarounds? I mean something like this:

With helper_table As ( Select * From dummy2 ) Insert Into dummy1 Values (Select t.a From helper_table t Where t.a = 'X' ); 

Thx!

My example is too dummy, so I add some extended code (thx for the answers so far).

INSERT INTO    dummy values (a,b)  //more values WITH    helper_table AS     (     SELECT  *     FROM    dummy2     ) WITH    helper_table2 AS   //from more tables     (     SELECT  *     FROM    dummy3     )          SELECT  t.value as a, t2.value as b FROM    helper_table t  join helper_table t2 on t.value = t2.value //some join WHERE   t.value = 'X' and t2.value = 'X'   //other stuff 
like image 292
user2424380 Avatar asked May 04 '11 14:05

user2424380


People also ask

Can we use insert with where clause?

You cannot use Where Clause with INSERT Statement.

Can we use where clause in insert statement in Oracle?

The Oracle INSERT INTO SELECT statement requires the data type of the source and target tables match. If you want to copy all rows from the source table to the target table, you remove the WHERE clause. Otherwise, you can specify which rows from the source table should be copied to the target table.

Can we use insert and select together?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

Can we use function of WITH clause in Oracle?

Defining functions in the WITH clause is now possible in Oracle 12c. It's one of the many new features in this version that are useful for developers. You can define these functions which are just used by your query.


2 Answers

You may use as many 'helper_tables' as you wish.

create table t(helper1 varchar2(50) , helper2 varchar2(50) , dataElement varchar2(50) );   insert into t(helper1, helper2, dataelement) with      de as(select level lvl from dual connect by level <10)      ,h1 as (select lvl, lvl/1.5 hp from de)      ,h2 as (select lvl,  lvl/2 hp2 from de) select h1.hp , h2.hp2, de.lvl   from de          inner join        h1 on de.lvl = h1.lvl         inner join        h2 on de.lvl = h2.lvl / 

With this in mind, you may be able to do all of your joins via normal joining of the tables to the master table

like image 183
Harrison Avatar answered Sep 23 '22 00:09

Harrison


INSERT INTO    dummy1 WITH    helper_table AS         (         SELECT  *         FROM    dummy2         ) SELECT  t.a FROM    helper_table t WHERE   t.a = 'X' 
like image 35
Quassnoi Avatar answered Sep 25 '22 00:09

Quassnoi