pl sql 如何减少我的代码

pl sql How to make my code less

谁能帮我减少代码量? (如果你能注意到两个 if-elsif 语句,我做了相同的 Select.. 所以我希望有一种方法可以使这个 select 一次。并根据 [= 更新为 1 或 0 16=]). 下面是我的代码。

create or replace
PROCEDURE F_16 (TRK_ID NUMBER, pilot_action NUMBER) IS
BEGIN
  BEGIN 

    IF pilot_action=0 THEN
          UPDATE "ControlTow"
          SET "Intention"=0
          WHERE "Id" IN (              
          SELECT "Id" FROM "ControlTow" WHERE "Id"=TRK_ID );

    ELSIF pilot_action=1 THEN
          UPDATE "ControlTow"
          SET "Intention"=1        
          WHERE "Id" IN (
          SELECT "Id" FROM "ControlTow" WHERE "Id"=TRK_ID );
       END IF;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN dbms_output.put_line('False Alarm');
  COMMIT;  
  END;    
END F_16;

提前谢谢你。

由于您似乎将 pilot_action 分配给 Intention,我将执行以下操作:

create or replace
PROCEDURE F_16 (TRK_ID NUMBER, pilot_action NUMBER) IS
BEGIN
  BEGIN 

    IF pilot_action IN (0, 1) THEN
       -- if the only condition in subselect is the ID then use it directly
       UPDATE "ControlTow"
          SET "Intention"= pilot_action
        WHERE "Id"=TRK_ID;
       -- if there are more conditions than just the ID then subselect may be the way to go 
       --(hard to say without more information)
       -- WHERE "Id" IN (              
       --   SELECT "Id" FROM "ControlTow" WHERE "Id"=TRK_ID AND ... )
    ELSE
      Null; -- do whatever you need in this case. Raise exception?
    END IF;
  EXCEPTION
    WHEN NO_DATA_FOUND THEN dbms_output.put_line('False Alarm');
    COMMIT;  
  END;    
END F_16;

编辑:正如@user272735 所说,代码还有更多改进的余地。具体重写 if 条件以使用 in 并简化 where 子句(假设 Id 实际上是要更新 select 行的唯一条件)。

您的代码有几个问题,我已在下面的评论中解决。请注意,未讨论事务管理,因为根据 commit/rollback 何时应该发生的问题尚不清楚。

-- #1 use of explicit parameter mode
create or replace procedure f_16(p_trk_id in number, p_pilot_action in number) is
begin
  -- #2 use of in
  if p_pilot_action in (0, 1)
  then
    -- #3 unnecessary subquery removed
    update controltow
       set intention = p_pilot_action
     where id = p_trk_id;

    -- #4 use pl/sql implicit cursor attribute to check the number of affected rows
    if sql%rowcount = 0
    then
      dbms_output.put_line('false alarm');
    end if;
  end if;
end;