0

I am trying to create a sql query and having a bit of difficulty in using 'operator'

See below array is kinda splat in the query string and only the first one makes it.

c:\>"select * from mytable where kerberosID in ('{0}')" -f @('a','b','c')
select * from mytable where kerberosID in ('a')

My desired SQL query would be:

select * from mytable where kerberosID in ('a','b','c')

What would be the best way to pass that array into the query string?

Actual code snippet

    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. A similar issue is mentioned here, though for a different purpose: http://connect.microsoft.com/PowerShell/feedback/details/518276/f-format-operator-bug-when-right-side-value-is-an-array-variable

1 Answer 1

2

The linked code is formatting the array as a string first, using a bit of a curious join, then inserting that string into the SQL query as a single thing.

e.g. for your example:

c:\> "select * from mytable where kerberosID in ('{0}')" -f (@('a','b','c') -join "', '")
select * from mytable where kerberosID in ('a', 'b', 'c')

because

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it's a funny way of doing it but it works. Thank you! This is pretty much what I thought I could do as a last resort but was wondering if there is another way used in sql queries that I am not aware of. I will leave this for a while to see if anyone can come up with a different solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.