【问题标题】:SQL Server temporal table doesn't keep delete history for update and delete within a transactionSQL Server 时态表不保留删除历史记录以在事务中进行更新和删除
【发布时间】:2018-07-21 14:40:55
【问题描述】:

我有一个 SQL Server 时态表“人”,其记录如下:

name      | modified_by
-------------------------
John      | 1

如果我执行以下 sql 语句

update person set modified_by = 2 where name = 'John'
delete from person where name = 'John'

我在历史表中看到两条记录,modified_by = 1 和 2。

如果我在一个事务中执行这两个语句

begin transaction
  update person set modified_by = 2 where name = 'John'
  delete from person where name = 'John'
commit transaction

我只看到历史表中的一条记录,modified_by = 1

这是预期的行为吗?为什么?

【问题讨论】:

    标签: sql-server temporal


    【解决方案1】:

    是的,这是意料之中的。

    事务中的所有语句要么完全执行,要么根本不执行。没有中间步骤。

    在您的示例中,更新语句是一种资源浪费,因为无论如何都会删除相关行。

    但是,如果没有事务,您的第一个语句将导致表的三个一致状态:在第一个语句之前、更新之后和删除之后。

    【讨论】:

    • 这两个语句的目的是为了保留谁删除了记录的历史。所以第一个更新语句确保我知道那个人 (modified_by = 2) 是删除记录的人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    相关资源
    最近更新 更多