Troubleshooting Guide: Error 2241 – “%sVariable expected: ‘$name'”
Why This Error Happens
This error occurs when SQL Server 2025 encounters a malformed variable reference in a SQLCMD script, PowerShell invocation, or dynamic SQL statement where the $(variable) syntax is incorrectly parsed. The root cause is typically a missing or improperly escaped dollar-sign variable placeholder within a scripting context (such as sqlcmd -v scripting variables or SSIS/Agent job step variables) that SQL Server’s parser cannot resolve to a valid identifier. This can also stem from corrupted job step definitions or environment variable substitution failures introduced by recent Windows Server 2025 scripting engine updates.
Step-by-Step Resolution Guide
Step 1: Identify the Offending Script or Job Step
- Open SQL Server Management Studio (SSMS) and navigate to SQL Server Agent > Jobs.
- Right-click the failing job and select View History to locate the exact step throwing Error 2241.
- Check the T-SQL or SQLCMD script for
$(VariableName)syntax that may be missing a closing parenthesis or has a stray$symbol.
Step 2: Validate SQLCMD Scripting Variable Syntax
- Open the script in a text editor (not SSMS, to avoid auto-formatting) and confirm all variables follow the exact pattern:
$(VariableName). - Ensure there are no spaces between
$and(, as in$ (VariableName)— this is a common typo that triggers Error 2241. - If using
sqlcmdfrom command line, verify the-vflag syntax:sqlcmd -S servername -v name="value".
Step 3: Repair or Recreate the Job Step Definition
- In SSMS, right-click the affected job step and select Properties.
- Clear the Command text box entirely and manually retype the script instead of pasting (paste operations can introduce hidden Unicode characters that corrupt the
$symbol). - Save the job step and run Start Job at Step to test in isolation.
Step 4: Check Environment Variable Resolution on Windows Server 2025
- Open System Properties > Environment Variables and confirm any OS-level variables referenced in the script (e.g., via
%VAR%syntax mixed incorrectly with SQLCMD$()syntax) are correctly defined. - Restart the SQL Server Agent service after any environment variable changes:
net stop SQLSERVERAGENT
net start SQLSERVERAGENT
Step 5: Update SQL Server 2025 Cumulative Update
- Navigate to Help > About in SSMS to check your current build number.
- Download and apply the latest Cumulative Update (CU) from the Microsoft Update Catalog, as early SQL Server 2025 builds had a known SQLCMD parser regression affecting variable substitution.
Alternative or Verification Steps
- Run the corrected script manually via command line using
sqlcmd -S <server> -i script.sql -v varname="testvalue"to confirm no Error 2241 is thrown before re-enabling the scheduled job. - If the error persists, bypass SQLCMD scripting mode entirely by hardcoding the variable value directly into the script and removing the
$()reference as a temporary workaround.