How SQL calculates NEXT_RUN_DATE for a job schedule? - sql

I have to make a manual calculation of the next run date for a job, can you help me?

to get the next run date for a job you can use then sysschedules and sysjobschedules tables
check the next_run_date and next_runtime columns from the table sysjobschedules
next_run_date int Next date on which
the job is scheduled to run. The date
is formatted YYYYMMDD.
next_run_time int Time at which the
job is scheduled to run. The time is
formatted HHMMSS, and uses a 24-hour
clock.
see this script
Select sched.*,jobsched.* FROM msdb.dbo.sysschedules AS sched
inner Join msdb.dbo.sysjobschedules AS jobsched ON sched.schedule_id = jobsched.schedule_id
or you can use the msdb.dbo.sp_help_jobschedule stored procedure, to get the same info.
UPDATE
if you need calculate manually the next_run_date you must check the sysschedules table and see the freq_interval, freq_subday_type, freq_subday_interval, freq_relative_interval, freq_recurrence_factor, active_start_date, active_start_time columns to determine the formula.
check this link to see an example of use.

Check this one:
SELECT
J.NAME JOB,
DATEADD(SS,(H.RUN_TIME)%100,DATEADD(N,(H.RUN_TIME/100)%100,DATEADD(HH,H.RUN_TIME/10000,CONVERT(DATETIME,CONVERT(VARCHAR(8),H.RUN_DATE),112))))
JOB_STARTED,
DATEADD(SS,((H.RUN_DURATION)%10000)%100,DATEADD(N,((H.RUN_DURATION)%10000)/100,DATEADD(HH,(H.RUN_DURATION)/10000,DATEADD(SS,(H.RUN_TIME)%100,DATEADD(N,(H.RUN_TIME/100)%100,DATEADD(HH,H.RUN_TIME/10000,CONVERT(DATETIME,CONVERT(VARCHAR(8),H.RUN_DATE),112)))))))
JOB_COMPLETED,
CONVERT(VARCHAR(2),(H.RUN_DURATION)/10000) + ':' +
CONVERT(VARCHAR(2),((H.RUN_DURATION)%10000)/100)+ ':' +
CONVERT(VARCHAR(2),((H.RUN_DURATION)%10000)%100) RUN_DURATION,
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'
END RUN_STATUS
,CASE S.FREQ_TYPE
WHEN 1 THEN 'ONCE'
WHEN 4 THEN ' DAILY'
WHEN 8 THEN ' WEEKLY'
WHEN 16 THEN ' MONTHLY'
WHEN 32 THEN ' MONTHLY RELATIVE'
WHEN 64 THEN ' WHEN SQL SERVER'
ELSE 'N/A' END [FREQ]
,CASE
WHEN S.NEXT_RUN_DATE > 0 THEN DATEADD(N,(NEXT_RUN_TIME%10000)/100,DATEADD(HH,NEXT_RUN_TIME/10000,CONVERT(DATETIME,CONVERT(VARCHAR(8),NEXT_RUN_DATE),112)))
ELSE CONVERT(DATETIME,CONVERT(VARCHAR(8),'19000101'),112) END NEXT_RUN
FROM
MSDB..SYSJOBHISTORY H,
MSDB..SYSJOBS J,
MSDB..SYSJOBSCHEDULES S,
(
SELECT
MAX(INSTANCE_ID) INSTANCE_ID
,JOB_ID
FROM MSDB..SYSJOBHISTORY GROUP BY JOB_ID
) M
WHERE
H.JOB_ID = J.JOB_ID
AND
J.JOB_ID = S.JOB_ID
AND
H.JOB_ID = M.JOB_ID
AND
H.INSTANCE_ID = M.INSTANCE_ID
-- IF you want to check all job for today then uncomments below
-- AND
-- RUN_DATE = (YEAR(GETDATE())*10000) + (MONTH(GETDATE()) * 100) + DAY(GETDATE())
ORDER BY NEXT_RUN

The short answer is that there's no single formula - it varies by value of freq_type.
The site seems to be down at the moment of writing, but there is an article at http://www.sqlmag.com/Article/ArticleID/99593/sql_server_99593.html which covers how to derive this information. Unfortunately, the site doesn't allow Google to cache its content, so it can't be retrieved until the site comes back up
This looks like a decent alternative source for the kind of query you're trying to write.

