Identify Blocked SQL Processes Quickly: Listing 2: SQL SERVER: Call the dba_GetSQLForSpid Function

Make a call to the database function dba_GetSQLForSpid to get the underlying SQL, which can show you why performance is slow. The function accepts one parameter: the SQL Server process ID (@spid) of a running process.

CREATE Function [dbo].[dba_GetSQLForSpid]
(
   @spid SMALLINT
)
RETURNS NVARCHAR(4000)

/*-------------------------------------------------

Purpose:   Returns the SQL text for a given spid.

---------------------------------------------------

Parameters:   @spid   - SQL Server process ID.
Returns:   @SqlText - SQL text for a given spid.
Revision History:
      01/12/2006   [email protected] Initial version
Example Usage:
   SELECT dbo.dba_GetSQLForSpid(51)
   SELECT dbo.dba_GetSQLForSpid(spid) AS [SQL text]
      , * FROM sys.sysprocesses WITH (NOLOCK) 

--------------------------------------------------*/

BEGIN
   DECLARE @SqlHandle BINARY(20)
   DECLARE @SqlText NVARCHAR(4000)
   -- Get sql_handle for the given spid.
   SELECT @SqlHandle = sql_handle 
      FROM sys.sysprocesses WITH (nolock) WHERE 
      spid = @spid
   -- Get the SQL text for the given sql_handle.
   SELECT @SqlText = [text] FROM 
      sys.dm_exec_sql_text(@SqlHandle)
   RETURN @SqlText

END
comments powered by Disqus

Featured

  • Spring AI 2.0 Goes GA, Giving Java Developers a More Mature AI App Stack

    Spring AI 2.0 advances the Java framework for generative AI apps with a Spring Boot 4 baseline, cleaner agentic tooling, Model Context Protocol support and vendor-backed integrations including Azure Cosmos DB.

  • Kubernetes for Developers

    Microsoft's Dan Wahlin previews his introductory "Kubernetes for Developers" session at Visual Studio Live! San Diego 2026, explaining how developers can get past the Kubernetes learning curve by starting locally, mastering Pods first, and using Services to make containerized applications reliably accessible.

  • VS Code Keeps Eye on Costs in v1.126 Update

    Visual Studio Code 1.126 adds session-level Copilot cost information, continuing Microsoft's recent focus on helping developers monitor and manage usage-based GitHub Copilot billing.

  • Open VSX 1.0.0 Puts Focus on Open Extension Registry for VS Code Ecosystem

    Eclipse Open VSX has reached 1.0.0, highlighting its role as a vendor-neutral registry for VS Code-compatible extensions.

Subscribe on YouTube