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

SQL CMD: pass variables with brackets and single quotes

我正在尝试创建一个脚本来提供一些数据库的大小。 我已经创建了有效的原始查询,但现在我想动态地创建它。

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

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

然后脚本的其余部分遍历此 table 中的行,并给出每个相应数据库的大小。

我正在考虑在 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 '('.

感谢您的帮助。

考虑这段代码:

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);