here is a very nice script where you can get the next run date.
-- http://www.sqlprofessionals.com/blog/sql-scripts/2014/10/06/insight-into-sql-agent-job-schedules/
SELECT [JobName] = [jobs].[name]
,[Enabled] = CASE [jobs].[enabled] WHEN 1 THEN 'Yes' ELSE 'No' END
,[Scheduled] = CASE [schedule].[enabled] WHEN 1 THEN 'Yes' ELSE 'No' END
,[Next_Run_Date] =
CASE [jobschedule].[next_run_date]
WHEN 0 THEN CONVERT(DATETIME, '1900/1/1')
ELSE CONVERT(DATETIME, CONVERT(CHAR(8), [jobschedule].[next_run_date], 112) + ' ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [jobschedule].[next_run_time]), 6), 5, 0, ':'), 3, 0, ':'))
END
,[Category] = [categories].[name]
,[Owner] = SUSER_SNAME([jobs].[owner_sid])
,[Description] = [jobs].[description]
,[Occurs] =
CASE [schedule].[freq_type]
WHEN 1 THEN 'Once'
WHEN 4 THEN 'Daily'
WHEN 8 THEN 'Weekly'
WHEN 16 THEN 'Monthly'
WHEN 32 THEN 'Monthly relative'
WHEN 64 THEN 'When SQL Server Agent starts'
WHEN 128 THEN 'Start whenever the CPU(s) become idle'
ELSE ''
END
,[Occurs_detail] =
CASE [schedule].[freq_type]
WHEN 1 THEN 'O'
WHEN 4 THEN 'Every ' + CONVERT(VARCHAR, [schedule].[freq_interval]) + ' day(s)'
WHEN 8 THEN 'Every ' + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ' weeks(s) on ' +
LEFT(
CASE WHEN [schedule].[freq_interval] & 1 = 1 THEN 'Sunday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 2 = 2 THEN 'Monday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 4 = 4 THEN 'Tuesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 8 = 8 THEN 'Wednesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 16 = 16 THEN 'Thursday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 32 = 32 THEN 'Friday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 64 = 64 THEN 'Saturday, ' ELSE '' END ,
LEN(
CASE WHEN [schedule].[freq_interval] & 1 = 1 THEN 'Sunday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 2 = 2 THEN 'Monday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 4 = 4 THEN 'Tuesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 8 = 8 THEN 'Wednesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 16 = 16 THEN 'Thursday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 32 = 32 THEN 'Friday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 64 = 64 THEN 'Saturday, ' ELSE '' END
) - 1
)
WHEN 16 THEN 'Day ' + CONVERT(VARCHAR, [schedule].[freq_interval]) + ' of every ' + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ' month(s)'
WHEN 32 THEN 'The ' +
CASE [schedule].[freq_relative_interval]
WHEN 1 THEN 'First'
WHEN 2 THEN 'Second'
WHEN 4 THEN 'Third'
WHEN 8 THEN 'Fourth'
WHEN 16 THEN 'Last'
END +
CASE [schedule].[freq_interval]
WHEN 1 THEN ' Sunday'
WHEN 2 THEN ' Monday'
WHEN 3 THEN ' Tuesday'
WHEN 4 THEN ' Wednesday'
WHEN 5 THEN ' Thursday'
WHEN 6 THEN ' Friday'
WHEN 7 THEN ' Saturday'
WHEN 8 THEN ' Day'
WHEN 9 THEN ' Weekday'
WHEN 10 THEN ' Weekend Day'
END + ' of every ' + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ' month(s)'
ELSE ''
END
,[Frequency] =
CASE [schedule].[freq_subday_type]
WHEN 1 THEN 'Occurs once at ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':')
WHEN 2 THEN 'Occurs every ' +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ' Seconds(s) between ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':') + ' and ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ':'), 3, 0, ':')
WHEN 4 THEN 'Occurs every ' +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ' Minute(s) between ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':') + ' and ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ':'), 3, 0, ':')
WHEN 8 THEN 'Occurs every ' +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ' Hour(s) between ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':') + ' and ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ':'), 3, 0, ':')
ELSE ''
END
,[AvgDurationInSec] = CONVERT(DECIMAL(10, 2), [jobhistory].[AvgDuration])
FROM [msdb].[dbo].[sysjobs] AS [jobs] WITh(NOLOCK)
LEFT OUTER JOIN [msdb].[dbo].[sysjobschedules] AS [jobschedule] WITh(NOLOCK)
ON [jobs].[job_id] = [jobschedule].[job_id]
LEFT OUTER JOIN [msdb].[dbo].[sysschedules] AS [schedule] WITh(NOLOCK)
ON [jobschedule].[schedule_id] = [schedule].[schedule_id]
INNER JOIN [msdb].[dbo].[syscategories] [categories] WITh(NOLOCK)
ON [jobs].[category_id] = [categories].[category_id]
LEFT OUTER JOIN
( SELECT [job_id], [AvgDuration] = (SUM((([run_duration] / 10000 * 3600) +
(([run_duration] % 10000) / 100 * 60) +
([run_duration] % 10000) % 100)) * 1.0) / COUNT([job_id])
FROM [msdb].[dbo].[sysjobhistory] WITh(NOLOCK)
WHERE [step_id] = 0
GROUP BY [job_id]
) AS [jobhistory]
ON [jobhistory].[job_id] = [jobs].[job_id];

Related

How to get per hour in data set?

