Oracle Trigger Help Needed!

Status
Not open for further replies.

Norrick

Ars Legatus Legionis
16,491
I've got a guy here at work trying to help on this too, but he's known for being constantly interrupted, so I'm not sure he'll be able to come through for me.

I have two tables. TableA and TableB. Table B is a lookup table.

There is a foreign key relationship between TableA.Blah and TableB.Blah.

So here's what I need the trigger to do.

Whenever a value is inserted or updated in TableA.Blah, check for that value in TableB.Blah.

If it DOES exist in TableB.Blah, fine and dandy. Let TableA.Blah finish being updated/inserted.

If it does NOT exist in TableB.Blah, insert it into TableB.Blah and then let TableA.Blah finish inserting/updating.

It's probably simple as all hell, but I've not written any kind of trigger before. So, heeeeeeeeeeeeeeeeeeeeelp...
 

Dandy Andy

Ars Tribunus Militum
2,458
Ignoring the philosophical questions of sticking an arbitrary value in a lookup table to stop an insert failing, then try this :

Code:
CREATE TRIGGER a_b_fk_trg
BEFORE INSERT ON a
FOR EACH ROW
DECLARE

  CURSOR c_b (
    cp_blah IN b.blah%TYPE)
  IS
    SELECT 'X'
      FROM b
     WHERE blah = cp_blah ;

  l_dummy  VARCHAR2(1) ;

BEGIN

  IF :NEW.blah IS NOT NULL THEN

    OPEN c_b (
      :NEW.blah) ;

    FETCH c_b
     INTO l_dummy ;

    IF c_b%NOTFOUND THEN

      INSERT INTO b (
        blah
      VALUES (
        :NEW.blah) ;

    END IF ;

    CLOSE c_b ;

  END IF ;

END ;
 

Dandy Andy

Ars Tribunus Militum
2,458
I missed a bracket...

Code:
CREATE TRIGGER a_b_fk_trg
BEFORE INSERT ON a
FOR EACH ROW
DECLARE
  CURSOR c_b (
    cp_blah IN b.blah%TYPE)
  IS
    SELECT 'X'
      FROM b
     WHERE blah = cp_blah ;

  l_dummy  VARCHAR2(1) ;

BEGIN
  IF :NEW.blah IS NOT NULL THEN

    OPEN c_b (
      :NEW.blah) ;

    FETCH c_b
     INTO l_dummy ;

    IF c_b%NOTFOUND THEN

      INSERT INTO b (
        blah)
      VALUES (
        :NEW.blah) ;

    END IF ;

    CLOSE c_b ;

  END IF ;

END ;
Code:

See? It was in the INSERT statement.

:rolleyes:

[This message was edited by Dandy Andy on May 20, 2002 at 05:37.]
 
Status
Not open for further replies.