How to delete all data from a database with T-SQL
Let’s assume you have a database messing around with sample data and want an easy and fast way to delete all data.
What you can use:
sp_MSforeachtable: Stored Procedure to perform same actions for all tables in the specified database
DELETE: Removes rows from a table or view. More here
TRUNCATE TABLE name: Identical to DELETE statement with no Where clause. Both removes all rows in a table but TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.
Have in Mind
You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint, so instead, use DELETE statement without a WHERE clause. The reason is that
TRUNCATE TABLE is not logged and it cannot activate a trigger.
-- Disable Referential Integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO
EXEC sp_MSForEachTable 'IF OBJECTPROPERTY(object_id(''?''), ''TableHasForeignRef'') = 1 DELETE FROM ? else TRUNCATE TABLE ? '
GO
-- Enable Referential Integrity Again
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
GO




