【发布时间】:2014-11-30 11:30:28
【问题描述】:
列表中有大约一百万条记录。并在列表中的 foreach 中查询数据库以获取基于 id 的修改日期。一旦我得到它,它会在条件下进行测试以插入或更新它..但是有没有办法将它作为批量(一次或批量)插入或更新..??
foreach (No_kemi no_list in newforSQL)
{
DateTime eModifiedDate = no_list.ModifiedDate.Value;
string Id = no_list.ID.ToString();
String selectQuery = "SELECT ModifiedDate FROM NO_table WHERE ID = '" + Id + "'";
DateTime? dbmoddate = null;
using (SqlCommand selectCommand = new SqlCommand(selectQuery, connection))
{
// Use the above SqlCommand object to create a SqlDataReader object.
using (SqlDataReader rdr = selectCommand.ExecuteReader())
{
while (rdr.Read())
{
dbmoddate = (DateTime)rdr["ModifiedDate"];
}
}
}
string eType = null;
string SubGUID = null;
string trimSubKey = no_list.SubscriberKey;
try
{
if ((trimSubKey.Length > 3) && (trimSubKey != ""))
{
if (trimSubKey.Contains(","))
{
string[] values = trimSubKey.Split(',');
SubGUID = values[0];
eType = values[1];
}
else
{
SubGUID = trimSubKey;
eType = "";
}
}
else
{
SubGUID = "";
eType = "";
}
}
catch (Exception ex)
{
logger.Error("Error : " + ex.Message );
}
if (dbmoddate == null)
{
DateTime no_listinsetdate = DateTime.Now;
String insertQuery = "INSERT INTO NO_table (CreatedDate, ModifiedDate, ID, eType, SubGUID, DbDate) VALUES (@CreatedDate, @ModifiedDate, @ID, @eType, @SubGUID, @DbDate,)";
using (SqlCommand insertCommand = new SqlCommand(insertQuery, connection))
{
insertCommand.Parameters.AddWithValue("@CreatedDate", no_list.CreatedDate);
insertCommand.Parameters.AddWithValue("@ModifiedDate", no_list.ModifiedDate);
insertCommand.Parameters.AddWithValue("@ID", no_list.ID);
insertCommand.Parameters.AddWithValue("@eType", eType);
insertCommand.Parameters.AddWithValue("@SubGUID", SubGUID);
insertCommand.Parameters.AddWithValue("@DbDate", no_listinsetdate);
insertCommand.ExecuteNonQuery(); // execute the query
}
}
else if (eModifiedDate > dbmoddate)
{
DateTime no_listinsetdate = DateTime.Now;
String updateQuery = "UPDATE NO_table SET CreatedDate = @CreatedDate, ModifiedDate = @ModifiedDate, ID = @ID, eType = @eType, SubGUID = @SubGUID, DbDate = @DbDate WHERE ID = '" + Id + "'";
using (SqlCommand updateCommand = new SqlCommand(updateQuery, connection))
{
updateCommand.Parameters.AddWithValue("@CreatedDate", no_list.CreatedDate);
updateCommand.Parameters.AddWithValue("@ModifiedDate", no_list.ModifiedDate);
updateCommand.Parameters.AddWithValue("@ID", no_list.ID);
updateCommand.Parameters.AddWithValue("@eType", eType);
updateCommand.Parameters.AddWithValue("@SubGUID", SubGUID);
updateCommand.Parameters.AddWithValue("@DbDate", no_listinsetdate);
updateCommand.ExecuteNonQuery(); // execute the query
}
}
}
任何加快进程的方法...完成操作需要很多时间...或者有时我会收到超时错误...
谢谢
【问题讨论】:
-
你应该永远使用这样的东西:
WHERE ID = '" + Id + "'";- 像在其他任何地方一样使用参数!
标签: c# database sql-server-2012