PostgreSQL 如何写一段简单的循环语句

比如,我要连接插入100条数据。借鉴其它sql的写法不能用
纠正:是我要连续插入数据,类似

declare @i int
set @i=1
while @i<30
begin
insert into test (userid) values(@i)
set @i=@i+1
end

工具/材料:Management Studio。 

1、首先在桌面上,点击“Management Studio”图标。 

2、再者在该界面中,点击左上角“新建查询”选项。 

3、继续在该界面中,输入循环增加新数据sql语句“declare @i int set @i=1 while @i<100 begin insert into test1(no,name)values(@i,'用户名') set @i=@i+1 end”。 

4、再者在该界面中,点击左上方“执行”按钮。 

5、最后在该界面中,显示循环增加新数据成功。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-10-03

PostgreSQL中一般使用PL/PgSQL作为其编程语句,其语法与SQL Server / MySQL的有些不同。要实现这样的功能可以这样写(注意:分号不能少掉):

do $$
declare
v_idx integer := 1;
begin
  while v_idx < 30 loop
    insert into test (userid) values (v_idx);  -- 执行插入
  end loop;
end $$;

本回答被提问者和网友采纳
第2个回答  推荐于2017-10-01
create or replace function aa1(a1 char(10),a2 bigint) returns
void AS $$
declare ii integer;
begin
II:=1;
FOR ii IN 1..a2 LOOP
insert into user1 values(ii,a1);
end loop;
end;
$$ LANGUAGE plpgsql;

select aa1('a123',10)
or
create or replace function aa2(a1 char(10),a2 bigint) returns SETOF user1 AS $$
declare ii integer;
begin
II:=1;
FOR ii IN 1..a2 LOOP
insert into user1 values(ii,a1);
end loop;
return query SELECT * FROM user1;
end;
$$ LANGUAGE plpgsql;

select * from aa2('a123',20)
相似回答