I've got a segment of C# code that restores a SQL Server database. This works well. The issue is running it again on another .bak file. Even though the second backup has a different name, it needs to write to the same directory as the first backup and also has the same naming scheme for the .mdf and .ldf files.
I'm just curious if there is a way to modify the naming scheme of the .mdf and .ldf files, or if there is some other method to create subdirs under the initial SQL Server directory for these files to be restored to.
Error message that I'm currently getting:
Additional information: The file XXXXXX.MDF cannot be overwritten. It is being used by database XAXAXAXAX
I figure I could use a move statement, but I am trying to keep from needing all of the directory values hardcoded or logged in a config somewhere.
string sql = "SELECT database_id FROM sys.databases WHERE Name = '"+yuy+"'";
SqlConnection con = new SqlConnection(@"" + singleconn.Replace(@"\\", @"\"));
SqlCommand command = new SqlCommand(sql, con);
con.Open();
object resultObj = command.ExecuteScalar();
con.Close();
if (resultObj == null)
{
string sql2 = "Restore Database " + yuy + " FROM DISK = '" + @"\" + localdir.Replace(@"\\", @"\") + @"\" + FileName + "'";
SqlCommand command2 = new SqlCommand(sql2, con);
con.Open();
command2.ExecuteNonQuery();
con.Close();
con.Dispose();
File.Delete(@"\" + localdir.Replace(@"\\", @"\") + @"\" + FileName);
MessageBox.Show("Database recovered successfully!");
}
else
{
Random rnd = new Random();
int card = rnd.Next(52);
MessageBox.Show("There is already a database under this name; renaming the DB to " + yuy + card.ToString());
string sql2 = "Restore Database " + yuy + card.ToString() + " FROM DISK = '" + @"\" + localdir.Replace(@"\\", @"\") + @"\" + FileName + "'";
SqlCommand command2 = new SqlCommand(sql2, con);
con.Open();
command2.ExecuteNonQuery();
con.Close();
con.Dispose();
File.Delete(@"\" + localdir.Replace(@"\\", @"\") + @"\" + FileName);
MessageBox.Show("Database Recovered Successfully!");
}
Figured most of this out thanks to scsimon, for now the last thing I am getting in terms of errors is this.
Additional information: Logical file 'XXXXXX.mdf' is not part of database 'Databasename'. Use RESTORE FILELISTONLY to list the logical file names.
The thing is I am pulling this straight from the Databasename properties. any help would be appreciated.