我想编写一个过程来检查表中列中是否存在特定的输入值。如果值确实存在,则输出错误消息,否则插入新行。
例如,这是所需的逻辑
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;
答案 0 :(得分:1)
您可以尝试这样的事情:
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;
答案 1 :(得分:0)
为了避免使用捕获异常等的仪式,我们只需计算给定值出现的行。然后使用行数作为表中存在的值的标志。
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;