Oracle sql 存储过程检查输入是否已存在 table 如果不插入

Oracle sql Stored Procedure checking if an input already exists in a table if not insert

我想编写一个过程来检查 table 中的列中是否存在特定输入值。如果该值确实存在,则输出一条错误消息,否则插入一个新行。

例如,这就是所需的逻辑

CREATE OR REPLACE PROCEDURE class_day (p_class_day IN varchar2)
AS
  classday varchar2;
BEGIN

    IF ( SELECT class_Day INTO classday
           FROM tutprac
          WHERE classday = p_class_day) THEN

            dbms_output.put_line('do not allow insert');
    ELSE
      dbms_output.put_line('allow insert');
    END IF;
END;

您可以尝试这样的操作:

CREATE OR REPLACE PROCEDURE class_day (p_class_day IN varchar2) 
AS
 classday tutprac.class_Day%TYPE;
BEGIN
   SELECT class_Day 
     INTO classday
     FROM tutprac
    WHERE classday = p_class_day;

   -- If you get here, the record has been selected, therefore it already exists
   dbms_output.put_line('do not allow insert');
EXCEPTION
   WHEN no_data_found
   THEN
      -- The record did not exist, create it!
      dbms_output.put_line('allow insert');
   WHEN others
   THEN
      -- An unexpected error has occurred, report it!
      dbms_output.put_line(sqlerrm);
      RAISE;

END class_day;

为了避免捕获异常等仪式,我们可以简单地计算给定值出现的行数。然后使用行数作为table.

中值存在的标志
CREATE OR REPLACE PROCEDURE class_day (p_class_day IN varchar2) 
AS
  l_count NUMBER;
BEGIN
   SELECT count(*)
     INTO l_count
     FROM tutprac
    WHERE classday = p_class_day
      AND rownum = 1; -- this line makes the query execution a little bit faster
                      -- and later we can remove it if we need exact amount of rows

   -- coming at this line
   -- we have fetched `l_count` value is either 0 or 1
   -- and guaranteed to avoid NO_DATA_FOUND and TOO_MANY_ROWS exceptions

   IF l_count = 0 THEN 
     -- value `p_class_day` is not found
     dbms_output.put_line('do not allow insert');
   ELSE
     -- at least one `p_class_day` is found
     dbms_output.put_line('allow insert');
   END IF;

END class_day;