【问题标题】:Update 2000 records with one query一次查询更新 2000 条记录
【发布时间】:2014-04-25 10:22:40
【问题描述】:

我有一个数据库表:

Item

ID (uniqueidentifier)

Index (int)

我有一个包含 2000 个键值对项目的列表,其中键是 ID,值是 Index,我需要对其进行更新。如何使用一个 sql 查询更新数据库中的所有 2000 项?

现在我有这样的东西:

// this dictionary has 2000 values
Dictionary<Guid, int> values = new Dictionary<Guid,int>(); 
foreach(KeyValuePair<Guid, int> item in values)
{
    _db.Database.ExecuteSqlCommand("UPDATE [Item] SET [Index] = @p0 WHERE [Id] = @p1", item.Value, item.Key);
}

但是,我向 SQL Server 发出了太多请求,我想改进这一点。

【问题讨论】:

标签: asp.net sql sql-server entity-framework


【解决方案1】:

使用 table value parameters 将这些值发送到 SQL Server 并一次性更新 Items 表:

CREATE TYPE KeyValueType AS TABLE 
(
    [Key] GUID,
    [Value] INT
);

CREATE PROCEDURE dbo.usp_UpdateItems
@pairs KeyValueType READONLY
AS
BEGIN
    UPDATE I
    SET [Index] = P.Value
    FROM
        [Item] I
        INNER JOIN @pairs P ON P.Id = I.Id
END;
GO

【讨论】:

    【解决方案2】:

    如果您真的需要以这种方式进行更新并且没有其他选择 - 解决它的主要方法可能是这种相当“丑陋”的技术(因此很少使用,但仍然很好用);

    将所有 2000 条语句放在一个字符串中,然后执行该字符串。这将调用包含 2000 次更新的数据库。

    所以基本上是这样的(代码没有实际运行,这是一个示例,所以 t

    Dictionary<Guid, int> values = new Dictionary<Guid, int>();
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    foreach (KeyValuePair<Guid, int> item in values)
    {
        sb.Append(String.Format("UPDATE [Item] SET [Index] = {0} WHERE [Id] = '{1}';", item.Value, item.Key));
    
    }
    _db.Database.ExecuteSqlCommand(sb.ToString);     
    

    【讨论】:

      猜你喜欢
      • 2021-09-22
      • 2011-11-22
      • 1970-01-01
      • 2015-06-02
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多