我正在尝试根据下面链接上的图片上的问题创建触发器。但我正在努力处理重复更新并处理插入和更新时的最大字符长度。这是我的解决方案。
CREATE OR REPLACE TRIGGER check_author
BEFORE UPDATE OR INSERT ON bk_author
FOR EACH ROW
DECLARE
v_authorid bk_author.authorid%type;
BEGIN
IF UPDATING THEN
IF LENGTH(:NEW.fname) > 10 THEN
RAISE_APPLICATION_ERROR(-20004,'Author name cannot exceed 10 characters');
END IF;
ELSIF INSERTING THEN
SELECT authorid
INTO v_authorid
FROM bk_author
WHERE authorid = :NEW.authorid;
RAISE_APPLICATION_ERROR(-20003,'Author id already existing cannot be added');
IF LENGTH(:NEW.fname) > 10 THEN
RAISE_APPLICATION_ERROR(-20004,'Author name cannot exceed 10 characters');
END IF;
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Author '||:NEW.authorid||' added');
END;
/
答案 0 :(得分:0)
您不会检查条件以提出有关重复的错误,无论数据库中是否有ID,它都会执行。
你应该在它之前添加IF
类似
ELSIF INSERTING THEN
SELECT authorid
INTO v_authorid
FROM bk_author
WHERE authorid = :NEW.authorid;
IF v_authorid is not null then
RAISE_APPLICATION_ERROR(-20003,'Author id already existing cannot be
added');
end if;
答案 1 :(得分:0)
尝试下面的代码,它应该适合你。
CREATE OR REPLACE TRIGGER check_author
BEFORE UPDATE OR INSERT ON bk_author
FOR EACH ROW
DECLARE
v_authorid number;
BEGIN
IF UPDATING THEN
IF LENGTH(:NEW.fname) > 10 THEN
RAISE_APPLICATION_ERROR(-20004,'Author name cannot exceed 10 characters');
END IF;
ELSIF INSERTING THEN
SELECT count(authorid) INTO v_authorid
FROM bk_author
WHERE authorid = :NEW.authorid;
DBMS_OUTPUT.PUT_LINE('Author id already existing cannot be added');
RAISE;
IF LENGTH(:NEW.fname) > 10 THEN
DBMS_OUTPUT.PUT_LINE('Author name cannot exceed 10 characters');
RAISE;
END IF;
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Author '||:NEW.authorid||' added');
END;
/