繁体   English   中英

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

[英]How to find affected rows, after an update in SQL

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

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

我正在使用 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM