The naming convention used here is... confusing. Nevertheless, there are several things wrong with your query:
- The following code will break if there was more than one
backupFileName within the previous hour.
SET @sql = (SELECT backupFileName
FROM #checkBackupTime
WHERE backupFileName >= DATEADD(HH, -1, GETDATE()))
- In the above code, you are only ever checking for
backupFileNames in the past hour (more on that in #3).
- The following code can only ever return one of three values:
NULL, 0, or 1. The reason it can only ever be those three values is because you are limiting the results to just those files in the previous hour, and then asking how many hours old it is. It will realistically only ever be 0 or NULL (in the case that there were no backups made in the last hour).
SET @dateDifference = (SELECT DATEDIFF(HOUR, @sql, CURRENT_TIMESTAMP))
- The following code should generate an error. You need to convert the
@dateDifference to a VARCHAR:
SET @bodyMessage = 'The lastest backup file is ' + @dateDifference + ' hours old'
Because the value can only ever be NULL or 0, @bodyMessage would end up being NULL if @dateDifference is NULL. (a VARCHAR + NULL = NULL).
You are only ever sending the email if @SQL IS NULL or ''! You complain about your email coming out blank, but you're only ever sending it if it is!
IF @sql IS NULL OR @sql = ''
BEGIN
EXEC msdb.dbo.sp_send_dbmail
...
Proposed changes
Remove the time constraint and grab the MAX(backupFileName):
Select @Sql = Max(backupFileName)
From #checkBackupTime
Use COALESCE() and CONVERT() for the value:
SET @bodyMessage = 'The lastest backup file is '
+ Coalesce(Convert(Varchar, @dateDifference), '')
+ ' hours old'
And change the email condition to check the time since the last backup:
If @DateDifference > 1
Begin
Exec msdb.dbo.sp_send_dbmail
...
BackupFileNameaDATETIME? Why is theBackupFileNamebeing set to a variable named@sql? The nomenclature used here is perplexing...