I have written a program in C# to use SQL 2008.
I want to backup the database and restore it. My code for backup works correctly but restore doesn’t work and the database becomes single user.
Get the following error :
The tail of the log for the database
“doctor” has not been backed up. Use
BACKUP LOG WITH NORECOVERY to backup
the log if it contains work you do not
want to lose. Use the WITH REPLACE or
WITH STOPAT clause of the RESTORE
statement to just overwrite the
contents of the log. RESTORE DATABASE
is terminating abnormally.
Nonqualified transactions are being
rolled back. Estimated rollback
My code:
private void Backup(string strFileName)
{
try
{
string command = @"BACKUP DATABASE doctor TO DISK='"+ strFileName+"'";
SqlCommand oCommand = null;
SqlConnection oConnection = null;
oConnection = new SqlConnection("Data Source=.;Initial Catalog=doctor;Integrated Security=True");
if (oConnection.State != ConnectionState.Open)
oConnection.Open();
oCommand = new SqlCommand(command, oConnection);
oCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Restore(string strFileName)
{
try
{
string command = "ALTER DATABASE doctor SET SINGLE_USER with ROLLBACK IMMEDIATE " + "use master " + " RESTORE DATABASE doctor FROM DISK='" + strFileName + "'";
SqlCommand oCommand = null;
SqlConnection oConnection = null;
oConnection = new SqlConnection("Data Source=.;Initial Catalog=doctor;Integrated Security=True");
if (oConnection.State == ConnectionState.Closed)
{
oConnection.Open();
oCommand = new SqlCommand(command, oConnection);
oCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I think if you concat
with your restore string it would work.