如果记录存在,Oracle 存储过程更新行

Oracle Stored Procedure update rows if records exist

我有以下 Oracle 存储过程。传入子代码或样式代码。如果值不为空,则当前它是更新行。我想添加逻辑,以便仅当 table 上存在行时才进行更新,如果不存在,我喜欢打印 "The subcode xxxx doesn't exists" 或 "The stylecode xxxx doesn't exists" 之类的消息。我不认为 merge into works here.

create or replace PROCEDURE "REMOVE_PRICES"
(
  RESULT OUT VARCHAR2 
  , STYLECODE_ IN NUMBER 
  , SUBCODE_ IN NUMBER 
) AS 
BEGIN
IF (SUBCODE_ is null AND STYLECODE_ is null)
THEN
    raise_application_error(-20005, 'ERROR: Please provide either SUBCODE or STYLECODE!');
END IF;
IF SUBCODE_ IS NOT NULL THEN
  UPDATE prices
  SET type = null
  WHERE subcode=SUBCODE_;
  RESULT := SQL%ROWCOUNT || ' price for subcode ' || SUBCODE_ || ' is    removed';

ELSIF STYLECODE_ IS NOT NULL THEN
  UPDATE prices
  SET type = null
  WHERE stylecode=STYLECODE_;
  RESULT := SQL%ROWCOUNT || ' price for stylecode ' || STYLECODE_ || ' is removed';
END IF;
END REMOVE_PRICES;

如果更新会影响行,您不能只选择进行更新,除非您首先使用相同的条件进行查询,然后进行计数;并且您仍然可能与其他会话存在竞争条件,这意味着数据可能会在 selectupdate 之间更改,除非您锁定行。这一切似乎有点过分和昂贵。

您可以只检查 SQL%ROWCOUNT 的值,如果它为零则显示该消息,否则显示您当前的消息:

IF SUBCODE_ IS NOT NULL THEN
  UPDATE prices
  SET type = null
  WHERE subcode=SUBCODE_;
  IF SQL%ROWCOUNT = 0 then
    RESULT := 'The subcode ' || SUBCODE || ' does not exist';
  ELSE
    RESULT := SQL%ROWCOUNT || ' price for subcode ' || SUBCODE_ || ' is removed';
  END IF;
ELSIF STYLECODE_ IS NOT NULL THEN
  UPDATE prices
  SET type = null
  WHERE stylecode=STYLECODE_;
  IF SQL%ROWCOUNT = 0 then
    RESULT := 'The stylecode ' || STYLECODE || ' does not exist';
  ELSE
    RESULT := SQL%ROWCOUNT || ' price for stylecode ' || STYLECODE_ || ' is removed';
  END IF;
END IF;