75

I have an ASP.NET MVC 5 project that works local and whenever I need to blow away the DB, I just open a new query on it, change the available database dropdown to master, then close the connection on my local db and run the query "drop database [name]". Then I build the project, go into the package manager console and run "Update-Database". This seems to rebuild a fresh local database and runs the seed method in my configuration.cs file.

The problem is when I need to test things in a live environment so I can test API's and such better, I will do a deploy to an Azure Website and the accompanying Azure DB, which is nice and easy to do. I check off the "Execute code first migrations" in the publish wizard and most of the time it works and I can run and debug my live version. Sometimes I need to blow away that db and start from scratch again, but the only way I've really found to do it is to go into the Azure portal, delete the database, and then re-create it with the same name. This takes some time for Azure to process, so this is a slow testing cycle.

Is there a quick way to just drop/reset a Azure SQL DB to it's fresh, empty, virgin state and then re-publish with "execute code first migrations" to have it re-create the tables and re-seed the data?

I've seen some talk of creating an initial migration after I create the db, and then trying to use the Powershell to do some sort of roll-back to that initial state, but I haven't had luck getting it to work, and I want to delete all the data at the same time. Maybe I've just got the wrong syntax or haven't found a good enough tutorial. While I can run a query on the Azure DB to "drop database [x]" it literally kills the SQL Azure DB instance as you'd expect and you need to go back into the portal to recreate it. Sometimes that initial state is no good as the model has since been updated, so this may not be useful anyway.

I feel like there should be some easier quicker way to test changes on a live environment as there all these great tools and shortcuts provided by MS, but did they just drop the ball here for this phase of development or am I missing something?

Joseph Idziorek
  • 4,853
  • 6
  • 23
  • 37
Ivan
  • 1,093
  • 1
  • 10
  • 15

9 Answers9

107

Since there is not an API way to do this that I am aware of, we have used this script to leverage a T-SQL query to clear the database.

To delete each table (and maintain your EF migration histories if you want)

while(exists(select 1 from INFORMATION_SCHEMA.TABLES 
             where TABLE_NAME != '__MigrationHistory' 
             AND TABLE_TYPE = 'BASE TABLE'))
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_TYPE = 'BASE TABLE'
exec (@sql)
 /* you dont need this line, it just shows what was executed */
 PRINT @sql
end

To remove the foreign keys first if you need to

while(exists(select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='FOREIGN KEY'))
begin
 declare @sql nvarchar(2000)
 SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME
 + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
 FROM information_schema.table_constraints
 WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
 exec (@sql)
 PRINT @sql
end

In my testing, this worked without issues (except I did not have the where clause in the DROP TABLE while query since I don't use Code First or EF migrations).

Community
  • 1
  • 1
Tommy
  • 39,592
  • 10
  • 90
  • 121
  • This doesn't seem to work on Azure, it deletes like 1/8th the tables then spins forever, and when I hit stop I see a bunch of errors that it has no permission to delete some special tables. The foreign key one seemed to run, but didn't really help with the other issues. – Ivan Jan 26 '16 at 12:29
  • 1
    @Ivan - I found the issue, the WHERE clause was incorrect, you also have to filter by `TABLE_TYPE`. Check the updates and let me know if you are still having a problem? – Tommy Jan 26 '16 at 14:10
  • 2
    It's working like a charm ran on sql server in Azure! – dorsz Apr 21 '16 at 15:29
  • Care, INFORMATION_SCHEMA.TABLES sometimes returns as rows also View objects, making while looping forever (because they are never deleted). Better use Gizmo answer! – izio Jan 23 '20 at 13:08
  • @izio Gizmo's won't work in any business that follow a good practice of not using dbo for everything. It could easily be adapted, but I just want to point it out so people don't dismiss this answer. – Tipx Jan 27 '20 at 17:03
  • @Ivan I had the same issue, you need to run the below script to disable foreign key checking before you can run the script to delete tables. – Caspi Aug 08 '22 at 21:07
87

Just to add to the answers since the accepted answer did not work for me on Azure. Use the below script to Delete all the tables and basically reset the azure database. It firstly deletes all constraints and then drops all of the tables.

As @Skorunka František commented this script assumes you use the default [dbo] schema. Although you could replace it with your own schema name.

/* Azure friendly */
/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)

WHILE @name is not null
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint IS NOT NULL
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
        EXEC (@SQL)
        PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint is not null
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
        EXEC (@SQL)
        PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Table: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

Sadly I cannot find the source for this code anymore as i had it saved in one of my repositories. I hope it helps someone.

