tags:

views:

84

answers:

3

I'm using Postgres, and I have a large number of rows that need to be inserted into the database, that differ only in terms of an integer that is incremented. Forgive what may be a silly question, but I'm not much of a database guru. Is it possible to directly enter a SQL query that will use a loop to programatically insert the rows?

Example in pseudo-code of what I'm trying to do:

for i in 1..10000000 LOOP
  INSERT INTO articles VALUES(i)
end loop;
+2  A: 

Afaik, you can't write a loop directly as SQL, you'd have to create a stored procedure to do it.

This will do though (but someone can probably make it cleaner)

INSERT INTO articles WITH RECURSIVE i AS
(
 SELECT 1 x
  UNION ALL
 SELECT x + 1
  FROM i
 WHERE x < 10000000 
)
 SELECT x
 FROM i;
nos
The [recursive WITH is 8.4+](http://www.postgresql.org/docs/8.4/static/queries-with.html), but there's [nothing in the documentation about supporting it in an INSERT statement](http://www.postgresql.org/docs/9.0/static/sql-insert.html). That's not necessarily definitive...
OMG Ponies
OP confirmed using v8.3, can't use recursive WITH :(
OMG Ponies
+2  A: 

In SQL Server you can do:

DECLARE @i int
SET @i = 1

WHILE @i<1000000
    BEGIN
        INSERT INTO articles
        VALUES @i
        SET @i=@i+1
    END
JNK
Someone like OMGPonies can tell us if this will work in postgre
JNK
My pgPLSQL is weak, but: http://www.linuxtopia.org/online_books/database_guides/Practical_PostgreSQL_database/PostgreSQL_x20238_002.htm I'd use the recursive WITH if possible (like you see in nos' answer), but I don't have an instance to test so it looks like a loop is required (for prior to 8.4, at a minimum). But with PostgreSQL v9 adding anonymous pgPLSQL blocks (finally, dunno how long Oracle supported), it's easier for one time use.
OMG Ponies
+4  A: 

Hopefully I've understood what you need (tested on 8.2):

INSERT INTO articles (id, name) SELECT x.id, 'article #' || x.id FROM generate_series(1,10000000) AS x(id);
Milen A. Radev