Separate database programmatically

I have a database "D: \ MDF CONNECTION SAMPLE \ BIN \ DEBUG \ HARMDATABASE.MDF". I am trying to split 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 the error:

Incorrect syntax near '\'.

+4
source share
3 answers

You left a quote inside the request, and as @KyleHale pointed out, this should be the name of the database, not the path to it.

Edit:

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

:

cmd.CommandText = @"sys.sp_detach_db 'dbName'";
+6
source

To detach the database and solve the error at the same time

Cannot detach database "YOUR_DATABASE" because it is currently in use

you can just 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);
            }
        }
    }

, YOUR_DATABASE , . YOUR_DATABASE .mdf , ...

-:

: SQL Server -

, SQL SERVER 2014

+5

SMO?

Microsoft.SqlServer.Smo, , SQL Express SQL Server.

using Microsoft.SqlServer.Management.Smo;

void Detach()
{
  Server smoServer = new Server("MSSQLSERVER2008");
  smoServer.DetachDatabase("HARMDATABASE", False);
}
+4

All Articles