MS SQL - Truncate table with foreign key constraints

By xngo on October 15, 2019

In MS SQL server, the typical process to truncate a table is to do the followings:

  1. Drop the table constraints.
  2. Truncate the table.
  3. Recreate the constraints.

An easier way to do this is to use the DELETE statement. It doesn't require you to find out what are the foreign key constraints and write SQL statements to recreate those constraints. However, it is very slow. It will iterate through each record. Don't do this if you have millions of records.

DELETE FROM TABLENAME
DBCC CHECKIDENT ('DATABASENAME.dbo.TABLENAME', RESEED, 0)

Batch delete

If you are getting the following error:

The transaction log for database 'DATABASENAME' is full due to 'ACTIVE_TRANSACTION'.

Then, you should consider delete in batch by including a WHERE clause. For example,

DELETE FROM TABLENAME WHERE ID < 7000
DBCC CHECKIDENT ('DATABASENAME.dbo.TABLENAME', RESEED, 0);
 
DELETE FROM TABLENAME WHERE ID < 17000
DBCC CHECKIDENT ('DATABASENAME.dbo.TABLENAME', RESEED, 0);
 
DELETE FROM TABLENAME WHERE ID < 87000
DBCC CHECKIDENT ('DATABASENAME.dbo.TABLENAME', RESEED, 0);

Log_backup is full

Using the DELETE statement will generate a lot of logs. It might fill up your log_backup file. Then, it will throw the following error message:

The transaction log for database 'DATABASENAME' is full due to 'LOG_BACKUP'.

To resolve this issue, flush the log file with the following statements.

USE DATABASENAME
 
ALTER DATABASE DATABASENAME
SET RECOVERY SIMPLE
GO
 
DBCC SHRINKFILE('DATABASENAME_log', 1)
GO
 
ALTER DATABASE DATABASENAME
SET RECOVERY FULL
GO

For more details, see MS SQL - Error - The transaction log for database 'DATABASENAME' is full due to 'LOG_BACKUP'.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.