I have seen many posts that address how to convert an Oracle "connect by prior" statement to a SQL Server common table expression. However, I have an Oracle "connect by prior" statement that has a "start with fieldname in ('value1','value2','value3')" clause on it, and I am not seeing any examples out there on how to convert this to SQL Server. I believe this is considered "bottom to top" recursion.
Here is my Oracle query:
select distinct KEY
from MY_HIERARCHICAL_TABLE
connect by prior PARENT_KEY = KEY
start with KEY in ('CHILD-A1','CHILD-C1')
Sample table:
MY_HIERARCHICAL_TABLE
---------------------
KEY
PARENT_KEY
Sample data:
KEY PARENT_KEY
--------- ----------
TOP null
PARENT-A TOP
CHILD-A1 PARENT-A
CHILD-A2 PARENT-A
PARENT-B TOP
CHILD-B1 PARENT-B
PARENT-C TOP
CHILD-C1 PARENT-C
My query should work as follows:
- CHILD-A1 and its parents will be included: TOP, PARENT-A, CHILD-A1
- CHILD-C1 and its parents will be included: TOP, PARENT-C, CHILD-C1
- CHILD-A2 will be excluded since CHILD-A2 is not in my list. PARENT-A will get included because CHILD-A1 is in my list.
- PARENT-B & CHILD-B1 will get excluded since CHILD-B1 is not in my list.
- Final, distinct result set will be TOP, PARENT-A, CHILD-A1, PARENT-C, CHILD-C1
I hope I have explained this well. I have been searching for examples that fit this for a while today. Any input would be greatly appreciated.