gpt4 book ai didi

sql - 如何在 SQL Profiler 中配置警报和终止长时间运行的查询

转载 作者:行者123 更新时间:2023-12-02 00:16:02 25 4
gpt4 key购买 nike

我是否可以使用 SQL Profiler 或 Management Studios 中的其他工具配置警报并终止长时间运行的查询?

最佳答案

您可以编写一个存储过程来监视 master 中的系统进程。信用转到 SQL Alert when stored procedure executes for too long

首先,您需要一个新的 UDF,它将作业 ID 转换为 JOIN 的进程 ID:

CREATE FUNCTION dbo.udf_SysJobs_GetProcessid(@job_id uniqueidentifier)
RETURNS VARCHAR(8)
AS
BEGIN
RETURN (substring(left(@job_id,8),7,2) +
substring(left(@job_id,8),5,2) +
substring(left(@job_id,8),3,2) +
substring(left(@job_id,8),1,2))
END

然后是存储过程:

CREATE PROC sp_check_job_running 
@job_name char(50),
@minutes_allowed int,
@person_to_notify varchar(50)

AS

DECLARE @minutes_running int,
@message_text varchar(255)

SELECT @minutes_running = isnull(DATEDIFF(mi, p.last_batch, getdate()), 0)
FROM master..sysprocesses p
JOIN msdb..sysjobs j ON dbo.udf_sysjobs_getprocessid(j.job_id) = substring(p.program_name,32,8)
WHERE j.name = @job_name

IF @minutes_running > @minutes_allowed
BEGIN
SELECT @message_text = ('Job ' + UPPER(SUBSTRING(@job_name,1,LEN(@job_name))) + ' has been running for ' + SUBSTRING(CAST(@minutes_running AS char(5)),1,LEN(CAST(@minutes_running AS char(5)))) + ' minutes, which is over the allowed run time of ' + SUBSTRING(CAST(@minutes_allowed AS char(5)),1,LEN(CAST(@minutes_allowed AS char(5)))) + ' minutes.')
EXEC msdb.dbo.sp_send_dbmail
@recipients = @person_to_notify,
@body = @message_text,
@subject = 'Long-Running Job to Check'
END

然后你可以将存储过程执行为

EXEC sp_check_job_running 'JobNameGoesHere', 5, 'admin@mycompany.com'

关于sql - 如何在 SQL Profiler 中配置警报和终止长时间运行的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13069084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com