在执行建库脚本时往往会先将原有的数据库drop掉由于SqlServer检测到有数据连接时禁止执行drop database操作所以建库脚本经常执行失败为此我们需要一种能强制断开数据库已有连接的方法可以过如下tsql实现
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= begin exec(kill +@i) fetch next from cur into @i end close cur deallocate cur
我们可以把这条sql写到建库的批处理脚本里放在脚本的开始
:: Disconnect existing Fortune database connections
osql S"%" U"%" P"%" 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= begin exec(kill +@i) fetch next from cur into @i end close cur deallocate cur"