Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

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

, 21 Dec 2010
Rate this:
Please Sign up or sign in to vote.
Some considerations:- Use a table variable instead of #tempTable. Temporary tables create an actual table in the temp database, that needs to be dropped afterwards. When something bad happens, the table will not be dropped.- Use a FAST_FORWARD cursor, when it is read-only. For large tables,...
Some considerations:
- Use a table variable instead of #tempTable. Temporary tables create an actual table in the temp database, that needs to be dropped afterwards. When something bad happens, the table will not be dropped.
- Use a FAST_FORWARD cursor, when it is read-only. For large tables, it performs a lot better.
- Try not to use a cursor. Cursors are the last option to consider.
- Try not to update table design. Resetting identity columns and foreign key constraints are easely forgotten after code like this. Have a look at the query SQL management studio performs when doing a table design change(it creates another table, and uses a transaction).
 
A better performing query (without my last consideration in mind) would be:
 
USE YourDataBase
 
DECLARE @TmpTable TABLE (id int, rowNumber int)
 
INSERT INTO @TmpTable
SELECT Id,ROW_NUMBER() OVER (ORDER BY Id ) AS RowNumber FROM MyTable
 
UPDATE MyTable SET ID = tmp.rowNumber
FROM MyTable t
INNER JOIN @TmpTable tmp ON tmp.id = t.ID
 
Or without variables:
 
WITH cte_Temp(Id, RowNumber)
AS
(
    SELECT Id,ROW_NUMBER() OVER (ORDER BY Id ) AS RowNumber FROM MyTable
)
UPDATE MyTable SET ID = tmp.rowNumber
FROM MyTable t
INNER JOIN cte_Temp tmp ON tmp.id = t.ID

License

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

About the Author

Eskern
Software Developer (Senior)
Belgium Belgium
No Biography provided

Comments and Discussions

 
Questionidentity column Pinmemberpaddy_ya27-Sep-13 1:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 21 Dec 2010
Article Copyright 2010 by Eskern
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid