Script to disconnect all users except one from two databases

Hi. I need a script to kill existing sessions on [db1] and [db2] except sessions from [user1]. I have a script like this now:

USE master
GO

DECLARE @kill varchar(8000) = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'
FROM master..sysprocesses 
WHERE dbid = db_id('db1)

EXEC(@kill);

I just need to extend to run on db2 and don't kill sessions from user1

Thanks.

August 20th, 2015 9:15am

Do you want to disconnect users except the ones on both DB1 and DB2?
Free Windows Admin Tool Kit Click here and download it now
August 20th, 2015 10:05am

Hi niklaserene,

This should work for you

DECLARE @DatabaseName nvarchar(50)
DECLARE @SPId int
SET @DatabaseName = N'your_db_name'
DECLARE KillCursor CURSOR FAST_FORWARD FOR
SELECT SPId FROM MASTER..SysProcesses WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId AND nt_username <> 'user1'
OPEN KillCursor 
FETCH NEXT FROM KillCursor INTO @SPId
WHILE @@FETCH_STATUS = 0
BEGIN
 KILL @SPId
 FETCH NEXT FROM KillCursor INTO @SPId
END
CLOSE KillCursor
DEALLOCATE KillCursor

August 20th, 2015 10:12am

yes that's correct.
Free Windows Admin Tool Kit Click here and download it now
August 21st, 2015 3:32am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics