【发布时间】:2021-11-21 20:50:36
【问题描述】:
我正在从包含一百万条记录的表中读取数据,我对某些列进行了一些修改,我想将它们批量保存。我想在每 10000 条记录后执行一次批量更新。
我正在使用 .Net Core 3.1
我的代码:
public void FixText()
{
SqlConnection cnn = new SqlConnection(strConn);
string queryString = "SELECT ClientID, ServerName, Text FROM [dbo].[Client]";
SqlCommand selectCmd = new SqlCommand(queryString, cnn);
cnn.Open();
int j = 0;
SqlDataReader reader = selectCmd.ExecuteReader();
List<Client> clients = new List<Client>();
try
{
while (reader.Read())
{
j++;
ClientID = (int)reader["ClientID"];
ServerName = reader["ServerName"].ToString();
Text = reader["Text"].ToString();
//Modify Text & set ServerName
string Text = UpdateText(Text);
if text.StartWith("doo"){ServerName = "re";}
//perform bulk update
if (j > 10000)
{
Client client = new Client()
{
ClientID = (int)ClientID,
ServerName = ServerName,
Text = Text,
};
clients.Add(client);
//I'm struggling here on what to use to do a bulk update
j = 0;
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
reader.Close();
}
cnn.Close();
}
任何帮助表示赞赏!
【问题讨论】:
-
你能完全在 SQL 中完成它们,以避免任何 C# 吗?
-
很遗憾我做不到,有很多数据超出了 SQL 范围。
-
90% 的时间最快的解决方案是将
SqlBulkCopy到一个临时/临时表,然后通过 JOIN 对原始表运行更新。 -
我被你的 if(j>10000) 条件弄糊涂了……你不应该每次都添加一个新客户吗?如果 j>10000 则保存?还有什么理由您不使用实体框架来进行数据操作?如果您想坚持使用此解决方案,我会阅读所有内容,然后打开一个新连接,遍历您的记录并根据您的数据创建更新语句。每 10k 条记录运行更新命令。
标签: c# sql asp.net-core ado.net bulkupdate