WHERE IN (array of IDs)

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

    First you're going to need a function and a sproc. The function will split your data and return a table:

    CREATE function IntegerCommaSplit(@ListofIds nvarchar(1000))
    returns @rtn table (IntegerValue int)
    AS
    begin
    While (Charindex(',',@ListofIds)>0)
    Begin
        Insert Into @Rtn 
        Select ltrim(rtrim(Substring(@ListofIds,1,Charindex(',',@ListofIds)-1)))
        Set @ListofIds = Substring(@ListofIds,Charindex(',',@ListofIds)+len(','),len(@ListofIds))
    end
    Insert Into @Rtn 
        Select  ltrim(rtrim(@ListofIds))
    return 
    end
    

    Next you need a sproc to use that:

    create procedure GetAdminEvents 
        @buildingids nvarchar(1000),
        @startdate datetime
    as
    SELECT id,startDateTime, endDateTime From
                tb_bookings t INNER JOIN 
    dbo.IntegerCommaSplit(@buildingids) i
    on i.IntegerValue = t.id
     WHERE startDateTime <= @fromDate
    

    Finally, your code:

    [WebMethod]
            public MiniEvent[] getAdminEvents(int[] buildingIDs, DateTime startDate)
            command.CommandText = @"exec GetAdminEvents";
     SqlParameter buildID= new SqlParameter("@buildingIDs", buildingIDs);
    

    That goes way beyond what your question asked but it will do what you need.

    Note: should you pass in anything that's not an int, the whole database function will fail. I leave the error handling for that as an exercise for the end user.

提交回复
热议问题