如何获取我批量更新的SQL Server的ID

3

我该如何获取批量更新中受影响行的ID?因为我想把所有的更新/事务插入到tbl.history表中。

以下是我的示例表:

Original Answer翻译成“最初的回答”

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 |
+------+-----------+------------+   

这是我的批量更新查询:

Update tbl.myTable set Amount = 0 where Date = '01/01/2019'

使用这个查询将会更新/影响ID为1和3的两条数据。我该如何获取这些ID并将它们插入到另一个表(tbl.history)中?

最初的回答:

你可以在更新查询之前先查询一次,以获取要更新的记录的ID。然后,将这些ID插入到tbl.history表中。


1
使用TRIGGERS https://learn.microsoft.com/zh-cn/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-2017 - undefined
1
@Juan,我对你的观点持不同意见。这个请求相当简单且只需一次性处理,所以目前已有的答案比触发器更加简洁和快速,我个人认为。 - undefined
3个回答

5

使用OUTPUT子句。它会提供一个名为deleted的“表”,其中包含更新前的值,以及一个名为inserted的“表”,其中包含新值。

因此,您可以运行

Update tbl.myTable set Amount = 0
output inserted.*,deleted.*
where Date = '01/01/2019'

为了理解它是如何工作的,接下来,您可以创建一个临时表,并将您想要的字段OUTPUT到其中:
Update tbl.myTable set Amount = 0
output inserted.*,deleted.* into temp_table_with_updated
where Date = '01/01/2019'

3
你可以通过使用OUTPUT来实现这一点。最初的回答。
declare @outputIDs as TABLE
(
   ID int
)

Update tbl.MyTable Set [Amount] = 0
OUTPUT INSERTED.ID into @outputIDs
WHERE [Date] = '01/01/2019'
< p > @outputIDs表将有两个更新后的ID。

最初的回答:The table @outputIDs will contain the two updated IDs.

0
使用缓存机制(表变量、CTE等)
declare @temp table (id int)
insert into @temp select id from tbl.myTable where Date = '01/01/2019'
update tbl.myTable set Amount=0 where id in (select id from @temp)
-- do more stuff with the id's

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接