SQLTeam.com | Weblogs | Forums

Strange Syntax Error

Why the heck am I getting this syntax error in SSMS?

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

Incorrect syntax near '38'.

"38" is underlined in red

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

That appears to be a "smart" quote rather than a standard quote, which SQL won't recognize and will mess up the parsing.

Hmmm how did you determine that it;s a smart quote, @ScottPletcher ? I deleted the tick mark and retyped it on both ends. Same error

I retyped that line in notepad, pasted into SMSS and STILL get the syntax error.

You are correct, @ScottPletcher. I wrote the sql code in Word and copied to SSMS. But it's only erroring on this one line. And even after I retyped it completely I still get the syntax error

I fixed it.I was missing an End statemnt. Also retyped all the quotes. Resolved. Thanks @ScottPletcher
Gotta always use Notepad!