Search code examples
phpsql-serversqlcmdsql-scripts

SQL Server: Stopping Queries Externally


I run queries using SQLCMD utility via PHP and I wanted to know if there was a way to stop queries or scripts that I have executed via another SQL command by passing the process ID or something.

I also make use of the PHP Driver for SQL Server would it be easier to do this way?

Or is none of this possible - once a query runs you can not stop it?

Thanks all


Solution

  • SQL Server keeps track of all executing processes. You can review the list by using stored procedures SP_WHO and SP_WHO2 - each process has a unique SPID.

    In the past, I have copied and customized the code behind these procedures for my own purposes.

    You can check the query last executed on a SPID using DBCC INPUTBUFFER (@SPID)

    You can kill most processes using KILL @SPID

    Do note that it is not generally considered a good idea to kill processes because you may not be sure about exactly what they are doing.