Click here to Skip to main content
15,867,594 members
Articles / Programming Languages / SQL
Alternative
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.67/5 (2 votes)
21 Dec 2010CPOL 19.5K   3   1
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:

SQL
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:

SQL
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)


Written By
Software Developer (Senior)
Belgium Belgium
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionidentity column Pin
paddy_ya27-Sep-13 1:13
paddy_ya27-Sep-13 1:13 

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

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