SQL Server - find users connected to databases

Reference: https://jimsalasek.com/2019/01/09/sql-server-find-users-connected-to-databases/

SELECT @@ServerName AS server
 ,NAME AS DatabaseName
 ,COUNT(STATUS) AS number_of_connections
 ,GETDATE() AS Query_Run_Time
FROM sys.databases sd
LEFT JOIN sysprocesses sp ON sd.database_id = sp.dbid
WHERE NAME not in ('master','model','msdb','tempdb')
GROUP BY NAME

With actual usernames and machines that are connected


SELECT @@ServerName AS SERVER
 ,NAME
 ,login_time
 ,STATUS
 ,hostname
 ,program_name
 ,nt_username
 ,loginame
FROM sys.databases d
LEFT JOIN sysprocesses sp ON d.database_id = sp.dbid
WHERE  NAME not in ('master','model','msdb','tempdb')
 AND loginame IS NOT NULL order by 2



0 comments:

 
Copyright © peyotest