SQL 更新后如何查找受影响的行

How to find affected rows, after an update in SQL

我有一个 table 和一个存储过程。我使用存储过程来更新table。存储过程中有一些游标,SP 正在更新 table。我想通过存储过程更新行。我不想要更新的行数,我只想要更新的行。

我创建了一个临时 table 来插入更新的行,但无法获取更新的行。我怎样才能得到?

我正在使用 SQL 服务器。

如果您的 RDBMS 支持它,您可以像这样使用 update returning

sql> update your_table 
        set your_field = 'my new value' 
      where other_field = 'your condition'
     returning *; -- this returning will return a result set with the modified rows
                  -- you could also specify a list of columns here if you don't want
                  -- all fields returned

使用 returning 子句应该适用于 PostgreSQL、Oracle 和其他软件。

如果您使用的是 SQLServer(正如您刚刚在问题更新中所述),则可以使用 output:

sql> update your_table 
        set your_field = 'my new value' 
     output your_list_of_fields -- this is a comma separated list of the
                                -- columns you want to return
      where other_field = 'your condition';

您可以使用为此目的创建的 INSERTEDDELETED 虚拟或“伪”表。在 UPDATE 语句中,可以使用 OUTPUT 子句访问虚拟表。这是一个例子

drop table if exists #t;
go
create table #t(col_x        char(1));

insert #t values('a');

update #t
set col_x='b'
output inserted.col_x as new_val,
       deleted.col_x as old_val;
new_val old_val
b       a