I developed a good application with backup and restore feature. It works fine. every time I added new features to its SQL Server 2008 R2 database, for example add a new stored procedure or user-defined table type to upgrade my software.
My backup function is this:
protected int BackUpDataBase(string dbName, string address)
{
try
{
using (_con)
{
string command = "Backup database " + dbName + " to disk='" + address + "'";
SqlCommand cmd = new SqlCommand(command, _con);
cmd.CommandType = CommandType.Text;
connect();
cmd.ExecuteNonQuery();
return 1;
}
}
catch (SqlException ex)
{
return ex.Number * (-1);
}
}
and my restore function is here:
protected int RecoverDataBase(string dbName, string address)
{
try
{
SqlConnection temp = new SqlConnection(_addressMaster);
string Restore = "USE master" + Environment.NewLine;
if (CheckDatabaseExists(dbName))
{
Restore += @"ALTER DATABASE [" + dbName + "]" + Environment.NewLine;
Restore += @"SET OFFLINE WITH ROLLBACK IMMEDIATE" + Environment.NewLine;
Restore += @"ALTER DATABASE [" + dbName + "] SET ONLINE" + Environment.NewLine;
}
Restore += @"RESTORE DATABASE [" + dbName + "] FROM DISK = N'" + address + @"' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10" + Environment.NewLine;
Restore += @"ALTER DATABASE [" + dbName + "] SET Single_User WITH Rollback Immediate" + Environment.NewLine;
Restore += @"ALTER DATABASE [" + dbName + "] SET Multi_User" + Environment.NewLine;
using (temp)
{
using (SqlCommand cmd = new SqlCommand(Restore, temp))
{
cmd.CommandText = Restore;
cmd.CommandType = CommandType.Text;
temp.Open();
cmd.ExecuteNonQuery();
temp.Close();
return 1;
}
}
}
catch (SqlException ex)
{
return ex.Number * (-1);
}
}
Everything is ok BUT! The problem is here: I developed my upgraded Windows App with new stored procedures and etc, then install it to a new computer and wants to restore the old backup to my upgraded app, all new stored procedures and feature will back to Old because I restored entire old backup not only its data. So how can I restore only tables data from a backup file using C# and SQL query?