How to use a SQL for loop to insert rows into database?

前端 未结 3 591
攒了一身酷
攒了一身酷 2020-12-23 11:22

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

相关标签:
3条回答
  • 2020-12-23 12:05

    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;
    
    0 讨论(0)
  • 2020-12-23 12:11

    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);
    
    0 讨论(0)
  • 2020-12-23 12:12

    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
    
    0 讨论(0)
提交回复
热议问题