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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2020-12-16 我要评论
在执行建库脚本时,往往会先将原有的数据库drop掉,由于SqlServer检测到有数据连接时禁止执行drop database操作,所以建库脚本经常执行失败,为此我们需要一种能强制断开数据库已有连接的方法,需要的朋友可以参考下
在执行建库脚本时,往往会先将原有的数据库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"

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们