CREATE proc killspid (@dbname varchar(20))
as
begin
declare @sql nvarchar(500)
declare @spid int--SPID 值是当用户进行连接时指派给该连接的一个唯一的整数
set @sql='declare getspid cursor for
select spid from sysprocesses where dbid=db_id('''+@dbname+''')'
--sysprocesses 包含有关 SQL Server 进程的信息。
exec (@sql)
open getspid
fetch next from getspid into @spid
while @@fetch_status<>-1--如果FETCH 语句没有执行失败或此行不在结果集中。
begin
exec('kill '+@spid)--终止正常连接
fetch next from getspid into @spid
end
close getspid
deallocate getspid
end
GO
===================================================================
#region 还原数据库
private void btnRestoreDB_Click(object sender, System.EventArgs e)
{
string path = null;
string server = cmbServer.Text.Trim();
string name = txtName.Text.Trim();
string pwd = txtPassword.Text.Trim();
string database = cmbDatabase.Text.Trim();
openFileDialog1.Filter = "数据库备份文件|*.bak|所有文件|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.InitialDirectory = Application.StartupPath;
openFileDialog1.RestoreDirectory = true;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
path = openFileDialog1.FileName;
}
if(path == null || path.Trim() == "") return;
this.pBar1.Visible = true;
SQLDMO.Restore oRestore = new SQLDMO.RestoreClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
oRestore.Action = 0 ;
SQLDMO.RestoreSink_PercentCompleteEventHandler pceh = new SQLDMO.RestoreSink_PercentCompleteEventHandler(Step);
oRestore.PercentComplete += pceh;
try
{
if(this.rdWindow.Checked)//用Windows身份验证明
{
oSQLServer.LoginSecure = true;
oSQLServer.Connect(null,null,null) ;
}
else//用SQL Server中的用户登录
{
oSQLServer.LoginSecure = false;
oSQLServer.Connect(server,name,pwd);
}
SQLDMO.QueryResults qr = oSQLServer.EnumProcesses(-1) ;
int iColPIDNum = -1 ;
int iColDbName = -1 ;
//杀死其它的连接进程
for(int i=1;i<=qr.Columns;i++)
{
string strName = qr.get_ColumnName(i) ;
if (strName.ToUpper().Trim() == "SPID")
{
iColPIDNum = i ;
}
else if (strName.ToUpper().Trim() == "DBNAME")
{
iColDbName = i ;
}
if (iColPIDNum != -1 && iColDbName != -1)
break ;
}
for(int i=1;i<=qr.Rows;i++)
{
int lPID = qr.GetColumnLong(i,iColPIDNum) ;
string strDBName = qr.GetColumnString(i,iColDbName);
if (strDBName.ToUpper() == "CgRecord".ToUpper())
oSQLServer.KillProcess(lPID) ;
}
oRestore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
oRestore.Database = database;
oRestore.Files = path;
oRestore.FileNumber = 1;
oRestore.ReplaceDatabase = true;
oRestore.SQLRestore(oSQLServer);
}
catch(System.Exception ex)
{
throw new Exception("数据还原失败:
" + ex.ToString());
}
finally
{
oRestore = null;
oSQLServer.DisConnect();
oSQLServer = null;
}
MessageBox.Show("数据库恢复成功!","恢复数据库完成",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
#endregion