Skip to content

Instantly share code, notes, and snippets.

@hunty
Created April 5, 2019 09:23
Show Gist options
  • Save hunty/15145923b12cf51c4a205c97df0e2c5b to your computer and use it in GitHub Desktop.
Save hunty/15145923b12cf51c4a205c97df0e2c5b to your computer and use it in GitHub Desktop.
Delete all tables in database ignoring costraints
USE YOUR_DATABASE_NAME
-- Disable all referential integrity constraints
EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO
-- Drop all PKs and FKs
declare @sql nvarchar(max)
SELECT @sql = STUFF((SELECT '; ' + 'ALTER TABLE ' + Table_Name +' drop constraint ' + Constraint_Name from Information_Schema.CONSTRAINT_TABLE_USAGE ORDER BY Constraint_Name FOR XML PATH('')),1,1,'')
EXECUTE (@sql)
GO
-- Drop all tables
EXEC sp_MSforeachtable 'DROP TABLE ?'
GO
-- see in https://stackoverflow.com/a/39523139/6263057
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment