Reputation: 5433
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
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
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
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
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