string connectionStringTest = "server=" + ServerName + ";database=master;uid=" + UserName + ";pwd=" + PassWord + "";
SqlConnection connection = new SqlConnection(connectionStringTest);
string backupstr = "restore database " + DataBaseName + " from disk='" + BackFilePath + "';";
try
{
string sql = "exec PRO_Killspid '" + DataBaseName + "'";
SqlCommand cmd = new SqlCommand(sql, connection);
connection.Open();
cmd.ExecuteNonQuery();
cmd = new SqlCommand(backupstr, connection);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
js.ShowMessage(this, ex.ToString());
throw ex;
}
finally
{
connection.Close();
}
注意事项:
存储过程 PRO_Killspid 创建于系统数据库Master中,具体内容为:
CREATE proc PRO_Killspid (@dbname varchar(20))
as
begin
declare @sql nvarchar(500)
declare @spid int
set @sql='declare getspid cursor for
select spid from sysprocesses where dbid=db_id('''+@dbname+''')'
exec (@sql)
open getspid
fetch next from getspid into @spid
while @@fetch_status <>-1
begin
exec('kill '+@spid)
fetch next from getspid into @spid
end
close getspid
deallocate getspid
end
GO