I have the following table:
Location:
ID Name Depth ParentID HierachyPath ContactID
1 US 0 NULL \ 25
2 Florida 1 1 \001 NULL
3 Miami 2 2 \001\001 NULL
4 Dade County 3 3 \001\001\001 NULL
5 Orlando 2 2 \001\002 15
6 County1 3 3 \001\002\001 12
I will be pased a location ID such as 4. I will get multiple location ID's passed to me at once, so I may need to find the contact for 1 location or 1000 locations at once. If there is not a contact at location 4 I need to travel up the HierachyPath until I find a contact. Any ideas on how to do this?
I added the second solution (multiple IDs)
First solution
Results:
Second solution (multiple IDs)
You could use a recursive common-table expression to walk up until you find a parent with a contact. For example:
Example at SQL Fiddle.
I am not sure if your data is correct as Florida has no ParentId which exists in the given list of data. I think following query will give you the results you need. Using
CTE
SQL-FIDDLE-DEMO
This works only if you pass a single Id, not for your updated question. Little change can make it work for that as well. @Andomar has addressed that above.