>  기사  >  데이터 베이스  >  SqlServer强制断开数据库连接的方法

SqlServer强制断开数据库连接的方法

WBOY
WBOY원래의
2016-06-07 16:17:471754검색

在执行建库脚本时,往往会先将原有的数据库drop掉,由于SqlServer检测到有数据连接时禁止执行drop database操作,所以建库脚本经常执行失败,为此我们需要一种能强制断开数据库已有连接的方法,可以过如下t-sql实现: declare @i int declare cur cursor for

 在执行建库脚本时,往往会先将原有的数据库drop掉,由于SqlServer检测到有数据连接时禁止执行drop database操作,所以建库脚本经常执行失败,为此我们需要一种能强制断开数据库已有连接的方法,可以过如下t-sql实现:

declare @i int declare cur cursor for select spid from sysprocesses where db_name(dbid)= 'Your_Database_Name' open cur fetch next from cur into @i while @@fetch_status=0 begin exec('kill '+@i) fetch next from cur into @i end close cur deallocate cur

我们可以把这条sql写到建库的批处理脚本里,放在脚本的开始:

:: Disconnect existing Fortune database connections
osql -S"%1" -U"%2" -P"%3" -Q"declare @i int declare cur cursor for select spid from sysprocesses where db_name(dbid)= ' Your_Database_Name ' open cur fetch next from cur into @i while @@fetch_status=0 begin exec('kill '+@i) fetch next from cur into @i end close cur deallocate cur"

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.