Search code examples
sql-server-2012identitytemp-tables

How to store table rows in a temp table


I have a table with around 600000 records. I want to reseed the identity column of this table. Here's my plan:

  1. Store contents of this table in temp table
  2. Delete all records from this table
  3. Reseed identity
  4. Insert records from that temp table into this one

So how do I store this table into a temp one?


Solution

  • If there is nothing else behind the scene then try this:

    SET IDENTITY_INSERT TABLE_NAME ON
    GO
    
    UPDATE  CTE
    SET     ID = RN
    FROM
    (
        SELECT  ID, ROW_NUMBER() OVER(ORDER BY ID) AS RN
        FROM    TABLE_NAME
    ) AS CTE
    
    SET IDENTITY_INSERT TABLE_NAME OFF
    GO
    
    DBCC CHECKIDENT('TABLE_NAME', RESEED, 600001)
    GO