简体   繁体   English

参考Datatable C#更新SQL表的最佳方法

[英]Best way to update SQL Table with reference to a Datatable C#

I have a data table that contains an Id column. 我有一个包含Id列的数据表。 The Id Column matches My tables ID Column. Id列与我的表ID列匹配。 i need to use this ids to set a single value to my sql table. 我需要使用此ID为我的sql表设置单个值。 But the data table structure is not the same as my table structure, ie 但是数据表结构与我的表结构不一样,即

  Data Table                        Sql Table
____________      _______________________________________________
ID                ID    | col 1 | col2 | col3 | col4 |final value
1                 1     | a     | b    |c     |d     |N
2                 2     | x     | y    |z     |a     |N

The data table at any given time is going to have more than 500,000 entries. 任何给定时间的数据表将有超过500,000个条目。

My Question Are: 我的问题是:

1) will it be faster to build the Update Statement in and Execute them in a parallel loop within one transaction as shown below: 1)如何在一个事务中的并行循环中构建Update语句并执行它们会更快,如下所示:

Sqltrn = Sqlconn.BeginTransaction();
Parallel.For (0; Datatable.Rows.Count; i =>
    {
       SqlCmd.CommandText = BuildStatemet;
       SqlCmd.ExecuteNonQuery();
    });
SqlTrn.Commit();

And will the above method cause dead lock on my table? 以上方法会导致我的桌子死锁吗?

or 要么

2) Execute a single statement by building a contacted string from the dt tables as such: 2)通过从dt表构建一个联系的字符串来执行单个语句,如下所示:

Update MyTable set  FinalValue = 'Y' WHERE ID in (CreateConcactedStringHere)

Which method is faster and safer, since i need to complete the updation in the least time possible and also avoid the table from locking since its a major transaction table in my database. 哪种方法更快更安全,因为我需要在尽可能短的时间内完成更新,并避免表锁定,因为它是我数据库中的主要事务表。 Or is there any other way i can achieve this? 或者还有其他方法可以达到这个目的吗?

Individual rows update will be slower rather than a single update from a select. 单个行更新速度较慢,而不是选择的单个更新。 for this purpose I would recomment to 为此,我会建议

  1. in your DB create a table like following TicketTable { TicketID, TargetID, SomePrecalculatedRes1, ..., SomePrecalculatedResN} 在你的数据库中创建一个像TicketTable一样的表{TicketID,TargetID,SomePrecalculatedRes1,...,SomePrecalculatedResN}
  2. In C# create a DataTable object whith the same structure as the table from above 在C#中创建一个与上面表格结构相同的DataTable对象
  3. Fill the table content by data you will be using for your update. 按照您将用于更新的数据填写表格内容。 Each row has of the DataTable to have the same ticketId. DataTable的每一行都具有相同的ticketId。 (Parallel processing might give you some benifits) (并行处理可能会给你一些好处)
  4. Bulk insert the DataTable content into db.TicketTable (see SqlBulkCopy ) 批量将DataTable内容插入db.TicketTable(请参阅SqlBulkCopy
  5. create an update command that takes in consideration your ticketId and updates your target table from a select from your ticket table 创建一个更新命令,该命令会考虑您的ticketId并从您的故障单表中选择更新您的目标表

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

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