Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

How to Reset Identity Column Value In SQL Server without Delete Records.

4.29/5 (3 votes)
17 Dec 2010CPOL 20.9K  
You have deleted some records from different record position from your identity column table and you wan to reset it without delete records.
Remove foreign key reference (if any) from YourTabe and set Is Identity to No in column properties windows in Microsoft SQL Server Management Studio. Execute the bellow SQL using Management Studio.

SQL
USE YourDataBase

SELECT [YourTableId],ROW_NUMBER() OVER (ORDER BY YourTableId ) AS RowNumber
    into #tempTable from [YourTable]

DECLARE your_table_cursor CURSOR FOR
    SELECT [YourTableId], RowNumber
    FROM #tempTable

OPEN your_table_cursor

DECLARE @YourTableId int
DECLARE @RowNumber int

FETCH NEXT FROM your_table_cursor
INTO @YourTableId, @RowNumber

WHILE @@FETCH_STATUS = 0
BEGIN
    UPDATE  [YourTable]
        SET [YourTableId] = @RowNumber
        WHERE [YourTableId] = @YourTableId

    FETCH NEXT FROM your_table_cursor
    INTO @YourTableId, @RowNumber
END


CLOSE your_table_cursor
DEALLOCATE your_table_cursor

DROP TABLE #tempTable 


Set Is Identity to Yes and set Identity increment to 1 and Identity Seed to 1 in column properties windows in Management Studio. Then set reference.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)