People are judged from their questions and not their answers. I received wonderful question the other day.
How sqlcmd can be used along with currently running query script posted on your blog?
Please read following two posts before continuing this article as they cover background of this article.
If due to a long running query or any resource hogging query SQL Server is not responding sqlcmd can be used to connect to the server from another computer and kill the offending query. SQL Server provides a special diagnostic connection which allows administrators to access SQL Server when standard connection is not possible. Except very extreme situations dedicated administrator connection (DAC) is always successful.
Let us see how we can use DAC using sqlcmd.
Connect SQL Server using sqlcmd and -A option which will establish DAC.
C:\>sqlcmd -S localhost -U sa -P dev -d master -A
For our test purpose run following query which overload server and probably make it unresponsive. If your configure is not strong I strongly suggest not to run following query.
Following query is just for test purpose and not part of solution.
CROSS JOIN Person.Address a1
CROSS JOIN Person.Address a2
CROSS JOIN Person.Address a3
CROSS JOIN Person.Address a4
CROSS JOIN Person.Address a5
CROSS JOIN Person.Address a6
CROSS JOIN Person.Address a7
CROSS JOIN Person.Address a8
CROSS JOIN Person.Address a9
Once successfully connected it will provide prompt 1> enter following T-SQL query which will give SessionID of currently running query along with its elapsed time.
FROM sys.dm_exec_requests req
WHERE status = 'running'
AND req.total_elapsed_time > 1
Our previously running query gave session id 52 in on my server. The session id may be different for each SQL Server. Once the session id is figured out it can be killed using KILL [SessionID] command. Always make sure to type command GO after each complete query.
Once above query has run it will kill our example long running query and give following error.
Msg 233, Level 20, State 0, Line 0
A transport-level error has occurred when receiving results from the server. (provider: Shared Memory Provider, error: 0 – No process is on the other end of the pipe.)
sqlcmd is really useful utility of SQL Server and it comes in handy when server is not responsive. I strongly suggest to bookmark this article as it can come to rescue when nothing works and SQL Server is unresponsive.
Reference : Pinal Dave (http://blog.SQLAuthority.com)