Postgresql - 初识SQL Functions - 向表中循环插入实验数据

SQL Function可以实现很多强大的功能。

我们先来认识一下简单的SQL Function。向一张表中插入数据。

环境:CentOS 7 + PG11 (使用新版本来做实验,与其他版本并无太大差别)

先建立表,

create sequence test01_id_seq;

create table test01 (id int default nextval('test01_id_seq') primary key, col1 varchar(20) not null , i_time timestamp without time zone default now );

建立Function

create or replace function insert_test01(x int) --定义函数名称,以及传入的参数及其类型

returns void as $$

declare i int; -- 定义函数内使用的变量

begin -- function开始

i:=1; -- 定义函数中使用的变量

for i in 1..x loop -- 循环开始

insert into test01(col1, i_time) values( repeat('abcde',2), now()); -- 向表中插入数据

i = i+1;

end loop; -- 循环结束

end; -- function结束

$$ language plpgsql; -- 说明语言类型

运行function

mytest=# select insert_test01(1000);

insert_test01

---------------

(1 row)

猜你喜欢

转载自blog.csdn.net/chuckchen1222/article/details/81912307