在 C# 中分离 SQL 服务器数据库

Detach SQL Server database in C#

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

我收到这个错误:

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

我该怎么办?

你能试试这个吗:

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_whosp_whoisactive 来查找当前连接并终止它们。