I have a stored procedure that extracts historical information — a lot of historical information — but sometimes end users, perhaps by mistake or due to bad practices, send queries larger than they need.
When they realize they've made a mistake, they assume the application has crashed, close the application process, and reopen it to make another request. But internally, the stored procedure continues working on the server to obtain the information. This creates an excessive workload on the server, and I need to stop the execution somehow.
There are several points to consider:
How can I stop execution if the client abruptly closed the connection? or simply if the client stopped expecting an output for that query?
Is there any setting I can enable to limit the stored procedure's response time or detect if the client is still listening? Based on what I've researched, there's no way, but I don't know if anyone has encountered this scenario and resolved it in some clever way.
SQL Server itself does not have visibility into whether the client is still listening or has abandoned the request. Once the stored procedure is invoked, it runs to completion unless:
KILL <SPID>
).Detecting Client Disconnects There’s no built-in SQL Server mechanism to detect client disconnects mid-query. But you can:
sp_who2
or sys.dm_exec_requests
to monitor active sessions and manually kill long-running ones.Limit Execution Time Internally if you have access to SP
You can simulate timeout logic inside the SP:
DECLARE @StartTime DATETIME = GETDATE();
WHILE (DATEDIFF(SECOND, @StartTime, GETDATE()) < 300)
BEGIN
-- Your logic here
-- Break if timeout exceeded
END
This won’t stop the SP if the client disconnects, but it can prevent runaway loops.