前两天某SQLServer服务器断断续续出现性能问题,综合排查之后怀疑是job定时任务引起的,于是查了一下job的schedule和最近一次执行情况,大部分job的schedule都没有问题,由于当前实例是启用了复制分发,无意中喵到'Distribution clean up: distribution这个job的下一次执行时间明显不正常,启用了复制分发之后,自动生成的Distribution clean up: distribution这个job还是比较熟悉的,该job是每10分钟运行一次,这里查出来的LastRunDateTime和NextRunDate竟然是一样的?一度怀疑这个SQL有问题,不过也用了很多年了,之前也没有留意有这个问题。

但是通过作业活动监视器(job activity monitor)看到job的下一次运行时间又是正常的。

查了下资料,有人指出这种方式查询出来的下一次运行时间有同样的问题,原来这是一个一直存在的问题,评论区里出高手:
The only problem with this query is that the next_run_time value could be not accurate for jobs with an interval less then 20min because the sysjobschedules view is refreshed at the same interval, 20min. So the view (and the query from the article) will return a next_run_time that is actually in the past until the next time it will be refreshed. 
就是说SQLServer系统表刷新间隔是20mins一次,如果一个job执行完之后,还没有来得及刷新,查出来的最后执行时间以及下一次执行时间可能是不准确的,可以通过exec msdb.dbo.sp_get_composite_job_info这个系统存储过程来查询。

https://blog.sqlauthority.com/2008/12/22/sql-server-find-next-running-time-of-scheduled-job-using-t-sql/ 参考评论区

T-SQL代码

select 	 j.name as 'JobName'	 ,j.job_id	 ,case h.run_status		when 0 then 'Failed'		when 1 then 'Succeeded'		when 2 then 'Retry'		when 3 then 'Canceled'		when 4 then 'In Progress'	else 'unknow' end as RunStatus	 ,msdb.dbo.agent_datetime(h.run_date, h.run_time) as 'LastRunDateTime'	 ,run_duration as [RunDuration]	 ,sj.next_run_date	 ,sj.next_run_time	 ,case 		 when sj.next_run_date>0 and sj.next_run_time>0 			then  msdb.dbo.agent_datetime(sj.next_run_date, sj.next_run_time)		 else 			null  end as 'NextRunDateTime'From msdb.dbo.sysjobs j cross apply (select top 1 * from msdb.dbo.sysjobhistory h where j.job_id = h.job_id order by instance_id desc )hleft join msdb.dbo.sysjobschedules sj on j.job_id = sj.job_id  where  j.name  = 'Distribution clean up: distribution'order by JobName desc;--怀疑上面SQL有问题,单独查原始表,结果也是一样的select * from msdb.dbo.sysjobs where job_id = 'BECFCA04-E800-4F8B-9FCA-F3DFDD279C11';select * from msdb.dbo.sysjobschedules where job_id = 'BECFCA04-E800-4F8B-9FCA-F3DFDD279C11';--启用OPENROWSETEXEC sp_configure 'show advanced options', 1;RECONFIGURE;EXEC sp_configure 'Ad Hoc Distributed Queries', 1;RECONFIGURE;--通过OPENROWSET执行,可以筛选出想要的字段SELECT *FROM OPENROWSET('SQLNCLI', 'server=localhost,2433;UID=sa;PWD=******;','exec msdb.dbo.sp_get_composite_job_info')--或者执行执行sp_get_composite_job_infoexec msdb.dbo.sp_get_composite_job_info

 

本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:[email protected]