C# sp_attach_db execute
-
I need to detach and then re-attach my MSDE db from within my C# application. Can someone give me a clue on how to do this? I have no problem doing it in Querey Analyzer but can't seem to make the transition into C3? Thanks, cb
Connect to the master database and simply execute the
sp_attach_db
stored proc on the database (using all three parameters, using paths local to the target machine - not yours!) like so:SqlConnection conn = new SqlConnect(
"Integrated Security=SSPI;Data Source=DBSRV1;Initial Catalog=master");
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_attach_db";
cmd.Parameters.Add("@dbname", SqlDbType.NVarChar, 128).Value = "MyDB";
cmd.Parameters.Add("@filename1", SqlDbType.NVarChar, 260).Value =
@"C:\Program Files\Microsoft SQL Server\MSSQL\Data\MyDB.mdf";
cmd.Parameters.Add("@filename2", SqlDbType.NVarChar, 260).VAlue =
@"C:\Program Files\Microsoft SQL Server\MSSQL\Data\MyDB.ldf";
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}Microsoft MVP, Visual C# My Articles
-
Connect to the master database and simply execute the
sp_attach_db
stored proc on the database (using all three parameters, using paths local to the target machine - not yours!) like so:SqlConnection conn = new SqlConnect(
"Integrated Security=SSPI;Data Source=DBSRV1;Initial Catalog=master");
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_attach_db";
cmd.Parameters.Add("@dbname", SqlDbType.NVarChar, 128).Value = "MyDB";
cmd.Parameters.Add("@filename1", SqlDbType.NVarChar, 260).Value =
@"C:\Program Files\Microsoft SQL Server\MSSQL\Data\MyDB.mdf";
cmd.Parameters.Add("@filename2", SqlDbType.NVarChar, 260).VAlue =
@"C:\Program Files\Microsoft SQL Server\MSSQL\Data\MyDB.ldf";
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}Microsoft MVP, Visual C# My Articles
-
Thanks Heath, I'm getting an "Unrecognized escape sequence" for the values for filename1 and filename2. Doesn't like the '\'. I tried putting the value in paren's but that didn't help either. cb
-
Thanks Heath, I'm getting an "Unrecognized escape sequence" for the values for filename1 and filename2. Doesn't like the '\'. I tried putting the value in paren's but that didn't help either. cb
-
Thanks Heath, I'm getting an "Unrecognized escape sequence" for the values for filename1 and filename2. Doesn't like the '\'. I tried putting the value in paren's but that didn't help either. cb
Either escape them using "\" (so "\\") or use the literal string identifier "@" before the string, like "@C:\Program Files...". Looking at the documentation for the compiler error would've told you that.
Microsoft MVP, Visual C# My Articles