当前位置: 移动技术网 > IT编程>数据库>MSSQL > SqlServer强制断开数据库已有连接的方法

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

天天基金110010,芊芳草,演员金莉莉

在执行建库脚本时,往往会先将原有的数据库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"

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网