I work at a company that has a project management department which needs to receive periodic email updates about changes that occur in our database. The database is structured with a fair amount of foreign key relationships that result in a somewhat complex set of relationships that all sit underneath a 'Project' table.
Furthermore, we have a 'Contact' table which is related in a many-to-many fashion to our 'Project' table via a 'Contact_Relationship' table. This table maintains the type of the relationship as well as the relationship itself. Assume every other subtable, subsubtable, etc. is in a one-to-many relationship with the table above it in the hierarchy.
See here for an overly simplified example:
Project
Contact_Relationship
Subtable1
Subsubtable1
Subtable2
Subsubtable2
Subsubtable3
I have been tasked with implementing an update messaging system that polls periodically for changes to either a project entry or any of its subitems and posts a message. To accomplish this, I need to implement a procedure to get the ultimate parent entry in the 'Project' table of an entry in any of the applicable tables, find the 'Contact_Relationship' entries where the type is "Project manager", and then return those entries so that I can post an update message with the information to the applicable contacts. Now, given that the structure of the subtables, subsubtables, etc. in the database is in continuous development and will certainly see more tables added in the future, is there a way to build a dynamic query using some sort of cross apply on SQL server's administrative tables to get at the ultimate parent entry from any potential subtable or subsubtable? Am I way off-base here and there's a much simpler and more obvious solution? I've been stuck on this problem for a while now and am beginning to run up on deadlines to get this whole thing implemented, and I'm worried the SQL knowledge required here is currently beyond my reach.
Unlike the question Get Root parent of child in Hierarchical table, in this case I am traversing foreign key relationships between tables, rather than a parent-child relationship in the same table.