I'm trying to get data per hour however as I execute, the data for day is displayed in the table. IDC_YMD with per hour result must be in the table and I'm not sure if I have the right SUBSTR(string, start, length).
SELECT EQP_ID, EQP_NAME, 'WorkPreparation' GUBUN,WorkPreparation
CNT,SITE_CODE,GODS_CODE,STEP_NAME,IDC_YMD,IDC_SUMR_UNIT_CODE,MTBI,MTBA
FROM
(
SELECT CASE WHEN WorkPreparation = 0 THEN '-' ELSE EQP_ID END AS EQP_ID, CASE WHEN WorkPreparation =
0 THEN '-' ELSE SUBSTR(EQP_NAME,1,4) END AS EQP_NAME,
WorkPreparation,SITE_CODE,GODS_CODE,STEP_NAME,IDC_YMD,IDC_SUMR_UNIT_CODE,MTBI,MTBA
FROM(
SELECT EQP_ID, EVENT_COMMENT EQP_NAME, SUM(WORK_PRE_CNT) WorkPreparation, A.SITE_CODE
, A.GODS_CODE
, A.EES_STEP_ID AS STEP_NAME
, TO_CHAR(TO_NUMBER(SUBSTR(A.IDC_YMD, 12, 2))) || '/' || TO_CHAR(TO_NUMBER(SUBSTR(A.IDC_YMD, 12,
2))) AS IDC_YMD
, 'D' AS IDC_SUMR_UNIT_CODE
, CASE WHEN (SUM(NVL(A.INTR_CNT, 0)) + SUM(NVL(A.BRDN_CNT, 0))) = 0
THEN ROUND(SUM(NVL(A.OPER_MOP, 0)),1)
ELSE ROUND(SUM(NVL(A.OPER_MOP, 0)) / (SUM(NVL(A.INTR_CNT, 0)) + SUM(NVL(A.BRDN_CNT, 0))) /
60,1)
END AS MTBI
, CASE WHEN (SUM(NVL(A.INTR_CNT, 0)) + SUM(NVL(A.BRDN_CNT, 0)) + SUM(NVL(A.WORK_PRE_CNT, 0)) +
SUM(NVL(A.PROD_CHANGE_CNT, 0)) + SUM(NVL(A.QUAL_EXATN_CNT, 0)) +
SUM(NVL(A.MTR_EXATN_CNT, 0)) + SUM(NVL(A.STEP_CHRC_LOSS_CNT, 0)) +
SUM(NVL(A.IDLE_3MN_UND_EXCPT_CNT, 0))) = 0
THEN 0
ELSE ROUND(SUM(NVL(A.OPER_MOP, 0)) / (SUM(NVL(A.INTR_CNT, 0)) + SUM(NVL(A.BRDN_CNT, 0)) +
SUM(NVL(A.WORK_PRE_CNT, 0)) + SUM(NVL(A.PROD_CHANGE_CNT, 0)) + SUM(NVL(A.QUAL_EXATN_CNT, 0)) +
SUM(NVL(A.MTR_EXATN_CNT, 0)) + SUM(NVL(A.STEP_CHRC_LOSS_CNT,
0)) + SUM(NVL(A.IDLE_3MN_UND_EXCPT_CNT, 0))) / 60,1)
END AS MTBA
FROM IFR_EES_PCL A
WHERE SITE_CODE = 'E502AA'
AND GODS_CODE = 'N5210'
AND MTBI_MNG_YN = 'Y'
AND EES_STEP_ID = 'TP'
AND A.IDC_YMD BETWEEN TO_CHAR(SYSDATE-6, 'YYYYMMDDHH') AND TO_CHAR(SYSDATE, 'YYYYMMDD')
GROUP BY EQP_ID, EVENT_COMMENT,A.SITE_CODE
, A.GODS_CODE
,A.EQP_TYPE
, A.EES_STEP_ID
, TO_CHAR(TO_NUMBER(SUBSTR(A.IDC_YMD, 12, 2)))
, A.IDC_YMD
ORDER BY A.IDC_YMD, MTBI DESC--TO_CHAR(TO_NUMBER(SUBSTR(A.IDC_YMD, 12, 2)))
))
WHERE ROWNUM <= 10
and EQP_NAME like 'TA%'
Thank you!

SQL Query not producing 'Disabled' jobs within the results, alongside 'Failed' jobs

