• Below is my try with formulated data

    Declare @Id int = 3;

    declare @t table (IdRelation int, Parent int,Child int)

    insert into @t

    select data.IdRelation, data.parent,data.child from (

    select 1 as IdRelation, 1 as parent, 2 as child union all

    select 2 as IdRelation, 1 as parent, 3 as child union all

    select 3 as IdRelation,1 as parent, 4 as child union all

    select 4 as IdRelation, 5 as parent, 6 as child union all

    select 5 as IdRelation, 5 as parent, 7 as child union all

    select 6 as IdRelation, 5 as parent, 8 as child ) data

    If EXISTS(select 1 from @t where parent = @Id)

    BEGIN

    select child as UserId from @t where parent = @Id union all

    select @Id as UserId -- as parent exists, so need of selecting from table

    END

    ELSE If EXISTS(select 1 from @t where child = @Id)

    BEGIN

    select parent as UserId from @t where child = @Id union all

    select child as UserId from @t where parent =

    (select parent as UserId from @t where child = @Id)

    END

    is there any best way to achieve this.