Related
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.
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;
Kindly see my Stored Proc below. I'm trying to pass through a value of 1 or 0 from a parameter in a CASE statement.
I get the error which I can tell are in the SELECT statement calling the parameter #payment_status in the CASE statment:
Msg 102, Level 15, State 1, Line 17 Incorrect syntax near '='.
Msg 102, Level 15, State 1, Line 21 Incorrect syntax near '='.
Here's the script:
ALTER PROC ash_ap_cash_req_sp (#End_Date NVARCHAR(12),
#Payment_Hold NVARCHAR(32))
AS
SET NOCOUNT ON
DECLARE #debug INT,
#julian_end_date VARCHAR(7),
#ap_cash_req NVARCHAR(4000),
#payment_status VARCHAR(400)
SET #End_Date = RIGHT('00' + CONVERT(VARCHAR(2), datepart(mm, #End_Date)), 2) + '/' + RIGHT('00' + CONVERT(VARCHAR(2), datepart(dd, #End_Date)), 2) + '/' + RIGHT('0000' + CONVERT(VARCHAR(4), datepart(yyyy, #End_Date)), 4)
SET #julian_end_date = (SELECT datediff(dd, '1/1/1753', #End_Date) + 639906)
IF #Payment_Hold = 'All'
BEGIN
SET #payment_status = '
SELECT payment_hold_flag
FROM dbase.dbo.apvchr
WHERE payment_hold_flag in (0,1)'
END
ELSE IF #Payment_Hold = 'Yes'
BEGIN
SET #payment_status = '
SELECT payment_hold_flag
FROM dbase.dbo.apvchr
WHERE payment_hold_flag = 1'
END
ELSE IF #Payment_Hold = 'No'
BEGIN
SET #payment_status = '
SELECT payment_hold_flag
FROM dbase.dbo.apvchr
WHERE payment_hold_flag = 0'
END
SET #debug = 0
SET #ap_cash_req = '
IF OBJECT_ID(''temp.dbo.##ash_ap_cash_req_sp'') is NOT NULL
DROP TABLE ##ash_ap_cash_req_sp;
CREATE TABLE ##ash_ap_cash_req_sp
(vendor varchar(12)
, pay_to varchar(12)
, vendor_name varchar(32)
, voucher_no varchar(12)
, invoice_no varchar(32)
, date_doc varchar(12)
--, date_doc_jd varchar(12)
, date_due varchar(12)
--, date_due_jd varchar(12)
, date_applied varchar(12)
--, date_applied_jd varchar(12)
, paid_status varchar(8)
--, payment_status varchar(12)
, payment_hold_status varchar(8)
, amount_open decimal(20,2)
, days_diff float
, days_0_to_30 decimal(20,2)
, days_31_to_60 decimal(20,2)
, days_61_to_90 decimal(20,2)
, days_91_to_120 decimal(20,2)
, days_121_to_150 decimal(20,2)
, total_over_90 decimal(20,2)
, total_over_150 decimal(20,2)
, payment_code varchar(8)
)'
IF #debug = 1
BEGIN
PRINT #ap_cash_req
PRINT ''
END
ELSE
BEGIN
EXEC sp_executesql #ap_cash_req
END
SET #ap_cash_req = '
SELECT
m.vendor
, m.pay_to
, m.address_name as vendor_name
, h.trx_ctrl_num as voucher_no
, h.doc_ctrl_num as invoice_no
, CONVERT(varchar(12),dateadd(dd,(h.date_doc- 639906),''1/1/1753''),101) as date_doc
--, h.date_doc as date_doc_jd
, CONVERT(varchar(12),dateadd(dd,(h.date_due- 639906),''1/1/1753''),101) as date_due
--, h.date_due as date_due_jd
, CONVERT(varchar(12),dateadd(dd,(h.date_applied- 639906),''1/1/1753''),101) as date_applied
--, h.date_applied as date_applied_jd
, paid_status = CASE WHEN h.paid_flag = 1
THEN ''Paid''
ELSE ''Not Paid'' END
, h.payment_hold_flag = CASE
WHEN ' + #payment_status + ' = 1 THEN ''On Hold''
ELSE ''Not On Hold''
END as payment_hold_status
, amount_open = (amt_net-amt_paid_to_date)
, h.payment_code
, days_dif = (' + #julian_end_date + ' - h.date_applied)
, days_0_to_30 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-30
THEN h.amt_net --(h.amt_net-h.amt_paid_to_date)
ELSE 0 END
, days_31_to_60 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-60
AND h.date_applied <= ' + #julian_end_date + '-31
THEN h.amt_net
ELSE 0 END
, days_61_to_90 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-90
AND h.date_applied <= ' + #julian_end_date + '-61
THEN h.amt_net
ELSE 0 END
, days_91_to_120 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-120
AND h.date_applied <= ' + #julian_end_date + '-91
THEN h.amt_net
ELSE 0 END
, days_121_to_150 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-150
AND h.date_applied <= ' + #julian_end_date + '-121
THEN h.amt_net
ELSE 0 END
, total_over_90 = CASE WHEN h.date_applied <= ' + #julian_end_date + '-91
THEN h.amt_net
ELSE 0 END
, total_over_150 = CASE WHEN h.date_applied <= ' + #julian_end_date + '-151
THEN h.amt_net
ELSE 0 END
FROM dbase.dbo.apvchr h
JOIN dbase.dbo.apvdet d
ON h.trx_ctrl_num = d.trx_ctrl_num
JOIN dbase.dbo.master m
ON h.vendor = m.vendor
AND h.pay_to = m.pay_to
GROUP BY m.vendor, m.pay_to, m.address_name
, h.trx_ctrl_num, h.doc_ctrl_num, h.date_doc, h.date_due, h.date_applied, h.paid_flag, h.payment_hold_flag
, h.amt_net, h.amt_paid_to_date, h.payment_code, h.payment_hold_flag
--ORDER BY NEWID()
'
IF #debug = 1
BEGIN
PRINT #ap_cash_req
PRINT ''
END
ELSE
BEGIN
EXEC sp_executesql #ap_cash_req
END
SET #ap_cash_req = '
SELECT * FROM ##ash_ap_cash_req_sp
';
SET #ap_cash_req = '
DROP TABLE ##ash_ap_cash_req_sp
';
IF #debug = 1
BEGIN
PRINT #ap_cash_req
PRINT ''
END
ELSE
BEGIN
EXEC sp_executesql #ap_cash_req
END
EXEC dbase.dbo.ash_ap_cash_req_sp;1 '03/11/2013','Yes'
Because #payment_status is a 'SELECT...', you'll need to wrap it with braces
h.payment_hold_flag = CASE
WHEN ('+#payment_status+') = 1 THEN ''On Hold''
ELSE ''Not On Hold''
END as payment_hold_status
but, that aside, I would question the syntax :
, amount_open = (amt_net-amt_paid_to_date)
- do you mean
, (amt_net-amt_paid_to_date) as amount_open?
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];
This is a two-pronged question:
Scenario:
I have a script to query MSDB and get me details of job schedules. Obviously, the tables differ from SQL 2000 to SQL 2005. Hence, I want to check the version running on the box and query accordingly. Now the questions:
Question 1:
This is what I am doing.
IF LEFT(CAST(SERVERPROPERTY('ProductVersion') As Varchar),1)='8'
BEGIN
PRINT 'SQL 2000'--Actual Code Goes Here
END
IF LEFT(CAST(SERVERPROPERTY('ProductVersion') As Varchar),1)='9'
BEGIN
PRINT 'SQL 2005'--Actual Code Goes Here
END
Is there a better way of doing this?
Question 2:
Though the above script runs fine on both 2000 and 2005 boxes, when I replace the "Print.." statements with my actual code, it runs fine on a 2000 box, but when executed on a 2005 box,tries to run the code block meant for 2000 and returns errors.
Here is the actual code:
USE [msdb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--Check SQL Server Version
IF LEFT(CAST(SERVERPROPERTY('ProductVersion') As Varchar),1)='9'
BEGIN
SELECT ##SERVERNAME
,sysjobs.name
,dbo.udf_schedule_description(dbo.sysschedules.freq_type, dbo.sysschedules.freq_interval,
dbo.sysschedules.freq_subday_type, dbo.sysschedules.freq_subday_interval, dbo.sysschedules.freq_relative_interval,
dbo.sysschedules.freq_recurrence_factor, dbo.sysschedules.active_start_date, dbo.sysschedules.active_end_date,
dbo.sysschedules.active_start_time, dbo.sysschedules.active_end_time) AS [Schedule Description]
, CONVERT(CHAR(8), CASE WHEN LEN(msdb.dbo.sysschedules.Active_Start_Time) = 3
THEN CAST('00:0' + LEFT(msdb.dbo.sysschedules.Active_Start_Time, 1) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)),
2, 2) AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysschedules.Active_Start_Time) = 4
THEN CAST('00:'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)),
1, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)),
3, 2) AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysschedules.Active_Start_Time) = 5
THEN CAST('0' + LEFT(msdb.dbo.sysschedules.Active_Start_Time, 1) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)),
2, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)),
4, 2) AS VARCHAR(8))
WHEN msdb.dbo.sysschedules.Active_Start_Time = 0
THEN '00:00:00'
ELSE CAST(LEFT(msdb.dbo.sysschedules.Active_Start_Time, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)),
3, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.Active_Start_Time AS VARCHAR(6)),
5, 2) AS VARCHAR(8))
END, 108) AS Start_Time,
CONVERT(CHAR(8), CASE WHEN LEN(msdb.dbo.sysschedules.active_end_time) = 3
THEN CAST('00:0' + LEFT(msdb.dbo.sysschedules.active_end_time, 1) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)),
2, 2) AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysschedules.active_end_time) = 4
THEN CAST('00:'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)),
1, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)),
3, 2) AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysschedules.active_end_time) = 5
THEN CAST('0' + LEFT(msdb.dbo.sysschedules.active_end_time, 1) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)),
2, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)),
4, 2) AS VARCHAR(8))
WHEN msdb.dbo.sysschedules.active_end_time = 0
THEN '00:00:00'
ELSE CAST(LEFT(msdb.dbo.sysschedules.active_end_time, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)),
3, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysschedules.active_end_time AS VARCHAR(6)),
5, 2) AS VARCHAR(8))
END, 108) AS End_Time
,CAST(CASE WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 1
THEN CAST('00:00:0' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 1)AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 2
THEN CAST('00:00:' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 2)AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 3
THEN CAST('00:0' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 1) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
2, 2) AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 4
THEN CAST('00:'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
1, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
3, 2) AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 5
THEN CAST('0' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 1) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
2, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
4, 2) AS VARCHAR(8))
WHEN msdb.dbo.sysjobservers.last_run_duration = 0
THEN '00:00:00'
ELSE CAST(LEFT(msdb.dbo.sysjobservers.last_run_duration, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
3, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
5, 2) AS VARCHAR(8))
END AS VARCHAR(8)) AS LastRunDuration
FROM msdb.dbo.sysjobs INNER JOIN
msdb.dbo.syscategories ON msdb.dbo.sysjobs.category_id = msdb.dbo.syscategories.category_id LEFT OUTER JOIN
msdb.dbo.sysoperators ON msdb.dbo.sysjobs.notify_page_operator_id = msdb.dbo.sysoperators.id LEFT OUTER JOIN
msdb.dbo.sysjobservers ON msdb.dbo.sysjobs.job_id = msdb.dbo.sysjobservers.job_id LEFT OUTER JOIN
msdb.dbo.sysjobschedules ON msdb.dbo.sysjobschedules.job_id = msdb.dbo.sysjobs.job_id LEFT OUTER JOIN
msdb.dbo.sysschedules ON msdb.dbo.sysjobschedules.schedule_id = msdb.dbo.sysschedules.schedule_id
WHERE sysjobs.enabled = 1 AND msdb.dbo.sysschedules.Active_Start_Time IS NOT NULL
ORDER BY Start_time,sysjobs.name
END
IF LEFT(CAST(SERVERPROPERTY('ProductVersion') As Varchar),1)='8'
BEGIN
SELECT ##SERVERNAME
,sysjobs.name
,dbo.udf_schedule_description(sysjobschedules.freq_type, sysjobschedules.freq_interval,
sysjobschedules.freq_subday_type, sysjobschedules.freq_subday_interval, sysjobschedules.freq_relative_interval,
sysjobschedules.freq_recurrence_factor, sysjobschedules.active_start_date, sysjobschedules.active_end_date,
sysjobschedules.active_start_time, sysjobschedules.active_end_time) AS [Schedule Description]
, CONVERT(CHAR(8), CASE WHEN LEN(msdb.dbo.sysjobschedules.Active_Start_Time) = 3
THEN CAST('00:0' + LEFT(msdb.dbo.sysjobschedules.Active_Start_Time, 1) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)),
2, 2) AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysjobschedules.Active_Start_Time) = 4
THEN CAST('00:'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)),
1, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)),
3, 2) AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysjobschedules.Active_Start_Time) = 5
THEN CAST('0' + LEFT(msdb.dbo.sysjobschedules.Active_Start_Time, 1) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)),
2, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)),
4, 2) AS VARCHAR(8))
WHEN msdb.dbo.sysjobschedules.Active_Start_Time = 0
THEN '00:00:00'
ELSE CAST(LEFT(msdb.dbo.sysjobschedules.Active_Start_Time, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)),
3, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.Active_Start_Time AS VARCHAR(6)),
5, 2) AS VARCHAR(8))
END, 108) AS Start_Time,
CONVERT(CHAR(8), CASE WHEN LEN(msdb.dbo.sysjobschedules.active_end_time) = 3
THEN CAST('00:0' + LEFT(msdb.dbo.sysjobschedules.active_end_time, 1) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)),
2, 2) AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysjobschedules.active_end_time) = 4
THEN CAST('00:'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)),
1, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)),
3, 2) AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysjobschedules.active_end_time) = 5
THEN CAST('0' + LEFT(msdb.dbo.sysjobschedules.active_end_time, 1) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)),
2, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)),
4, 2) AS VARCHAR(8))
WHEN msdb.dbo.sysjobschedules.active_end_time = 0
THEN '00:00:00'
ELSE CAST(LEFT(msdb.dbo.sysjobschedules.active_end_time, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)),
3, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobschedules.active_end_time AS VARCHAR(6)),
5, 2) AS VARCHAR(8))
END, 108) AS End_Time
,CAST(CASE WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 1
THEN CAST('00:00:0' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 1)AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 2
THEN CAST('00:00:' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 2)AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 3
THEN CAST('00:0' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 1) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
2, 2) AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 4
THEN CAST('00:'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
1, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
3, 2) AS VARCHAR(8))
WHEN LEN(msdb.dbo.sysjobservers.last_run_duration) = 5
THEN CAST('0' + LEFT(msdb.dbo.sysjobservers.last_run_duration, 1) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
2, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
4, 2) AS VARCHAR(8))
WHEN msdb.dbo.sysjobservers.last_run_duration = 0
THEN '00:00:00'
ELSE CAST(LEFT(msdb.dbo.sysjobservers.last_run_duration, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
3, 2) + ':'
+ SUBSTRING(CAST(msdb.dbo.sysjobservers.last_run_duration AS VARCHAR(6)),
5, 2) AS VARCHAR(8))
END AS VARCHAR(8)) AS LastRunDuration
FROM sysjobs LEFT OUTER JOIN
msdb.dbo.sysjobservers ON msdb.dbo.sysjobs.job_id = msdb.dbo.sysjobservers.job_id INNER JOIN
sysjobschedules ON sysjobs.job_id = sysjobschedules.job_id
WHERE sysjobs.enabled = 1
ORDER BY Start_time,sysjobs.name
END
This script requires a udf in MSDB. Here is the code for the function:
USE [msdb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[udf_schedule_description] (#freq_type INT ,
#freq_interval INT ,
#freq_subday_type INT ,
#freq_subday_interval INT ,
#freq_relative_interval INT ,
#freq_recurrence_factor INT ,
#active_start_date INT ,
#active_end_date INT,
#active_start_time INT ,
#active_end_time INT )
RETURNS NVARCHAR(255) AS
BEGIN
DECLARE #schedule_description NVARCHAR(255)
DECLARE #loop INT
DECLARE #idle_cpu_percent INT
DECLARE #idle_cpu_duration INT
IF (#freq_type = 0x1) -- OneTime
BEGIN
SELECT #schedule_description = N'Once on ' + CONVERT(NVARCHAR, #active_start_date) + N' at ' + CONVERT(NVARCHAR, cast((#active_start_time / 10000) as varchar(10)) + ':' + right('00' + cast((#active_start_time % 10000) / 100 as varchar(10)),2))
RETURN #schedule_description
END
IF (#freq_type = 0x4) -- Daily
BEGIN
SELECT #schedule_description = N'Every day '
END
IF (#freq_type = 0x8) -- Weekly
BEGIN
SELECT #schedule_description = N'Every ' + CONVERT(NVARCHAR, #freq_recurrence_factor) + N' week(s) on '
SELECT #loop = 1
WHILE (#loop <= 7)
BEGIN
IF (#freq_interval & POWER(2, #loop - 1) = POWER(2, #loop - 1))
SELECT #schedule_description = #schedule_description + DATENAME(dw, N'1996120' + CONVERT(NVARCHAR, #loop)) + N', '
SELECT #loop = #loop + 1
END
IF (RIGHT(#schedule_description, 2) = N', ')
SELECT #schedule_description = SUBSTRING(#schedule_description, 1, (DATALENGTH(#schedule_description) / 2) - 2) + N' '
END
IF (#freq_type = 0x10) -- Monthly
BEGIN
SELECT #schedule_description = N'Every ' + CONVERT(NVARCHAR, #freq_recurrence_factor) + N' months(s) on day ' + CONVERT(NVARCHAR, #freq_interval) + N' of that month '
END
IF (#freq_type = 0x20) -- Monthly Relative
BEGIN
SELECT #schedule_description = N'Every ' + CONVERT(NVARCHAR, #freq_recurrence_factor) + N' months(s) on the '
SELECT #schedule_description = #schedule_description +
CASE #freq_relative_interval
WHEN 0x01 THEN N'first '
WHEN 0x02 THEN N'second '
WHEN 0x04 THEN N'third '
WHEN 0x08 THEN N'fourth '
WHEN 0x10 THEN N'last '
END +
CASE
WHEN (#freq_interval > 00)
AND (#freq_interval < 08) THEN DATENAME(dw, N'1996120' + CONVERT(NVARCHAR, #freq_interval))
WHEN (#freq_interval = 08) THEN N'day'
WHEN (#freq_interval = 09) THEN N'week day'
WHEN (#freq_interval = 10) THEN N'weekend day'
END + N' of that month '
END
IF (#freq_type = 0x40) -- AutoStart
BEGIN
SELECT #schedule_description = FORMATMESSAGE(14579)
RETURN #schedule_description
END
IF (#freq_type = 0x80) -- OnIdle
BEGIN
EXECUTE master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE',
N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent',
N'IdleCPUPercent',
#idle_cpu_percent OUTPUT,
N'no_output'
EXECUTE master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE',
N'SOFTWARE\Microsoft\MSSQLServer\SQLServerAgent',
N'IdleCPUDuration',
#idle_cpu_duration OUTPUT,
N'no_output'
SELECT #schedule_description = FORMATMESSAGE(14578, ISNULL(#idle_cpu_percent, 10), ISNULL(#idle_cpu_duration, 600))
RETURN #schedule_description
END
-- Subday stuff
SELECT #schedule_description = #schedule_description +
CASE #freq_subday_type
WHEN 0x1 THEN N'at ' + CONVERT(NVARCHAR, cast(
CASE WHEN LEN(cast((#active_start_time / 10000)as varchar(10)))=1
THEN '0'+cast((#active_start_time / 10000) as varchar(10))
ELSE cast((#active_start_time / 10000) as varchar(10))
END
as varchar(10)) + ':' + right('00' + cast((#active_start_time % 10000) / 100 as varchar(10)),2))
WHEN 0x2 THEN N'every ' + CONVERT(NVARCHAR, #freq_subday_interval) + N' second(s)'
WHEN 0x4 THEN N'every ' + CONVERT(NVARCHAR, #freq_subday_interval) + N' minute(s)'
WHEN 0x8 THEN N'every ' + CONVERT(NVARCHAR, #freq_subday_interval) + N' hour(s)'
END
IF (#freq_subday_type IN (0x2, 0x4, 0x8))
SELECT #schedule_description = #schedule_description + N' between ' +
CONVERT(NVARCHAR, cast(
CASE WHEN LEN(cast((#active_start_time / 10000)as varchar(10)))=1
THEN '0'+cast((#active_start_time / 10000) as varchar(10))
ELSE cast((#active_start_time / 10000) as varchar(10))
END
as varchar(10)) + ':' + right('00' + cast((#active_start_time % 10000) / 100 as varchar(10)),2) )
+ N' and ' +
CONVERT(NVARCHAR, cast(
CASE WHEN LEN(cast((#active_end_time / 10000)as varchar(10)))=1
THEN '0'+cast((#active_end_time / 10000) as varchar(10))
ELSE cast((#active_end_time / 10000) as varchar(10))
END
as varchar(10)) + ':' + right('00' + cast((#active_end_time % 10000) / 100 as varchar(10)),2) )
RETURN #schedule_description
END
I have got this far and have spent too much time trying to find out what the problem is. Please help.
the errors are compile time (I ran on 2005):
Msg 207, Level 16, State 1, Line 106
Invalid column name 'freq_type'.
Msg 207, Level 16, State 1, Line 106
Invalid column name 'freq_interval'.
Msg 207, Level 16, State 1, Line 107
Invalid column name 'freq_subday_type'.
Msg 207, Level 16, State 1, Line 107
Invalid column name 'freq_subday_interval'.
Msg 207, Level 16, State 1, Line 107
Invalid column name 'freq_relative_interval'.
Msg 207, Level 16, State 1, Line 108
Invalid column name 'freq_recurrence_factor'.
Msg 207, Level 16, State 1, Line 108
Invalid column name 'active_start_date'.
Msg 207, Level 16, State 1, Line 108
Invalid column name 'active_end_date'.
Msg 207, Level 16, State 1, Line 109
Invalid column name 'active_start_time'.
Msg 207, Level 16, State 1, Line 109
Invalid column name 'active_end_time'.
Msg 207, Level 16, State 1, Line 110
I added PRINTs and they never appear.
your code has problems because the column names are not compatible with the database you are running. SQL Server 2005 does not have a "sysjobschedules.freq_type" column.
Make a stored procedure XYZ, put the 2000 version in the 2000 database, put the same XYZ procedure on the 2005 machine and put the 2005 version in it. No IF necessary...
EDIT
run this code:
PRINT 'Works'
now run this code
PRINT 'will not see this'
error
try this:
PRINT 'will not see this'
SELECT xyz from sysjobschedules
now try running this, but only highlight the PRINT line:
PRINT 'you can see this' --only select this line of code and run it
SELECT xyz from sysjobschedules
see how compile errors prevent anything from running
EDIT
you might try something like this...
DECLARE #Query varchar(max)
IF LEFT(CAST(SERVERPROPERTY('ProductVersion') As Varchar),1)='8'
BEGIN
SET #Query=......
END
IF LEFT(CAST(SERVERPROPERTY('ProductVersion') As Varchar),1)='9'
BEGIN
SET #Query=......
END
EXEC (#Query)
The original question is only specific to 2000,2005 but here's some code that should work on 2000, 2005, 2008 and onwards
DECLARE #ver NVARCHAR(128)
DECLARE #majorVersion int
SET #ver = CAST(SERVERPROPERTY('productversion') AS NVARCHAR)
SET #ver = SUBSTRING(#ver,1,CHARINDEX('.',#ver)-1)
SET #majorVersion = CAST(#ver AS INT)
IF #majorVersion < 11
PRINT 'Plesae Upgrade'
ELSE
PRINT #majorVersion
I tried the code on 2008 and it ran fine. are you in the msdb database when running it?
to get the version you can also do this
SELECT
PARSENAME(CONVERT(VARCHAR(100),SERVERPROPERTY('ProductVersion')),4)
AS SqlServerVersion
--I found it easier this way to code for service pack features for multiple SQL versions.
For example, say I want all the new performance counters and know they were released on a particular service pack on multiple SQL versions. So if I code for greater than SQL Server 12 SP3, SQL 2014 SP2, AND SQL 2016 or better I would do this.
DECLARE #sql_version INT = CONVERT(INT,LEFT(REPLACE(CAST(SERVERPROPERTY('ProductVersion') AS CHAR(15)),'.',''),7))
SELECT
CASE
WHEN
(#sql_version >= 1106020 AND #sql_version < 1200000) OR
(#sql_version >= 1205000 AND #sql_version < 1300000) OR
#sql_version >= 1301601
THEN
'Execute code block'
ELSE
'Execute code block'
END
or shorthand like this...
SELECT
CASE
WHEN
(#sql_version BETWEEN 1106020 AND 1200000) OR
(#sql_version BETWEEN 1205000 AND 1300000) OR
#sql_version >= 1301601
THEN
'Execute code block'
ELSE
'Execute code block'
END
Easy, eh?