I have a SQL-Server 2008 database and a schema which uses foreign key constraints to enforce referential integrity. Works as intended. Now the user creates views on the original tables to work on subsets of the data only. My problem is that filtering certain datasets in some tables but not in others will violate the foreign key constraints.
Imagine two tables “one” and “two”. “one” contains just an id column with values 1,2,3. “Two” references “one”. Now you create views on both tables. The view for table “two” doesn’t filter anything while the view for table “one” removes all rows but the first. You’ll end up with entries in the second view that point nowhere.
Is there any way to avoid this? Can you have foreign key constraints between views?
Some Clarification in response to some of the comments:
I’m aware that the underlying constraints will ensure integrity of the data even when inserting through the views. My problem lies with the statements consuming the views. Those statements have been written with the original tables in mind and assume certain joins cannot fail. This assumption is always valid when working with the tables – but views potentially break it.
Joining/checking all constraints when creating the views in the first place is annyoing because of the large number of referencing tables. Thus I was hoping to avoid that.
Peter already hit on this, but the best solution is to:
I.e.,
Sure, syntactic sugar for propagating filters for views on one table to views on subordinate tables would be handy, but alas, it’s not part of the SQL standard. That said, this solution is still good enough — efficient, straightforward, maintainable, and guarantees the desired state for the consuming code.