临时表 + 事务批量操作

临时表 + 事务批量操作

临时表存储在内存中,只有当前会话有效,会话退出自动删除。

create table #temp(id int)
insert into #temp(id) values(1)
insert into #temp(id) values(2)
select * from #tempCode language: CSS (css)

以前批量删除可能用 IN 方式:

delete from aaa where bh in ('1,2,34')Code language: JavaScript (javascript)

但 ID 多时 IN 子句过长,用临时表更合适。借助事务在 LINQ 中完成:

var ids = "1,2,5";

using (var db = new DataClasses1DataContext())
{
    if (db.Connection != null)
    {
        db.Connection.Open(); // 开启会话
    }

    DbTransaction tran = db.Connection.BeginTransaction(); // 开启事务
    db.Transaction = tran;

    try
    {
        // 创建临时表
        db.ExecuteCommand("create table #temp(id int)");

        var idarray = ids.Split(',').Select(m => Convert.ToInt32(m)).ToList();
        foreach (var item in idarray)
        {
            // 逐条插入临时表
            db.ExecuteCommand("insert into #temp(id) values({0})", item);
        }

        // JOIN 临时表批量更新
        db.ExecuteCommand(@"update s
                            set s.age = {0}
                            from dbo.Student s
                            join #temp t on s.id = t.id", 18);

        // 删除临时表
        db.ExecuteCommand("drop table #temp");

        // 提交事务
        tran.Commit();
    }
    catch (Exception)
    {
        // 回滚事务
        tran.Rollback();
    }
}Code language: PHP (php)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注