SQL CMD:传递带括号和单引号的变量

时间:2020-09-10 10:21:33

标签: sql-server variables escaping sqlcmd

我正在尝试创建一个脚本,该脚本可以提供一些数据库的大小。 我已经创建了可以运行的原始查询,但是现在我想动态地进行查询。

我的脚本根据提交的变量创建一个临时表。 例如:

        create table #temptbl (idx int IDENTITY(1,1), valuex varchar(256))
        INSERT INTO #temptbl (valuex) values ('PARTS'),('PARTS_Master'),('PARTS2_4'),('PARTS2_7'),('Projects')

然后,脚本的其余部分循环遍历该表中的行,并为我提供每个相应数据库的大小。

我一直想像这样在sqlcmd中传递变量:

sqlcmd -v variables ="('PARTS'),('PARTS_Master'),('PARTS2_4'),('PARTS2_7'),('Projects')" -S MYSERVERNAME\sqlexpress -i DatabaseSize.sql -d Parts

,然后在我的sql脚本中将其更改为:

        create table #tables (idx int IDENTITY(1,1), valuex varchar(256))
        INSERT INTO #tables (valuex) values '$(variables)'

这给我一个错误:

Msg 102, Level 15, State 1, Server ServerName\SQLEXPRESS, Line 16
Incorrect syntax near '('.

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

考虑以下代码:

create table #tables (idx int IDENTITY(1,1), valuex varchar(256))
INSERT INTO #tables (valuex) values '$(variables)'

变量替换后,它变为:

create table #tables (idx int IDENTITY(1,1), valuex varchar(256))
INSERT INTO #tables (valuex) values '('PARTS'),('PARTS_Master'),('PARTS2_4'),('PARTS2_7'),('Projects')'

请注意,行构造函数的列表用单引号引起来,从而导致无效的T-SQL语法。因此,解决方案是简单地删除SQLCMD变量周围的引号:

CREATE TABLE #tables (idx int IDENTITY(1,1), valuex varchar(256))
INSERT INTO #tables (valuex) VALUES $(variables);
相关问题