Getting error using "GROUP BY WITH ROLLUP" and "ORDER BY" - sql

I could use your help on this. I am running a stored procedure in SQL Server 2008 R2 where I import data into an Excel worksheet.
I am able to import the information I need just fine except for the order of the output.
This is what I get:
1 - OUTCO
10 - OUT
11 - MATCH
12 - UNRSL
2 - INCO
3 - UNDEL
4 - MAIL
5 - NOTSU
6 - NOMSI
7 - RSRCH
9 - IN
9 - INCOM
I would like to display it with the proper numeric order.
1,2,3,4,5,6,7,9,9,10,11,12.
Here is the code:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [Temp].[dmv_import]
#date DATE = NULL,
#import_type VARCHAR(5) = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE #date_work DATE
IF #date IS NULL
SET #date_work = GETDATE()
ELSE
SET #date_work = #date
SELECT
CASE
WHEN CONVERT(VARCHAR(8), import_code) + ' - ' + vi.import_reason IS NULL
THEN 'TOTAL'
ELSE CONVERT(VARCHAR(8), import_code) + ' - ' + vi.import_reason
END AS 'Category',
SUM(CASE WHEN CONVERT(DATE, vi.createdate, 101) = #date_work THEN 1 ELSE 0 END) AS 'received',
SUM(CASE WHEN CONVERT(DATE, vi.processed_date, 101) = #date_work THEN 1 ELSE 0 END) AS 'processed'
FROM
DIMSNet.dbo.voter_import vi
WHERE
vi.import_type IN ('DMV', 'DUP','INET')
AND import_code < 13
GROUP BY
CONVERT(VARCHAR(8), import_code) + ' - ' +vi.import_reason WITH ROLLUP
END
I have tried a few different ORDER BY clauses, but I keep getting conversion errors.
1) ORDER BY CONVERT(INT, LEFT((vi.import_code + ' - ' + vi.import_reason), 2))
2) ORDER BY LEFT((vi.import_code + ' - ' + vi.import_reason),PATINDEX('%[-]%',(vi.import_code + ' - ' + vi.import_reason)-1), CAST(RIGHT((vi.import_code + ' - ' + vi.import_reason), LEN((vi.import_code + ' - ' + vi.import_reason)) - 2) AS INT)
3) ORDER BY (CONVERT(VARCHAR(8), import_code) + ' - ' + vi.import_reason) ASC
4) order by
case
WHEN ISNUMERIC(vi.import_code + ' - ' + vi.import_reason) = 1
THEN CAST(vi.import_code + ' - ' + vi.import_reason AS FLOAT)
WHEN ISNUMERIC(LEFT((vi.import_code + ' - ' + vi.import_reason),1)) = 0 THEN ASCII(LEFT(LOWER((vi.import_code + ' - ' + vi.import_reason)),1))
ELSE 2147483647 End
None of these has returned a properly formatted output.
Any help would be appreciated.

Assuming your codes are all numeric, try this:
order by cast(max(import_code) as int)
If not, you can use a case expression:
order by (case when isnumeric(max(import_code)) = 1
then max(import_code)
end)
The key here is using the aggregation function to just order by the import_code.

Related

Select more values on clause IF in the stored procedure

