如何使用 Dapper 在 IN 子句中使用超过 2100 个值?

How can I use more than 2100 values in an IN clause using Dapper?

我有一个包含 ID 的列表,我想使用 Dapper 将其插入到临时 table 中,以避免 'IN' 子句中参数的 SQL 限制。

所以目前我的代码是这样的:

public IList<int> LoadAnimalTypeIdsFromAnimalIds(IList<int> animalIds)
{
    using (var db = new SqlConnection(this.connectionString))
    {
        return db.Query<int>(
            @"SELECT a.animalID        
            FROM
            dbo.animalTypes [at]
            INNER JOIN animals [a] on a.animalTypeId = at.animalTypeId
            INNER JOIN edibleAnimals e on e.animalID = a.animalID
            WHERE
            at.animalId in @animalIds", new { animalIds }).ToList();
    }
}

我需要解决的问题是,当 animalIds 列表中的 id 超过 2100 个时,我会得到一个 SQL 错误 "The incoming request has too many parameters. The server supports a maximum of 2100 parameters"。

所以现在我想创建一个临时文件 table,其中填充了传递给方法的 animalIds。然后我可以在临时 table 上加入动物 table 并避免使用巨大的 "IN" 子句。

我尝试了各种语法组合,但没有成功。 这就是我现在所在的位置:

public IList<int> LoadAnimalTypeIdsFromAnimalIds(IList<int> animalIds)
{
    using (var db = new SqlConnection(this.connectionString))
    {
        db.Execute(@"SELECT INTO #tempAnmialIds @animalIds");

        return db.Query<int>(
            @"SELECT a.animalID        
            FROM
            dbo.animalTypes [at]
            INNER JOIN animals [a] on a.animalTypeId = at.animalTypeId
            INNER JOIN edibleAnimals e on e.animalID = a.animalID
            INNER JOIN #tempAnmialIds tmp on tmp.animalID = a.animalID).ToList();
    }
}

我无法让 SELECT INTO 使用 ID 列表。我是不是以错误的方式解决这个问题,也许有更好的方法来避免 "IN" 子句限制。

我确实有一个备用解决方案,因为我可以将传入的 animalID 列表分成 1000 个块,但我读到大型 "IN" 子句会受到性能影响并加入临时 table 会更有效率,这也意味着我不需要额外的 'splitting' 代码来将 id 批量化为 1000 个块。

在您的示例中,我看不到的是您的 animalIds 列表实际上是如何传递给要插入到 #tempAnimalIDs table.[=20 中的查询的=]

有一种方法可以在不使用临时 table 的情况下使用具有 table 值参数的存储过程。

SQL:

CREATE TYPE [dbo].[udtKeys] AS TABLE([i] [int] NOT NULL)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[myProc](@data as dbo.udtKeys readonly)AS
BEGIN
    select i from @data;
END
GO

这将创建一个名为 udtKeys 的用户定义 table 类型,它仅包含一个名为 i 的 int 列,以及一个需要该类型参数的存储过程。 proc 除了 select 您传递的 ID 之外什么都不做,但是您当然可以将其他 table 加入其中。有关语法的提示,see here.

C#:

var dataTable = new DataTable();
dataTable.Columns.Add("i", typeof(int));
foreach (var animalId in animalIds)
    dataTable.Rows.Add(animalId);
using(SqlConnection conn = new SqlConnection("connectionString goes here"))
{
    var r=conn.Query("myProc", new {data=dataTable},commandType: CommandType.StoredProcedure);
    // r contains your results
}

过程中的参数通过传递数据表来填充,并且该数据表的结构必须与您创建的 table 类型相匹配。

如果您确实需要传递超过 2100 个值,您可能需要考虑索引您的 table 类型以提高性能。如果你不传递任何重复的键,你实际上可以给它一个主键,像这样:

CREATE TYPE [dbo].[udtKeys] AS TABLE(
    [i] [int] NOT NULL,
    PRIMARY KEY CLUSTERED 
    (
        [i] ASC
    )WITH (IGNORE_DUP_KEY = OFF)
)
GO

您可能还需要将类型的执行权限分配给执行此操作的数据库用户,如下所示:

GRANT EXEC ON TYPE::[dbo].[udtKeys] TO [User]
GO

另见 here and here

好的,这是您想要的版本。我将其添加为单独的答案,因为我使用 SP/TVP 的第一个答案使用了不同的概念。

public IList<int> LoadAnimalTypeIdsFromAnimalIds(IList<int> animalIds)
{
  using (var db = new SqlConnection(this.connectionString))
  {
    // This Open() call is vital! If you don't open the connection, Dapper will
    // open/close it automagically, which means that you'll loose the created
    // temp table directly after the statement completes.
    db.Open();

    // This temp table is created having a primary key. So make sure you don't pass
    // any duplicate IDs
    db.Execute("CREATE TABLE #tempAnimalIds(animalId int not null primary key);");
    while (animalIds.Any())
    {
      // Build the statements to insert the Ids. For this, we need to split animalIDs
      // into chunks of 1000, as this flavour of INSERT INTO is limited to 1000 values
      // at a time.
      var ids2Insert = animalIds.Take(1000);
      animalIds = animalIds.Skip(1000).ToList();

      StringBuilder stmt = new StringBuilder("INSERT INTO #tempAnimalIds VALUES (");
      stmt.Append(string.Join("),(", ids2Insert));
      stmt.Append(");");

      db.Execute(stmt.ToString());
    }

    return db.Query<int>(@"SELECT animalID FROM #tempAnimalIds").ToList();
  }
}

待测:

var ids = LoadAnimalTypeIdsFromAnimalIds(Enumerable.Range(1, 2500).ToList());

您只需将 select 声明修改为原来的样子。由于我的环境中没有您所有的 table,我只是 select 从创建的临时文件 table 中编辑,以证明它按应有的方式工作。

陷阱,见评论:

  • 一开始就打开连接,否则temp table会 在 dapper 自动关闭连接后立即消失 创建 table.
  • INSERT INTO的这种特殊口味是有限的 一次最多 1000 个值,因此传递的 ID 需要拆分为 相应地分块。
  • 不要传递重复键,因为临时 table 上的主键不允许这样做。

编辑

看起来 Dapper 支持基于集合的操作,这也将使这项工作有效:

public IList<int> LoadAnimalTypeIdsFromAnimalIdsV2(IList<int> animalIds)
{
  // This creates an IEnumerable of an anonymous type containing an Id property. This seems
  // to be necessary to be able to grab the Id by it's name via Dapper.
  var namedIDs = animalIds.Select(i => new {Id = i});
  using (var db = new SqlConnection(this.connectionString))
  {
    // This is vital! If you don't open the connection, Dapper will open/close it
    // automagically, which means that you'll loose the created temp table directly
    // after the statement completes.
    db.Open();

    // This temp table is created having a primary key. So make sure you don't pass
    // any duplicate IDs
    db.Execute("CREATE TABLE #tempAnimalIds(animalId int not null primary key);");

    // Using one of Dapper's convenient features, the INSERT becomes:
    db.Execute("INSERT INTO #tempAnimalIds VALUES(@Id);", namedIDs);

    return db.Query<int>(@"SELECT animalID FROM #tempAnimalIds").ToList();
  }
}

我不知道与以前的版本(即 2500 个单插入,而不是三个分别具有 1000、1000、500 个值的插入)相比,它的性能如何。但文档建议,如果与异步、MARS 和流水线一起使用,它的性能会更好。

对我来说,我能想出的最好方法是在 C# 中将列表转换为逗号分隔列表,然后使用 SQL 中的 string_split 将数据插入临时 table。这可能有上限,但就我而言,我只处理了 6,000 条记录,而且速度非常快。

public IList<int> LoadAnimalTypeIdsFromAnimalIds(IList<int> animalIds)
{
    using (var db = new SqlConnection(this.connectionString))
    {
        return db.Query<int>(
            @"  --Created a temp table to join to later. An index on this would probably be good too.
                CREATE TABLE #tempAnimals (Id INT)
                INSERT INTO #tempAnimals (ID)
                SELECT value FROM string_split(@animalIdStrings)

                SELECT at.animalTypeID        
                FROM dbo.animalTypes [at]
                JOIN animals [a] ON a.animalTypeId = at.animalTypeId
                JOIN #tempAnimals temp ON temp.ID = a.animalID -- <-- added this
                JOIN edibleAnimals e ON e.animalID = a.animalID", 
            new { animalIdStrings = string.Join(",", animalIds) }).ToList();
    }
}

可能值得注意的是,string_split 仅适用于 SQL Server 2016 或更高版本,或者如果使用 Azure SQL,则兼容模式 130 或更高版本。 https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-ver15