Home > SQL Server > Using SMO to drop a SQL Database

Using SMO to drop a SQL Database

SQL Server Management Objects(SMO) is the API you can use to manipulate the sql server,like create databse and delete database.
To get more details you can check the msdn documentation.
There are 2 ways you can drop a database
1. You could create a Database object and call Drop method:


Dim database As Database = New Database(Your database name)
 database.Drop()

2.However if you have existing connections to the database ,attempting to drop it using the above method will fail.Recall that when you try to drop the database from management studio ,you can tick the check box to close all the connections before drop the database.It is not so obvious , but you can do the exact same thing using SMO:


Dim server As Server= New Server(ServerConn)
                server.KillAllProcesses(Your database name)
                server.KillDatabase(Your database name)


Shout it

Advertisements
Categories: SQL Server
  1. Behtash Moradi
    May 15, 2010 at 1:23 pm

    Thank you indeed, second way worked for me

  2. November 16, 2011 at 11:44 pm

    Thanks Second way is awesome!!!!!!!

  3. Cyphy
    June 7, 2012 at 11:50 pm

    Thank you very much!

  4. M.Arshad
    August 28, 2012 at 10:59 pm

    v Thank

  5. Aadi
    September 23, 2012 at 9:25 am

    many thanx…!

  6. MerlinTintin
    December 24, 2014 at 9:26 pm

    Here is C# code:

    Method 1 produces following error: “You cannot execute this operation since the object has not been created.”

    Server server = new Server(connection.serverName);
    Database newDB = new Database(server, database);
    newDB.Drop();

    Method 2 works

    Server server = new Server(connection.serverName);
    server.KillAllProcesses(database);
    server.KillDatabase (database);

    Thanks for your post đŸ™‚

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: