WHERE IN (array of IDs)

后端 未结 9 1270
暖寄归人
暖寄归人 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:57

    NOTE: I am not generally for using unparameterized queries. IN THIS INSTANCE, however, given that we are dealing with an integer array, you could do such a thing and it would be more efficient. However, given that everyone seems to want to downgrade the answer because it doesn't meet their criteria of valid advice, I will submit another answer that performs horribly but would probably run in LINK2SQL.

    Assuming, as your question states, that you have an array of ints, you can use the following code to return a string that would contain a comma delimited list that SQL would accept:

    private string SQLArrayToInString(Array a)
    {
     StringBuilder sb = new StringBuilder();
     for (int i = 0; i < a.GetUpperBound(0); i++)
      sb.AppendFormat("{0},", a.GetValue(i));
     string retVal = sb.ToString();
     return retVal.Substring(0, retVal.Length - 1);
    }
    

    Then, I would recommend you skip trying to parameterize the command given that this is an array of ints and just use:

    command.CommandText = @"SELECT id,
                startDateTime, endDateTime From
                tb_bookings WHERE buildingID IN
                (" + SQLArrayToInString(buildingIDs) + ") AND startDateTime <=
                @fromDate";
    

提交回复
热议问题