Get-sqmLongRunningQueries
Performance
sqmSQLTool v1.8.2+ · Get
🔓 VIEW SERVER STATE required
sys.dm_exec_requests for active sessions exceeding a duration or CPU threshold. Resolves the exact current statement (not just the batch) via statement_start/end_offset, and enriches each result with wait type, isolation level, query hash, estimated completion time, and blocking information. System sessions (SPID ≤ 50) and the caller's own SPID are always excluded. The -ExcludeWaitType filter (applied in PowerShell, not SQL) removes idle wait types from the result. -IncludeQueryPlan adds the XML execution plan per row — useful interactively, but too expensive for Agent Jobs.
Parameters
| Parameter | Type | Required | Default | Notes |
|---|---|---|---|---|
| -SqlInstance | string | Optional | $env:COMPUTERNAME | Target SQL Server instance. |
| -SqlCredential | PSCredential | Optional | — | SQL or Windows credential. |
| -MinDurationSeconds | int | Optional | 30 | Minimum elapsed time in seconds. Applied in SQL via DATEDIFF(s, start_time, GETDATE()). |
| -MinCpuMs | int | Optional | 0 | Minimum CPU time (ms). Only added to the WHERE clause when > 0. |
| -ExcludeWaitType | string[] | Optional | ~30 idle types | Wait types to exclude. Filter applied in PowerShell per row, not in SQL. Default list covers SLEEP_*, XE, HADR background waits, etc. |
| -IncludeSystemSessions | switch | Switch | $false | Include SPIDs ≤ 50 (background tasks). Default: excluded via AND session_id > 50. |
| -IncludeQueryPlan | switch | Switch | $false | Fetch XML execution plan from sys.dm_exec_query_plan per row. Expensive — use interactively only, not in Agent Jobs. |
| -OutputPath | string | Optional | — | Write a CSV snapshot (QueryPlanXml and FullBatch excluded). Directory created automatically. |
| -EnableException | switch | Switch | $false | Throw on error instead of Write-Error. |
Execution Flow
Examples
Queries running longer than 30 seconds on the local instance
Get-sqmLongRunningQueries
Queries running longer than 60 seconds on a named instance
Get-sqmLongRunningQueries -SqlInstance "SQL01" -MinDurationSeconds 60
Top 10 by duration, minimum threshold lowered
Get-sqmLongRunningQueries -MinDurationSeconds 10 |
Sort-Object DurationSeconds -Descending |
Select-Object -First 10Agent Job snapshot — save CSV when queries exceed 2 minutes
Get-sqmLongRunningQueries -MinDurationSeconds 120 -OutputPath "C:\System\WinSrvLog\MSSQL\LongRunning"
Include XML execution plan (interactive use only)
Get-sqmLongRunningQueries -SqlInstance "SQL01" -IncludeQueryPlan |
Select-Object SessionId, DurationSeconds, QueryPlanXml