WHERE IN (array of IDs)

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(
  "@buildingID", 
  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).

Leave a Comment