Count the maximum number of continuous not null columns - sql

I have a table in the following structureL
{col_a1, .. ,Col_a15, Continuous_count}
These columns might have either a NULL or a particular value (in col_a1 to col_a15).
I need to find out the most continuous set of data and keep the count in the column continuous_count. For example:
Columns: col_a1 col_a2 col_a3 col_a4 col_a5 col_a6 col_a7 Continuous_count
ROW_1: NULL NULL 2 2 3 NULL 2 3
ROW_2: NULL 1 2 2 3 NULL 2 4
ROW_3: NULL NULL NULL 2 3 NULL 2 2
ROW_4: 2 1 2 2 3 NULL 2 5
I am not able to write the query, i wrote one but looks too big with a lot of ifs and else's. is there a simple method to do this.

The only way I see is check for all combinations of adjacent columns.
I am using power(1,col_ax) below to get 1 for any value and null for null. When adding, combinations having at least one null result in null (and thus in 0 for the use of NVL, because otherwise GREATEST would result in null).
select mytable.*,
greatest
(
nvl(power(1,col_a1), 0),
nvl(power(1,col_a1) + power(1,col_a2), 0),
nvl(power(1,col_a1) + power(1,col_a2) + power(1,col_a3), 0),
nvl(power(1,col_a1) + power(1,col_a2) + power(1,col_a3) + power(1,col_a4), 0),
nvl(power(1,col_a1) + power(1,col_a2) + power(1,col_a3) + power(1,col_a4) + power(1,col_a5), 0),
nvl(power(1,col_a1) + power(1,col_a2) + power(1,col_a3) + power(1,col_a4) + power(1,col_a5) + power(1,col_a6), 0),
nvl(power(1,col_a1) + power(1,col_a2) + power(1,col_a3) + power(1,col_a4) + power(1,col_a5) + power(1,col_a6) + power(1,col_a7), 0),
nvl(power(1,col_a2), 0),
nvl(power(1,col_a2) + power(1,col_a3), 0),
nvl(power(1,col_a2) + power(1,col_a3) + power(1,col_a4), 0),
nvl(power(1,col_a2) + power(1,col_a3) + power(1,col_a4) + power(1,col_a5), 0),
nvl(power(1,col_a2) + power(1,col_a3) + power(1,col_a4) + power(1,col_a5) + power(1,col_a6), 0),
nvl(power(1,col_a2) + power(1,col_a3) + power(1,col_a4) + power(1,col_a5) + power(1,col_a6) + power(1,col_a7), 0),
nvl(power(1,col_a3), 0),
nvl(power(1,col_a3) + power(1,col_a4), 0),
nvl(power(1,col_a3) + power(1,col_a4) + power(1,col_a5), 0),
nvl(power(1,col_a3) + power(1,col_a4) + power(1,col_a5) + power(1,col_a6), 0),
nvl(power(1,col_a3) + power(1,col_a4) + power(1,col_a5) + power(1,col_a6) + power(1,col_a7), 0),
nvl(power(1,col_a4), 0),
nvl(power(1,col_a4) + power(1,col_a5), 0),
nvl(power(1,col_a4) + power(1,col_a5) + power(1,col_a6), 0),
nvl(power(1,col_a4) + power(1,col_a5) + power(1,col_a6) + power(1,col_a7), 0),
nvl(power(1,col_a5), 0),
nvl(power(1,col_a5) + power(1,col_a6), 0),
nvl(power(1,col_a5) + power(1,col_a6) + power(1,col_a7), 0),
nvl(power(1,col_a6), 0),
nvl(power(1,col_a6) + power(1,col_a7), 0),
nvl(power(1,col_a7), 0),
0
) as continous_count
from mytable;

Related

SQL select, sum and group

I'm struggling with an Access database:
I have a large database with the headers TAG, ZST, KL and R1H00 to R1H23 (24 of them, each one stands for one hour of a day) and I need to get a specific dataset out of it:
SELECT TAG, ZST, (R1H00 + R1H01 + R1H02 + R1H03 + R1H04 + R1H05 + R1H06 + R1H07 + R1H08 + R1H09 + R1H10 + R1H11 + R1H12 + R1H13 + R1H14 + R1H15 + R1H16 + R1H17 + R1H18 + R1H19 + R1H20 + R1H21 + R1H22 + R1H23) AS TOTAL
FROM Klassendaten
WHERE KL = "SWISS7_PW"
So far so good, but the result contains many items with the same ID (ZST). I need to sum all entries with the same ZST, but I couldn't manage to do it so far. (I tried to use the GROUP BY statement, but that only results in errors)
Any experienced SQL people here that could help me with this?
use group by
SELECT TAG, ZST, sum(R1H00 + R1H01 + R1H02 + R1H03 + R1H04 + R1H05 + R1H06 + R1H07 + R1H08 + R1H09 + R1H10 + R1H11 + R1H12 + R1H13 + R1H14 + R1H15 + R1H16 + R1H17 + R1H18 + R1H19 + R1H20 + R1H21 + R1H22 + R1H23) AS TOTAL
FROM Klassendaten
WHERE KL = "SWISS7_PW"
GROUP BY TAG, ZST;
Use the Sum() function
SELECT TAG, ZST, Sum(R1H00 + R1H01 + R1H02 + R1H03 + R1H04 + R1H05 + R1H06 + R1H07 + R1H08 + R1H09 + R1H10 + R1H11 + R1H12 + R1H13 + R1H14 + R1H15 + R1H16 + R1H17 + R1H18 + R1H19 + R1H20 + R1H21 + R1H22 + R1H23) AS TOTAL
FROM Klassendaten
where ZST = '(Whatever it is)'
group by tag, zst