Gizmo3399
  • 1,719
  • 13
  • 7
  • Thanks, that was exactly what I was looking for. Connect to the Azure server with SSMS, new query against my target database, execute the above and bingo, fresh SQL database. – Dane Vinson Jul 30 '16 at 04:22
  • 2
    The above does not work if you do not use the default "dbo" schema. – Skorunka František Dec 11 '16 at 18:07
  • 2
    I just declared a schema variable and added 'AND CONSTRAINT_SCHEMA = @Schema' in the where clauses – chris31389 Aug 09 '17 at 08:59
  • 1
    Ok this worked for me on server where i didn't have permissions to drop db. Thanks – sensei Nov 29 '17 at 15:56
  • Well, I tried to edit this script to add temporal tables deletion, but an admin refused it... This script won't work with SQL 2016 and temporal tables. – jsgoupil Jan 15 '18 at 04:40
  • The script in this answer throws FK errors. The FK constraints need to be lifted before the PK constraints. A dirty workaround is to execute this script several times as it eventually clears everything up anyway. A better fix is to [first drop all FK constraints](https://stackoverflow.com/a/40006214/952296), which can simple be prepended to the script in this answer. – Flater Aug 22 '18 at 10:04
  • @Flater Okay, that is strange since the first step of the script is trying to remove the Foreign Keys before it drops the Primary Keys. Could there a an error with the way the script does this, that makes it miss a few FK's? Or could be just replace the first part of the script with your suggestion instead of prepending it to this script? – Gizmo3399 Nov 29 '18 at 10:44
  • 1
    Works well on Azure SQL. Thanks for the post Gizmo3399! – Edd Jan 05 '20 at 03:00
  • 1
    This worked for me like a charm on an Azure SQL Database. Thanks a lot! – Thomas Barnekow May 09 '21 at 15:23
11

Just to add my variant to the mix... This one also takes into account Views and External Tables. It will not barf on External Tables which have to be removed separately with DROP EXTERNAL TABLE. This caused the original version to spin forever.

while(exists(select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='FOREIGN KEY'))
begin
 declare @sql nvarchar(2000)
 SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME
 + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
 FROM information_schema.table_constraints
 WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
 exec (@sql)
 PRINT @sql
end


while(exists(select 1 from INFORMATION_SCHEMA.TABLES 
    where TABLE_NAME != 'database_firewall_rules' 
    AND TABLE_TYPE = 'BASE TABLE'
    AND TABLE_NAME NOT IN (select name from sys.external_tables)))
begin
 declare @sql1 nvarchar(2000)
 SELECT TOP 1 @sql1=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']')
 FROM INFORMATION_SCHEMA.TABLES
 WHERE TABLE_NAME != 'database_firewall_rules'
    AND TABLE_TYPE = 'BASE TABLE'
    AND TABLE_NAME NOT IN (select name from sys.external_tables)
exec (@sql1)
 PRINT @sql1
end
Nich Overend
  • 822
  • 8
  • 16
5

I usually

  1. open SQL Server Management Studio or from Visual Studio open SQL Server Object Explorer
  2. I connect to the Azure SQL Server (i.e: yourserver.database.windows.net with your username and password for SQL Server authentication option selected) (also remember that you would need to add a firewall exception in Azure portal to connect from your PC to the database in this way)
  3. Right click on the Database and delete.

As simple as that.

Then, since you mentioned that you have a code first migrations approach, simply run the migrations again in the Azure SQL Server (for example when publishing make sure you check the option to apply migrations for the given sql server connection string)

I usually delete the remote database and then re-deploy the application with the command to re-run the migrations. This will create again the database with the new tables. The code to seed the database is in my Startup code so it's seeded any time the app is initialized if there is no values in DB.

This is also valid for AspNet Core Mvc (MVC6)

diegosasw
  • 13,734
  • 16
  • 95
  • 159
  • I think this does not work for Azure SQL, at leas did not work for me. I had to create DB in Azure Portal again. – Skorunka František Dec 11 '16 at 18:08
  • Strange, I tried few minutes ago. Deleted DB in MSSMS, then tried to run migration and get an user "cat'n access provided database" error, or similar. – Skorunka František Dec 11 '16 at 20:30
  • I am using Asp.Net Core and EF Core and I apply migrations through Visual Studio when publishing (by checking the option apply migration). Maybe you're using EF 6? If so maybe you have to run `Add-Migration InitialCreate` to specify that the database does not exist and you want to create it again. Haven't tried this though. – diegosasw Dec 11 '16 at 20:35
  • Never, ever let any tools automatically create Azure databases for you. The default database is very expensive. Instead, create the database using the Azure portal so you can double check the selected plan. Then you can point your app at it to run migrations, etc. – Evil Pigeon Jun 08 '20 at 06:55
2

Azure SQL is essentially SQL server. So you can use MS SQL Server Management Studio https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms

Open the database in Management Studio using your admin account, then execute drop table SQL commands or use the GUI right click menu to do whatever you want, just like using a local database.

