When I run the complete block of code, the error occurs:
DECLARE @ReportName varchar(50)
DECLARE @xml NVARCHAR(MAX)
DECLARE @body NVARCHAR(MAX)
DECLARE @currDate smalldatetime = GETDATE();
DECLARE @EmailDistribution varchar(500)
DECLARE @SubjectMain varchar(80)
DECLARE @Recipients varchar(200) = 'Me@somwhere.com'
Set @SubjectMain = 'Last Auto Rater Step Ran’
CREATE TABLE #JobSteps(
ID int IDENTITY(1,1) Not Null,
StepName varchar(250) NULL,
DateRan int)
insert into #JobSteps (StepName, DateRan)
select step_name, MAX(run_date) from msdb.dbo.sysjobhistory
where job_id = '38AEDDC6-9C5B-470B-A2A0-F628D3974DE5'
Group by step_name
select TOP 1 Stepname, DateRan from #JobSteps
order by ID desc
SET @xml = CAST((Select TOP 1 StepName AS 'td', '', DateRan as 'td'
from #JobSteps
order by ID desc
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX));
/* If Have Last Step Ran */
If LEN(@xml) > 100
BEGIN
SET @body ='
Automated Auto Rater: Last Step Ran
'
SET @body = @body + @xml +'
'Last Auto Rater Step Ran | Date Ran |
'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'My Profile',
@Subject = @SubjectMain,
@body = @body,
@body_format ='HTML',
@recipients = @Recipients;
But when I only run this it succeeds:
CREATE TABLE #JobSteps(
ID int IDENTITY(1,1) Not Null,
StepName varchar(250) NULL,
DateRan int)
insert into #JobSteps (StepName, DateRan)
select step_name, MAX(run_date) from msdb.dbo.sysjobhistory
where job_id = '38AEDDC6-9C5B-470B-A2A0-F628D3974DE5'
Group by step_name
select TOP 1 Stepname, DateRan from #JobSteps
order by ID desc