public int UpdateAmount(List<MyTable> myBizObjList)
{
SqlTransaction sqltxn;
DbClass db = new DbClass();
SqlConnection cs;
cs = db.GetConnection();
string commandText = @"Update MyTable Set amt = @amt where empno = @empno and mydate = @mydate";
int x = myBizObjList.Count;
int y = 0,rowsaffected;
cs.Open();
using (cs)
{
sqltxn = cs.BeginTransaction();
foreach (MyTable myBizObj in myBizObjList)
{
SqlCommand command = new SqlCommand(commandText, cs, sqltxn);
command.Parameters.Add("@empno", SqlDbType.Int);
command.Parameters["@empno"].Value = myBizObj.Empno;
command.Parameters.Add("@mydate", SqlDbType.Date);
command.Parameters["@mydate"].Value = myBizObj.Mydate;
command.Parameters.Add("@amt", SqlDbType.Decimal);
command.Parameters["@amt"].Value = myBizObj.Amt;
try
{
rowsAffected = command.ExecuteNonQuery();
if (rowsAffected == 1)
y++;
}
catch (Exception ex)
{
throw (ex);
}
}
if (y == x)
{
sqltxn.Commit();
}
else
{
sqltxn.Rollback();
y = 0;
}
cs.Close();
return y;
}
}
Question: I am querying a table and getting say 50K records which I am converting to a List of objects. I am processing the List in my BLL and sending to my DAL. The above is a method in my DAL. Is there a better way? I am also checking if all rows are updated & then Commit or Rollback.
user defined table typeandstored procedureto update all records at once in single transaction at Database end.using, also you should moveusing(cs)up to the settercs = .... Also you can shortencommand.Parameters.Add("@empno", SqlDbType.Int).Value = myBizObj.Empnothrow ex;whereexis a caught exception. You will lose your stack trace. Just dothrow;. Of course...your catch block isn't doing anything at all except rethrowing, so it's entirely redundant and the try/catch should be removed from this code. There's also no need forcs.Close();, the using block will ensure that the connection is closed and disposed when it goes out of scope.