Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLCMD, command-line variables and script :setvar

Tags:

When running SQLCMD.exe and providing command-line arguments for scripting variables, I expect that the values provided on the command-line will override those defined in the SQL script file.

e.g.

Given the following SQL Script:

:setvar XXX "SQL script"
print '$(XXX)'

And the command line:

sqlcmd.exe -S <Server> -d <Database> -E -b -i <Script> -v XXX="Batch script"

I expect the output to be:

Batch script

However the output is:

SQL script

Is this the intention, or must the :setvar statements in the SQL script be removed?

I provided the :setvar statements in script, so I can edit/test the script in SQL Management Studio with SQLCMD mode, but run the scripts from the command-line in my test and production environments.

like image 470
VirtualStaticVoid Avatar asked May 07 '09 09:05

VirtualStaticVoid


People also ask

How do I declare a variable in SQLCMD?

Variable values that are defined by using setvar or the -v option must be enclosed by quotation marks if the string value contains spaces. If quotation marks are part of the variable value, they must be escaped. For example: : setvar MyVar "spac""e" .

Can you run a SQL script from command line?

Overview of SQL Command LineSQL Command Line (SQL*Plus) is a command-line tool for accessing Oracle Database XE. It enables you to enter and run SQL, PL/SQL, and SQL*Plus commands and statements to: Query, insert, and update data. Execute PL/SQL procedures.

How do I use SQLCMD commands in the SSMS Query editor?

To enable SQLCMD mode, click the SQLCMD Mode option under the Query menu: Another way to enable the SQLCMD Mode is by using a combination of keys ALT+Q+M from the keyboard. In SSMS, there is an option to set the query windows to be opened in the SQLCMD mode by default.


1 Answers

This appears to be by design; somebody has already raised a change request on Connect: http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=382007

The only way around the issue I can see would be to comment out (or otherwise remove) the :setvar commands on release.

like image 79
Ed Harper Avatar answered Sep 19 '22 01:09

Ed Harper