Ying
Ying

Reputation: 1990

loops and conditionals inside triggers

I have this piece of logic I would like to implement as a trigger, but I have no idea how to do it! I want to create a trigger that, when a row is deleted, it checks to see if the value of one of its columns exists in another table, and if it does, it should also perform a delete on another table based on another column.

So say we had a table Foo that has columns Bar, Baz. This is what id be doing if i did not use a trigger:

function deleteFromFooTable(FooId)
{
  SELECT (Bar,Baz) FROM FooTable WHERE id=FooId
  if not-empty(SELECT * FROM BazTable WHERE id=BazId)
    DELETE FROM BarTable WHERE id=BarId

  DELETE FROM FooTable WHERE id=FooId

}

I jumped some hoops in that pseudo code, but i hope you all get where im going. It seems what i would need is a way to do conditionals and to loop(in case of multiple row deletes?) in the trigger statement. So far, I haven't been able to find anything. Is this not possible, or is this bad practice? Thanks!

Upvotes: 0

Views: 490

Answers (1)

Kevin Crowell
Kevin Crowell

Reputation: 10180

If you do not have Foreign Key relationships setup between these tables, you need to do that. I will show you the command for setting up what you want when you create the table. Clearly, you will just need to update the table.

CREATE TABLE foo (id INT, bar_id INT,
    FOREIGN KEY (bar_id) REFERENCES bar(id)
        ON DELETE CASCADE
) ENGINE=INNODB;

This will delete any "orphans" when a Foo record is deleted.

Upvotes: 2

Related Questions