How could I set a constraint on a table to enforce that exactly one record per group is flagged as "primary".
E.g. in the database of a company providing risky thrill sports, they have table Customer and table EmergencyContact, where there is a FK constraint from EmergencyContact to Customer. There may be zero or more EmergencyContact records for each Customer record. If there is one or more emergency contacts for a customer, then one of them must be marked as primary. If there's exactly one emergency contact, then that's obviously the one that has to be marked as primary.
Note that a related constraint is easy to implement, and may be part of the solution - enforcing that no more than one emergency contact per customer is flagged as primary. There are already many such questions (and good answers) on stackoverflow, e.g. here, here etc. However, I haven't found an answer (or any other way) to enforce that at least one child record per group be flagged, where any child records exists.
If possible, I'd like to avoid using triggers, or constraints based on UDFs in computed columns. Triggers can get disabled, and don't always fire (see pg 208 of Alex Kuznetsov's excellent book Defensive Database Programming), and UDFs wrapped in check constraints can get bypassed or ignored in certain situations as well (see page 184 onwards of the same book).
I've tried several ways to attack the problem such as indexed views as well as a FK constraint from parent to child table, without success yet.