如何在批量更新中获取受影响的行的ID?当我试图在表tbl.history上插入所有更新/事务时。
下面是我的示例表:
table tbl.myTable
+------+-----------+------------+
| ID | Amount | Date |
+------+-----------+------------+
| 1 | 100 | 01/01/2019 |
+------+-----------+------------+
| 2 | 200 | 01/02/2019 |
+------+-----------+------------+
| 3 | 500 | 01/01/2019 |
+------+-----------+------------+
| 5 | 500 | 01/05/2019 |
+------+-----------+------------+
Run Code Online (Sandbox Code Playgroud)
这是我的批量更新查询:
Update tbl.myTable set Amount = 0 where Date = '01/01/2019'
Run Code Online (Sandbox Code Playgroud)
通过查询,它将更新/影响ID为1和3的两个数据。如何获取那些ID以将其插入到另一个表中(tbl.history)?
使用OUTPUT子句。它为您提供了一个名为“表”的表,该表deleted包含更新前的值,以及一个名为“表”的表inserted,其中包含新值。
因此,您可以运行
Update tbl.myTable set Amount = 0
output inserted.*,deleted.*
where Date = '01/01/2019'
Run Code Online (Sandbox Code Playgroud)
要了解它是如何工作的,在此之后,您现在可以创建一个临时表和OUTPUT所需的字段INTO:
Update tbl.myTable set Amount = 0
output inserted.*,deleted.* into temp_table_with_updated
where Date = '01/01/2019'
Run Code Online (Sandbox Code Playgroud)