我如何在postgres中执行自动增量?(How do I enforce an auto increment in postgres?)

编程入门 行业动态 更新时间:2024-10-28 10:32:27
我如何在postgres中执行自动增量?(How do I enforce an auto increment in postgres?)

我可以通过设置序列并将表列默认值设置为该序列来创建自动增量,但我仍然可以手动输入一个不是该序列的值。 我如何在插入时对此执行约束? 唯一使用触发器的方法是?

I can create an auto increment by setting a sequence and setting a tables column default value to be that sequence, but I can still manually enter a value that is not that sequence. How can I enforce a constraint to this on insert? Is using a trigger the only way?

最满意答案

这有帮助吗?

我测试过了,只要它的UNIQUE就可以插入主键。 如果它的Null自动序列踢入( tablename_colname_seq )并插入一个UNIQUE主键。

-- Table: test CREATE SEQUENCE tablename_colname_seq; CREATE TABLE foo( primary_id int not null UNIQUE default nextval('tablename_colname_seq'), a_nother int ) WITH ( OIDS=FALSE );

ALTER TABLE foo所有者postgres;

- 测试数据

insert into foo (primary_id) values(14) insert into foo (a_nother) values(13); select * from foo;

祝一切顺利

Does this help?

Ive tested this and you can insert the primary key as long as its UNIQUE. If its Null the auto sequence kicks in (tablename_colname_seq) and inserts a UNIQUE primary key.

-- Table: test CREATE SEQUENCE tablename_colname_seq; CREATE TABLE foo( primary_id int not null UNIQUE default nextval('tablename_colname_seq'), a_nother int ) WITH ( OIDS=FALSE );

ALTER TABLE foo OWNER TO postgres;

-- Test Data

insert into foo (primary_id) values(14) insert into foo (a_nother) values(13); select * from foo;

All the best

更多推荐

本文发布于:2023-08-02 13:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1377001.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:增量   如何在   postgres   increment   enforce

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!