Skip to content

Instantly share code, notes, and snippets.

@richardkundl
Last active March 14, 2023 20:04
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save richardkundl/ec3849fe2d62741f77ec to your computer and use it in GitHub Desktop.
Save richardkundl/ec3849fe2d62741f77ec to your computer and use it in GitHub Desktop.
Drop all tables in a SQL Server database (Azure Friendly!)
-- original source: http://edspencer.me.uk/2013/02/25/drop-all-tables-in-a-sql-server-database-azure-friendly/
-- drop all constraint
while(exists(select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='FOREIGN KEY'))
begin
declare @sql1 nvarchar(2000)
SELECT TOP 1 @sql1=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME
+ '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
FROM information_schema.table_constraints
WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
exec (@sql1)
PRINT @sql1
end
GO
-- drop all table
while(exists(select 1 from INFORMATION_SCHEMA.TABLES where TABLE_NAME != '__MigrationHistory'))
begin
declare @sql2 nvarchar(2000)
SELECT TOP 1 @sql2=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME
+ ']')
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME != '__MigrationHistory'
exec (@sql2)
PRINT @sql2
end
@uxweb
Copy link

uxweb commented Aug 29, 2017

I think that both queries must be filtered to only drop user tables and constraints. The second query will try to delete sys objects.

@uxweb
Copy link

uxweb commented Aug 29, 2017

while(exists(select 1 from INFORMATION_SCHEMA.TABLES where TABLE_NAME != '__MigrationHistory' and TABLE_SCHEMA = 'dbo'))
begin
 declare @sql nvarchar(2000)
 SELECT TOP 1 @sql=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME
 + ']')
 FROM INFORMATION_SCHEMA.TABLES
 WHERE TABLE_NAME != '__MigrationHistory'
     AND
 TABLE_SCHEMA = 'dbo'
exec (@sql)
 PRINT @sql
end

@mexmirror
Copy link

The schema must be inside square brackets as well. In my case the schema name "Identity" could not be deleted without it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment