Query executing command in concurrent sessions on MSSQL

執行下列語法可以查詢出非 sa 帳號與正在執行中的command原始SQL語句:

DECLARE @AllConnections 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
);
INSERT INTO @AllConnections EXEC sp_who2;
SELECT sqltext.TEXT [SQL Command], req.session_id [Session ID], ac.LOGIN [Login User],
    ac.HostName [Host Name], ac.ProgramName [Program Name],
    ac.DBName [Database Name], req.start_time [Start Time],
    req.status [Status], req.command [Command Type],
    req.cpu_time [CPU Time], req.total_elapsed_time [Elapsed Time], ac.DiskIO [Disk IO]
FROM sys.dm_exec_requests req
    CROSS APPLY sys.dm_exec_sql_text(req.sql_handle) AS sqltext
JOIN @AllConnections ac
     ON ac.SPID = req.session_id
WHERE req.session_id IN (
    SELECT SPID FROM @AllConnections WHERE LOGIN NOT IN ('sa') AND SPID IN (
        SELECT SESSION_ID FROM sys.dm_exec_requests
        WHERE STATUS='running'
    )
);

留言

熱門文章