【问题标题】:Modifying condition for PL/SQL procedure修改 PL/SQL 过程的条件
【发布时间】:2018-11-11 18:58:41
【问题描述】:

我有一个 PL/SQL 过程,用于删除对应于具有 NULL 值的字段的记录。我可以通过以下查询来实现这一点。

set serveroutput on;

begin
    dbms_output.put_line('Execution started');

    for rec in (
        select name from employee where emp_id is null
        and location = 'SITE_A'
    )
    loop
        delete from employeedetails@sitea where name = rec.name;
        dbms_output.put_line('name '|| rec.name ||' deleted');
    end loop;

    dbms_output.put_line('Execution completed');
end;
/

set serveroutput off;

我正在从一个数据库运行 for 循环查询,并使用数据库链接删除另一个数据库 ( sitea ) 中的记录。

我需要添加一个条件,例如,如果name=rec.name 没有返回任何要删除的记录,那么dbms_output.put_line('No records to be deleted');

有没有一种舒适的方法来实现它?

【问题讨论】:

    标签: plsql oracle11g


    【解决方案1】:

    您可以使用sql%rowcount implicit cursor attribute 查看DML 语句影响了多少行;跨数据库链接以及本地工作:

    if sql%rowcount = 0 then
      dbms_output.put_line('No records to be deleted');
    else
      dbms_output.put_line('name '|| rec.name ||' deleted');
    end if;
    

    您也可以将其包含在消息中:

    if sql%rowcount = 0 then
      dbms_output.put_line('name '|| rec.name ||': no records to be deleted');
    else
      dbms_output.put_line('name '|| rec.name ||': '|| sql%rowcount ||' record(s) deleted');
    end if;
    

    然后你会看到类似的东西:

    Execution started
    name B: 1 record(s) deleted
    name C: no records to be deleted
    Execution completed
    
    
    PL/SQL procedure successfully completed.
    

    由于name 可能不是唯一的,您可能会在循环中遇到两次相同的值;在这种情况下,第一次删除将找到多行,而第二次删除将找不到。您可以通过在光标查询中添加 distinct 来避免第二个问题。

    如果您不想查看哪些名称有和没有要删除的远程数据,那么您可以使用更简单的单次删除,没有循环或 PL/SQL,但无论如何这似乎是一个练习...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-20
      • 2023-03-07
      • 1970-01-01
      • 2019-02-02
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      相关资源
      最近更新 更多