6

I have a database "D:\MDF CONNECTION SAMPLE\BIN\DEBUG\HARMDATABASE.MDF". I am trying to detach or rename it, with this code:

SqlConnection conn = new SqlConnection("Data Source=.\\MSSQLSERVER2008;database=Master;Integrated Security=True;");
SqlCommand cmd = new SqlCommand("", conn);
cmd.CommandText = @"sys.sp_detach_db D:\MDF CONNECTION SAMPLE\BIN\DEBUG\HARMDATABASE.MDF";
conn.Open(); 
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Dispose();

But getting an error:

Incorrect syntax near '\'.

msiyer
  • 821
  • 6
  • 20
user3812553
  • 129
  • 2
  • 9

3 Answers3

7

In order to detach a database and at the same time solve the error

Cannot detach the database 'YOUR_DATABASE' because it is currently in use

you can simply use the following code:

    private void DetachDatabase()
    {
        String databaseConnectionString = "Data Source=localhost;MultipleActiveResultSets=True;Integrated Security=True";
        using (SqlConnection sqlDatabaseConnection = new SqlConnection(databaseConnectionString))
        {
            try
            {
                sqlDatabaseConnection.Open();
                string commandString = "ALTER DATABASE YOUR_DATABASE SET OFFLINE WITH ROLLBACK IMMEDIATE ALTER DATABASE YOUR_DATABASE SET SINGLE_USER EXEC sp_detach_db 'YOUR_DATABASE'";
                SqlCommand sqlDatabaseCommand = new SqlCommand(commandString, sqlDatabaseConnection);
                sqlDatabaseCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

Notice that YOUR_DATABASE is sometimes written without the single quotes, and sometimes with the single quotes. Only replace YOUR_DATABASE with the name of your database without .mdf extension and leave the rest of the string as it is...

Thanks to this website: Detach database dropping connections

And this website: SQL Server – How to Detach a Database

By the way, this worked for me on SQL SERVER 2014

Hazem Labeeb
  • 295
  • 1
  • 3
  • 11
6

You left out a quote inside the query, and as @KyleHale pointed out - it needs to be the name of the database, not a path to it.

Change:

cmd.CommandText = @"sys.sp_detach_db D:\MDF CONNECTION SAMPLE\BIN\DEBUG\HARMDATABASE.MDF;";

to be:

cmd.CommandText = @"sys.sp_detach_db 'dbName'";
Ruslan
  • 2,691
  • 1
  • 19
  • 29
  • 4
    Also, sp_detach_db takes a database name (it must be a valid sysname value), not a file path. – Kyle Hale Sep 19 '14 at 21:19
  • Yep, missed that out. Updated my answer. Thanks for noting! – Ruslan Sep 19 '14 at 21:20
  • Thanks. But now this error : Cannot detach the database 'D:\MDF CONNECTION SAMPLE\BIN\DEBUG\HARMDATABASE.MDF' because it is currently in use. – user3812553 Sep 19 '14 at 21:26
  • My dbname is 'D:\MDF CONNECTION SAMPLE\BIN\DEBUG\HARMDATABASE.MDF'. when i attach the mdf file from directory, the database name was it. – user3812553 Sep 19 '14 at 21:41
  • The path is the name of your database? It is what you see on the left-hand side of SQL Management studio, where the databases are listed? That entire path? – Ruslan Sep 19 '14 at 21:45
  • If that is truly the case (I'm not even sure if that's possible), try wrapping it into an identifier. Like this: sys.sp_detach_db '[D:\MDF CONNECTION SAMPLE\BIN\DEBUG\HARMDATABASE.MDF]' – Ruslan Sep 19 '14 at 21:46
  • I think that \ was solved but But now this error : Cannot detach the database 'D:\MDF CONNECTION SAMPLE\BIN\DEBUG\HARMDATABASE.MDF' because it is currently in use. – user3812553 Sep 19 '14 at 21:56
  • Check out this SO question: http://stackoverflow.com/questions/11620/how-do-you-kill-all-current-connections-to-a-sql-server-2005-database – Ruslan Sep 19 '14 at 22:01
5

How about using SMO?

You need to add a reference to Microsoft.SqlServer.Smo which is available when you have SQL Express or SQL Server installed on your dev machine.

using Microsoft.SqlServer.Management.Smo;

void Detach()
{
  Server smoServer = new Server("MSSQLSERVER2008");
  smoServer.DetachDatabase("HARMDATABASE", False);
}
C-Pound Guru
  • 15,967
  • 6
  • 46
  • 67
  • I cant find Microsoft.SqlServer.Smo.dll in my system. – user3812553 Sep 19 '14 at 22:13
  • 1
    You need to add a reference to Microsoft.SqlServer.Smo which is available when you have SQL Express or SQL Server installed on your dev machine. Check out the SMO link above. – C-Pound Guru Sep 20 '14 at 21:03