0

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.

4

1 に答える 1

1

レコードを選択するのは簡単ですが、それらを並べ替える方法がわかりません

with 
param as (
  select *
  from ( values 
        ('CHILD-A1'),('CHILD-C1')
       ) v (child)
),
dat as (
  select * 
  from ( values 
        ('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')
       ) v(child,parent)
), 
rec as (
  select dat.* 
  from dat join param on dat.child=param.child
  union all 
  select dat.*
  from dat join rec on dat.child=rec.parent
)  
select distinct * from rec

http://sqlfiddle.com/#!6/9eecb/4021/0

于 2015-04-15T18:31:54.713 に答える