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.
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());
}
}