简体   繁体   English

如何在SQL Server中为自动增量列指定特定值?

[英]How to specify a specific value for an auto increment column in SQL Server?

I have an auto increment identity column in sql server, but I want to specify a specific value for one of the rows. 我在sql server中有一个自动增量标识列,但我想为其中一行指定一个特定的值。 So the number scheme would be as follows: 所以号码方案如下:

1 ...,
2....,
999 - for the reserved entry,
3....,
n....

How can I do this? 我怎样才能做到这一点?

You need to use IDENTITY_INSERT : 您需要使用IDENTITY_INSERT

SET IDENTITY_INSERT MyTableName ON

INSERT INTO MyTableName
(IdField, <list of all the fields>)
VALUES
(999, <list of other values)

SET IDENTITY_INSERT MyTableName OFF

DBCC CHECKIDENT(MyTableName, RESEED, 2)

You also have to use the explicit field list in the INSERT statement, and are limited to one active IDENTITY_INSERT per session. 您还必须在INSERT语句中使用显式字段列表,并且每个会话仅限于一个活动IDENTITY_INSERT

This will also reset the seed value to be whatever you inserted if it's higher than the current ID value. 如果种子值高于当前ID值,这也会将种子值重置为您插入的内容。

You can get around this too by using DBCC CHECKIDENT but it'll be a big pain to manage. 您也可以使用DBCC CHECKIDENT来解决这个DBCC CHECKIDENT但要管理它将是一件非常痛苦的事情。

You can use IDENTITY_INSERT : 您可以使用IDENTITY_INSERT

SET IDENTITY_INSERT [tablename] ON;
INSERT INTO [tablename] (identitycolumn, ... ) VALUES (999, ...);
SET IDENTITY_INSERT [tablename] OFF;

Having to resort to this is always a code smell. 不得不求助于此始终是代码味道。 It is onyl acceptable as a data load practice for table population, or for replicating data. 作为表填充或复制数据的数据加载实践,它是可接受的。 For an app to 'reserve' IDs is aa bad practice and indicates a data model design flaw. 对于“保留”ID的应用程序是一种不好的做法,并指出数据模型设计缺陷。

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

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