Teis Lindemark Teis Lindemark - 6 months ago 63
SQL Question

SQLCMD variable in path

I am working with some SQL-scripts that I want to be reusable, så I need to use some variables.

I have a bat script that run the sql script with sqlcmd

sqlcmd -S <SERVER> -v PROJECT="<PROJECTNAME>" -i .\start.sql

In the start.sql script, I execute another sql script like this:

:r .\<PROJECTNAME>\init.sql

So I have hardcoded the value of the variable and that works perfectly. I want to use the variable itself, but I can not get that to work.

:r .\$(PROJECT)\init.sql

The last line here is what I thought would work. I have tested printed out the value in the variable PROJECT by doing this:


That gives me the value of the variable.

Hope anyone can help me with using the variable to execue the script in the folder.

Thanks in advance.

PRINT $(PROJECT) gived the following error message:The name "XXX" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.

XXX = value of the variable.


I did a little experiment, as I know I've managed to get a syntax similar to this to work for me before now. I found that if I replicated what you had done, I got the following error:

A fatal scripting error occurred. Cannot find directory in the path specified for ":r" command.

If instead, I put the whole of the path into the variable - it works. So try changing your .sql file to this:


and calling it from SQLCMD like this:

sqlcmd -S <SERVER> -v PROJECT_FILE_NAME=".\<PROJECTNAME>\init.sql" -i .\start.sql

When I took this approach, it ran the file init.sql with no errors.