我在 sql server 中有一个自动增量标识列,但我想为其中一行指定一个特定值。所以编号方案如下:
1 ...,
2....,
999 - for the reserved entry,
3....,
n....
我怎样才能做到这一点?
我在 sql server 中有一个自动增量标识列,但我想为其中一行指定一个特定值。所以编号方案如下:
1 ...,
2....,
999 - for the reserved entry,
3....,
n....
我怎样才能做到这一点?
您需要使用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
但管理起来会很痛苦。
您可以使用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.