Search code examples
sql-serverlinuxsqlcmd

Using variables in SQLCMD for Linux


I'm running the Microsoft SQLCMD tool for Linux (CTP 11.0.1720.0) on a Linux box (Red Hat Enterprise Server 5.3 tikanga) with Korn shell. The tool is properly configured, and works in all cases except when using scripting variables.

I have an SQL script, that looks like this.

SELECT COLUMN1 FROM TABLE WHERE COLUMN2 = '$(param1)';

And I'm running the sqlcmd command like this.

sqlcmd -S server -d database -U user -P pass -i input.sql -v param1="DUMMYVALUE"

When I execute the above command, I get the following error.

Sqlcmd: 'param1=DUMMYVALUE': Invalid argument. Enter '-?' for help.

Help lists the below syntax.

[-v var = "value"...]

Am I missing something here?


Solution

  • In the RTP version (11.0.1790.0), the -v switch does not appear in the list of parameters when executing sqlcmd -?. Apparently this option isn't supported under the Linux version of the tool.
    As far as I can tell, importing parameter values from environment variables doesn't work either.

    If you need a workaround, one way would be to concatenate one or more :setvar statements with the text file containing the commands you want to run into a new file, then execute the new file. Based on your example:

    echo :setvar param1 DUMMYVALUE > param_input.sql
    cat input.sql >> param_input.sql
    sqlcmd -S server -d database -U user -P pass -i param_input.sql