I have the following code for a SQL Query I'm working on..
DECLARE #Date datetime
SET #Date = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
DECLARE #jobHistory TABLE
(
job_id UNIQUEIDENTIFIER
, success INT
, cancel INT
, fail INT
, retry INT
, last_execution_id INT
, last_duration CHAR(8)
, last_execution_start DATETIME
);
WITH lastExecution
AS
(
SELECT job_id
, MAX(instance_id) AS last_instance_id
FROM msdb.dbo.sysjobhistory
WHERE step_id = 0
GROUP BY job_id
)
INSERT INTO #jobHistory
SELECT sjh.job_id
, SUM(CASE WHEN sjh.run_status = 1 AND step_id = 0 THEN 1 ELSE 0 END) AS success
, SUM(CASE WHEN sjh.run_status = 3 AND step_id = 0 THEN 1 ELSE 0 END) AS cancel
, SUM(CASE WHEN sjh.run_status = 0 AND step_id = 0 THEN 1 ELSE 0 END) AS fail
, SUM(CASE WHEN sjh.run_status = 2 THEN 1 ELSE 0 END) AS retry
, MAX(CASE WHEN sjh.step_id = 0 THEN instance_id ELSE NULL END) last_execution_id
, SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),2,2) + ':'
+ SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),4,2) + ':'
+ SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),6,2)
AS last_duration
, MAX(CASE WHEN le.last_instance_id IS NOT NULL THEN
CONVERT(datetime, RTRIM(run_date))
+ ((run_time / 10000 * 3600)
+ ((run_time % 10000) / 100 * 60)
+ (run_time % 10000) % 100) / (86399.9964)
ELSE '1900-01-01' END) AS last_execution_start
FROM msdb.dbo.sysjobhistory AS sjh
LEFT JOIN lastExecution AS le
ON sjh.job_id = le.job_id
AND sjh.instance_id = le.last_instance_id
GROUP BY sjh.job_id;
DECLARE #weekDay TABLE (
mask INT
, maskValue VARCHAR(32)
);
INSERT INTO #weekDay
SELECT 1, 'Sunday' UNION ALL
SELECT 2, 'Monday' UNION ALL
SELECT 4, 'Tuesday' UNION ALL
SELECT 8, 'Wednesday' UNION ALL
SELECT 16, 'Thursday' UNION ALL
SELECT 32, 'Friday' UNION ALL
SELECT 64, 'Saturday';
WITH myCTE
AS(
SELECT sched.name AS 'scheduleName'
, sched.schedule_id
, jobsched.job_id
, CASE
WHEN sched.freq_type = 1
THEN 'Once'
WHEN sched.freq_type = 4
AND sched.freq_interval = 1
THEN 'Daily'
WHEN sched.freq_type = 4
THEN 'Every ' + CAST(sched.freq_interval AS VARCHAR(5)) + ' days'
WHEN sched.freq_type = 8 THEN
REPLACE( REPLACE( REPLACE((
SELECT maskValue
FROM #weekDay AS x
WHERE sched.freq_interval & x.mask <> 0
ORDER BY mask FOR XML RAW)
, '"/><row maskValue="', ', '), '<row maskValue="', ''), '"/>', '')
+ CASE
WHEN sched.freq_recurrence_factor <> 0
AND sched.freq_recurrence_factor = 1
THEN '; weekly'
WHEN sched.freq_recurrence_factor <> 0
THEN '; every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' weeks' END
WHEN sched.freq_type = 16 THEN 'On day '
+ CAST(sched.freq_interval AS VARCHAR(10)) + ' of every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' months'
WHEN sched.freq_type = 32 THEN
CASE
WHEN sched.freq_relative_interval = 1 THEN 'First'
WHEN sched.freq_relative_interval = 2 THEN 'Second'
WHEN sched.freq_relative_interval = 4 THEN 'Third'
WHEN sched.freq_relative_interval = 8 THEN 'Fourth'
WHEN sched.freq_relative_interval = 16 THEN 'Last'
END +
CASE
WHEN sched.freq_interval = 1 THEN ' Sunday'
WHEN sched.freq_interval = 2 THEN ' Monday'
WHEN sched.freq_interval = 3 THEN ' Tuesday'
WHEN sched.freq_interval = 4 THEN ' Wednesday'
WHEN sched.freq_interval = 5 THEN ' Thursday'
WHEN sched.freq_interval = 6 THEN ' Friday'
WHEN sched.freq_interval = 7 THEN ' Saturday'
WHEN sched.freq_interval = 8 THEN ' Day'
WHEN sched.freq_interval = 9 THEN ' Weekday'
WHEN sched.freq_interval = 10 THEN ' Weekend'
END
+ CASE
WHEN sched.freq_recurrence_factor <> 0
AND sched.freq_recurrence_factor = 1
THEN '; monthly'
WHEN sched.freq_recurrence_factor <> 0
THEN '; every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' months'
END
WHEN sched.freq_type = 64 THEN 'StartUp'
WHEN sched.freq_type = 128 THEN 'Idle'
END AS 'frequency'
, ISNULL('Every ' + CAST(sched.freq_subday_interval AS VARCHAR(10)) +
CASE
WHEN sched.freq_subday_type = 2 THEN ' seconds'
WHEN sched.freq_subday_type = 4 THEN ' minutes'
WHEN sched.freq_subday_type = 8 THEN ' hours'
END, 'Once') AS 'subFrequency'
, REPLICATE('0', 6 - LEN(sched.active_start_time))
+ CAST(sched.active_start_time AS VARCHAR(6)) AS 'startTime'
, REPLICATE('0', 6 - LEN(sched.active_end_time))
+ CAST(sched.active_end_time AS VARCHAR(6)) AS 'endTime'
, REPLICATE('0', 6 - LEN(jobsched.next_run_time))
+ CAST(jobsched.next_run_time AS VARCHAR(6)) AS 'nextRunTime'
, CAST(jobsched.next_run_date AS CHAR(8)) AS 'nextRunDate'
FROM msdb.dbo.sysschedules AS sched
JOIN msdb.dbo.sysjobschedules AS jobsched
ON sched.schedule_id = jobsched.schedule_id
WHERE sched.enabled = 1
)
SELECT job.name AS [Job Name]
, CASE WHEN job.enabled = 1 THEN 'Enabled' ELSE 'Disabled' END AS [Job Status]
, COALESCE(sched.subFrequency, '') AS [Frequency]
, COALESCE(jh.last_duration, '') AS [Last Run Duration]
, COALESCE(jh.last_execution_start, '') AS [Last Run Time/Date]
FROM msdb.dbo.sysjobs AS job
LEFT JOIN myCTE AS sched
ON job.job_id = sched.job_id
LEFT JOIN #jobHistory AS jh
ON job.job_id = jh.job_id
WHERE jh.last_execution_start >= DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
AND job.name like '%MAINTENANCE - BACKUP%'
ORDER BY nextRunDate;
but although the results show the expected 'Failed' jobs, the 'Disabled' jobs are missing. I have also had help with this, as I have no SQL experience.
This Query has been created to check the Job History of roughtly 5/10 Backup Jobs within a 24 hour period, noting all the Failures (even if the last Run Succeeded). The seconds on the [Last Run Time/Date] also seem to be off, showing as soemthign like '50:00.0'
I also need a new column for the [Last Run Outcome] - to show if the Job 'Failed/Succeeded' as a Status.
Please let me know if you require any further information or a PasteBin of my code.

