public bool restore_sql(string database, string fileurl)
{
SqlConnection con = db.CreateConnection();
con.Open();
//连接数据库
try
{
string sql = "use master";//数据库原本存在的
,选连接到master数据库
SqlCommand conR = new SqlCommand(sql, con);
conR.ExecuteNonQuery();//执行该SQL语句
//调用存储过程killspid杀线程
SqlCommand sqlcom = new SqlCommand("killspid", con);
SqlParameter sp = new SqlParameter("@dbname", database);
sqlcom.CommandType = CommandType.StoredProcedure;
sqlcom.Parameters.Add(sp);
sqlcom.ExecuteNonQuery();
//返原
string strsql = "restore database " + database + " from disk='" + fileurl + "' WITH REPLACE";
SqlCommand condb = new SqlCommand(strsql, con);
condb.ExecuteNonQuery();
//SQLHelper.ExecNonQuery(strsql);
return true;
}
catch(Exception ex)
{
string mes = ex.Message;
return false;
}
finally
{
//重新使用database
string sqlReturn = "use " + database;
SqlCommand conReturn = new SqlCommand(sqlReturn, con);
conReturn.ExecuteNonQuery();
con.Close();
}
存储过程
在master数据库添加下面存储过程
create proc 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
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO