SQL server identity column values start at 0 instead of 1

后端 未结 6 1988
孤城傲影
孤城傲影 2020-12-01 20:40

I\'ve got a strange situation with some tables in my database starting its IDs from 0, even though TABLE CREATE has IDENTITY(1,1). This is so for some tables, but not for ot

相关标签:
6条回答
  • 2020-12-01 21:02

    From DBCC CHECKIDENT

    DBCC CHECKIDENT ( table_name, RESEED, new_reseed_value )
    

    If no rows have been inserted to the table since it was created, or all rows have been removed by using the TRUNCATE TABLE statement, the first row inserted after you run DBCC CHECKIDENT uses new_reseed_value as the identity. Otherwise, the next row inserted uses new_reseed_value + the current increment value.

    So, this is expected for an empty or truncated table.

    0 讨论(0)
  • 2020-12-01 21:04

    If you pass a reseed value the DB will start the identity from that new value:

    DBCC CHECKIDENT (SyncSession, RESEED, 0); --next record should be 0 + increment
    

    You don't have to pass the a value though, if you don't IDENTITY(a,b) will be used instead:

    DBCC CHECKIDENT (SyncSession, RESEED); --next record should be the seed value 'a'
    

    This is usually better practice, as it leaves the table closer to its initial created state.

    0 讨论(0)
  • 2020-12-01 21:06

    Try this

    DECLARE @c TABLE (TanvtechId varchar(10),NewTanvtechId Varchar(10))
    INSERT INTO @c
    SELECT TanvtechId , Row_Number() OVER (ORDER BY TanvtechId ) from Tanvtech 
    
    UPDATE G
    SET G.TanvtechId =a.NewTanvtechId 
    FROM Tanvtech as G INNER JOIN @c as a ON a.TanvtechId =G.TanvtechId 
    
    0 讨论(0)
  • 2020-12-01 21:07

    I have the same problem, restoring from a backup after modifying the DB. I just add a dummy record and then delete it... then set RESEED to 0. Seems to work.

    0 讨论(0)
  • 2020-12-01 21:14
    DBCC CHECKIDENT ( Table_Name, RESEED, 0 )
    

    This is a way to start an id with Zero(0), then delete all the rows from table and again put the data back into the table.

    0 讨论(0)
  • 2020-12-01 21:18

    This is logical, since you've changed (reseeded) the identity value to zero ?

    DBCC CHECKIDENT (SyncSession, reseed, 1)
    

    will reseed your identity column, and make sure that the first new record will start with 1.

    0 讨论(0)
提交回复
热议问题