Select all parents or children in same table relation SQL Server

后端 未结 4 2075
日久生厌
日久生厌 2021-02-05 11:10

SQL developers, I have a badly planned database as task to learn a lot about SQL Server 2012.

SO, there is the table Elem:

+-----------+----         


        
4条回答
  •  广开言路
    2021-02-05 11:37

    here is a recursive query giving you both all ancestors and all descendants of an element. Use these together or separate according to the situation. Replace the where clauses to get the desired record. In this example I am looking for key 13 (this is the element with name = b) and find its ancestor 12/a and its descendant 14/c.

    with all_ancestors(relation, version, name, elem_key, parent_key, dist_key)
    as 
    (
      -- the record itself
      select 'self      ' as relation, self.version, self.name, self.elem_key, self.parent_key, self.dist_key
      from elem self
      where elem_key = 13
      union all
      -- all its ancestors found recursively
      select 'ancestor  ' as relation, parent.version, parent.name, parent.elem_key, parent.parent_key, parent.dist_key
      from elem parent
      join all_ancestors child on parent.elem_key = child.parent_key
    )
    , all_descendants(relation, version, name, elem_key, parent_key, dist_key)
    as 
    (
      -- the record itself
      select 'self      ' as relation, self.version, self.name, self.elem_key, self.parent_key, self.dist_key
      from elem self
      where elem_key = 13
      union all
      -- all its descendants found recursively
      select 'descendant' as relation, child.version, child.name, child.elem_key, child.parent_key, child.dist_key
      from elem child
      join all_descendants parent on parent.elem_key = child.parent_key
    )
    select * from all_ancestors
    union
    select * from all_descendants
    order by elem_key
    ;
    

    Here is the SQL fiddle: http://sqlfiddle.com/#!6/617ee/28.

提交回复
热议问题