Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can sql server queries be really cancelled/killed?

Tags:

c#

sql-server

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.

  • Cmd - SqlCommand
  • DA - DataAdapter
  • Conn - SqlConnection
  • CurrentSearch - Thread
  • LongQuery - Singleton

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?

like image 981
Candide Avatar asked Oct 20 '11 14:10

Candide


People also ask

What happens when you cancel a query in SQL Server?

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.

How do I stop a running query in SQL Server?

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.

What is cancel query?

The CANCEL QUERY statement cancels a running SQL query.

How do you end a 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.


1 Answers

IF you really absolutely want to kill it for good use this approach:

  • store away the session ID right before starting the long-running query by calling SELECT @@SPID AS 'SESSIONID' on the same connection

When you want to kill it:

  • Open a new DB connection
  • issue a KILL command for that session ID
    BEWARE as the MSDN documentation states you need the permission ALTER ANY CONNECTION to do this
like image 189
Yahia Avatar answered Oct 01 '22 04:10

Yahia