Reputation: 554
Working with sysjobs and sysjobhistory on SQL Server and I have been googling around but I can't seem to find a direct answer to this question. I think it is because I'm trying to do this in a WHERE clause.
So basically trying to select a job that has failed on the same day that it ran (basically today's date), since the current code is selecting all of the existing jobs that failed.
Below is my code:
SELECT DISTINCT
sj.name,
COUNT(sjh.instance_id) AS errors
FROM
msdb..sysjobhistory sjh
JOIN
msdb.dbo.sysjobs sj ON sj.job_id = sjh.job_id
WHERE
name IN ('SQLAgentJob1', 'SQLAgentJob2')
AND sjh.run_status = 1
AND (SELECT CONVERT(DATE, CONVERT(INT, sjh.run_date), 112)) = (SELECT CONVERT(DATE, GETDATE(), 112))
GROUP BY
sj.name
I keep getting an error stating:
Msg 529, Level 16, State 2, Line 13
Explicit conversion from data type int to date is not allowed.
Any ideas?
Upvotes: 2
Views: 5787
Reputation: 131729
You don't have to do all those conversions, just convert your parameter (ie the current date) to the unseparated date format with 112:
SELECT DISTINCT sj.name, COUNT(sjh.instance_id) AS errors
FROM msdb..sysjobhistory sjh
JOIN msdb.dbo.sysjobs sj ON sj.job_id = sjh.job_id
WHERE name IN ('SQLAgentJob1','SQLAgentJob2')
AND sjh.run_status = 1
AND sjh.run_date= CONVERT(nvarchar(8), GETDATE(), 112)
GROUP BY sj.name
There is no integer to date conversion because there is no integer representation for dates.
The run_date
column stores the YYYYMMDD
format as an integer, perhaps to reduce space consumption (4 bytes instead of 8), perhaps for some other reason.
To compare against it, just create the equivalent string with CONVERT(nvarchar(8), GETDATE(), 112)
. The conversion from string to integer is implicit
Upvotes: 5
Reputation: 12459
This should work.
SELECT DISTINCT sj.name,
COUNT(sjh.instance_id) AS errors
FROM msdb..sysjobhistory sjh
JOIN msdb.dbo.sysjobs sj ON sj.job_id = sjh.job_id
WHERE name IN ('SQLAgentJob1',
'SQLAgentJob2')
AND sjh.run_status = 1
AND CAST(CONVERT(datetime, CAST(SJH.[run_date] AS CHAR(8))) as DATE) = CAST(GETDATE() as DATE)
GROUP BY sj.name
Upvotes: 2