I have created the following method that drops a database which is in use.
I came up with the following string
query after looking this SO question. Note that the query runs successfully in the SQL Server Management Studio.
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;
}
}
This is how I call my method on the 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;
}
}
Briefly when the user clicks the button a message box is presented.
- If the user clicks Yes the database is dropped and the user is re-directed to the login screen.
- But if the user clicks No then it returns in the same screen.
However, when I execute the whole thing I get the following error:
How can I solve this issue?
The issue persists despite the fact that the query is successful in the SQL Server Management Studio.
UPDATE
I made connection to "master" database instead of USE the master DB
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);