MyISAM Foreign Key insertion

Currently the MyISAM storage engine has no support for foreign keys, but is there any way to put the logic for foreign key checking in a stored procedure.

 #

It is really simple to insert the logic for foreign key checking in a stored procedure.

Example of a sample store procedure is:

CREATE PROCEDURE foreignkey_insert (p_fk INT, p_animal VARCHAR(10))
BEGIN
DECLARE v INT;
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION, NOT FOUND
SET v = 0;
IF p_fk IS NOT NULL THEN
SELECT 1 INTO v FROM tpk WHERE cpk = p_fk LIMIT 1;
INSERT INTO tfk VALUES (p_fk, p_animal);
ELSE
SET v = 1;
END IF;
END;
IF v <> 1 THEN
DROP TABLE `The insertion failed`;
END IF;
END;

Explanation:
You are going to get either an SQLEXCEPTION or a NOT FOUND condition will cause v to be zero, but otherwise v will be one, because the SELECT will put one into it and the EXIT HANDLER won't
set it back to zero.

The store procedure call result:

mysql> CREATE TABLE tpk (cpk INT PRIMARY KEY);//
Query OK, 0 rows affected (0.01 sec)
mysql> CREATE TABLE tfk (cfk INT, canimal VARCHAR(10));//
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO tpk VALUES (1),(7),(10);//
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> CALL foreignkey_insert(1,'wombat');//
Query OK, 1 row affected (0.02 sec)
mysql> CALL foreignkey_insert(NULL,'wallaby');//
Query OK, 0 rows affected (0.00 sec)
mysql> CALL foreignkey_insert(17,'wendigo');//
ERROR 1051 (42S02): Unknown table 'The insertion failed'

keep rocking !!

 

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.

Cumulus Tag Cloud

Kiran Says

I love work environment which is:

Informal yet professional
Demanding yet rewarding
Challenging yet inspiring
Mediocrity is not an option
Having fun is serious business
Making mistakes is human
Forgiveness is Company Policy

Travelling Sucks