2

我在 sql server 中有一个自动增量标识列,但我想为其中一行指定一个特定值。所以编号方案如下:

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

我怎样才能做到这一点?

4

2 回答 2

6

您需要使用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)

您还必须在语句中使用显式字段列表,并且每个会话INSERT限制为一个活动字段。IDENTITY_INSERT

如果种子值高于当前 ID 值,这也会将种子值重置为您插入的任何值。

你也可以通过使用来解决这个问题,DBCC CHECKIDENT但管理起来会很痛苦。

于 2012-04-18T17:04:55.667 回答
5

您可以使用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 a a bad practice and indicates a data model design flaw.

于 2012-04-18T17:06:03.987 回答