oracle 在插入SQL之前检查另一个表中是否存在值

wkyowqbh  于 2022-12-11  发布在  Oracle
关注(0)|答案(2)|浏览(136)

I have table: " daysoff " and table: " rdv "

the rdv table looks like this :

temps_rdvetat_rdvID_RDV
12-10-2022reservee2

the daysoff table looks like this :

IDDATE_OFFREASON
212-06-2023conge

i want to insert values in rdv table, but before inserting any thing i need to check first if " temps_rdv " doesn't exist in the daysoff table

example: I can not add a rdv with temps_rdv = 12-06-2023

I tried a trigger, but it doesn't seem to work

CREATE OR REPLACE TRIGGER TRIGGER1 
BEFORE INSERT ON rdv
FOR EACH ROW
    BEGIN
        IF EXISTS (
            select daysoff.date_off
            From Available daysoff  -- CHANGED THE ALIAS TO A
            where (NEW.temps_rdv = daysoff.date_off)
        ) THEN 
           CALL:='Insert not allowed';

        END IF;
END;
vaj7vani

vaj7vani1#

您可以创建一个临时表,将值插入临时表中,然后在dayoff表上使用not exists条件从临时表中poupolate rdv。

CREATE GLOBAL TEMPORARY TABLE tmp_rdv_insert(
  temps_rdv date,
  etat_rdv varchar(255),
  ID_RDV int
 );

INSERT INTO tmp_rdv_insert(temps_rdv, etat_rdv, ID_RDV)
VALUES (TO_DATE('2023-06-12','YYYY-MM-DD'), 'test', 5);

INSERT INTO rdv
select * from tmp_rdv_insert tmp
where not exists (select 1 from daysoff where DATE_OFF = tmp.temps_rdv);

此处为SQL小键盘

rbpvctlc

rbpvctlc2#

使用MERGE。然后处理WHEN NOT MATCHED以进行插入或更新。触发器是一种糟糕的方法。更糟糕的情况是,您最终得到了一个变异触发器,一切都变得一团糟。如果您不想依赖SQL,可以使用PL/SQL。如果所有其他方法都失败了,可以使用临时表(例如当前会话的临时表)来检查所需的值(或者不需要)。根据你想要实现的目标,我建议你先看一下MERGE。它可能正是你所需要的。

相关问题