我创建了以下方法来删除正在使用的数据库。在查看了这个SO question之后
,我提出了以下查询。请注意,查询在 SQL Server Management Studio 中成功运行。string
public static bool DeleteProject(string connectionstring, string dbname)
{
string connString = connectionstring;
string query = String.Format(
"USE master;\n" +
"GO\n" +
"IF EXISTS(select* from sys.databases where name = '{0}') DROP DATABASE {0}; \n" +
"GO", dbname);
Debug.WriteLine(query);
using SqlConnection conn = new SqlConnection(connString);
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
SqlCommand cmd = new SqlCommand(query, conn);
//conn.Open();
return (cmd.ExecuteNonQuery() == -1);
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString(), "Test Connection", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
}
这就是我在以下位置调用我的方法的方式button.Click()
:
private void DeleteProjectButton_Click(object sender, RoutedEventArgs e)
{
MessageBoxResult deletebutton = MessageBox.Show(String.Format("Would you like to delete the project database '{0}'? \n\n Click Yes to trigger the delete \n Click No to cancel the delete", HomePageTab.Header.ToString().Split(" - ")[1]), "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (deletebutton == MessageBoxResult.Yes)
{
bool commandExecuted=DeleteProject(SQLServerConnectionDetails(), HomePageTab.Header.ToString().Split(" - ")[1]);
if (commandExecuted)
{
MessageBox.Show(String.Format("Project database '{0}' successfully deleted!", HomePageTab.Header.ToString().Split(" - ")[1]), "Confirmation", MessageBoxButton.OK, MessageBoxImage.Information);
}
LoginScreen win_loginscreen = new LoginScreen();
win_loginscreen.Show();
this.Close();
}
else
{
return;
}
}
简而言之,当用户单击按钮时,会显示一个消息框。
- 如果用户单击是,则删除数据库并将用户重定向到登录屏幕。
- 但是,如果用户单击否,则它会在同一屏幕中返回。
但是,当我执行整个事情时,我收到以下错误:
我该如何解决这个问题?
尽管查询在 SQL Server Management Studio 中成功,但问题仍然存在。
更新
我连接到“主”数据库而不是使用主数据库
string connString = "Server=Name;Database=master;Integrated Security=SSPI"
string query = String.Format("ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE; \n" +
"DROP DATABASE [{0}]", dbname);