SQL triggers: Set a default value if the foreign key does not exist

elimiter //
CREATE TRIGGER account_insert BEFORE INSERT ON account
FOR EACH ROW BEGIN
DECLARE row_exists INTEGER;
SELECT COUNT(*) INTO row_exists FROM banker WHERE id=NEW.banker_id;
IF row_exists=0 THEN SET NEW.banker_id=0;
END IF;
END//
delimiter ;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: