将序列作为列的默认值

23

我已经创建了一个序列:

create sequence mainseq as bigint start with 1 increment by 1

我该如何将这个序列用作一列的默认值?

create table mytable(
    id      bigint not null default mainseq     -- how?
    code    varchar(20) not null
)
3个回答

46

结果证明,这相当容易:

create table mytable (
    id      bigint not null constraint DF_mytblid default next value for mainseq,
    code    varchar(20) not null
)

或者如果表已经创建:

alter table mytable
add constraint DF_mytblid
default next value for mainseq
for id

(感谢Matt Strom的纠正!)


2
只是一个小注释:因为它使用了“default”,所以仅在您未提供值或null时适用。用户仍然可以通过在查询中提供值来覆盖自动序列值。 - Adam Plocher
2
有没有办法强制使用默认值? - Mattias Nordqvist
1
@MattiasNordqvist 使用 identity - Andre Figueiredo

13

ALTER语句还不够完整,需要添加另一个FOR子句来将默认值分配给所需的字段。

ALTER TABLE mytable
ADD CONSTRAINT DF_mytblid
DEFAULT (NEXT VALUE FOR mainseq) FOR [id]

-4
create table users(
    u_id int identity(1,1) primary key,
    u_type varchar(30) default 'member', 
    entrydate datetime default (getdate()), 
    updatedate  datetime default (getdate()),
    isactive bit default 1,
    firstname varchar(30),
    lastname varchar(30),
    email varchar(50),
    password varchar(50)
)

2
你的回答如何展示序列作为列默认值的用法? - dreamca4er
8
这不是一个序列,而是内置的身份标识。 - Damon Drake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接