Search code examples
c#sql-servermstest

Deleting database from C#


I have an MDF file that I'm attaching to my local SQL server during testing with MSTEST and I don't want to have to go delete those temporary databases by hand after I've run the test set 50 times. (I've already done that and I don't like it >.<)

I'm look for a way to delete the database from the server after I'm done with the tests, during my TestCleanup method. I just need a little guidance on what SQL statements I would use to do this.

EDIT (By Software Monkey, from OP's rejected edit to ODED's answer)

Here is the code which worked for me:

var server = new Server(serverName); // Can use overload that specifies 

foreach (Database db in server.Databases)
{
     if (db.Name.ToLower().Contains(testDatabaseIdentifier))
     {
          databasesToDelete.Add(db.Name);
     }
}
databasesToDelete.ForEach(x =>
{
     Database db = new Database(server, x);
     db.Refresh();
     db.Drop();
});

Solution

  • Take a look at the SMO (SQL Server Management Objects) .NET wrappers.

    These allow you to manage all aspects of SQL Server from code, including deleting of databases.

    The database object has a Drop method.

    The code below is to illustrate how you could use the object model, though I have not tested it:

    var server = new Server(serverName); // Can use overload that specifies 
    
    foreach (Database db in server.Databases)
    {
         if (db.Name.ToLower().Contains(testDatabaseIdentifier))
         {
              databasesToDelete.Add(db.Name);
         }
    }
    databasesToDelete.ForEach(x =>
    {
         Database db = new Database(server, x);
         db.Refresh();
         db.Drop();
    });