在執行建庫腳本時往往會先將原有的數據庫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"
From:http://tw.wingwit.com/Article/program/MySQL/201311/29520.html