我的 SQL 代码从列表中将 10,000 条记录插入到表中。如果记录已经存在,它会更新一些字段。
目前它需要超过 10 分钟并且超时,除非我限制要处理的记录数。我的代码中有什么可以解决这个问题的吗?
foreach(RMSResponse rmsObj in rmsList) {
try {
string connectionString = @"server=localhost\sqlexpress;" + "Trusted_Connection=yes;" + "database=MyDB; " + "connection timeout=30";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
string str = "";
str += "SELECT * ";
str += "FROM RMSResponse ";
str += "WHERE LeadID = @RecruitID";
int LeadID;
Boolean IsPositive = true;
SqlCommand selectCommand = new SqlCommand(str, conn);
selectCommand.CommandType = CommandType.Text;
selectCommand.Parameters.Add(new SqlParameter("@RecruitID", rmsObj.RecruitID));
SqlDataReader sqlDataReader = selectCommand.ExecuteReader();
bool hasRows = sqlDataReader.HasRows;
while (sqlDataReader.Read()) {
LeadID = sqlDataReader.GetInt32(1);
IsPositive = sqlDataReader.GetBoolean(2);
IsPositive = (IsPositive == true) ? false : true;
Console.WriteLine("Lead ID: " + LeadID + " IsPositive: " + IsPositive);
}
sqlDataReader.Close();
if (hasRows) {
SqlCommand updateCommand = new SqlCommand("UPDATE RMSResponse set IsPositive=@IsPositive, OptOutDate=@OptOutDate where LeadID=@LeadID", conn);
updateCommand.Parameters.AddWithValue("@LeadID", rmsObj.RecruitID);
updateCommand.Parameters.AddWithValue("@IsPositive", IsPositive);
updateCommand.Parameters.AddWithValue("@OptOutDate", DateTime.Now);
updateCommand.ExecuteNonQuery();
sqlDataReader.Close();
}
if (!hasRows) {
SqlCommand insertCommand = new SqlCommand("INSERT INTO RMSResponse (LeadID, IsPositive, ReceivedDate) " + "VALUES(@LeadID, @IsPositive, @ReceivedDate)", conn);
insertCommand.Parameters.AddWithValue("@LeadID", rmsObj.RecruitID);
insertCommand.Parameters.AddWithValue("@IsPositive", true);
insertCommand.Parameters.AddWithValue("@ReceivedDate", DateTime.Now);
int rows = insertCommand.ExecuteNonQuery();
}
} catch (SqlException ex) {
Console.WriteLine(ex.Message);
}
}