SET nocount ON
CREATE TABLE #tmpName (ID int, [Name] varchar(255))
CREATE TABLE #tmpRelation (ID int, ID_Parent int)
INSERT #tmpName (ID, [Name]) select 1, 'value1'
INSERT #tmpName (ID, [Name]) select 2, 'value2'
INSERT #tmpName (ID, [Name]) select 2, 'value3'
INSERT #tmpName (ID, [Name]) select 2, 'value4'
INSERT #tmpName (ID, [Name]) select 4, 'value5'
INSERT #tmpRelation (ID, ID_Parent) select 1, 2
INSERT #tmpRelation (ID, ID_Parent) select 2, 3
INSERT #tmpRelation (ID, ID_Parent) select 3, 4
INSERT #tmpRelation (ID, ID_Parent) select 4, NULL
INSERT #tmpRelation (ID, ID_Parent) select 5, 1
declare @ID_Start int, @Level int
SELECT @Level = 0
SELECT @ID_Start = 1
CREATE TABLE #tmpResult (ID int, ID_Parent int, [Level] int)
while NOT @ID_Start IS NULL
begin
SELECT @Level = @Level + 1
INSERT #tmpResult (ID, ID_Parent, [Level])
SELECT R.ID, R.ID_Parent, @Level
FROM #tmpRelation R
WHERE ID = @ID_Start
SELECT @ID_Start = ID_Parent FROM #tmpRelation where ID = @ID_Start
end
--> NR = 3 display
SELECT R.ID AS NR, N.Name AS Value, ID_Parent AS Dad, [Level]
FROM #tmpResult R left join #tmpName N on
R.ID = N.ID
--> NR = 3 not display
SELECT R.ID AS NR, N.Name AS Value, ID_Parent AS Dad, [Level]
FROM #tmpResult R inner join #tmpName N on
R.ID = N.ID
DROP TABLE #tmpResult
DROP TABLE #tmpName
DROP TABLE #tmpRelation