简体   繁体   English

路径中的SQLCMD变量

[英]SQLCMD variable in path

I am working with some SQL-scripts that I want to be reusable, så I need to use some variables. 我正在使用一些我希望可重用的SQL脚本,因此我需要使用一些变量。

I have a bat script that run the sql script with sqlcmd 我有一个使用sqlcmd运行sql脚本的bat脚本

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

In the start.sql script, I execute another sql script like this: 在start.sql脚本中,我执行另一个sql脚本,如下所示:

: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: 通过执行以下操作,我测试了打印出变量PROJECT中的值:

PRINT '$(PROJECT)'

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. 提前致谢。

EDIT: PRINT $(PROJECT) gived the following error message:The name "XXX" is not permitted in this context. 编辑:打印$(PROJECT)给出以下错误消息:在这种情况下不允许使用名称“ XXX”。 Valid expressions are constants, constant expressions, and (in some contexts) variables. 有效表达式是常量,常量表达式和(在某些情况下)变量。 Column names are not permitted. 不允许使用列名。

XXX = value of the variable. XXX =变量的值。

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. 在为“:r”命令指定的路径中找不到目录。

If instead, I put the whole of the path into the variable - it works. 如果相反,我将整个路径放入变量中-它起作用。 So try changing your .sql file to this: 因此,尝试将您的.sql文件更改为此:

:r $(PROJECT_FILE_NAME)

and calling it from SQLCMD like this: 然后像这样从SQLCMD调用它:

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. 当我采用这种方法时,它运行文件init.sql时没有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM