在 Oracle 中将查询从合并转换为 select 计数

convert query from merge to select count in Oracle

我有以下语法的合并查询:

MERGE INTO target_table 
USING source_table 
ON search_condition
    WHEN NOT MATCHED THEN
        INSERT (col1,col2,...)
        values(value1,value2,...)
        WHERE <insert_condition>;

但我想更改此查询以查看将插入多少行并使用以下查询,但我不确定这是正确的查询:

select count(*) from target_table where not exists (select 1 from source_table where search_condition)

您不必单独计算插入的行数。如果你 运行 它在 SQL*Plus 中,它会显示数字本身。

如果您将该 MERGE 用作 PL/SQL 过程的一部分,那么您将使用 SQL%ROWCOUNT:

declare
  l_cnt number;
begin
  merge into target_table
    using ...;

  l_cnt := SQL%ROWCOUNT;            --> this is what you want

  dbms_output.put_line('Inserted ' || l_cnt || ' rows');
end;

我将它存储到一个局部变量中,以便稍后可以用它做一些事情(将它与其他一些值进行比较)。

MERGE 语句将 source_table 中的行插入到 target_table 中。因此,您要计算的 target_table 中尚不存在 source_table 中的数据。

select count(*)
from source_table 
where <insert_condition>
and not exists
(
  select *
  from target_table
  where <search_condition>
);