I am wondering what an efficient way to crawl up a company structure would be by using the parent ID. Essentially what I am trying to do is find the first ContactID that exists, as these contacts are inherited down to the child locations.
For Example:
Test Account
-North
--Michigan - Bob
---Detroit
----Algoma
-South
-East
-West
So Bob would be inherited to Detroit and Algoma. Each level has an ID and a Parent ID which of course matches the ID of the Parent. If given the ChildID(Algoma) how would I crawl up and check each level above Algoma for a contact until I get to Michigan? Each level only has 1 contact. There is no set structure so the contact could be at the child location, or it could be 20 levels up before you get to the contact, but it is always the first 1 going up the tree structurally. Any ideas are appriciated.
TABLE:
ID ParentID LevelName ContactID
1 NULL TestCo. NULL
2 3 Algoma NULL
3 4 Detroit NULL
4 5 Michigan 2
5 1 North 3
6 1 South 1
7 1 East 3
8 1 West NULL
Pass in @ID = 2, it would return ContactID = 2. This is not a static structure for every company, there can be many levels deeper or shorter.
Recursive queries to the rescue!
There’s also a parent-first version:
(have a working SQLFiddle example.)