在SQL Server 2008中为零主键

Nit*_*esh 2 sql sql-server-2008

是否可以0在SQL Server 2008中的表的主键字段中插入?

Ian*_*nry 6

只要它是一个数字领域,是的......跟在家里!

create table TestTable
(
    TestColumn int not null primary key
)

insert TestTable values(0)
Run Code Online (Sandbox Code Playgroud)

primary key限制只规定值是唯一的,列不为空.

对于一个identity领域:

create table TestTable
(
    TestColumn int identity(1, 1) not null primary key --start at 1
)

set identity_insert TestTable on
insert TestTable (TestColumn) values (0) --explicitly insert 0
set identity_insert TestTable off
Run Code Online (Sandbox Code Playgroud)

identity(1, 1)指"每一个东西被插入的时间开始于一个增量".您可能必须identity(-100, 10)从每次开始-100并递增10.或者你可以从0.没有限制.

您通常可以通过尝试它们并查看它们是否有效来回答这些问题.这比在StackOverflow上询问更快,通常更有益.