简体   繁体   中英

How to Control a Long-Running Query

We are currently managing a web application that runs stored procedures, one of which is triggered whenever a user searches for a particular item. Unfortunately we encountered a very serious issue one day for this SP as it went long-running, thus it caused the database to perform very poorly. This eventually caused a lot of problems for our applications. I found out that a long-running query was causing the problem by running this database script:

SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
where
    sqltext.[Text] NOT LIKE '--''check%'
ORDER BY req.cpu_time DESC

So what we did to fix this was to execute KILL [SESSION_ID] and after a few seconds our application was back to normal. Now, we would like to handle this type of problem proactively so when I say control, I would like to know if it is possible for the web application to terminate this session gracefully (not causing subsequent problems) after a certain period or time or should it be handled within SQL Server itself?

If anyone still needs further clarification, please feel free to comment.

Do you really need where sqltext.[Text] NOT LIKE '--''check%' 1.sys.dm_exec_requests also has a start time column, which you currently are not using the where clause. Pass in a start time, so its not going to the beginning of all the data 2. look at the data and try to modify the where clause accordingly. 3. Pull the execution plan for the proc pretty sure it will to do a table scan which is not good.

Here are the steps to get the execution plan Step 1 Please modify dates, proc db name

select distinct top 1000 qs.plan_handle,o.name,d.name--,--ps.database_id
from sys.dm_exec_query_stats  qs
    ,sys.dm_exec_procedure_stats    ps
    ,sys.objects o
    ,sys.databases d
where qs.last_execution_time > '2017-03-29 17:06:42.340' 
and qs.last_execution_time < '2017-03-30 18:19:45.653'
and ps.sql_handle = qs.sql_handle
and o.object_id = ps.object_id
AND o.name = 'Your proc name here'
AND d.database_id = ps.database_id
AND d.name = 'database name '

Step 2 Set output to grid and save as .sqlplan You get a link, if you have enough permissions you can click on it and it will open. Make sure the have query output options set so there is enough space given for xml output.

select query_plan
from sys.dm_exec_query_plan (copy your handle here from step 1, do no use quotes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM