My Technical Notes

Tuesday, 27 January 2015

Deleting all tables from an SQL Server Database

The SQL is:


EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all';
EXEC sp_msforeachtable 'DROP TABLE ?'

In a C# context, we can write the following code to do it:


var query = 
    @"EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all';
      EXEC sp_msforeachtable 'DROP TABLE ?'";
            
using (var connection = new SqlConnection("" /* connection string */))
{
    connection.Open();
    var sqlCommand = new SqlCommand(query, connection);
    sqlCommand.ExecuteNonQuery();
}

No comments: