Subject Re: [firebird-support] Was poor selectivity in foreign keys
Author Helen Borrie
At 10:46 PM 16/10/2004 -0300, you wrote:

>Helen:
>
> >I still dont understand wich is the idea in creating that foreign keys
> >if i dont use internal RI (i use that in triggers, i mind).

Sorry, I don't understand what you are saying here. Custom RI is the
*alternative* to creating a foreign key, i.e. declarative RI, in situations
where the effect of declarative RI is worse than the risk of a RI
violation. You would not have both a FOREIGN KEY constraint *and* custom
RI on this relationship.

> >please can you show me how to write a trigger avoiding delete a record
> >in ANAGRAPHICS if tehere anyc child record in teh others tables?

It is the "other face": the equivalent of a foreign key with the default
action.

CREATE EXCEPTION CANNOT_DELETE
'Cannot delete record that has records depending on it';

commit;

CREATE TRIGGER BD_ANAGRAPHICS FOR ANAGRAPHICS
ACTIVE BEFORE DELETE
AS
BEGIN
IF (
(EXISTS (
SELECT 1 FROM LOG_TOTALS
WHERE LOG_OWNER = OLD.ID_ANAGRAPHIC))
OR (EXISTS (
SELECT 1 FROM REGION_TOTALS
WHERE LOG_OWNER = OLD.ID_ANAGRAPHIC))
OR (EXISTS (
SELECT 1 FROM PROVINCE_TOTALS
WHERE LOG_OWNER = OLD.ID_ANAGRAPHIC))
OR (EXISTS (
SELECT 1 FROM QSO
WHERE LOG_OWNER = OLD.ID_ANAGRAPHIC))
) THEN
EXCEPTION CANNOT_DELETE;
END

If you need to apply custom RI triggers, be mindful of the possible
outcomes if you use transaction configurations that are at the "dirty" end
of the scale. ReadCommitted isolation, when carelessly used, allows the
possibility of phantom rows and undesirable overwriting. Declarative RI
-the FOREIGN KEY constraint - provides better protection than custom RI
triggers against the integrity breakages inherent in such conditions.

./heLen