What’s up SQL? – Number 4 – SQL Queries by Session

Sometimes it’s good to know what the users are up to.

In a SQL Server, you can get a picture of what is happening with a bit of T-SQL coding.

Here’s what i use to know what the users queries are.

First I start by finding
IF OBJECT_ID(‘TMPTable’) IS NOT NULL
    DROP TABLE TMPTable

      SELECT sqltext.TEXT,
            req.session_id,
            req.status,
            req.command,
            req.cpu_time,
            req.total_elapsed_time
      INTO TMPTable
      FROM sys.dm_exec_requests req
      CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
      WHERE 1 = 2

DECLARE @LOOP AS INTEGER
SET @LOOP = 1

WHILE (@LOOP = 1)
BEGIN
      INSERT TMPTable
      SELECT sqltext.TEXT,
            req.session_id,
            req.status,
            req.command,
            req.cpu_time,
            req.total_elapsed_time
      FROM sys.dm_exec_requests req
      CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
      WHERE session_id = ‘INSERT USER SESSION HERE’
END
After you just have to execute a select query to see the results.
SELECT * from TMPTable ORDER BY cpu_time DESC

Leave a Reply

Your email address will not be published. Required fields are marked *