Related
I've been away for sometime and need help with, what is probably a simple solution but at this time I'm stuck. I have this select statement and need to combine rows with like elements for the same department but the group by would have a very large select list, is there another way like MERGE? Here is the sql stmt I'm dealing with along with the output:
SELECT distinct sg.Description as 'Groups', si.Store_Name, a.Store_ID, si.Store_ID1 as 'Store #2', d.Department_ID as 'Dept', a.Vendor_ID,
IIF(d.Delivery_Day = 1, dbo.DayOfWeekToString(d.Order_Day),null) as 'Sun',
IIF(d.Delivery_Day = 1, CONCAT(CONVERT(varchar, d.Deadline_Hour) , ':', RIGHT('00' + CONVERT(varchar, d.Deadline_Minute), 2)) ,null ) as 'time',
IIF(d.Delivery_Day = 2, dbo.DayOfWeekToString(d.Order_Day),null) as 'Mon',
IIF(d.Delivery_Day = 2, CONCAT(CONVERT(varchar, d.Deadline_Hour) , ':', RIGHT('00' + CONVERT(varchar, d.Deadline_Minute), 2)) ,null ) as 'time',
IIF(d.Delivery_Day = 3, dbo.DayOfWeekToString(d.Order_Day),null) as 'Tue',
IIF(d.Delivery_Day = 3, CONCAT(CONVERT(varchar, d.Deadline_Hour) , ':', RIGHT('00' + CONVERT(varchar, d.Deadline_Minute), 2)) ,null ) as 'time',
IIF(d.Delivery_Day = 4, dbo.DayOfWeekToString(d.Order_Day),null) as 'Wed',
IIF(d.Delivery_Day = 4, CONCAT(CONVERT(varchar, d.Deadline_Hour) , ':', RIGHT('00' + CONVERT(varchar, d.Deadline_Minute), 2)) ,null ) as 'time',
IIF(d.Delivery_Day = 5, dbo.DayOfWeekToString(d.Order_Day),null) as 'Thu',
IIF(d.Delivery_Day = 5, CONCAT(CONVERT(varchar, d.Deadline_Hour) , ':', RIGHT('00' + CONVERT(varchar, d.Deadline_Minute), 2)) ,null ) as 'time',
IIF(d.Delivery_Day = 6, dbo.DayOfWeekToString(d.Order_Day),null) as 'Fri',
IIF(d.Delivery_Day = 6, CONCAT(CONVERT(varchar, d.Deadline_Hour) , ':', RIGHT('00' + CONVERT(varchar, d.Deadline_Minute), 2)) ,null ) as 'time',
IIF(d.Delivery_Day = 7, dbo.DayOfWeekToString(d.Order_Day),null) as 'Sat',
IIF(d.Delivery_Day = 7, CONCAT(CONVERT(varchar, d.Deadline_Hour) , ':', RIGHT('00' + CONVERT(varchar, d.Deadline_Minute), 2)),null) as 'time'
from Delivery_Schedule_Header a Join Vendor_Info b ON (a.Vendor_ID = b.Vendor_ID) Join Delivery_Schedule_Detail d on d.UID_Delivery = a.UID
Join Store_Info si on si.Store_ID = a.Store_ID Join Store_Group sg on sg.GroupStore_UID = si.GroupStore_UID
Where a.Vendor_ID = #Vendor_Id and si.GroupStore_UID = Case when #Group_Id = -1 then si.GroupStore_UID else #Group_Id end
and the results:
Groups Store_Name Store_ID Store #2 Dept Vendor_ID Sun time Mon time Tue time Wed time Thu time Fri time Sat time
Balls Price Chopper 18 18 18 3200 70038000 NULL NULL NULL NULL NULL NULL NULL NULL Wednesday 11:00 NULL NULL NULL NULL
Balls Price Chopper 18 18 18 3200 70038000 NULL NULL NULL NULL Monday 11:00 NULL NULL NULL NULL NULL NULL NULL NULL
Balls Price Chopper 18 18 18 3200 70038000 Saturday 11:00 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
These three rows need to be combined under the same department
sorry if this is rather elementary but I've been out of this type of work for sometime now and need a refresher. Thanks
You want conitional aggregation. This works by creating a group by clause that contains all columns except those you want to merge, and then surround the conditional expression with an aggregate function (such as MIN() or MAX():
SELECT
sg.Description as Groups,
si.Store_Name,
a.Store_ID,
si.Store_ID1 as Store_2,
d.Department_ID as Dept,
a.Vendor_ID,
MAX(CASE WHEN d.Delivery_Day = 1 THEN dbo.DayOfWeekToString(d.Order_Day) END) as Sun,
MAX(CASE
WHEN d.Delivery_Day = 1
THEN CONCAT(CONVERT(varchar, d.Deadline_Hour) , ':', RIGHT('00' + CONVERT(varchar, d.Deadline_Minute), 2))
) as Sun_time,
...
FROM Delivery_Schedule_Header a
JOIN Vendor_Info b ON a.Vendor_ID = b.Vendor_ID
JOIN Delivery_Schedule_Detail d ON d.UID_Delivery = a.UID
JOIN Store_Info si ON si.Store_ID = a.Store_ID
JOIN Store_Group sg ON sg.GroupStore_UID = si.GroupStore_UID
WHERE
a.Vendor_ID = #Vendor_Id
AND si.GroupStore_UID = CASE WHEN #Group_Id = -1 THEN si.GroupStore_UID ELSE #Group_Id END
GROUP BY
sg.Description as Groups,
si.Store_Name,
a.Store_ID,
si.Store_ID1 as Store_2,
d.Department_ID as Dept,
a.Vendor_ID
Side notes:
I rewrote the IIF() expressions to use CASE (the latter is standard SQL, while the former is TSQL-specific)
single quotes should be used for litteral strings, not for column identifiers (although SQL Server tolerates this)
you have multiple columns in the resultset that have the same name (time), this is not a good practice
I have N jobs with M steps in each, that could change any time(Add/delete some steps). Jobs have different schedule to run. I want a query to get last run status, job id, job name of each job. Is it right way to do this scenario by (Job outcome) ?
This is the query I use (a little tuned) to check job status. This variation will select the last job outcome for each job.
SELECT
JobName = J.name,
H.*
FROM
msdb.dbo.sysjobs AS J
CROSS APPLY (
SELECT TOP 1
JobName = J.name,
StepNumber = T.step_id,
StepName = T.step_name,
StepStatus = CASE T.run_status
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Succeeded'
WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Canceled'
ELSE 'Running' END,
ExecutedAt = msdb.dbo.agent_datetime(T.run_date, T.run_time),
ExecutingHours = ((T.run_duration/10000 * 3600 + (T.run_duration/100) % 100 * 60 + T.run_duration % 100 + 31 ) / 60) / 60,
ExecutingMinutes = ((T.run_duration/10000 * 3600 + (T.run_duration/100) % 100 * 60 + T.run_duration % 100 + 31 ) / 60) % 60,
Message = T.message
FROM
msdb.dbo.sysjobhistory AS T
WHERE
T.job_id = J.job_id
ORDER BY
T.instance_id DESC) AS H
ORDER BY
J.name
If you change the TOP 1 for TOP 2, then you will also see the last step executed, aside from the job outcome.
You can not get everything in a single query and need more research. For e.g., to know Job execution information you can try the following query.
SELECT
[sJOB].[job_id] AS [JobID]
, [sJOB].[name] AS [JobName]
, CASE
WHEN [sJOBH].[run_date] IS NULL OR [sJOBH].[run_time] IS NULL THEN NULL
ELSE CAST(
CAST([sJOBH].[run_date] AS CHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJOBH].[run_time] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS DATETIME)
END AS [LastRunDateTime]
, CASE [sJOBH].[run_status]
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Succeeded'
WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Canceled'
WHEN 4 THEN 'Running' -- In Progress
END AS [LastRunStatus]
, STUFF(
STUFF(RIGHT('000000' + CAST([sJOBH].[run_duration] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS [LastRunDuration (HH:MM:SS)]
, [sJOBH].[message] AS [LastRunStatusMessage]
, CASE [sJOBSCH].[NextRunDate]
WHEN 0 THEN NULL
ELSE CAST(
CAST([sJOBSCH].[NextRunDate] AS CHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJOBSCH].[NextRunTime] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS DATETIME)
END AS [NextRunDateTime]
FROM
[msdb].[dbo].[sysjobs] AS [sJOB]
LEFT JOIN (
SELECT
[job_id]
, MIN([next_run_date]) AS [NextRunDate]
, MIN([next_run_time]) AS [NextRunTime]
FROM [msdb].[dbo].[sysjobschedules]
GROUP BY [job_id]
) AS [sJOBSCH]
ON [sJOB].[job_id] = [sJOBSCH].[job_id]
LEFT JOIN (
SELECT
[job_id]
, [run_date]
, [run_time]
, [run_status]
, [run_duration]
, [message]
, ROW_NUMBER() OVER (
PARTITION BY [job_id]
ORDER BY [run_date] DESC, [run_time] DESC
) AS RowNumber
FROM [msdb].[dbo].[sysjobhistory]
WHERE [step_id] = 0
) AS [sJOBH]
ON [sJOB].[job_id] = [sJOBH].[job_id]
AND [sJOBH].[RowNumber] = 1
ORDER BY [JobName]
You can get and learn in details - Here and Here
I have a list of months that get populated into my DB. These months then get populated into a drop down list for a web Application. The client wants the current month to be the default option in the drop down list. However, the current month's data is not always available (Or ActiveFlag=Y in the database). So in that case, the client wants the default to be the first month of the year instead.
So I am testing that the drop down list and the DB table match using Selenium automation with C#. I have an SQL query that returns the Top 1 sorted in Descending order (This works to return the last active month in the year, because BroadcastMonthofYearNbr contains integers 1 through 12 month numbers):
SELECT top 1 CONCAT(RTRIM(left(M.Name, CHARINDEX(',',M.Name)-1)), ' (', STUFF(REPLACE('/'+CONVERT( VARCHAR(10), M.StartDate, 101), '/0', '/'), 1, 1, ''), '-', STUFF(REPLACE('/'+CONVERT(VARCHAR(10), M.EndDate, 101), '/0', '/'), 1, 1, ''), ')')
FROM [AudienceProjections].[dbo].[BroadcastCalendarQuarterMonthMap] QMP,
AudienceProjections.dbo.BroadcastCalendarYear Y,
AudienceProjections.dbo.BroadcastCalendarMonth M,
AudienceProjections.dbo.BroadcastCalendarQuarter Q
WHERE y.BroadcastCalendarYearUuid = q.BroadcastCalendarYearUuid
AND q.BroadcastCalendarQuarterUuid = qmp.BroadcastCalendarQuarterUuid
AND qmp.BroadcastCalendarMonthUuid = m.BroadcastCalendarMonthUuid
AND M.ActiveStatus = 'ACTIVE'
AND y.ActiveStatus = 'ACTIVE'
AND q.BroadcastQuarterType = 'STANDARD'
AND y.BroadcastCalendarYear = YEAR(GETDATE())
ORDER BY qmp.BroadcastMonthofYearNbr DESC
The query above returns this:
No Column Name
April (3/28/2016-4/24/2016)
The current month for when I am posting this question is May 5th. Notice that the above query result returns April, not May. This is because May data has not yet been imported into the DB (See below table for distinction of the data being there or not. I.e Active versus Inactive). So my query wont work in this case. I would now need a CASE THEN ELSE, or an IF EXISTS type of function, to return January if this situation occurs
Here is the Month table that you can see have May as INACTIVE:
Name StartDate EndDate ActiveStatus
January, 2016 2015-12-28 2016-01-31 ACTIVE
February, 2016 2016-02-01 2016-02-28 ACTIVE
March, 2016 2016-02-29 2016-03-27 ACTIVE
April, 2016 2016-03-28 2016-04-24 ACTIVE
May, 2016 2016-04-25 2016-05-29 INACTIVE
NOTE: I forgot about the situation of the current date being January, and if January isnt there, then the Year wouldnt be there yet either. So the condition in the query would need to take Year into account. The year table (BroadcastCalendarYear) also has an ActiveStatus column which can be used.
So if the year is also inactive, then return me a string that says "No data in DB for Year".
I assume you will be able to adapt the following to your specific schema but here is an example as order by that would work. Note you may not need and should remove some of the where statements hard to know without knowing the dataset.
Also what month should be returned if it is January of the current year and nothing is active? You may have to adapt the order by depending on that answer.
SELECT TOP 1 *
FROM
#Months
WHERE
ActiveStates = 'ACTIVE'
AND ????
ORDER BY
CASE WHEN YEAR(GETDATE()) = YearInt THEN 9999 ELSE YearInt END DESC -- Assumes you want to order by most recent to oldest and that youcould potentially have a future year loaded in the table. Othwerwuse simply use YearInt DESC
,CASE WHEN MONTH(GETDATE()) = MonthInt THEN 0 ELSE 1 END --Puts precedence on current month
,MonthInt DESC
I hope this helps.
IF OBJECT_ID(N'tempdb..#Month') IS NOT NULL
DROP TABLE #Month
CREATE TABLE #Month
(Year INT, Month VARCHAR(3), ActiveStatus CHAR(1))
INSERT INTO #Month(Year, Month, ActiveStatus)
VALUES(2016,'Jan','A')
,(2016,'Feb','A')
,(2016,'Mar','A')
,(2016,'Apr','A')
,(2016,'May','I')
;WITH x AS
(
SELECT
*,EOMONTH(CONCAT(Year,'-',Month,'-','01')) As Date
FROM #Month
)
SELECT
*
FROM X
WHERE
-- current month is active or current month is inactive then first month of the current year
Year = YEAR(GETDATE()) AND
(DATEPART(MONTH,Date)=DATEPART(MONTH,GETDATE()) AND ActiveStatus='A') OR (1=DATEPART(MONTH,Date) AND EXISTS(SELECT 1 FROM x WHERE DATEPART(MONTH,Date)=DATEPART(MONTH,GETDATE()) AND ActiveStatus='I'))
I figured it out with a long and convoluted solution, but it works.
SELECT CASE WHEN t.month = (SELECT left(M.Name, CHARINDEX(',',M.Name)-1) FROM [AudienceProjections].[dbo].[BroadcastCalendarMonth] M
WHERE StartDate <= GETDATE() AND EndDate >= GETDATE() ) THEN CONCAT(RTRIM(left(t.Name, CHARINDEX(',',t.Name)-1)), ' (', STUFF(REPLACE('/'+CONVERT( VARCHAR(10), t.StartDate, 101), '/0', '/'), 1, 1, ''), '-', STUFF(REPLACE('/'+CONVERT(VARCHAR(10), t.EndDate, 101), '/0', '/'), 1, 1, ''), ')') ELSE ( SELECT CONCAT(RTRIM(left(M.Name, CHARINDEX(',',M.Name)-1)), ' (', STUFF(REPLACE('/'+CONVERT( VARCHAR(10), M.StartDate, 101), '/0', '/'), 1, 1, ''), '-', STUFF(REPLACE('/'+CONVERT(VARCHAR(10), M.EndDate, 101), '/0', '/'), 1, 1, ''), ')') FROM AudienceProjections.dbo.BroadcastCalendarMonth M WHERE NAME = CONCAT( DATENAME(month,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)), ', ', DATENAME(year,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)) ) ) END month FROM (
SELECT top 1 left(M.Name, CHARINDEX(',',M.Name)-1) AS month,
M.Name, M.StartDate, M.EndDate
FROM [AudienceProjections].[dbo].[BroadcastCalendarQuarterMonthMap] QMP,
AudienceProjections.dbo.BroadcastCalendarYear Y,
AudienceProjections.dbo.BroadcastCalendarMonth M,
AudienceProjections.dbo.BroadcastCalendarQuarter Q
WHERE y.BroadcastCalendarYearUuid = q.BroadcastCalendarYearUuid
AND q.BroadcastCalendarQuarterUuid = qmp.BroadcastCalendarQuarterUuid
AND qmp.BroadcastCalendarMonthUuid = m.BroadcastCalendarMonthUuid
AND M.ActiveStatus = 'ACTIVE'
AND q.BroadcastQuarterType = 'STANDARD'
AND y.ActiveStatus = 'ACTIVE'
AND y.BroadcastCalendarYear = YEAR(GETDATE())
ORDER BY qmp.BroadcastMonthofYearNbr DESC) t
Using IF EXISTS, ELSE IF EXISTS, ELSE accomplishes all 3 conditions:
IF EXISTS (
SELECT CONCAT(q.DisplayName, ' (', STUFF(REPLACE('/'+CONVERT( VARCHAR(10), q.StartDate, 101), '/0', '/'), 1, 1, ''), '-', STUFF(REPLACE('/'+CONVERT(VARCHAR(10), q.EndDate, 101), '/0', '/'), 1, 1, ''), ')')
FROM AudienceProjections.dbo.BroadcastCalendarYear Y,
AudienceProjections.dbo.BroadcastCalendarQuarter Q
WHERE y.BroadcastCalendarYearUuid = q.BroadcastCalendarYearUuid
AND q.BroadcastQuarterType = 'STANDARD'
AND y.ActiveStatus = 'ACTIVE'
AND q.ActiveStatus = 'ACTIVE'
AND y.BroadcastCalendarYear = YEAR(GETDATE())
AND Q.StartDate <= GETDATE()
and Q.EndDate >= GETDATE())
SELECT CONCAT(q.DisplayName, ' (', STUFF(REPLACE('/'+CONVERT( VARCHAR(10), q.StartDate, 101), '/0', '/'), 1, 1, ''), '-', STUFF(REPLACE('/'+CONVERT(VARCHAR(10), q.EndDate, 101), '/0', '/'), 1, 1, ''), ')')
FROM AudienceProjections.dbo.BroadcastCalendarYear Y,
AudienceProjections.dbo.BroadcastCalendarQuarter Q
WHERE y.BroadcastCalendarYearUuid = q.BroadcastCalendarYearUuid
AND q.BroadcastQuarterType = 'STANDARD'
AND y.ActiveStatus = 'ACTIVE'
AND q.ActiveStatus = 'ACTIVE'
AND y.BroadcastCalendarYear = YEAR(GETDATE())
AND Q.StartDate <= GETDATE()
and Q.EndDate >= GETDATE() ELSE IF EXISTS (
SELECT TOP 1 CONCAT(q.DisplayName, ' (', STUFF(REPLACE('/'+CONVERT( VARCHAR(10), q.StartDate, 101), '/0', '/'), 1, 1, ''), '-', STUFF(REPLACE('/'+CONVERT(VARCHAR(10), q.EndDate, 101), '/0', '/'), 1, 1, ''), ')')
FROM [AudienceProjections].[dbo].[BroadcastCalendarQuarterMonthMap] QMP,
AudienceProjections.dbo.BroadcastCalendarYear Y,
AudienceProjections.dbo.BroadcastCalendarQuarter Q
WHERE y.BroadcastCalendarYearUuid = q.BroadcastCalendarYearUuid
AND q.BroadcastCalendarQuarterUuid = qmp.BroadcastCalendarQuarterUuid
AND q.BroadcastQuarterType = 'STANDARD'
AND y.ActiveStatus = 'ACTIVE'
AND q.ActiveStatus = 'ACTIVE'
AND y.BroadcastCalendarYear = YEAR(GETDATE()) ORDER BY qmp.BroadcastMonthofYearNbr ASC ) SELECT TOP 1 CONCAT(q.DisplayName, ' (', STUFF(REPLACE('/'+CONVERT( VARCHAR(10), q.StartDate, 101), '/0', '/'), 1, 1, ''), '-', STUFF(REPLACE('/'+CONVERT(VARCHAR(10), q.EndDate, 101), '/0', '/'), 1, 1, ''), ')')
FROM [AudienceProjections].[dbo].[BroadcastCalendarQuarterMonthMap] QMP,
AudienceProjections.dbo.BroadcastCalendarYear Y,
AudienceProjections.dbo.BroadcastCalendarQuarter Q
WHERE y.BroadcastCalendarYearUuid = q.BroadcastCalendarYearUuid
AND q.BroadcastCalendarQuarterUuid = qmp.BroadcastCalendarQuarterUuid
AND q.BroadcastQuarterType = 'STANDARD'
AND y.ActiveStatus = 'ACTIVE'
AND q.ActiveStatus = 'ACTIVE'
AND y.BroadcastCalendarYear = YEAR(GETDATE())
ORDER BY qmp.BroadcastMonthofYearNbr ASC; ELSE SELECT 'No Active quarters are in the database for the current year yet';
I am writing a query to find currently running job in SQL (I know we can view it in Job Active Monitor, but I've a need to do in TSQL). Though I can query sysjobactivity table to find currently running job, it's nowhere telling what job step is running (because my job might have more than 1 step).
Query I used:
SELECT s.name AS [JOB_NAME],
'' AS [STEP_ID],
'' AS STEP_NAME,
'Processing' AS STATUS,
sja.run_requested_date AS START_TIME,
null AS END_DATE,
convert(varchar, (getdate() - sja.run_requested_date), 8) AS Duration
FROM sysjobactivity sja, sysjobs s
WHERE sja.job_id = s.job_id
AND sja.run_requested_date > getdate() - 1
AND sja.stop_execution_date IS NULL
Please help me finding the step ID & Step name in which the job is currently progressing.
I think below script help to get SQL Jobs with current execution step, try this
msdb.dbo.sp_help_job #execution_status = 1
DECLARE #StepCount INT
SELECT #StepCount = COUNT(1)
FROM msdb.dbo.sysjobsteps
WHERE job_id = '0523333-5C24-1526-8391-AA84749345666' --JobID
SELECT
[JobName]
,[JobStepID]
,[JobStepName]
,[JobStepStatus]
,[RunDateTime]
,[RunDuration]
FROM
(
SELECT
j.[name] AS [JobName]
,Jh.[step_id] AS [JobStepID]
,jh.[step_name] AS [JobStepName]
,CASE
WHEN jh.[run_status] = 0 THEN 'Failed'
WHEN jh.[run_status] = 1 THEN 'Succeeded'
WHEN jh.[run_status] = 2 THEN 'Retry (step only)'
WHEN jh.[run_status] = 3 THEN 'Canceled'
WHEN jh.[run_status] = 4 THEN 'In-progress message'
WHEN jh.[run_status] = 5 THEN 'Unknown'
ELSE 'N/A'
END AS [JobStepStatus]
,msdb.dbo.agent_datetime(run_date, run_time) AS [RunDateTime]
,CAST(jh.[run_duration]/10000 AS VARCHAR) + ':' + CAST(jh.[run_duration]/100%100 AS VARCHAR) + ':' + CAST(jh.[run_duration]%100 AS VARCHAR) AS [RunDuration]
,ROW_NUMBER() OVER
(
PARTITION BY jh.[run_date]
ORDER BY jh.[run_date] DESC, jh.[run_time] DESC
) AS [RowNumber]
FROM
msdb.[dbo].[sysjobhistory] jh
INNER JOIN msdb.[dbo].[sysjobs] j
ON jh.[job_id] = j.[job_id]
WHERE
j.[name] = 'ProcessCubes' --Job Name
AND jh.[step_id] > 0
AND CAST(RTRIM(run_date) AS DATE) = CAST(GETDATE() AS DATE) --Current Date
) A
WHERE
[RowNumber] <= #StepCount
AND [JobStepStatus] = 'Failed'
Try this:
SELECT distinct
cast([sJOB].[job_id] as varchar(max)) AS execution_id
, [sJSTP].[step_name] AS executable_name
, [sJOB].[name] AS package_name
, CASE [sJSTP].[run_date]
WHEN 0 THEN NULL
ELSE
CAST(
CAST([sJSTP].[run_date] AS CHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJSTP].[run_time] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS DATETIME)
END AS start_time,
dateadd(ss, run_duration, CASE [sJSTP].[run_date]
WHEN 0 THEN NULL
ELSE
CAST(
CAST([sJSTP].[run_date] AS CHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJSTP].[run_time] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS DATETIME)
END) end_time
-- , [sJSTP].[run_duration] [looptijd in minuten]
, CASE [sJSTP].[run_status]
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Success'
WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Cancelled'
WHEN 5 THEN 'Unknown'
END AS execution_result_description
FROM
[msdb].[dbo].[sysjobhistory] AS [sJSTP]
INNER JOIN [msdb].[dbo].[sysjobs] AS [sJOB]
ON [sJSTP].[job_id] = [sJOB].[job_id]
inner join [msdb].[dbo].[sysjobsteps] steps
ON [sJSTP].[job_id] = [steps].[job_id]
where [sJSTP].[run_date] <> 0
and CASE [sJSTP].[run_date]
WHEN 0 THEN NULL
ELSE
CAST(
CAST([sJSTP].[run_date] AS CHAR(8))
+ ' '
+ STUFF(
STUFF(RIGHT('000000' + CAST([sJSTP].[run_time] AS VARCHAR(6)), 6)
, 3, 0, ':')
, 6, 0, ':')
AS DATETIME)
END between dateadd(hh, -20, getdate()) and getdate()
and [sJSTP].[step_name] not in ('(Job outcome)')
order by start_time desc
Additionally I use this query to see step result from a running SSIS job. However, this only shows you the finished steps, not the running ones. I still have to find an SQL to see the currently running step and merge it with this one.
select distinct
cast(e.execution_id as varchar(max)),
e.executable_name,
e.package_name,
CONVERT(datetime, es.start_time) AS start_time
, CONVERT(datetime, es.end_time) AS end_time
, datediff(mi, es.start_time, es.end_time) [running time]
, case es.execution_result
when 0 then 'Success'
when 1 then 'Failed'
when 2 then 'Completion'
when 3 then 'Cancelled'
else cast(es.execution_result as varchar(max)) end as execution_result_description
from ssisdb.catalog.executables e
left join ssisdb.catalog.executable_statistics es
on e.executable_id = es.executable_id
and e.execution_id = es.execution_id
order by 6 desc
We use the below mentioned Stored Procedure to get the history of our JOBS
SELECT --sysjobhistory.server,
sysjobs.name
AS
job_name,
CASE sysjobhistory.run_status
WHEN 0 THEN 'Failed'
WHEN 1 THEN 'Succeeded'
ELSE '???'
END
AS
run_status,
CAST(
Isnull(Substring(CONVERT(VARCHAR(8), run_date), 1, 4) + '-' +
Substring(CONVERT(VARCHAR
(8), run_date), 5, 2) + '-' +
Substring(CONVERT(VARCHAR(
8), run_date), 7, 2), '') AS DATETIME)
AS
[Run DATE],
Isnull(Substring(CONVERT(VARCHAR(7), run_time+1000000), 2, 2) + ':'
+
Substring(CONVERT(VARCHAR(7), run_time+1000000), 4, 2
)
+
':' +
Substring(CONVERT(VARCHAR(7), run_time+1000000), 6, 2), '')
AS
[Run TIME],
Isnull(Substring(CONVERT(VARCHAR(7), run_duration+1000000), 2, 2) +
':' +
Substring(CONVERT(VARCHAR(7), run_duration+1000000),
4,
2)
+ ':' +
Substring(CONVERT(VARCHAR(7), run_duration+1000000), 6, 2),
''
) AS
[Duration],
Isnull(Substring(CONVERT(VARCHAR(7), run_time+run_duration+1000000), 2, 2) + ':'
+
Substring(CONVERT(VARCHAR(7), run_time+run_duration+1000000), 4, 2
)
+
':' +
Substring(CONVERT(VARCHAR(7), run_time+run_duration+1000000), 6, 2), '')
AS
[Total TIME],
sysjobhistory.step_id,
sysjobhistory.step_name,
sysjobhistory.MESSAGE AS Msg
FROM msdb.dbo.sysjobhistory
INNER JOIN msdb.dbo.sysjobs
ON msdb.dbo.sysjobhistory.job_id = msdb.dbo.sysjobs.job_id
WHERE sysjobhistory.run_date <= Datepart(yyyy, #dateparam) * 10000 +
Datepart(mm, #dateparam) * 100 +
Datepart
(
dd, #dateparam)
AND sysjobs.name = #JobName --remove this line if you want to show all jobs for the specified day
But can anyone advise how to get error details if the job has failed for example (we are looking for this information which we can view thru log viewer)
Date 29/09/2011 07:57:04
Log Job History Step ID 5
Server
Job Name
Step Name extract
Duration 00:02:13
Sql Severity 0
Sql Message ID 0
Operator Emailed
Operator Net sent
Operator Paged
Retries Attempted 0
Message
(Need this error message also to come)
you can use the following script to grab the details of each step..first you have to get the failed job's job_id and pass to msdb.dbo.sp_help_jobhistory stored procedure.
I got this script by running trace while doing the activity on job activity monitor.
I hope this helps you on what you are looking for
To find STEP level messages, look at the message column where step_id <> 0
These records actually provide useful error messages.
declare #tmp_sp_help_jobhistory table
(
instance_id int null,
job_id uniqueidentifier null,
job_name sysname null,
step_id int null,
step_name sysname null,
sql_message_id int null,
sql_severity int null,
message nvarchar(4000) null,
run_status int null,
run_date int null,
run_time int null,
run_duration int null,
operator_emailed sysname null,
operator_netsent sysname null,
operator_paged sysname null,
retries_attempted int null,
server sysname null
)
insert into #tmp_sp_help_jobhistory
exec msdb.dbo.sp_help_jobhistory
#job_id = '329cac18-328d-499b-9216-593244d164b0', --change this job_id according to your requirement
#mode='FULL'
SELECT
tshj.instance_id AS [InstanceID],
tshj.sql_message_id AS [SqlMessageID],
tshj.message AS [Message],
tshj.step_id AS [StepID],
tshj.step_name AS [StepName],
tshj.sql_severity AS [SqlSeverity],
tshj.job_id AS [JobID],
tshj.job_name AS [JobName],
tshj.run_status AS [RunStatus],
CASE tshj.run_date WHEN 0 THEN NULL ELSE
convert(datetime,
stuff(stuff(cast(tshj.run_date as nchar(8)), 7, 0, '-'), 5, 0, '-') + N' ' +
stuff(stuff(substring(cast(1000000 + tshj.run_time as nchar(7)), 2, 6), 5, 0, ':'), 3, 0, ':'),
120) END AS [RunDate],
tshj.run_duration AS [RunDuration],
tshj.operator_emailed AS [OperatorEmailed],
tshj.operator_netsent AS [OperatorNetsent],
tshj.operator_paged AS [OperatorPaged],
tshj.retries_attempted AS [RetriesAttempted],
tshj.server AS [Server],
getdate() as [CurrentDate]
FROM #tmp_sp_help_jobhistory as tshj
ORDER BY [InstanceID] ASC