我正在尝试创建一个SQL查询,并且使用'operator'
时遇到一些困难请参阅下面的数组在查询字符串中有点splat,只有第一个创建它。
c:\>"select * from mytable where kerberosID in ('{0}')" -f @('a','b','c')
select * from mytable where kerberosID in ('a')
我想要的SQL查询是:
select * from mytable where kerberosID in ('a','b','c')
将该数组传递给查询字符串的最佳方法是什么?
实际代码段
param (
[string[]][Alias('host')]$ComputerName,
[string[]]$kerberosid
)
[System.Data.SqlClient.SqlConnection]$sqlConnection = Open-DatabaseConnection
$sqlCmd = New-Object System.Data.SqlClient.SqlCommand
$sqlCmd.Connection = $sqlConnection
### This is the line where I have the above query
$sqlCmd.CommandText = "SELECT * from dbo.vLogon where KerberosID in ('{0}')" -f @($kerberosid)
P.S。这里提到了类似的问题,但出于不同的目的:http://connect.microsoft.com/PowerShell/feedback/details/518276/f-format-operator-bug-when-right-side-value-is-an-array-variable
答案 0 :(得分:2)
链接代码首先将数组格式化为字符串,使用一些奇怪的连接,然后将该字符串作为单个内容插入SQL查询。
e.g。为你的例子:
c:\> "select * from mytable where kerberosID in ('{0}')" -f (@('a','b','c') -join "', '")
select * from mytable where kerberosID in ('a', 'b', 'c')
,因为
c:\> @('a','b','c') -join "', '"
a', 'b', 'c
# note how it's almost array notation, but is
# missing the start and end single quotes (which are in the other string)