Step 1: Create Table
CREATE TABLE [dbo].[AAA](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [nchar](10) NOT NULL,
[last] [nchar](10) NOT NULL)
Step 2: Insert Correct Value
insert into aaa values ('lkj', 'lkj')
This will Generate ID - 1
Step 3: Try to Insert Incorrect Value
insert into aaa values ('lkj', NULL)
This will error and no record will be inserted
Step 4:
insert into aaa values ('lkj', 'lkj')
This will insert again, But ID generated will be - 3 (Not 2) Because ID 2 was generated at Step 3 but no record was inserted.
I want that when I next enter any record ID generated should be 2 and not 3. I have searched and found solution for MySQL below, but I want it in SQL Server:
alter table tablename auto_increment =1
OR
alter table tablename auto_increment =#
Also there is another solution I found...
declare @max int;
select @max = max(key) from table;
dbcc checkident(table,reseed,@max)
This code is good and it works. But I have to execute this every time there is a skipped ID... Isn't there a permanent fix for this problem? I want something like "execute it once and then forget about it..." I am facing this problem on production server so I want a permanent solution. I am using entity framework for inserting data so i cant use this query every time.
Please let me know any way to fix it. Either in SQL Server 2012 or in Entity Framework 6. Thanks in Advance.