我正在恢复在基于c#的测试工具上使用的数据库。它在每次测试运行时恢复,有时在单独测试后恢复。
当我尝试新查询时,在恢复后数据库有时会失败时,我会出现间歇性错误。
我首先将其设置为离线:
using (SqlConnection conn = new SqlConnection(GetConnectionString("MasterDatabase")))
using (SqlCommand cmd = new SqlCommand(@"ALTER DATABASE MYDB SET OFFLINE WITH ROLLBACK IMMEDIATE", conn))
{
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
}
然后恢复:
using (SqlConnection conn = new SqlConnection(GetConnectionString("MasterDatabase")))
using (SqlCommand cmd = new SqlCommand(@"Restore Database MYDB
FROM Disk = 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\MYDB.bak'
WITH REPLACE, MOVE 'MYDB_Dat' TO 'c:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\MYDB.mdf',
MOVE 'MYDB_Log' TO 'c:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\MYDB.ldf'", conn))
{
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
}
任何进一步的数据库调用都会间歇性地失败。