Similar thing can be done in the Visual Studio SQL Server Object Explorer. Just right click the root "Add SQL server".

Serena Yu
  • 117
  • 2
  • 3
1

Addition to the answer given by @Gizmo3399. We use temporal tables with Entity Framework (EF) Core 5.0.2 with .NET 5. This is the command we use to clear our database. History is the schema we use for system-versioned temporal table. Currently needs to be ran twice to drop everything but no modifications needed otherwise.

/* Azure friendly */
/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
DECLARE @SQL2 VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)

WHILE @name is not null
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint IS NOT NULL
    BEGIN
        IF EXISTS (SELECT * FROM sys.schemas WHERE name = 'History') AND @name != '__EFMigrationsHistory'
            BEGIN
                 SELECT @SQL = 'ALTER TABLE [history].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
                 EXEC (@SQL)
            END
        SELECT @SQL2 = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
        EXEC (@SQL2)
        PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
DECLARE @SQL2 VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint is not null
    BEGIN
        IF EXISTS (SELECT * FROM sys.schemas WHERE name = 'History') AND @name != '__EFMigrationsHistory'
            BEGIN
                SELECT @SQL = 'ALTER TABLE [history].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
                EXEC (@SQL)
            END
        SELECT @SQL2 = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
        EXEC (@SQL2)
        PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
DECLARE @SQL2 VARCHAR(254)
DECLARE @SQL3 VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    IF EXISTS (SELECT * FROM sys.schemas WHERE name = 'History') AND @name != '__EFMigrationsHistory'
        BEGIN
            SELECT @SQL = ('ALTER TABLE [' + RTRIM(@name) +'] SET (SYSTEM_VERSIONING = OFF)');
            EXEC (@SQL)
            SELECT @SQL2 = 'DROP TABLE [history].[' + RTRIM(@name) +']'
            EXEC (@SQL2)
        END
    SELECT @SQL3 = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL3)
    PRINT 'Dropped Table: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

IF EXISTS (SELECT * FROM sys.schemas WHERE name = 'History')
BEGIN
    DROP SCHEMA History
END

GO
Ogglas
  • 62,132
  • 37
  • 328
  • 418
1

If somebody would like to have such a script but with a filter by schema then there you go:

/* Azure friendly */

/* Drop all Foreign Key constraints */

/* Arguments */
DECLARE @schema VARCHAR(128) = '<TODO_PROVIDE_SCHEMA>'


/* Variables */
DECLARE @tableName VARCHAR(128)
DECLARE @tableSchema VARCHAR(128)
DECLARE @constraintName VARCHAR(254)
DECLARE @SQL VARCHAR(254)


SELECT TOP 1
   @tableName = sourceTable.name,
   @tableSchema = SCHEMA_NAME(sourceTable.schema_id),
   @constraintName = f.name
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN sys.tables targetTable ON targetTable.OBJECT_ID = fc.referenced_object_id
INNER JOIN sys.tables sourceTable ON f.parent_object_id = sourceTable.object_id
WHERE targetTable.[schema_id] = SCHEMA_ID(@schema)
ORDER BY sourceTable.name

WHILE @tableName is not null
BEGIN

    SELECT @SQL = 'ALTER TABLE [' + RTRIM(@tableSchema) + '].[' + RTRIM(@tableName) +'] DROP CONSTRAINT [' + RTRIM(@constraintName) +']'
    EXEC (@SQL)
    PRINT 'Executed: ' + @SQL
    
    SET @tableName = NULL;

    SELECT TOP 1
       @tableName = sourceTable.name,
       @tableSchema = SCHEMA_NAME(sourceTable.schema_id),
       @constraintName = f.name
    FROM sys.foreign_keys AS f
    INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
    INNER JOIN sys.tables targetTable ON targetTable.OBJECT_ID = fc.referenced_object_id
    INNER JOIN sys.tables sourceTable ON f.parent_object_id = sourceTable.object_id
    WHERE targetTable.[schema_id] = SCHEMA_ID(@schema)
    ORDER BY sourceTable.name
END
GO
/* Drop all Primary Key constraints */

DECLARE @schema VARCHAR(128) = '<TODO_PROVIDE_SCHEMA>'

DECLARE @tableName VARCHAR(128)
DECLARE @tableSchema VARCHAR(128)
DECLARE @constraintName VARCHAR(254)
DECLARE @constraintSchema VARCHAR(128)
DECLARE @SQL VARCHAR(254)


SELECT 
    @tableName = t.name,
    @tableSchema = SCHEMA_NAME(t.schema_id),
    @constraintName = pk.name,
    @constraintSchema = SCHEMA_NAME(t.schema_id)
FROM sys.objects pk 
JOIN sys.objects t ON (pk.parent_object_id = t.object_id)
WHERE pk.[type] = 'PK'
    AND pk.schema_id = SCHEMA_ID(@schema)
