Close SQL Server database connections via C#


There are many ways to close other SQL Server database connections.
You may need to do this, when performing a full database restore.
This is the fastest & most reliable way I know:


Take database offline:
There is a SetOffLine() method you can call in C#.
However, the equivalent SQL statement is much faster than calling SetOffline():
Also, it rolls back any current transactions, which is safe.

private static void setDatabaseOffline(string cxnString)
{
using (SqlConnection cxn = new SqlConnection(cxnString))
{
cxn.Open();

string cmdText = string.Format("ALTER DATABASE {0} SET OFFLINE WITH ROLLBACK IMMEDIATE", //rolls back any current txns
cxn.Database
);

using (SqlCommand cmd = new SqlCommand(cmdText, cxn))
{
cmd.ExecuteNonQuery();
}

cxn.Close();
}
}



Set database online again:

private static void setDatabaseOnline(string cxnString)
{
using (SqlConnection cxn = new SqlConnection(cxnString))
{
Server server = new Server(cxn.DataSource);
Database unitTestingDatabase = server.Databases[cxn.Database];
unitTestingDatabase.Refresh();
unitTestingDatabase.SetOnline();
server.Refresh();
}
}

Comments