From experience I have to tell you this design is horrible to work with. Consider changing the design to copy the data to an 'audit trail' table then physically remove it from the main table.
If you won't consider this, at the very least bury this in a VIEW
and do everything you can to avoid exposing this to anyone wanting to query the database, using INSTEAD OF
triggers on the VIEW
if necessary. Otherwise, expect applications to have frequent bugs because someone forgot to add the AND isremoved = 0
predicate required by every query that uses this table.
But this 'answer' doesn't address the real question.
Yes. Sorry 'bout that. But sometimes you have to cure the disease rather than merely treat the symptoms.
The design is compromised: a table should model a single entity type, whereas this is modelling two. How can I tell? Because the OP has stated that once 'removed' the entity has different data requirement, by saying "The problem is ... how can we check that all its child table not referring this record".
So the 'real' answer is: move the entity to another distinct table.
But if you are in the business of treating symptoms then here's an answer:
- Add the
IsRemoved
column to your
so-called 'child' tables, with DEFAULT false
and ensure
it is NOT NULL
.
- Add a
CHECK
constraint to each
so-called 'child' table to test
isremoved = false
(or whatever
'boolean' means in your SQL
product).
- Add a compound key (e.g. using
UNIQUE
or PRIMARY KEY
) to your
so-called 'master' table on
(IsRemoved, <existing key columns
here>)
, or alter an existing key
accordingly.
- Add
FOREIGN KEY
constraints to each
so-called 'child' table to reference
the compound key created above.