要实现数据库的还原,需要数据库在没有使用的情况下才能进行数据库的还原,所以在本例中通过在master数据库中创建一个杀死数据库进程的存储过程,传入参数为数据库名称,存储过程名称代码如下:
1 create proc p_killspid 2 @dbname sysname 3 as 4 declare @s nvarchar(1000) 5 declare tb cursor local for 6 select s='kill '+cast(spid as varchar) 7 from master..sysprocesses 8 where dbid=db_id(@dbname) 9 10 open tb 11 fetch next from tb into @s 12 while @@fetch_status=0 13 begin 14 exec(@s) 15 fetch next from tb into @s 16 end 17 close tb 18 deallocate tb 19 go
C#实现数据库的备份代码:
1 public bool Backup(string fileName,string dataBaseName) 2 { 3 string backUpSql = string.Format("use master;backup database {0} to disk = '{1}';", dataBaseName, fileName); 4 return this.m_DataAccess.ExecuteNonQuery(backUpSql) >= 0 ? true : false; 5 }
C#实现数据库的还原代码:
1 public bool Restore(string fileName,string dataBaseName) 2 { 3 string restoreSql = string.Format("use master;exec p_killspid '{0}';restore database {0} From disk = '{1}' with replace;", dataBaseName, fileName); 4 return this.m_DataAccess.ExecuteNonQuery(restoreSql) >= 0 ? true : false; 5 }
来源:https://www.cnblogs.com/wuzi145/archive/2012/05/06/2486534.html