重要的是要认识到,尽管它们经常一起出现,IDENTITY
并且PRIMARY KEY
是两个正交的概念1。因此,对于所提出的问题,答案是否定的 - 因为IDENTITY
列将很乐意提供已在同一列中使用的值:
set nocount on
go
create table II (
ID int IDENTITY(1,1) not null,
Value varchar(10) not null
)
insert into II(Value) values ('abc'),('def')
set identity_insert II on
insert into II(ID,Value) values (6,'ghi')
set identity_insert II off
select * from II
insert into II(Value) values ('jkl')
select * from II
GO
dbcc checkident (II, RESEED, 5);
GO
insert into II(Value) values ('mno'),('pqr')
select * from II
结果:
ID Value
----------- ----------
1 abc
2 def
6 ghi
ID Value
----------- ----------
1 abc
2 def
6 ghi
7 jkl
Checking identity information: current identity value '7'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
ID Value
----------- ----------
1 abc
2 def
6 ghi
7 jkl
6 mno
7 pqr
而PRIMARY KEY
如果您尝试插入重复值 a 会抱怨:
create table III (
ID int IDENTITY(1,1) not null PRIMARY KEY,
Value varchar(10) not null
)
insert into III(Value) values ('abc'),('def')
set identity_insert III on
insert into III(ID,Value) values (6,'ghi')
set identity_insert III off
select * from III
insert into III(Value) values ('jkl')
select * from III
GO
dbcc checkident (III, RESEED, 5);
GO
insert into III(Value) values ('mno'),('pqr')
select * from III
go
(与上一个脚本唯一不同的是表名和添加的PRIMARY KEY
)
结果:
ID Value
----------- ----------
1 abc
2 def
6 ghi
ID Value
----------- ----------
1 abc
2 def
6 ghi
7 jkl
Checking identity information: current identity value '7'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK__III__3214EC27FCCBBCB7'. Cannot insert duplicate key in object 'dbo.III'. The duplicate key value is (6).
The statement has been terminated.
ID Value
----------- ----------
1 abc
2 def
6 ghi
7 jkl
1经常与这两者混为一谈的第三个概念是聚簇索引。一个表完全有可能有一个主键、一个标识列和一个没有共同列的聚集索引。