Frage

Let's say I want to delete all records in a SQL Server table that were inserted over three months ago and keep the records inserted since then. We're dealing with many records on both sides of the three month period so I decided instead of running a DELETE with WHERE clause statement I will just insert everything into a temporary table, truncate the original table, and then insert all records from temporary table back into the original table.

But I want to keep all of the values from the Primary key ID column which are used by a Foreign key in another table. How can I keep from resetting the seed value as well as inserting everything where the ID column is the same for each record?

War es hilfreich?

Lösung

Drop the foreign Key and disable identity increment from the original table. Then do the above process you mentioned. That is

  1. Insert records into temp table - (insert - select whatever you want and also foreign key rows present in another table).
  2. Truncate original table.
  3. Insert records from temp table to original table (if there are lot of records, drop original table and rename temp table to original table name).
  4. Add foreign key constraint and enable identity property
  5. reseed the identity. - DBCC CHECKIDENT (yourtable, reseed, 10045)

10045 - corresponds to number of rows in temp table. So that identity seed start from 10046.

Hope this helps.

Andere Tipps

Try:

SET IDENTITY_INSERT OLD_TABLE ON;
GO
INSERT INTO OLD_TABLE ( ... columns, including ID ... )  
     SELECT ( ... columns, including ID ... )  FROM TEMP_TABLE;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top