USE MASTER
GO
DECLARE @DBName varchar(50), @spid varchar(10)
SET @DBName= 'Orders'
WHILE(EXISTS(SELECT * FROM sysprocesses WHERE dbid= db_id('Orders')))
BEGIN
DECLARE spids CURSOR FAST_FORWARD FOR
SELECT convert(varchar, spid) FROM sysprocesses
WHERE dbid = db_id(@DBName)
OPEN spids
FETCH NEXT FROM spids INTO @spid
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC('kill ' + @spid)
FETCH NEXT FROM spids INTO @spid
END
CLOSE spids
DEALLOCATE spids
END
IF NOT exists(Select * FROM sysprocesses WHERE dbid = db_id(@DBName))
EXEC sp_dboption @DBName, offline, true
ELSE
BEGIN
PRINT 'The following processes are still using the database:'
SELECT spid, cmd, status, last_batch, open_tran, program_name, hostname
FROM sysprocesses
WHERE dbid = db_id(@DBName)
END
GO
This is one of many useful queries in my arsenal that I use from time to time to get the job done. You may find it useful.
Thank you.
EXEC sp_dboption @DBName, offline, true
ReplyDeletethis SP is not im my native SQL 2012 ? where du i find it