I have written following method with three sql queries in order to update a single column in a single table.since there are nearly 10000 records to be updated it takes more than 20 mins to complete.is there any other better way to do this updation.some thin like set based update…
private void UpdateLatest()
{
string connstr = "Data Source=CHAMARA-PC;Initial Catalog=PHPA_Production_fromEWP;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();
SqlTransaction myTransaction = conn.BeginTransaction();
try
{
DataTable dt = new DataTable();
DataTable DTT = new DataTable();
string command = "select dh.DocumentNumber,max(dr.RevisionDate) as latestdate from " +
"tblDocumentHeader dh inner join tblDocumentRevision dr on dh.DocumentHeaderID=dr.DocumentHeaderID " +
"group by dh.DocumentNumber ";
using (SqlCommand cmd = new SqlCommand(command, conn, myTransaction))
{
using (SqlDataAdapter adapt = new SqlDataAdapter())
{
adapt.SelectCommand = cmd;
adapt.Fill(dt);
}
}
label1.Text = dt.Rows.Count.ToString();
foreach (DataRow item in dt.Rows)
{
try
{
int res = 0;
string query2 = "select dr.DocumentRevisionID from " +
"tblDocumentHeader dh inner join tblDocumentRevision dr on dh.DocumentHeaderID=dr.DocumentHeaderID " +
" where dh.DocumentNumber='" + item["DocumentNumber"].ToString().Trim() + "' and dr.RevisionDate='" + item["latestdate"].ToString().Trim() + "'";
using (SqlCommand cmd = new SqlCommand(query2, conn, myTransaction))
{
using (SqlDataAdapter adapt = new SqlDataAdapter())
{
adapt.SelectCommand = cmd;
adapt.Fill(DTT);
}
}
foreach (DataRow Ritem in DTT.Rows)
{
string updatequery = "update tblDocumentRevision set LatestRev='latest' where DocumentRevisionID='" + Ritem["DocumentRevisionID"].ToString().Trim() + "'";
using (SqlCommand cmd = new SqlCommand(updatequery, conn, myTransaction))
{
cmd.ExecuteNonQuery();
res++;
}
}
listBox1.Items.Add(item["DocumentNumber"].ToString() + " " + "updated");
}
catch (Exception ex)
{
throw ex;
}
}
myTransaction.Commit();
MessageBox.Show("successfully updated");
}
catch (Exception ex)
{
myTransaction.Rollback();
MessageBox.Show(ex.Message);
}
}
}
I don’t have your database at hand to test this, but basically, your code boils down to this:
This can be very easily wrapped in a stored procedure, it does not use any dead slow cursors, and it does not cause any SQL injection possibilities.