Skip to content

Instantly share code, notes, and snippets.

@Davidblkx
Created October 30, 2020 14:18
Show Gist options
  • Save Davidblkx/4b3398366285db5e14ac0cdababc725a to your computer and use it in GitHub Desktop.
Save Davidblkx/4b3398366285db5e14ac0cdababc725a to your computer and use it in GitHub Desktop.
Delete all tables in a SQL SERVER database
DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_SCHEMA + '].[' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + '];'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec sp_executesql @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
EXEC sp_MSforeachtable 'DROP TABLE ?'
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment