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();
我收到此错误:
无法分离数据库' PhoneBookDB'因为它目前正在使用中。 将数据库上下文更改为' master'。
我该怎么办?
答案 0 :(得分:0)
你可以试试这个:
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();
您还可以尝试使用sp_who
或sp_whoisactive
来查找当前连接并将其终止。