set nocount on

drop table if exists #reduce;
drop table if exists #depend;

create table #depend(
	id int identity(1,1),
	t_t int
)

declare @round int = 1

select parent_object_id as s_t,referenced_object_id as t_t into #reduce from sys.foreign_key_columns
insert into #depend select object_id as t_t from sys.tables where object_id not in (select s_t from #reduce) and object_id not in (select t_t from #reduce)

--select (select count(*) from #reduce) a,(select count(*) from #depend) b,(select count(distinct t_t) from #depend) b1, (select count(*) from sys.tables) c, 'out'
--select #depend.id,sys.tables.name from #depend left join sys.tables on #depend.t_t = sys.tables.object_id

insert into #depend select distinct a1.t_t as t_t from #reduce a1 left join #reduce a2 on a1.t_t = a2.s_t where a2.s_t is null 
insert into #depend select distinct a1.s_t as t_t from #reduce a1 where a1.t_t in (select t_t from #depend) and a1.s_t not in (select t_t from #reduce) and a1.s_t not in (select t_t from #depend)
delete from #reduce where #reduce.t_t in (select t_t from #depend)

--select (select count(*) from #reduce) a,(select count(*) from #depend) b,(select count(distinct t_t) from #depend) b1, (select count(*) from sys.tables) c , 'out'
--select #depend.id,sys.tables.name from #depend left join sys.tables on #depend.t_t = sys.tables.object_id
/*
select * from #depend
select * from #reduce
*/

declare @count int = 100
select @count = count(*) from #reduce

while(@count>0)
begin 
	insert into #depend select distinct a1.t_t as t_t from #reduce a1 left join #reduce a2 on a1.t_t = a2.s_t where a2.s_t is null 
	insert into #depend select distinct a1.s_t as t_t from #reduce a1 where a1.t_t in (select t_t from #depend) and a1.s_t not in (select t_t from #reduce) and a1.s_t not in (select t_t from #depend)
	delete from #reduce where #reduce.t_t in (select t_t from #depend)

	--select (select count(*) from #reduce) a,(select count(*) from #depend) b,(select count(distinct t_t) from #depend) b1, (select count(*) from sys.tables) c, @round
	--select #depend.id,sys.tables.name from #depend left join sys.tables on #depend.t_t = sys.tables.object_id

	select @count = count(*) from #reduce
	set @round = @round + 1
end

print cast(@round as varchar(7)) + ' round to finished'

select #depend.id,sys.tables.name from #depend left join sys.tables on #depend.t_t = sys.tables.object_id order by #depend.id
select * from sys.tables where object_id not in (select t_t from #depend)

drop table if exists #reduce;
drop table if exists #depend;

set nocount off