convert this date time string

is it possible to convert this date time string
'20150819130706'
to something like this
'2015-08-19 13:07:06'
Here is one option:
DECLARE #DatetimeString char(14) = '20150819130706'
SELECT LEFT(#DatetimeString, 4) + '-' +
SUBSTRING(#DatetimeString, 5, 2) + '-' +
SUBSTRING(#DatetimeString, 7, 2) + ' ' +
SUBSTRING(#DatetimeString, 9, 2) +':' +
SUBSTRING(#DatetimeString, 11, 2) +':' +
RIGHT(#DatetimeString, 2)
If you want an actual datetime value, you can simply cast the entire thing to datetime:
SELECT CAST( LEFT(#DatetimeString, 4) + '-' +
SUBSTRING(#DatetimeString, 5, 2) + '-' +
SUBSTRING(#DatetimeString, 7, 2) + 'T' +
SUBSTRING(#DatetimeString, 9, 2) +':' +
SUBSTRING(#DatetimeString, 11, 2) +':' +
RIGHT(#DatetimeString, 2) As datetime)
Note: for converting to datetime you need to change the ' ' to 'T', see Lad2025's comment to this answer.
Select Convert(varchar(19),
cast(Substring('20150819130706', 1,8)
+ ' ' + Substring('20150819130706',9,2)
+ ':' + Substring('20150819130706',11,2)
+ ':' + Substring('20150819130706',13,2) as datetime),121);
Use this query.

How can I use SUM() to sum my result array?

My current method to add the rows together is like so:
$totalxp = $row['Attackxp'] + $row['Defencexp'] + $row['Strengthxp'] + $row['Hitpointsxp'] + $row['Rangedxp'] + $row['Prayerxp'] + $row['Magicxp'] + $row['Cookingxp'] + $row['Woodcuttingxp'] + $row['Fletchingxp'] + $row['Fishingxp'] + $row['Firemakingxp'] + $row['Craftingxp'] + $row['Smithingxp'] + $row['Miningxp'] + $row['Herblorexp'] + $row['Agilityxp'] + $row['Thievingxp'] + $row['Slayerxp'] + $row['Farmingxp'] + $row['Runecraftxp'] + $row['Constructionxp'];
But then I saw SUM() and I tried this:
SELECT SUM(xp) FROM skills WHERE playerName='Undercover'
It works but I needed all the values of xp, so I tried adding %xp but it wont work.
How could I use the Sum() function to add all the rows up instead of straining PHP?
Aggregate functions (IE: SUM, MIN, MAX, COUNT, etc) don't work across columns--they work on the values for the specific column, based on the grouping (GROUP BY) and filteration (JOIN and/or WHERE clause).
To add up values across columns, you need to add them like you would for normal mathematical equations:
SELECT Attackxp + Defencexp + Strengthxp + Hitpointsxp + Rangedxp + Prayerxp + Magicxp + Cookingxp+ Woodcuttingxp + Fletchingxp + Fishingxp + Firemakingxp + Craftingxp + Smithingxp + Miningxp + Herblorexp + Agilityxp + Thievingxp + Slayerxp + Farmingxp + Runecraftxp + Constructionxp AS total_xp
FROM skills
WHERE playerName = 'Undercover'
If you have more than one record associated to a playername, then you can use an aggregate function:
SELECT SUM(Attackxp + Defencexp + Strengthxp + Hitpointsxp + Rangedxp + Prayerxp + Magicxp + Cookingxp+ Woodcuttingxp + Fletchingxp + Fishingxp + Firemakingxp + Craftingxp + Smithingxp + Miningxp + Herblorexp + Agilityxp + Thievingxp + Slayerxp + Farmingxp + Runecraftxp + Constructionxp) AS total_xp
FROM skills
WHERE playerName = 'Undercover'
That depend of the table data if each player is one entity (row) then is enaught to add columns:
SELECT Attackxp + Defencexp + Strengthxp + Hitpointsxp +Rangedxp + Prayerxp + Magicxp + Cookingxp + Woodcuttingxp + Fletchingxp + Fishingxp + Firemakingxp + Craftingxp + Smithingxp + Miningxp + Herblorexp + Agilityxp + Thievingxp + Slayerxp + Farmingxp + Runecraftxp + Constructionxp
As totalSkills FROM skills WHERE playerName = 'Undercover'
But is there more rows per player then You will need to sum also the rows
SELECT SUM(Attackxp + Defencexp + Strengthxp + Hitpointsxp +Rangedxp + Prayerxp + Magicxp + Cookingxp + Woodcuttingxp + Fletchingxp + Fishingxp + Firemakingxp + Craftingxp + Smithingxp + Miningxp + Herblorexp + Agilityxp + Thievingxp + Slayerxp + Farmingxp + Runecraftxp + Constructionxp)
As totalSkills FROM skills WHERE playerName = 'Undercover'
SELECT SUM(`Attackxp`) + SUM(`Defencexp`) + ... AS `total_sum`
FROM skills
WHERE playerName='Undercover'

How SQL calculates NEXT_RUN_DATE for a job schedule?

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];

Best way to determine Server Product version and execute SQL accordingly?

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?