I have a problem of syntax in my stored procedure when a select more values in my IF, on code snippet 37 OR 35.
IF 37 OR 35 NOT IN (SELECT CodPerfilSistema
FROM [BRSAODB09].[ADMIN].[dbo].[PERFIL_USUARIO]
WHERE CodUsuario = #pCodUsuario)
BEGIN
SET #CondicaoEmpresa = ' AND [Lote].CodEmpresa = ' + CONVERT(varchar(10), #pCodEmpresa);
SET #CondicaoProjeto = ' AND [AUD_Projeto].CodProjeto = ' + CONVERT(varchar(10), #pCodProjeto);
END
I tried the code above.
And below is how the code is running
IF 37 NOT IN (SELECT CodPerfilSistema
FROM [BRSAODB09].[ADMIN].[dbo].[PERFIL_USUARIO]
WHERE CodUsuario = #pCodUsuario)
BEGIN
SET #CondicaoEmpresa = ' AND [Lote].CodEmpresa = ' + CONVERT(varchar(10), #pCodEmpresa);
SET #CondicaoProjeto = ' AND [AUD_Projeto].CodProjeto = ' + CONVERT(varchar(10), #pCodProjeto);
END
I need the permission for Id 37 and 35.
try the below
IF not exists (SELECT * FROM [BRSAODB09].[ADMIN].[dbo].[PERFIL_USUARIO] where CodUsuario = #pCodUsuario
and CodPerfilSistema in (37,35))
BEGIN
SET #CondicaoEmpresa = ' AND [Lote].CodEmpresa = ' + CONVERT(varchar(10), #pCodEmpresa);
SET #CondicaoProjeto = ' AND [AUD_Projeto].CodProjeto = ' + CONVERT(varchar(10), #pCodProjeto);
END
Thanks guys for the help, I found a way to solve the problem I had.
It stayed like this:
IF NOT EXISTS(
SELECT 1
FROM [BRSAODB09].[ADMIN].[dbo].[PERFIL_USUARIO]
WHERE CodUsuario = #pCodUsuario
AND CodPerfilSistema IN(37,35)
)
BEGIN
SET #CondicaoEmpresa = ' AND [Lote].CodEmpresa = ' + CONVERT(varchar(10),
#pCodEmpresa);
SET #CondicaoProjeto = ' AND [AUD_Projeto].CodProjeto = ' + CONVERT(varchar(10),
#pCodProjeto);
END

Replace Bit Values (1) with Day names SQL

with following query i select days (bit values) from my database into a string separated with blank space:
SELECT CONVERT(VARCHAR(20),BPL_MONDAY) + ' ' +
CONVERT(VARCHAR(20),BPL_TUESDAY) + ' ' +
CONVERT(VARCHAR(20),BPL_WEDNESDAY) + ' ' +
CONVERT(VARCHAR(20),BPL_THURSDAY) + ' ' +
CONVERT(VARCHAR(20),BPL_FRIDAY) + ' ' +
CONVERT(VARCHAR(20),BPL_SATURDAY) + ' ' +
CONVERT(VARCHAR(20),BPL_SUNDAY)
FROM BOS_PRICE_LIST
Result of the query looks something like this:
Now i want to replace 1 with current day name. Example of one row:
Current query result: 1 1 1 1 1 0 0
What i want: Monday Tuesday Wednesday Thursday Friday
Thanks for help
Greetings
Use CASE statement
SELECT case when BPL_MONDAY = 1 then 'Monday' else '' end +
case when BPL_TUESDAY = 1 then 'Tuesday' else '' end +
case when BPL_WEDNESDAY = 1 then 'Wednesday' else '' end +
case when BPL_THURSDAY = 1 then 'Thursday' else '' end +
case when BPL_FRIDAY = 1 then 'Friday' else '' end +
case when BPL_SATURDAY = 1 then 'Saturday' else '' end +
case when BPL_SUNDAY = 1 then 'Sunday' else '' end
FROM BOS_PRICE_LIST

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 example with checkbox

Need your help with checkboxes.
Here is my code:
CREATE PROCEDURE stad_list
#inp_location_code numeric (3,0) = -1
#inp_item_code_bgn numeric (5,0) = -1
#inp_item_code_end numeric (5,0) = -1
#inp_shipped numeric (2,0) = 0, --checkbox, if it is checked then returns the items in table which were shipped (value in table is 1)
#inp_check numeric (2,0) = 0, --checkbox, if it is checked then returns data which is still in process of checking for availability in warehouse (value in table is 0)
#inp_not_ship numeric(2,0) = 0 --checkbox, if it is checked then returns data which had not been shipped during some problems (valuein table is 2)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SELECT as varchar (3000) = ''
DECLARE #WHERE as varchar (1000) = ''
IF (#inp_location_code != -1)
SET #WHERE = #WHERE + ' WHERE [dbo].item.location =' + CONVERT(varchar,#inp_location_code)
IF (#inp_item_code_bgn != -1)
SET #WHERE = #WHERE + ' AND [dbo].item.code>=' + CONVERT(varchar, #inp_item_code_bgn)
IF (#inp_item_code_end != -1)
SET #WHERE = #WHERE + ' AND [dbo].item.code<=' + CONVERT(varchar, #inp_item_code_end)
IF (#inp_shipped = 1)
SET #WHERE = #WHERE + ' AND [dbo].item.ship = 1'
IF (#inp_check = 1)
SET #WHERE = #WHERE + ' AND [dbo].item.ship = 0'
IF (#inp_not_ship = 1)
SET #WHERE = #WHERE + ' AND [dbo].item.ship = 2'
SET #SELECT = #SELECT + '
SELECT
[dbo].item.name as ''NAME'',
[dbo].item.location as ''LOCATION'',
[dbo].item.code as ''CODE'',
[dbo].item.ship as ''STATUS''
FROM [dbo].item '
+ #WHERE
EXEC (#SELECT)
RETURN ##ROWCOUNT
END
It works fine when i am checking only one check box, but cant get any data while 2 of it are checked. So what to do in case when i want to check two check boxes? Any suggestions?
here is my table
Id Item_code Item_name Item_location Item_ship
1 14789 Juice Tokyo 0
2 14785 Boots Tokyo 2
3 98744 Hat Osaka 0
4 36987 Socks Kyoto 1
And there is three checkboxes
Shipped
Checking
Not shipped
If i check shipped then output will be like this:
Id Item_code Item_name Item_location Item_ship
4 36987 Socks Kyoto 1
but i want to do so for ex. when i check Shipped and Checking then the output will be:
Id Item_code Item_name Item_location Item_ship
1 14789 Juice Tokyo 0
3 98744 Hat Osaka 0
4 36987 Socks Kyoto 1
Use temp table as table of parameters
IF (#inp_shipped = 1) OR (#inp_check = 1) OR (#inp_not_ship = 1)
BEGIN
IF OBJECT_ID('tempdb.dbo.#Parameters') IS NOT NULL DROP TABLE dbo.#Parameters
SELECT *
INTO #Parameters
FROM (
SELECT CASE WHEN #inp_shipped = 1 THEN 1 END AS Ship
UNION ALL
SELECT CASE WHEN #inp_check = 1 THEN 0 END
UNION ALL
SELECT CASE WHEN #inp_not_ship = 1 THEN 2 END
) p
WHERE p.Ship IS NOT NULL
SET #WHERE = #WHERE + ' AND [dbo].item.ship IN (SELECT ship FROM #Parameters)'
END
For better performance(made ​​to use index seek operation) if you have an index on the ship column, need to create an index on a temporary table:
CREATE INDEX x ON #Parameters(ship)
You could combine you options into this kind of construction:
declare #orcheck varchar(255)
set #orcheck = 'AND 1=2 ('
IF (#inp_shipped = 1)
SET #orcheck = #orcheck + ' OR [dbo].item.ship = 1'
IF (#inp_check = 1)
SET #orcheck = #orcheck + ' OR [dbo].item.ship = 0'
IF (#inp_not_ship = 1)
SET #orcheck = #orcheck + ' OR [dbo].item.ship = 2'
set #orcheck = #orcheck + ')'
This way, when you have all 3 checkboxes selected, the WHERE clause would look like this:
AND (1=2
OR [dbo].item.ship = 1
OR [dbo].item.ship = 0
OR [dbo].item.ship = 2
)
And when nothing is select, it would be:
AND (1=2
)
Which is what you expect, I believe.

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