C# – WHERE IN (array of IDs)

ado.netcsql serversqlparametertsql

I have webservice which is passed an array of ints.
I'd like to do the select statement as follows but keep getting errors. Do I need to change the array to a string?

public MiniEvent[] getAdminEvents(int buildingID, DateTime startDate)
    command.CommandText = @"SELECT id,
                            startDateTime, endDateTime From
                            tb_bookings WHERE buildingID IN
                            (@buildingIDs) AND startDateTime <=

    SqlParameter buildID = new SqlParameter("@buildingIDs", buildingIDs);

Best Answer

You can't (unfortunately) do that. A Sql Parameter can only be a single value, so you'd have to do:

WHERE buildingID IN (@buildingID1, @buildingID2, @buildingID3...)

Which, of course, requires you to know how many building ids there are, or to dynamically construct the query.

As a workaround*, I've done the following:

WHERE buildingID IN (@buildingID)

command.CommandText = command.CommandText.Replace(
  string.Join(buildingIDs.Select(b => b.ToString()), ",")

which will replace the text of the statement with the numbers, ending up as something like:

WHERE buildingID IN (1,2,3,4)
  • Note that this is getting close to a Sql injection vulnerability, but since it's an int array is safe. Arbitrary strings are not safe, but there's no way to embed Sql statements in an integer (or datetime, boolean, etc).