Click here to Skip to main content
15,922,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to delete a database soon after creating it...
I used drop database query. but when I am deleting it I am getting a msg that database is currently is in use, you can't delete it. can anyone help me with this?
Posted

You can't delete like this when your application using it.you have to change your database.

try

SQL
USE master;
    GO

running this before you are running the drop query.
Hope it will help..
 
Share this answer
 
You need to drop everything inside of the database before you can drop the database. Make sure you drop your tables and indexes, then you can drop your database.

C#
using (SqlConnection connection = new SqlConnection(connectionString))
{
    if (DbTableExists(connectionString, TableName))
    {
        strCheckTable = "DROP TABLE " + TableName;
        command = new SqlCommand(strCheckTable, connection);
        command.CommandType = CommandType.Text;
        connection.Open();
        command.ExecuteNonQuery();
    }
}

if (DBExist(connectionString, databaseName))
{
    strCheckTable = "DROP DATABASE " + databaseName;
    command = new SqlCommand(strCheckTable, connection);
    command.CommandType = CommandType.Text;
    connection.Open();
    command.ExecuteReader();
    connection.Close
}

private static bool DBExist(string connectionString, string databaseName)
{
    int i32;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        string strCheckTable =
           "SELECT COUNT(name) FROM master.sys.databases WHERE name = '" + databaseName + "'";

         SqlCommand command = new SqlCommand(strCheckTable, connection);
         command.CommandType = CommandType.Text;
         connection.Open();
         i32 = Convert.ToInt32(command.ExecuteScalar());
         return (i32 == 1);
    }
}

private static bool DbTableExists(string strConnection, string strTableNameAndSchema)
{
     using (SqlConnection connection = new SqlConnection(strConnection))
     {
         string strCheckTable =
            String.Format(
                      "IF OBJECT_ID('{0}', 'U') IS NOT NULL SELECT 'true' ELSE SELECT 'false'",
                      strTableNameAndSchema);

         SqlCommand command = new SqlCommand(strCheckTable, connection);
         command.CommandType = CommandType.Text;
         connection.Open();

         return Convert.ToBoolean(command.ExecuteScalar());
      }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900