Foreign key

How to inform the user that he cannot delete a record with a foreign key

Well, why can’t he delete it? So, let’s say you have a name in one table and it is linked to a list of memo’s or post’s or whatever. You can delete the name, but, you need to delete all the others that are linked to it also.

Or, if you just want to not allow them and do not know if the record contains a foreign key, you can check it first. Here are queries from Stack Overflow that says how to check a table or col for them:

But, it would be better to just correctly delete the record along with the associated data.
For a Table:

SELECT 
  TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_SCHEMA = '<database>' AND
  REFERENCED_TABLE_NAME = '<table>';

For a Column:

SELECT 
  TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_SCHEMA = '<database>' AND
  REFERENCED_TABLE_NAME = '<table>' AND
  REFERENCED_COLUMN_NAME = '<column>';
Sponsor our Newsletter | Privacy Policy | Terms of Service