【问题标题】:Sequence as default value for a column序列作为列的默认值
【发布时间】:2019-09-26 16:05:17
【问题描述】:

我已经创建了一个序列:

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
)

【问题讨论】:

    标签: sql-server tsql sql-server-2012 sequence


    【解决方案1】:

    事实证明这很容易:

    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 的更正!)

    【讨论】:

    • 就像一个对某些人来说可能非常明显的小注释......因为它使用default,它仅适用于您不提供值或null。用户仍然可以通过在查询中提供值来覆盖自动序列值。
    • 有什么办法可以强制使用默认值?
    • @MattiasNordqvist 使用identity
    【解决方案2】:

    ALTER 语句并不完整。它需要另一个 FOR 子句来将默认值分配给所需的字段。

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

    【讨论】:

      【解决方案3】:
      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)
      )
      

      【讨论】:

      • 您的答案如何显示将序列用作列默认值?
      • 这不是序列这是内置的身份。
      猜你喜欢
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      • 2017-08-12
      • 2016-08-03
      相关资源
      最近更新 更多