ORDER BY t.name 

WHILE @tableName is not null
BEGIN
    SELECT @SQL = 'ALTER TABLE [' + RTRIM(@tableSchema) + '].[' + RTRIM(@tableName) +'] DROP CONSTRAINT [' + RTRIM(@constraintName) +']'
    PRINT 'Executing: ' + @SQL
    EXEC (@SQL)

    SET @tableName = null;
    SELECT 
        @tableName = t.name,
        @tableSchema = SCHEMA_NAME(t.schema_id),
        @constraintName = pk.name,
        @constraintSchema = SCHEMA_NAME(t.schema_id)
    FROM sys.objects pk 
    JOIN sys.objects t ON (pk.parent_object_id = t.object_id)
    WHERE pk.[type] = 'PK'
        AND pk.schema_id = SCHEMA_ID(@schema)
    ORDER BY t.name 
END
GO



/* Drop all tables */

DECLARE @schema VARCHAR(128) = '<TODO_PROVIDE_SCHEMA>'

DECLARE @tableName VARCHAR(128)
DECLARE @tableSchema VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT TOP 1 
    @tableName = [name],
    @tableSchema = SCHEMA_NAME(schema_id)
FROM sys.tables
WHERE [type] = 'U' 
    AND schema_id = SCHEMA_ID(@schema)

WHILE @tableName IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TABLE [' + RTRIM(@tableSchema) +'].[' + RTRIM(@tableName) +']'
    EXEC (@SQL)
    PRINT 'Dropped Table: ' + @tableName

    SET @tableName = NULL;
    SELECT TOP 1 
        @tableName = [name],
        @tableSchema = SCHEMA_NAME(schema_id)
    FROM sys.tables
    WHERE [type] = 'U' 
        AND schema_id = SCHEMA_ID(@schema)
END
GO


/* DROP Sequences */

DECLARE @schema VARCHAR(128) = '<TODO_PROVIDE_SCHEMA>'


DECLARE @seqName VARCHAR(128)
DECLARE @seqSchema VARCHAR(128)
DECLARE @SQL VARCHAR(254)


SELECT TOP 1
    @seqName = s.name,
    @seqSchema = SCHEMA_NAME(s.schema_id)
FROM sys.sequences s
WHERE schema_id = SCHEMA_ID(@schema)
ORDER BY s.name


WHILE @seqName is not null
BEGIN
    SELECT @SQL = 'DROP SEQUENCE [' + RTRIM(@seqSchema) + '].[' + RTRIM(@seqName) +']'
    PRINT 'Executing: ' + @SQL
    EXEC (@SQL)

    SET @seqName = null
    SELECT TOP 1
        @seqName = s.name,
        @seqSchema = SCHEMA_NAME(s.schema_id)
    FROM sys.sequences s
    WHERE schema_id = SCHEMA_ID(@schema)
    ORDER BY s.name
END
GO

Before executing don't forget to change <TODO_PROVIDE_SCHEMA> to your schema

That script will find all FK that is related to the target schema so for example, when schema1.table1 has FK to schema2.table2 and if we want to delete schema2 then my script also deletes that FK (even if that is a different schema)

Script also drops sequences

KondzioSSJ4
  • 220
  • 4
  • 12
0

For someone that runs across this. This will delete all constrains, then views and then Tables:

/* Azure friendly */
/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)

WHILE @name is not null
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint IS NOT NULL
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
        EXEC (@SQL)
        PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint is not null
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
        EXEC (@SQL)
        PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop All Views */
while(exists(select 1 from INFORMATION_SCHEMA.VIEWS 
    where TABLE_NAME != 'database_firewall_rules' 
    AND TABLE_NAME NOT IN (select name from sys.external_tables)))
begin
 declare @sql1 nvarchar(2000)
 SELECT TOP 1 @sql1=('DROP VIEW ' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']')
 FROM INFORMATION_SCHEMA.VIEWS
 WHERE TABLE_NAME != 'database_firewall_rules'
    AND TABLE_NAME NOT IN (select name from sys.external_tables)
exec (@sql1)
 PRINT @sql1
end

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Table: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
Ruan
  • 33
  • 7
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 21 '23 at 18:43
  • This needs some adjustements because the script only uses dbo schema. How about other schemas? – Sven Jun 28 '23 at 08:50
-2

Alternatively, you can drop the database in C# and create a new database with ExecuteNonQuery.

queryString = "DROP DATABASE TestDB2";

SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();

Where connection is a connection to your Azure SQL Database master database.

Alternatively, to create a database:

queryString = "CREATE DATABASE TestDB2 ( EDITION = 'standard' )";
Joseph Idziorek
  • 4,853
  • 6
  • 23
  • 37