Skip to main content

SQL Server script to delete all records from every table in a database. The script leverages the undocumented SQL Server Stored Procedure sp_msforeachtable to perform the commands on each table in the target database.

use <database_name>;
go

--
-- To disable all table constraints and triggers:
exec sp_msforeachtable
    @command1 = "print 'Disabling Constraints on ?.'",
    @command2 = "ALTER TABLE ? NOCHECK CONSTRAINT all";
go
exec sp_msforeachtable
    @command1 = "print 'Disabling Triggers in ?.'",
    @command2 = "ALTER TABLE ? DISABLE TRIGGER all";
go

--
-- To delete all data from tables:
exec sp_msforeachtable
    @command2 = "print 'Deleting or Truncating records on ?.'",
    @command1 = '
IF OBJECTPROPERTY(object_id(''?''), ''TableHasForeignRef'') = 1
    BEGIN
        DELETE FROM ?
    END
ELSE
    BEGIN
        TRUNCATE TABLE ?
    END';
go

--
-- To re-enable all table constraints and triggers:
exec sp_msforeachtable
    @command1 = "print 'Enabling Constraints on ?.'",
    @command2 = "ALTER TABLE ? CHECK CONSTRAINT all";
go
exec sp_msforeachtable
    @command1 = "print 'Enabling Triggers in ?.'",
    @command2 = "ALTER TABLE ? ENABLE TRIGGER all";
go

-- -----------
--  Optional
-- -----------

--
-- To RESEED table identity values to '1':
-- exec sp_msforeachtable
--     @command1 = "print 'Reseeding ? table identity value to ""1"" (if table has ident.).'",
--     @command2 = '
-- IF OBJECTPROPERTY(object_id(''?''), ''TableHasIdentity'') = 1
-- BEGIN
--     DBCC CHECKIDENT (''?'', RESEED, 1)
-- END';
-- go