WHERE IN (array of IDs)

后端 未结 9 1263
暖寄归人
暖寄归人 2020-11-28 11:16

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?

9条回答
  •  日久生厌
    2020-11-28 11:36

    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).

提交回复
热议问题