CREATE SEQUENCE sequencename
[ INCREMENT increment ] -- 自增数,默认是 1
[ MINVALUE minvalue ] -- 最小值
[ MAXVALUE maxvalue ] -- 最大值
[ START start ] -- 设置起始值
[ CACHE cache ] -- 是否预先缓存
[ CYCLE ] -- 是否到达最大值的时候,重新返回到最小值
例如:
首先要有create sequence
或者create any sequence权限
1、创建sequence seq_1
create sequence seq_1
INCREMENT BY 1
START WITH 1
no MAXVALUE
cycle;
CREATE SEQUENCE
2、创建表格t1,id为自增序列。
create table t1(id int default nextval ('seq_1'),name text);
CREATE TABLE
3、创建触发器表t2,记录t1表中发生insert和update的时间。
create table t2(
update_time timestamp,
db_user varchar(40),
opr_type varchar(6)
);
4、创建触发器函数
create function log_trigger()
returns trigger as
$$
begin
insert into t2 values(now(),user,TG_OP);
return null;
end;
$$
language "plpgsql";
5、创建触发器
create trigger log_trigger
after insert or delete or update on t1
for statement execute procedure log_trigger();
6、向t1中插入数据
insert into t1 (name) values ('tony');
INSERT 0 1
insert into t1 (name) values ('tom');
INSERT 0 1
select * from t1
id | name
----+------
1 | tony
2 | tom
(2 rows)
select * from t2;
update_time | db_user | opr_type
----------------------------+----------+----------
2017-02-20 15:34:22.928945 | postgres | INSERT
2017-02-20 15:34:35.828583 | postgres | INSERT
(2 rows)
触发器问题
最新推荐文章于 2023-08-16 20:26:47 发布