20

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)

3
  • So, if multiple rows in value_list for the same id have val >= 50, do you want run row for that id in attribute_list? Commented Apr 17, 2012 at 19:41
  • @ShannonSeverance Cool question. I assume if I only wanted it to once I'd just select unique ids with a sub-select. Commented Apr 17, 2012 at 21:38
  • 1
    Or select distinct id, 'Y', 'is_leveled' from .... Commented Apr 17, 2012 at 22:41

4 Answers 4

37

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
Sign up to request clarification or add additional context in comments.

Comments

5

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;

2 Comments

I think this missed the point of the question. It inserts multiple values, but not with a single statement.
I consider these one line inserts convenient shorthands for the real thing: the loop. As soon as things get only mildly interesting, you have to loop anyway.
2

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.