connect by
if object_id ('tblx') is not null
drop table tblx
go
create table tblx
(idx int identity(1,1)
,emp_name varchar(1000)
,parent_seq int
,seq int
)
go
insert into tblx values
('minsouk', null, 1)
,('ben gan', 1, 2)
,('Kollor', 2, 4)
,('Sarka', 4, 6)
,('Christian', 4, 8)
,('Justin', 2, 5)
,('Brent', 5, 7)
,('James', 1, 3)
,('Steven', 2, 9)
go
;with c_tblx as (
select 0 as emplevel
, emp_name
, parent_seq
, seq
, convert(varchar(100), ' / ' +cast(seq as varchar(100)))
path_order -- siblings by
from tblx
where seq = 1 -- start with
union all
select emplevel + 1
, a.emp_name
, a.parent_seq
, a.seq
, convert(varchar(100), b.path_order + ' / ' + cast(a.seq as varchar(100)))
-- siblings by
from tblx a
join c_tblx b
on a.parent_seq = b.seq -- connect by prior
)
select replicate(' ', emplevel * 2) + cast(seq as varchar(100))
, *
from c_tblx
order by path_order