簡體   English   中英

如何將數組傳遞給SQL查詢?

[英]How to pass an array to SQL query?

我正在嘗試創建一個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)

PS這里提到了類似的問題,但出於不同的目的: http//connect.microsoft.com/PowerShell/feedback/details/518276/f-format-operator-bug-when-right-side-value-is-一個陣列可變

鏈接代碼首先將數組格式化為字符串,使用一些奇怪的連接,然后將該字符串作為單個內容插入到SQL查詢中。

例如,你的例子:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM