简体   繁体   English

SQL Server自动增加没有主键的列

[英]SQL Server auto increment a column without primary key

Is it possible to auto increment a column in SQL Server WITHOUT it being a primary key? 是否可以在没有作为主键的情况下自动递增SQL Server中的列?

If yes how can this be done. 如果是的话,该怎么做。

Thanks 谢谢

Yes. 是。 There is no requirement that IDENTITY columns be made a primary key. 不需要将IDENTITY列设置为主键。

CREATE TABLE T
(
X INT PRIMARY KEY,
Y INT IDENTITY(1,1)
)

Though I'm not sure when this would be useful. 虽然我不确定这何时会有用。 If you have a natural key that you want to use as the PK then you would probably want to put a unique constraint on the surrogate alternate key anyway. 如果您有一个要用作PK的自然键,那么您可能无论如何都要对代理替代键施加唯一约束。

For purposes of setting up FK relationships SQL Server doesn't care if the column(s) is the PK or not it just requires a unique index on it/them. 出于建立FK关系的目的,SQL Server不在乎列是否为PK,它只需要在其上具有唯一索引即可。

用IDENTITY关键字声明该列,并且仅不要在其上创建PRIMARY KEY约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM