Attachment Database
-
In MS SQL Server, it's got an attacth and dettach database, so i want to write a programme to do that, but i do not know where to start. Thanks Rock Throught The Night
-
In MS SQL Server, it's got an attacth and dettach database, so i want to write a programme to do that, but i do not know where to start. Thanks Rock Throught The Night
Use a
SqlCommand
to execute them, just like you'd type them in a command parser (like the Query Analyzer or osql.exe). Use aSqlConnection
that specifies the 'master' database as the 'Initial Catalog', however. The 'master' database must always exist, otherwise you can't do anything, so it's a good database to attach to when running commands like that. A simple example (without any error checking, like seeing if the files actually exist first):public void AttachDatabase(string name, string mdfFile, string ldfFile)
{
using (SqlConnection conn = new SqlConnection(
"Data Source=.;Initial Catalog=master;Integrated Security=SSPI"))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "exec sp_attach_db @dbname, @filename1, @filename2";
cmd.Parameters.Add("@dbname", SqlDbType.NVarChar, 128).Value = name;
cmd.Parameters.Add("@filename1", SqlDbType.NVarChar, 260).Value = mdfFile;
cmd.Parameters.Add("@filename2", SqlDbType.NVarChar, 260).Value = ldfFile;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}See the documentation for the
sp_attach_db
andsp_detach_db
stored procs, as well as theSqlCommand.Parameters
collection property for more information.Microsoft MVP, Visual C# My Articles
-
Use a
SqlCommand
to execute them, just like you'd type them in a command parser (like the Query Analyzer or osql.exe). Use aSqlConnection
that specifies the 'master' database as the 'Initial Catalog', however. The 'master' database must always exist, otherwise you can't do anything, so it's a good database to attach to when running commands like that. A simple example (without any error checking, like seeing if the files actually exist first):public void AttachDatabase(string name, string mdfFile, string ldfFile)
{
using (SqlConnection conn = new SqlConnection(
"Data Source=.;Initial Catalog=master;Integrated Security=SSPI"))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "exec sp_attach_db @dbname, @filename1, @filename2";
cmd.Parameters.Add("@dbname", SqlDbType.NVarChar, 128).Value = name;
cmd.Parameters.Add("@filename1", SqlDbType.NVarChar, 260).Value = mdfFile;
cmd.Parameters.Add("@filename2", SqlDbType.NVarChar, 260).Value = ldfFile;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}See the documentation for the
sp_attach_db
andsp_detach_db
stored procs, as well as theSqlCommand.Parameters
collection property for more information.Microsoft MVP, Visual C# My Articles
thank you very much.;) Rock Throught The Night