How to get the SQL Server job schdule in a readable format?

On SQL Server 2008, each job under sql agent can have a schedule. I can get the data from these 2 tables:
sysjobs
sysschedules
How do I use SQL to get the schedule data in readable format? For example, display it as:
Job Name, Daily + time
or
Job Name, Weekly + time
This may be a bit beyond the scope of what you're looking for however this script from Michelle Ufford should be way beyond what you need.
I'm also posting the code on the off chance the blog disappears.
Declare #weekDay Table (
mask int
, maskValue varchar(32)
);
Insert Into #weekDay
Select 1, 'Sunday' Union All
Select 2, 'Monday' Union All
Select 4, 'Tuesday' Union All
Select 8, 'Wednesday' Union All
Select 16, 'Thursday' Union All
Select 32, 'Friday' Union All
Select 64, 'Saturday';
With myCTE
As(
Select sched.name As 'scheduleName'
, sched.schedule_id
, jobsched.job_id
, Case When sched.freq_type = 1 Then 'Once'
When sched.freq_type = 4
And sched.freq_interval = 1
Then 'Daily'
When sched.freq_type = 4
Then 'Every ' + Cast(sched.freq_interval As varchar(5)) + ' days'
When sched.freq_type = 8 Then
Replace( Replace( Replace((
Select maskValue
From #weekDay As x
Where sched.freq_interval & x.mask <> 0
Order By mask For XML Raw)
, '"/><row maskValue="', ', '), '<row maskValue="', ''), '"/>', '')
+ Case When sched.freq_recurrence_factor <> 0
And sched.freq_recurrence_factor = 1
Then '; weekly'
When sched.freq_recurrence_factor <> 0 Then '; every '
+ Cast(sched.freq_recurrence_factor As varchar(10)) + ' weeks' End
When sched.freq_type = 16 Then 'On day '
+ Cast(sched.freq_interval As varchar(10)) + ' of every '
+ Cast(sched.freq_recurrence_factor As varchar(10)) + ' months'
When sched.freq_type = 32 Then
Case When sched.freq_relative_interval = 1 Then 'First'
When sched.freq_relative_interval = 2 Then 'Second'
When sched.freq_relative_interval = 4 Then 'Third'
When sched.freq_relative_interval = 8 Then 'Fourth'
When sched.freq_relative_interval = 16 Then 'Last'
End +
Case When sched.freq_interval = 1 Then ' Sunday'
When sched.freq_interval = 2 Then ' Monday'
When sched.freq_interval = 3 Then ' Tuesday'
When sched.freq_interval = 4 Then ' Wednesday'
When sched.freq_interval = 5 Then ' Thursday'
When sched.freq_interval = 6 Then ' Friday'
When sched.freq_interval = 7 Then ' Saturday'
When sched.freq_interval = 8 Then ' Day'
When sched.freq_interval = 9 Then ' Weekday'
When sched.freq_interval = 10 Then ' Weekend'
End
+ Case When sched.freq_recurrence_factor <> 0
And sched.freq_recurrence_factor = 1 Then '; monthly'
When sched.freq_recurrence_factor <> 0 Then '; every '
+ Cast(sched.freq_recurrence_factor As varchar(10)) + ' months' End
When sched.freq_type = 64 Then 'StartUp'
When sched.freq_type = 128 Then 'Idle'
End As 'frequency'
, IsNull('Every ' + Cast(sched.freq_subday_interval As varchar(10)) +
Case When sched.freq_subday_type = 2 Then ' seconds'
When sched.freq_subday_type = 4 Then ' minutes'
When sched.freq_subday_type = 8 Then ' hours'
End, 'Once') As 'subFrequency'
, Replicate('0', 6 - Len(sched.active_start_time))
+ Cast(sched.active_start_time As varchar(6)) As 'startTime'
, Replicate('0', 6 - Len(sched.active_end_time))
+ Cast(sched.active_end_time As varchar(6)) As 'endTime'
, Replicate('0', 6 - Len(jobsched.next_run_time))
+ Cast(jobsched.next_run_time As varchar(6)) As 'nextRunTime'
, Cast(jobsched.next_run_date As char(8)) As 'nextRunDate'
From msdb.dbo.sysschedules As sched
Join msdb.dbo.sysjobschedules As jobsched
On sched.schedule_id = jobsched.schedule_id
Where sched.enabled = 1
)
Select job.name As 'jobName'
, sched.scheduleName
, sched.frequency
, sched.subFrequency
, SubString(sched.startTime, 1, 2) + ':'
+ SubString(sched.startTime, 3, 2) + ' - '
+ SubString(sched.endTime, 1, 2) + ':'
+ SubString(sched.endTime, 3, 2)
As 'scheduleTime' -- HH:MM
, SubString(sched.nextRunDate, 1, 4) + '/'
+ SubString(sched.nextRunDate, 5, 2) + '/'
+ SubString(sched.nextRunDate, 7, 2) + ' '
+ SubString(sched.nextRunTime, 1, 2) + ':'
+ SubString(sched.nextRunTime, 3, 2) As 'nextRunDate'
/* Note: the sysjobschedules table refreshes every 20 min,
so nextRunDate may be out of date */
, 'Execute msdb.dbo.sp_update_job #job_id = '''
+ Cast(job.job_id As char(36)) + ''', #enabled = 0;' As 'disableScript'
From msdb.dbo.sysjobs As job
Join myCTE As sched
On job.job_id = sched.job_id
Where job.enabled = 1 -- do not display disabled jobs
Order By nextRunDate;

Can't put a second "with" statement into the query

I have a query - which is combining with a Union statement the 5 columns into 2 columns.
So basically - an ID + Some Information. As the ID could be in column 2-5 - several times... I rearranged to be everything in one ID column + the text.
Now - I wanted to use a second "with" statement - to combine the IDs of several rows - with a XML path. But here I got stuck.
That is the code - which gives me the two column - with content as expected:
With
STall as (Select
'Status: ' + ST.Status + Char(10) + 'Crew Information:' + Char(10) +
'Instructor: ' + ST.IP + Char(10) + 'Student: ' + ST.SP + Char(10) + Case
When ST.ACM1 = 'NA' Then '' Else 'ACM1: ' + ST.ACM1 + Char(10) End + Case
When ST.ACM2 = 'NA' Then '' Else 'ACM2: ' + ST.ACM2 + Char(10)
End + 'Lesson: ' + ST.Lesson + Char(10) + Case
When ST.ScheduleRemarks = '' Then ''
Else ' REM:' + ST.ScheduleRemarks + Char(10)
End + 'Equipment: ' + ST.EquipmentName + ' (' + ST.Callsign + ')' +
Char(10) + 'Start: ' + Convert(VARCHAR(10),ST.ScheduleTO,104) + ' - ' +
Convert(VARCHAR(5),ST.ScheduleTO,108) + ' UTC' + Char(10) + 'End: ' +
Convert(VARCHAR(10),ST.ScheduleTD,104) + ' - ' +
Convert(VARCHAR(5),ST.ScheduleTD,108) + ' UTC' + Char(10) + Case
When ST.ATC = 'NA' Then '' Else ST.ATC End As SInfo,
ST.IDIP,
ST.IDSP,
ST.IDA1,
ST.IDA2
From
(Select
Case When Schedule.StatusRelease = 1 Then 'OK' Else Case
When Schedule.StatusRequest = 1 Then 'STBY' Else 'N/A' End
End As Status,
Schedule.ContactIDIP,
Schedule.ContactIDSP,
MasterLesson.Lesson,
Equipment.EquipmentName,
CallSignList.Callsign,
Schedule.Meeting,
Schedule.ScheduleRemarks,
Schedule.StatusRelease,
Schedule.StatusRequest,
Schedule.ScheduleDay,
ContactList.FullNameTLC As IP,
ContactList1.FullNameTLC As SP,
Case When Schedule.ContactIDACM1 = 0 Then 'NA'
Else ContactList2.FullNameTLC End As ACM1,
Case When Schedule.ContactIDACM2 = 0 Then 'NA'
Else ContactList3.FullNameTLC End As ACM2,
Schedule.ScheduleTO,
Schedule.ScheduleTD,
Case When Schedule.RouteID = 0 Then 'NA'
Else 'Route: ' + Airport.ICAO + ' - ' + Case
When IsNull(Airport1.ICAO, 'NA') = 'NA' Then ' '
Else Airport1.ICAO + ' - ' End + Airport2.ICAO + Char(10) + Char(13)
End As ATC,
ContactList.Id As IDIP,
ContactList1.Id As IDSP,
ContactList2.Id As IDA1,
ContactList3.Id As IDA2
From
Schedule Inner Join
StudentLesson On Schedule.ScheduleLessonID = StudentLesson.StudentLessonID
Inner Join
MasterLesson On StudentLesson.LessonID = MasterLesson.ID Inner Join
Equipment On Schedule.EquipmentID = Equipment.ID Left Join
CallSignList On CallSignList.ID = Schedule.CallSignListID Left Join
Route On Route.ID = Schedule.RouteID Inner Join
ContactList On ContactList.Id = Schedule.ContactIDIP Inner Join
ContactList ContactList1 On ContactList1.Id = Schedule.ContactIDSP
Left Join
ContactList ContactList2 On Schedule.ContactIDACM1 = ContactList2.Id
Left Join
ContactList ContactList3 On Schedule.ContactIDACM2 = ContactList3.Id
Left Join
Airport On Route.AirportID_Dep = Airport.ID Left Join
Airport Airport1 On Route.AirportID_Via = Airport1.ID Left Join
Airport Airport2 On Route.AirportID_Arr = Airport2.ID
Where
((Schedule.StatusRelease = 1) Or
(Schedule.StatusRequest = 1)) And
Schedule.ScheduleDay = '21.02.2014') As ST)
Select Distinct
STall.IDIP,SInfo
From
STall
where STall.IDIP > 0
UNION
Select Distinct
STall.IDSP,SInfo
From
STall
where STall.IDSP > 0
UNION
Select Distinct
STall.IDA1,SInfo
From
STall
where STall.IDA1 > 0
UNION
Select Distinct
STall.IDA2,SInfo
From
STall
where STall.IDA2 > 0
Now - I tried to add another With STtotal as ( in the beginning...
and
)
Select Distinct
STsub.IDIP,
SubString((Select
+Char(10) + STn1.SInfo As [text()]
From
STsub STn1
Where
STn1.IDIP = STtotal.IDIP
Order By
STn1.IDIP
For Xml Path('')), 2, 1000) ScheduleInfo
From
STtotal
But I get an error - with wrong Statement at "with".
Maybe there is another approach - how to combine - the "Info Text" column with all IDs - which could be in column 2-5.
Thanks for any imput
Separate your CTEs with a comma; the WITH only needs to be specified once:
;WITH CTE1 AS (
...
), CTE2 AS (
...
)
SELECT ...
Did you remember to put a semi colon at the end of the first statement?

SQL Server 2000 - last run/execution time of SP/View/UDF

This is a production SQL Server 2000 database with about 1500 database objects (SPs, Views, UDFs). Now, I’m told that about 20% of these database objects are unused by the applications (200 of them mostly small built on multiple platforms/technologies) and I’m tasked to identify them.
Is there a script that I could run against the database to identify the “last run date/time” of these database objects?
Is there any other way to identify the unused database objects – APART FROM browsing through the code? Please note that this is SQL Server 2000. Any help is highly appreciated.
Thank you
I had to write some code for my SQL2000 servers.
I insert these into a table for constant monitoring
This first bit of code will tell you when jobs are scheduled to run
SET #SQL = 'SELECT
J.[name] AS [JobName]
, CASE S.[enabled]
WHEN 1 THEN ''Yes''
WHEN 0 THEN ''No''
END AS [IsEnabled]
, CASE
WHEN [freq_type] = 64 THEN ''Start automatically when SQL Server Agent starts''
WHEN [freq_type] = 128 THEN ''Start whenever the CPUs become idle''
WHEN [freq_type] IN (4,8,16,32) THEN ''Recurring''
WHEN [freq_type] = 1 THEN ''One Time''
END [ScheduleType]
, CASE [freq_type]
WHEN 1 THEN ''One Time''
WHEN 4 THEN ''Daily''
WHEN 8 THEN ''Weekly''
WHEN 16 THEN ''Monthly''
WHEN 32 THEN ''Monthly - Relative to Frequency Interval''
WHEN 64 THEN ''Start automatically when SQL Server Agent starts''
WHEN 128 THEN ''Start whenever the CPUs become idle''
END [Occurrence]
, CASE [freq_type]
WHEN 4 THEN ''Occurs every '' + CAST([freq_interval] AS VARCHAR(3)) + '' day(s)''
WHEN 8 THEN ''Occurs every '' + CAST([freq_recurrence_factor] AS VARCHAR(3))
+ '' week(s) on ''
+ CASE WHEN [freq_interval] & 1 = 1 THEN ''Sunday'' ELSE '''' END
+ CASE WHEN [freq_interval] & 2 = 2 THEN '', Monday'' ELSE '''' END
+ CASE WHEN [freq_interval] & 4 = 4 THEN '', Tuesday'' ELSE '''' END
+ CASE WHEN [freq_interval] & 8 = 8 THEN '', Wednesday'' ELSE '''' END
+ CASE WHEN [freq_interval] & 16 = 16 THEN '', Thursday'' ELSE '''' END
+ CASE WHEN [freq_interval] & 32 = 32 THEN '', Friday'' ELSE '''' END
+ CASE WHEN [freq_interval] & 64 = 64 THEN '', Saturday'' ELSE '''' END
WHEN 16 THEN ''Occurs on Day '' + CAST([freq_interval] AS VARCHAR(3))
+ '' of every ''
+ CAST([freq_recurrence_factor] AS VARCHAR(3)) + '' month(s)''
WHEN 32 THEN ''Occurs on ''
+ CASE [freq_relative_interval]
WHEN 1 THEN ''First''
WHEN 2 THEN ''Second''
WHEN 4 THEN ''Third''
WHEN 8 THEN ''Fourth''
WHEN 16 THEN ''Last''
END
+ '' ''
+ CASE [freq_interval]
WHEN 1 THEN ''Sunday''
WHEN 2 THEN ''Monday''
WHEN 3 THEN ''Tuesday''
WHEN 4 THEN ''Wednesday''
WHEN 5 THEN ''Thursday''
WHEN 6 THEN ''Friday''
WHEN 7 THEN ''Saturday''
WHEN 8 THEN ''Day''
WHEN 9 THEN ''Weekday''
WHEN 10 THEN ''Weekend day''
END
+ '' of every '' + CAST([freq_recurrence_factor] AS VARCHAR(3))
+ '' month(s)''
END AS [Recurrence]
, CASE [freq_subday_type]
WHEN 1 THEN ''Occurs once at ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([active_start_time] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
WHEN 4 THEN ''Occurs every ''
+ CAST([freq_subday_interval] AS VARCHAR(3)) + '' Minute(s) between ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([active_start_time] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
+ '' & ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([active_end_time] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
WHEN 8 THEN ''Occurs every ''
+ CAST([freq_subday_interval] AS VARCHAR(3)) + '' Hour(s) between ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([active_start_time] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
+ '' & ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([active_end_time] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
END [Frequency],
FROM '+ #Server +'.[msdb].[dbo].[sysjobschedules] AS S INNER JOIN
'+ #Server +'.[msdb].[dbo].[sysjobs] AS J ON S.[job_id] = J.[job_id]
WHERE S.[enabled] = 1
ORDER BY J.[Name]'
EXEC (#SQL)
This next bit of code will tell you last run of jobs and if the suceeded or not
SET #SQL = 'SELECT
[sJOB].[job_id] AS [JobID]
,[sJOB].[name] AS [JobName]
,CASE
WHEN [sJOBH].[run_date] IS NULL OR [sJOBH].[run_time] IS NULL THEN NULL
ELSE CAST(
CAST([sJOBH].[run_date] AS CHAR(8))
+ '' ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([sJOBH].[run_time] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
AS DATETIME)
END AS [LastRunDateTime]
, CASE [sJOBH].[run_status]
WHEN 0 THEN ''Failed''
WHEN 1 THEN ''Succeeded''
WHEN 2 THEN ''Retry''
WHEN 3 THEN ''Canceled''
WHEN 4 THEN ''Running''
END AS [LastRunStatus]
, STUFF(
STUFF(RIGHT(''000000'' + CAST([sJOBH].[run_duration] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
AS [LastRunDuration (HH:MM:SS)]
, [sJOBH].[message] AS [LastRunStatusMessage]
, CASE [sJOBSCH].[NextRunDate]
WHEN 0 THEN NULL
ELSE CAST(
CAST([sJOBSCH].[NextRunDate] AS CHAR(8))
+ '' ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([sJOBSCH].[NextRunTime] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
AS DATETIME)
END AS [NextRunDateTime]
FROM
'+ #Server +'.[msdb].[dbo].[sysjobs] AS [sJOB]
LEFT JOIN (
SELECT
[job_id]
, MAX([next_run_date]) AS [NextRunDate]
, MAX([next_run_time]) AS [NextRunTime]
FROM '+#Server +'.[msdb].[dbo].[sysjobschedules]
GROUP BY [job_id]
) AS [sJOBSCH]
ON [sJOB].[job_id] = [sJOBSCH].[job_id]
LEFT JOIN (
SELECT
[job_id]
, [run_date]
, [run_time]
, [run_status]
, [run_duration]
, [message]
FROM '+ #Server +'.[msdb].[dbo].[sysjobhistory]
WHERE [step_id] = 0
) AS [sJOBH]
ON [sJOB].[job_id] = [sJOBH].[job_id]
-- AND [sJOBH].[RowNumber] = 1
ORDER BY [JobName]'
--PRINT (#SQL)
EXEC (#SQL)
Replace the #Server with your server name or set the variable #Server to the name of the server you want to run the scripts against