如何在SQLCMD中将数组作为变量传递

时间:2019-02-19 08:47:22

标签: sql-server powershell sqlcmd

我正在尝试在sql脚本中传递服务器名称,但是它不起作用。 请帮助

SQL脚本<reference,我正在通过Powershell给出错误提示

patch_report.sql

错误

SELECT * from table where server in ('$(trimsqlstr)')
Msg 102,level Level 15, State 1, Server DBserver, Line 1
Incorrect syntax near 'server1'.

我希望它会像这样

$DB_server = 'DBserver'
$serverName = "server1
server2
server3
"
$serverName = $serverName -split "\n" | foreach {$_.ToString().TrimEnd()}
$trimsqlstr = foreach($server in $serverName){
if ($serverName.Indexof($server) -eq $($serverName.Length-1)){
"'$Server'"
} else {
"'$Server',"
}

SQLCMD.exe -v trimsqlstr = "$($trimsqlstr)" -E -S $DB_server -W -i patch_report.sql

2 个答案:

答案 0 :(得分:2)

可接受的答案是一个很好的解决方案,我只想向您介绍-join运算符。

-join运算符对于将数组的成员连接到字符串非常实用。

您可以执行以下操作:

$serverNames = "server1
server2
server3
"

$serverNameArray = $serverNames -split "\n" | foreach {$_.ToString().TrimEnd()} | Where-Object {$_} | foreach {"'$_'"}
$whereClause = $serverNameArray -join ','
$selectQuery = "SELECT * from table where server in ($whereClause)"

Where-Object {$_}正在删除空元素。

答案 1 :(得分:1)

您可以使用以下代码:

$DB_server = 'DBserver'
$serverName = "server1
server2
server3
"

$serverName = $serverName -split "\n" | foreach {$_.ToString().TrimEnd()}
ForEach($server in $serverName) 
{
$serverstring = $serverstring+"'"+$server+"'"+","
}
$trimsqlstr = $serverstring.Substring(0, $serverstring.Length-4)

然后在如下所示的查询中使用$ trimsqlstr

SELECT * from table where server in ($trimsqlstr)