序列作为列的默认值
我已经创建了一个序列:
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
)
结果很简单:
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的更正!)
ALTER语句不完整。 它需要另一个FOR子句来将默认值分配给所需的字段。
ALTER TABLE mytable
ADD CONSTRAINT DF_mytblid
DEFAULT (NEXT VALUE FOR mainseq) FOR [id]
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)
)
