本文介绍了C#SQL从对象列表逐行更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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;
}
}
问题:我正在查询一个表并得到50K条记录,这些记录正在转换为对象列表.我正在BLL中处理列表并发送给DAL.以上是我的DAL中的一种方法.有没有更好的办法?我还在检查所有行是否都已更新&然后提交或回滚.
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.
推荐答案
您可以将其转换为表值参数.
You can convert this to a table-valued parameter.
首先,我们需要一个表类型:
First we need a table type:
CREATE TYPE dbo.MyTVP (
empno int not null,
mydate date not null,
amt decimal not null
primary key (empno, mydate)
);
然后我们通过它.您不必要需要存储过程,您可以将其作为临时批处理:
Then we pass it through. You don't necessarily need a stored procedure, you can do this as an ad-hoc batch:
public int UpdateAmount(List<MyTable> myBizObjList)
{
var table = new DataTable();
table.Columns.Add("empno", typeof(int));
table.Columns.Add("mydate", typeof(datetime));
table.Columns.Add("amt", typeof(decimal));
foreach (MyTable myBizObj in myBizObjList)
table.Rows.Add(myBizObj.Empno, myBizObj.Mydate, myBizObj.Amt);
const string commandText = @"
Update tbl
Set amt = t.amt
FROM MyTable AS tbl
JOIN @tmp AS t ON t.empno = tbl.empno AND t.mydate = tbl.mydate;
";
using (var cs = db.GetConnection())
{
SqlCommand command = new SqlCommand(commandText, cs, sqltxn);
command.Parameters.Add(
new SqlParameter("@tmp", SqlDbType.Structured)
{
Direction = ParameterDirection.Input,
TypeName = "dbo.MyTVP",
Value = table
});
cs.Open();
return command.ExecuteNonQuery();
}
}
这篇关于C#SQL从对象列表逐行更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!