【问题标题】:How to find affected rows, after an update in SQL在 SQL 中更新后如何查找受影响的行
【发布时间】:2021-04-29 05:46:40
【问题描述】:

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

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

我正在使用 SQL Server。

【问题讨论】:

  • 听起来您需要修改存储过程以将修改后的行存储在某个地方,例如临时表或日志表。
  • 是的@GordonLinoff,我正在尝试修改 sp,但无法做到“这一行已更新,让我们将这一行插入临时表”
  • 无法获取更新的行 首先详细解释一下。但实际上不可能帮助您更改看不到的代码。如果该过程以某种方式生成包含所需行的结果集,那么问题在于执行该过程的过程。根据您之前的问题,您应该向更高级或资深的同事寻求帮助。

标签: sql sql-server tsql sql-update


【解决方案1】:

如果您的 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';

【讨论】:

  • 嗨,我使用 MS SQL。我试过你的建议,返回是行不通的。感谢您的宝贵时间
【解决方案2】:

您可以使用为此目的创建的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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2019-11-20
    • 2011-06-11
    相关资源
    最近更新 更多