I want to detach the database from SQL Server 2005 from my C# code. I use the DROP query to detach. But it statements delete the file from my local system. I want to detach the database and copy that database in runtime.
5 Answers
First try to connect to the SQL Server without providing any database name,or path just like below:
ConnectionString = @"Data Source= YourDataSource ;Integrated Security=True;Connect Timeout=30";
Note:
YourDataSource can either be . or .\SQLEXPRESS or .\MSSQLSERVER or (local)\SQLEXPRESS or (localdb)\v11.0 or etc.
Then by using the following query, detach your database.
"ALTER DATABASE [your DB] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db @dbname = [your DB]";
Ok.
My Sample code:
sql_connect1.ConnectionString = @"Data Source=.\sqlexpress;Integrated Security=True;Connect Timeout=30";
sql_command.CommandText = "ALTER DATABASE [IRAN] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db @dbname = [IRAN]";
sql_command.Connection = sql_connect1;
sql_connect1.Open();
sql_command.ExecuteNonQuery();
sql_connect1.Close();
Comments
The SQL Server SMO API let's you do anything Sql Server management studio can do (from c# code). Check out this link http://msdn.microsoft.com/en-us/library/ms162175.aspx
2 Comments
you can detach a database on SqlServer by the following code: There is a stored procedure in SqlServedr 'sp_detach_db' for detach a database, has one argument DataBaseName. Here in the code 'MyDatabase' is the database name you should change it with your database name
// C# Code
SqlConnection conn = new SqlConnection("Server=(local); Data Source=;Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand("", conn);
cmd.CommandText = "sys.sp_detach_db MyDatabase";
conn.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Dispose();
2 Comments
You can use stored procedures for your problem. following link can be useful:
Comments
Myo Thu's comments lead me in the right direction, so here's a summary of steps on how to detach the database.
Step 1: Reference the following DLL's in your project [Reference]:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.SqlEnum.dll
Step 2: using:
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
Step 3: Code
var server = new Server(new ServerConnection(@"MyMachine\SQL2012"));
// Ensure database is not in use
server.KillAllProcesses("TestDatabase");
server.DetachDatabase("TestDatabase", true);
EDIT: Now documented in my blog here