The ‘Sqlcmd: Error: Syntax error at line XYZ near command ‘X’ in file ‘file_name.sql’.’ error is encountered when running SQL script via sqlcmd utility

Applies to
ApexSQL Recover, ApexSQL Log

Summary
This article explains how to manually edit script created by ApexSQL Recover or ApexSQL Log which contains ‘$’ sign in order for it to be executable by sqlcmd

Symptoms
When executing a recovery script with sqlcmd utility, the ‘Sqlcmd: Error: Syntax error at line XYZ near command ‘X’ in file ‘file_name.sql’.’ error is encountered.

Cause
This is a sqlcmd utility limitation. If the SQL script contains dollar sign ($) in any form, the utility is unable to properly execute the script, since it is substituting all variables automatically by default.

Resolution
In order to execute script that has a dollar ($) sign in any form, it is necessary to add “-x” parameter to the command line.

e.g.

Original:
sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql

Fixed:
sqlcmd -s Server_name -d Database_name -E -i c:\Temp\Recovery_script.sql -x