create table #tempT (
IDFILE int,
[NAME] varchar(255),
[IDREFFERENCE] int,
[level] int
)
declare @idfile int, @idref int, @level int, @flag int;
declare @name varchar(max);
set @flag=0;
set @level=0;
DECLARE limit_cursor cursor for
select IDFILE,[NAME],IDREFFERENCE FROM tReferences
open limit_cursor
fetch next from limit_cursor into @idfile,@name,@idref
while(@@fetch_status=0)
begin
if(@idref=0)
begin
if(@flag=0)
begin
insert into #tempT values (@idfile,@name,@idref,0);
set @flag=1;
end
end
else if(@idref not in (select IDREFFERENCE from #tempT))
begin
set @level=@level+1;
insert into #tempT values (@idfile,@name,@idref,@level)
end
else if(@idref in (select IDREFFERENCE from #tempT))
begin
set @level=(select [level] from #tempT where @idref=IDREFFERENCE group by [level])
insert into #tempT values (@idfile,@name,@idref,@level)
end
fetch next from limit_cursor into @idfile,@name,@idref
end
close limit_cursor
deallocate limit_cursor
select IDFILE,[NAME],[level] from #tempT
truncate table #tempT