SQL Server 利用 sp_who2 來記錄資料庫伺服器的應用程式連線情形

  • 261
  • 0

參考: https://sdwh.dev/posts/2021/05/SQL-Server-Exec-SP-Who2/

DECLARE @Table TABLE(
       SPID INT,
       Status VARCHAR(MAX),
       LOGIN VARCHAR(MAX),
       HostName VARCHAR(MAX),
       BlkBy VARCHAR(MAX),
       DBName VARCHAR(MAX),
       Command VARCHAR(MAX),
       CPUTime INT,
       DiskIO INT,
       LastBatch VARCHAR(MAX),
       ProgramName VARCHAR(MAX),
       SPID_1 INT,
       REQUESTID INT
)
-- 將 sp_who2 寫入 Temp Table
INSERT INTO @Table EXEC sp_who2
SELECT * FROM @Table
--依連線數排序 BY 登入帳號&機器
SELECT SPID,LOGIN,HostName,count(*) FROM @Table group by SPID,LOGIN,HostName order by 4 desc
--依總/不重覆連線數排序
SELECT HostName,count(*) [總SESSION數],count(distinct SPID) [不重覆SESSION數] FROM @Table group by HostName order by 2 desc