How to fetch Paren Child Rows

  • I have one table as below structure.

    create table INF

    (

    InfringmentNo PK,

    ParentInfringementNo FK to InfringmentNo

    )

    Value of table is below.

    InfringmentNo ParentInfringementNo

    1 NULL

    2 1

    3 2

    4 3

    5 NULL

    6 NULL

    7 6

    Now I need to fetch all related record with where condition

    I write the below query

    select infp.InfringementNo,infP.OriginalInfringementNo

    from INF_Infringement inf inner Join INF_Infringement infP ON inf.OriginalInfringementNo=infP.InfringementNo

    output is..

    InfringementNo OriginalInfringementNo

    1 NULL

    2 1

    3 2

    While it should be like

    InfringementNo OriginalInfringementNo

    1 NULL

    2 1

    3 2

    4 3

    I want to specify the Infringment No in Where clause as below

    select infp.InfringementNo,infP.OriginalInfringementNo

    from INF_Infringement inf inner Join INF_Infringement infP ON inf.OriginalInfringementNo=infP.InfringementNo

    where infp.InfringementNo='4'

    Thanks in Advace

    KD

  • This was removed by the editor as SPAM

  • This is a hierarchy, and the recursive CTE handles it well. You can read more about it here:

    http://qa.sqlservercentral.com/articles/T-SQL/65540/

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply