簡體   English   中英

如何讓 C# 中的表更新更高效?

[英]How to make table updating more efficient in C#?

在下面的代碼中,我試圖通過客戶 ID 列表來 go 並更新Confirmed字段以匹配給定記錄中的 sysdate。 問題是,如果我分別為大約 40k 客戶執行此操作,則需要 15-20 分鍾才能運行,對於這樣的操作來說有點太多了。 您能否就如何改進我的代碼以更快地運行和/或減少數據庫請求的數量給我一些建議?

foreach (int i in confirmCustomers)
{
    queryString = @"
        UPDATE TABLENAME
        SET CONFIRMED = @datenow
        WHERE ID = @id";

    command = new SqlCommand(queryString, connection, transaction);
    command.Parameters.AddWithValue("@id", i);
    command.Parameters.AddWithValue("@datenow", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
    command.ExecuteNonQuery();
}

對於 SQL Server 2016+,您可以 append JSON 數組中的所有 ID,例如

"[1,2,3,4,5,6,7,8,9]"

並將其作為字符串參數傳遞給命令,然后運行:

queryString = @"
    UPDATE TABLENAME
    SET CONFIRMED = @datenow
    WHERE ID in (select cast(value as int) from openjson( @ids ) )";

嘗試這個:

        string queryString = @"UPDATE TABLENAME SET CONFIRMED = @datenow WHERE ID = @id";
        SqlCommand command = new SqlCommand(queryString, connection, transaction);
        command.Parameters.Add(new SqlParameter("@datenow", SqlDbType.DateTime));
        command.Parameters.Add(new SqlParameter("@id", SqlDbType.Int));
        command.Prepare();
        foreach (int i in confirmCustomers)
        {
            command.Parameters["@id"].Value = i;
            command.Parameters["@datenow"].Value = DateTime.Now;
            command.ExecuteNonQuery();
        }

您可以通過使用 string_split function 來使用表格方法,如下所示..

/* init query string */
string queryString = @"
    UPDATE tbl
        SET tbl.CONFIRMED = getdate()
    FROM TABLENAME tbl
    INNER JOIN (
        SELECT ID FROM string_split(@ids, ',')
    ) ids
    WHERE tbl.ID = ids.ID";

/* init command */
SqlCommand command = new SqlCommand(queryString, connection, transaction);
command.Parameters.Add(new SqlParameter("@ids", SqlDbType.Text, 4000));
command.Prepare();

/* init list of id */
List<int> ids = new List<int>();

/* update table for each confirm customers */
foreach (int i in confirmCustomers)
{
    /* add id to list */
    ids.add(i);

    /* update 100 customer ids */
    if (ids.Count == 100)
    {
        command.Parameters[0].Value = String.Join(",", ids);
        command.ExecuteNonQuery();

        /* reset list of id */
        ids.Clear();
    }
}

/* update remains customer id */
if (ids.Count > 0)
{
    command.Parameters[0].Value = String.Join(",", ids);
    command.ExecuteNonQuery();
}

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM