IF %new.effective_from_date > %new.effective_to_date THEN RAISERROR 18255 '%TriggerName: EFFECTIVE_TO_DATE cannot be earlier than EFFECTIVE_FROM_DATE.'; END IF; DELETE FROM %TableName WHERE customer_number = %new.customer_number AND ( effective_from_date BETWEEN %new.effective_from_date AND %new.effective_to_date OR effective_to_date BETWEEN %new.effective_from_date AND %new.effective_to_date OR %new.effective_from_date BETWEEN effective_from_date AND effective_to_date ) AND source_updated_ts <= %new.source_updated_ts AND id <> %new.id; -- If there is a conflicting newer record, we can't insert this one. IF EXISTS (SELECT * FROM %TableName WHERE customer_number = %new.customer_number AND ( effective_from_date BETWEEN %new.effective_from_date AND %new.effective_to_date OR effective_to_date BETWEEN %new.effective_from_date AND %new.effective_to_date OR %new.effective_from_date BETWEEN effective_from_date AND effective_to_date ) AND source_updated_ts > %new.source_updated_ts AND id <> %new.id ) THEN RAISERROR 18250 '%TriggerName: Newer record with conflicting criteria already exists.'; END IF;