1
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source =.; Initial Catalog = master; Integrated Security = True;";
con.Open();

string str = "USE master;" +
"EXEC sp_detach_db @dbname = N'PhoneBookDB'";

SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Detached", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
Application.Exit();

I get this error:

Cannot detach the database 'PhoneBookDB' because it is currently in use. Changed database context to 'master'.

What should I do?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272

1 Answers1

0

Could you try this:

SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source =.; Initial Catalog = master; Integrated Security = True;";
con.Open();

string str = "USE master;" +
"ALTER DATABASE PhoneBookDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE; EXEC sp_detach_db @dbname = N'PhoneBookDB'";

SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Detached", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
    Application.Exit();

You can also try used sp_who or sp_whoisactive to find the current connections and kill them.

gotqn
  • 42,737
  • 46
  • 157
  • 243