简体   繁体   English

Oracle sql存储过程检查是否未插入表中的输入

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

I want to write a procedure to check whether a particular input value exists in a column in a table. 我想编写一个过程来检查表的列中是否存在特定的输入值。 If the value does exists then output an error message else insert a new row. 如果该值确实存在,则输出错误消息,否则插入新行。

For example this is the sort of logic required 例如,这是所需的逻辑

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;

You could try something like this: 您可以尝试这样的事情:

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;

To avoid rituals with catching exceptions etc. we simply can count rows where given value appears. 为了避免带有捕获异常等的仪式,我们可以简单地计数出现给定值的行。 And then use the number of rows as a flag of the value existence in the 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM