2

The script below creates a table, temporarily turns off auto identity, inserts records whilst specifying the PK value, then re-enables auto identity.

DROP TABLE Foo;
GO

CREATE TABLE Foo (Id int IDENTITY (1,1) NOT NULL, 
                  Bar nvarchar(100) NOT NULL);
GO

ALTER TABLE Foo ADD CONSTRAINT FooConstraint PRIMARY KEY (Id);
GO

SET IDENTITY_INSERT Foo ON;
GO

INSERT INTO Foo(Id, Bar) VALUES (1, 'a');
GO
INSERT INTO Foo(Id, Bar) VALUES (2, 'b');
GO
INSERT INTO Foo(Id, Bar) VALUES (3, 'c');
GO

SET IDENTITY_INSERT Foo OFF;
GO

INSERT INTO Foo(Bar) VALUES ('d');
GO

Problem is that last insert - it complains that

A duplicate value cannot be inserted into a unique index. [ Table name = Foo,Constraint name = FooConstraint ]

This is unexpected. What am I doing wrong?

h bob
  • 3,610
  • 3
  • 35
  • 51
  • Don't get too cozy with Compact; [it has been deprecated and there are better options](http://stackoverflow.com/a/20364011/61305). – Aaron Bertrand Aug 21 '15 at 00:42
  • 1
    @AaronBertrand We still use it, and will continue to do so because it's very convenient. The db is just a file, which I can copy around. I am sure MS will restart support in some fashion, as it makes no sense to not have an in-process/single-file db engine for their platform. If it dies completely at some point, we'll just move to SQLite. – h bob Aug 21 '15 at 06:20

1 Answers1

2

You need to reset the seed like this

ALTER TABLE [Foo] ALTER COLUMN [Id] IDENTITY (4, 1)
ErikEJ
  • 40,951
  • 5
  • 75
  • 115