Jeremy
Jeremy

Reputation: 5433

Oracle SQL -- insert multiple rows into a table with one statement?

I'd like to do insert N rows that are all identical, except one of the values is different. Specifically, this is what I am trying:

insert into attribute_list (id,value,name)
values 
(
select (id,'Y','is_leveled') from value_list where val >= 50
);

So for every value that has a val >= 50, I would insert one row into attribute_list. Can this be done with one insert statement or should I just manually generate these inserts in excel?

(note: this is a cooked example simplified to clarify the issue, so no need to attack the needlessness of this specific case)

Upvotes: 20

Views: 61704

Answers (4)

Pavel Veller
Pavel Veller

Reputation: 6105

You need an INSERT from SELECT. To do so you should omit the VALUES and just do:

insert into attribute_list (id,value,name)
select (id,'Y','is_leveled') from value_list where val >= 50;

Here's an example: http://psoug.org/reference/insert.html

Upvotes: 2

nes1983
nes1983

Reputation: 15756

That is what FOR loops are for.

DECLARE
   x NUMBER := 100;
BEGIN
   FOR i IN 1..10 LOOP
      IF MOD(i,2) = 0 THEN     -- i is even
         INSERT INTO temp VALUES (i, x, 'i is even');
      ELSE
         INSERT INTO temp VALUES (i, x, 'i is odd');
      END IF;
      x := x + 100;
   END LOOP;
   COMMIT;
END;

Upvotes: 5

mwigdahl
mwigdahl

Reputation: 16588

You can absolutely do this in a single statement!

Try this:

INSERT INTO attribute_list (id, value, name)
SELECT id, 'Y', 'is_leveled'
FROM value_list WHERE val >= 50

Upvotes: 37

GavinCattell
GavinCattell

Reputation: 3963

You can do a SELECT ... INTO if you can query the data. Otherwise to create data you'd need to use PL/SQL

If you have the data then try:

select id,'Y','is_leveled'
INTO attribute_list 
from value_list where val >= 50

Upvotes: 1

Related Questions