我可以通过设置序列并将表列默认值设置为该序列来创建自动增量,但我仍然可以手动输入一个不是该序列的值。 我如何在插入时对此执行约束? 唯一使用触发器的方法是?
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
更多推荐
发布评论