簡體   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