WHERE IN (array of IDs)

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

    Here's a Linq solution I thought up. It'll automatically insert all items in the list as parameters @item0, @item1, @item2, @item3, etc.

    [WebMethod]
    public MiniEvent[] getAdminEvents(Int32[] buildingIDs, DateTime startDate)
    {
        // Gets a list with numbers from 0 to the max index in buildingIDs,
        // then transforms it into a list of strings using those numbers.
        String idParamString = String.Join(", ", (Enumerable.Range(0, buildingIDs.Length).Select(i => "@item" + i)).ToArray());
        command.CommandText = @"SELECT id,
                            startDateTime, endDateTime From
                            tb_bookings WHERE buildingID IN
                            (" + idParamString + @") AND startDateTime <=
                            @fromDate";
        // Reproduce the same parameters in idParamString 
        for (Int32 i = 0; i < buildingIDs.Length; i++)
                command.Parameters.Add(new SqlParameter ("@item" + i, buildingIDs[i]));
        command.Parameters.Add(new SqlParameter("@fromDate", startDate);
        // the rest of your code...
    }
    

提交回复
热议问题