SQL Job running a few select statements Incorrect syntax near '\'. [SQLSTATE 42000] (Error 102)

StackOverflow https://stackoverflow.com/questions/22839410

  •  27-06-2023
  •  | 
  •  

Question

I have a SQL job that contains a few select statements (4 views and 1 text).

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Database Email',
    @recipients = 'dbcheck@xxx.com',
    @subject = 'SQL Replication Deletion Check',
    @query = 'SELECT '\\server1\folder1\SQL\check.sql' AS [Script]
SELECT * FROM [repserv].[dbo].[1repdupecheck]
SELECT * FROM [repserv].[dbo].[2repdupecheck]
SELECT * FROM [repserv].[dbo].[3repdupecheck]
SELECT * FROM [repserv].[dbo].[4repdupecheck]',
    @attach_query_result_as_file = 1;

I currently get the following error when running it.

Message
Executed as user: SERVER1\sqlusr. Incorrect syntax near '\'. [SQLSTATE 42000] (Error 102).  The step failed.

Now I have also tried taking out the line with the '\' in and it works so I can only assume a bracket or something needs to be put around the back slashes in the select text.

Was it helpful?

Solution

You need to escape the backslashes and quotes

'SELECT ''\\\\server1\\folder1\\SQL\\check.sql'' AS [Script]

OTHER TIPS

Got it with help from the below, just needed to add double single quotes (didn't need to double up on back slashes)

'SELECT ''\\server1\folder1\SQL\check.sql'' AS [Script]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top