I have a running Windows application that is using a SQL Server database called LakDB
to run. I want to give an option to select another database file. The first thing I want to do is take the current database offline so I can setup the new data file with the same database name. But I keep getting this error:
System.Data.SqlClient.SqlException: User does not have permission to alter database 'LakDB', the database does not exist, or the database is not in a state that allows access checks. ALTER DATABASE statement failed.
The code I used is:
string conn = @"Server=(localdb)\MSSQLLocalDB;Integrated security=True;Connection Timeout=30";
using (SqlConnection c = new SqlConnection(conn))
{
string query = "use master";
using (SqlCommand cmd = new SqlCommand(query, c))
{
c.Open();
cmd.ExecuteNonQuery();
c.Close();
}
query = "alter database LakDB set offline with rollback immediate";
using (SqlCommand cmd = new SqlCommand(query, c))
{
c.Open();
cmd.ExecuteNonQuery();
c.Close();
}
query = "drop database if exists LakDB";
using (SqlCommand cmd = new SqlCommand(query, c))
{
c.Open();
cmd.ExecuteNonQuery();
c.Close();
}
}
And I keep getting the error at the first ExecuteNonQuery
command under the alter database LakDB
query.
What else can I do?