I would like to give a user the ability to cancel a running query. The query is really slow. (Query optimization is besides the point.) This is mainly out of my curiosity.
MSDN says:
If there is nothing to cancel, nothing occurs. However, if there is a command in process, and the attempt to cancel fails, no exception is generated.
Here's what I have:
var t = new Thread(AbortThread);
t.Start();
void AbortThread()
{
LongQuery.Current.Cmd.Cancel();
LongQuery.Current.Cmd.Dispose();
LongQuery.Current.DA.Dispose();
LongQuery.Current.Conn.Close();
LongQuery.Current.Conn.Dispose();
LongQuery.Current.Cmd = null;
LongQuery.Current.DA = null;
LongQuery.Current.Conn = null;
CurrentSearch.Abort();
CurrentSearch.Join();
CurrentSearch = null;
}
I noticed that CurrentSearch.Abort()
was blocking, that's why I wrapped it in a thread, which probably means that the thread is still working.
Finally, is there anything else than this that I can do to cancel a query? Is it actually possible to cancel such a long query from .NET?
It never cancels instantly. Somtimes it may have to finish the disk I/O or some complex calculation before it can actually stop the query. Sometimes, this doesn't happen until after the query is complete in SQL Server, but then it rollsback the and returns nothing, just like it never happened.
Use KILL SPID command to eliminate blocking in SQL Server Execute the following query in SSMS session. The SPID for this session is 60. In another session, it tries to get records of the table. The SPID for this session is 83.
The CANCEL QUERY statement cancels a running SQL query.
Scroll down to the SPID of the process you would like to kill. Right click on that line and select 'Kill Process'. A popup window will open for you to confirm that you want to kill the process. Once this is done, the process will be terminated and all uncompleted transactions will begin the rollback process.
IF you really absolutely want to kill it for good use this approach:
SELECT @@SPID AS 'SESSIONID'
on the same connectionWhen you want to kill it:
KILL
command for that session IDALTER ANY CONNECTION
to do thisIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With