繁体   English   中英

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

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

我有一个包含 ID 的列表,我想使用 Dapper 将其插入到临时表中,以避免对“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错误“传入的请求参数太多。服务器最多支持2100个参数”。

所以现在我想创建一个临时表,其中填充了传递给方法的动物 ID。 然后我可以加入临时表上的动物表并避免使用巨大的“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”子句会受到性能影响,加入临时表会更有效,这也意味着我不需要额外的“拆分”代码来将 id 分成 1000 个块。

好的,这就是你想要的版本。 我将此添加为单独的答案,因为我使用 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 语句修改为原来的样子。 由于我的环境中没有您的所有表,我只是从创建的临时表中进行选择以证明它可以正常工作。

陷阱,见评论:

  • 一开始就打开连接,否则临时表会在创建表后dapper自动关闭连接后消失。
  • 这种特殊风格的INSERT INTO限制为 1000 个值,因此需要将传递的 ID 相应地拆分为多个块。
  • 不要传递重复的键,因为临时表上的主键不允许这样做。

编辑

似乎 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 个值的三个插入)。 但该文档表明,如果与 async、MARS 和 Pipelining 一起使用,它的性能会更好。

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

有一种方法可以在不使用临时表的情况下使用带有表值参数的存储过程来完成。

查询语句:

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的用户定义表类型, udtKeys包含一个名为i int 列,以及一个需要该类型参数的存储过程。 proc 除了选择您传递的 ID 之外什么都不做,但是您当然可以将其他表加入它。 有关语法的提示,请参见此处

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
}

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

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

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

另请参阅此处此处

对我来说,我能想到的最好方法是在 C# 中将列表转换为逗号分隔的列表,然后在 SQL 中使用string_split将数据插入到临时表中。 这可能有上限,但就我而言,我只处理了 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM