I currently have the following Command
SqlCommand command = new SqlCommand(@"sys.sp_detach_db 'DBname'", conn);
to detach a database, but it throws an exception when I execute it. Saying that the database is in use. How can I drop the connection when or before I detach it?
Update: I am currently using SMO but it's still not working:
bool DetachBackup(string backupDBName)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var builder = new SqlConnectionStringBuilder(connectionString);
string serverName = builder.DataSource;
string dbName = builder.InitialCatalog;
try
{
Server smoServer = new Server(serverName);
smoServer.DetachDatabase(backupDBName + DateTime.Now.ToString("yyyyMMdd"), false);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
You'll need to execute this SQL statement first, before detaching:
ALTER DATABASE YourDbNameHere
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
It sets the database into single user mode, and tosses out any active connection immediately.
You can use SMO
Detaches the specified database from the instance of SQL Server with the option to update statistics before the database is detached.
using Microsoft.SqlServer.Management.Smo;
void DetachDatabase()
{
Server smoServer = new Server("MSSQLSERVER2008");
smoServer.DetachDatabase("Yourdatabasename", False);
}
To get server name from the app.config you can try like this:
string connectString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
string serverName = builder.DataSource; //Server name
string dbName = builder.InitialCatalog; //Database name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With