Selecting multiple rows by ID, is there a faster way than WHERE IN

后端 未结 3 1676
太阳男子
太阳男子 2021-01-04 05:46

I have a SQL Table and I would like to select multiple rows by ID. For example I would like to get the row with IDs 1, 5 and 9 from my table.

I have been doing this

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 06:12

    OK so I got it going really fast by defining a table type and then passing that type directly into the query and joining onto it.

    in SQL

    CREATE TYPE [dbo].[IntTable] AS TABLE(
        [value] [int] NULL
    )
    

    in code

    DataTable dataTable = new DataTable("mythang");
    dataTable.Columns.Add("value", typeof(Int32));
    
    toSelect.ToList().ForEach(selectItem => dataTable.Rows.Add(selectItem));
    
    using (SqlCommand command = new SqlCommand(
        @"SELECT * 
        FROM [dbo].[Entities] e 
        INNER JOIN @ids on e.id = value", con))
    {
        var parameter = command.Parameters.AddWithValue("@ids", dataTable);
        parameter.SqlDbType = System.Data.SqlDbType.Structured;
        parameter.TypeName = "IntTable";
    
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                results.Add(reader.GetInt32(0));
            }
        }
    }
    

    this produces the following results

    Querying for 1 random keys (passed in table value) took 2ms
    Querying for 1000 random keys (passed in table value) took 3ms
    Querying for 2000 random keys (passed in table value) took 4ms
    Querying for 3000 random keys (passed in table value) took 6ms
    Querying for 4000 random keys (passed in table value) took 8ms
    Querying for 5000 random keys (passed in table value) took 9ms
    Querying for 6000 random keys (passed in table value) took 11ms
    Querying for 7000 random keys (passed in table value) took 13ms
    Querying for 8000 random keys (passed in table value) took 17ms
    Querying for 9000 random keys (passed in table value) took 16ms
    Querying for 10000 random keys (passed in table value) took 18ms
    

提交回复
热议问题