在執行建庫腳本時,往往會先將原有的數據庫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"