如何使用SQL for循环将行插入数据库? [英] How to use a SQL for loop to insert rows into database?

查看:151
本文介绍了如何使用SQL for循环将行插入数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Postgres,并且有很多行需要插入到数据库中,它们的区别仅在于递增的整数。原谅可能是一个愚蠢的问题,但我并不是数据库专家。 是否可以直接输入一个使用循环以编程方式插入行的SQL查询?

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;


推荐答案

希望我已经了解您的需求(在8.2):

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);

这篇关于如何使用SQL for循环将行插入数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