user1418018
user1418018

Reputation: 189

sql trigger using two tables data

So I have three tables. First two have ID column and "rank" column (an integer). I will be inserting into the third table both IDs (ID1, ID2) but I need the trigger to check whether they are the same rank before I can insert. I can't get it to work.

CREATE OR REPLACE TRIGGER TRIGGER1 
AFTER INSERT ON TABLE_C 

BEGIN
IF NOT EXISTS (
SELECT TABLE_A.id, TABLE_B.id
FROM TABLE_A JOIN TABLE_B ON TABLE_A.rank = TABLE_B.rank
WHERE TABLE_A.id = inserted.id1 AND TABLE_B.id = inserted.id2 )
THEN
PRINT 'Not the same rank'
ROLLBACK
END
END;

I'm using Oracle db.

Upvotes: 0

Views: 3231

Answers (2)

pratik garg
pratik garg

Reputation: 3342

you can not use 'Rollback' or 'commit' in Oracle Triggers - please refer this

I think you can modify your trigger as follow -

CREATE OR REPLACE TRIGGER Trigger1
    AFTER INSERT ON Table_c
    FOR EACH ROW
  DECLARE
    l_Count NUMBER := 0;
  BEGIN
    SELECT COUNT(*)
      INTO l_Count
      FROM Table_a
      JOIN Table_b ON Table_a.Rank = Table_b.Rank
     WHERE Table_a.Id = :NEW.Id1
       AND Table_b.Id = :NEW.Id2;
    IF l_Count = 0 THEN
      DELETE FROM Table_c
       WHERE Id1 = :NEW.Id1
         AND Id2 = :NEW.Id2;
      --PRINT 'Not the same rank'
      Dbms_Output.Put_Line('Not the same rank');
    END IF;
  END;
/

Upvotes: 1

Semih Yagcioglu
Semih Yagcioglu

Reputation: 4101

Triggers are two kinds, BEFORE and AFTER Triggers. If you want to check whether the data has the same rank before the data is inserted, then you should use a BEFORE Trigger.

CREATE OR REPLACE TRIGGER TRIGGER1 
BEFORE INSERT ON TABLE_C

Then the logic will follow.

UPDATE: You can easily raise application error. Such as:

IF HasSameRank == 0 THEN
    raise_application_error(-21013, 'Not the same rank');
END IF;

Upvotes: 1

Related Questions