Subject RE: [firebird-support] Re: Foreign key reference target does not exist. [FB 2.5 beta 2]
Author Svein Erling Tysvær
>> Do you make FK over existing records?You probably already have old records
>> in second table which refer to nonexistent PK in first table.Delete all old
>> orphan records in second table, and then make FK.

> What is the best way to delete orphans? Years ago I had a similar problem
> with an MS Access DB, and simply created SQL query to delete Detail records
> that did not have a matching Master. I don't consider this to be the best
> solution because it doesn't give the user a chance to save the data. Another
> solution I used was to show the orphan record, and a list of Master record
> candidates so the user can decide to reassign or delete the orphan.
>
> In both of those solution, the user was required to run auxiliary routines.
> It would be nice to give the user a choice instead of the FB error message.
> I've tried to trap that error (Delphi 2007 using IBDax), but have not been
> successful.

The simple way:

DELETE FROM MySecondTable MST
WHERE NOT EXISTS(
SELECT *
FROM MyFirstTable MFT
WHERE MFT.MyPrimaryKey = MST.MyFieldSoonToBeAForeignKey)

I would consider selecting and inspecting the records before deleting them, you could e.g. issue

SELECT DISTINCT MST.MyFieldSoonToBeAForeignKey
FROM MySecondTable MST
WHERE NOT EXISTS(
SELECT *
FROM MyFirstTable MFT
WHERE MFT.MyPrimaryKey = MST.MyFieldSoonToBeAForeignKey)

HTH,
Set