默認值我已經創建了一個序列:順序爲列
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 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
(謝謝你,馬特·斯特羅姆的指正!)
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)
)
您的答案如何顯示用法一個序列作爲列的默認值? – dreamca4er
這不是一個內置身份的序列。 –
就像一個小紙條,可能是非常明顯的一些...因爲它使用'default',它僅適用,如果你不提供值或'null'。用戶仍然可以通過在查詢中提供值來覆蓋自動序列值。 –
有什麼辦法可以強制使用默認的? –
@MattiasNordqvist使用[identity](https://docs.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property) –