如何在Oracle中使用触发器

时间:2019-06-28 22:06:02

标签: oracle database-trigger

我创建了一个触发器,但是我不知道如何使用它。 有人可以帮我吗?

create or replace trigger user_id_trigger
              before insert on library_user
              for each row
              begin
                  if :new.user_id is null then
                      select USER_ID_O_SEQ.nextval into :new.user_id from library_user;
                 end if;
end;

create table LIBRARY_USER(      USER_ID number (20) primary key not null,
                                FIRST_NAME varchar (50) not null,
                                LAST_NAME varchar (50) not null,
                                USER_BDATE date not null,
                                USER_ADRESS varchar (200) not null,
                                USER_EMAIL varchar (50) not null,
                                USER_PHONE_NUMBER varchar (25),
                                USER_STATUS varchar (20) not null,
                                USERNAME varchar (50) not null,
                                PASSWORD varchar (50) not null);

1 个答案:

答案 0 :(得分:1)

在选择而非库中使用双重输入:

CREATE OR REPLACE TRIGGER user_id_trigger
    BEFORE INSERT
    ON library_user
    FOR EACH ROW
BEGIN
    IF :new.user_id IS NULL
    THEN
        SELECT user_id_o_seq.NEXTVAL INTO :new.user_id FROM dual;
    END IF;
END;

我记不清哪个版本允许您跳过选择(我认为是11.2),但是在较新的Oracle版本中,您可以使用:

CREATE OR REPLACE TRIGGER user_id_trigger
    BEFORE INSERT
    ON library_user
    FOR EACH ROW
BEGIN
    :new.user_id   := COALESCE( :new.user_id, user_id_o_seq.NEXTVAL );
END;