I posted this somewhere before, but I could not find it.
Code:
with temp1 as (
select distinct t.tabname,nullif(r.reftabname,t.tabname) as reftable from syscat.tables as t
left outer join syscat.references as r on t.tabschema = r.tabschema and t.tabname = r.tabname
where t.tabschema = 'MySchema' and t.type = 'T' ) ,
temp2 (table, reftable,lvl) as (
select tabname,reftable,1 from temp1 where reftable is null and
tabname not in (select tabname from temp1 where reftable is not null)
union all
select t.tabname,t.reftable,z.lvl+1 from temp1 as t, temp2 as z where t.reftable = z.table
) select table,max(lvl) as mlevel from temp2 as t
inner join syscat.tables as w on (t.table = w.tabname and w.tabschema = 'MySchema')
group by table order by mlevel,table
Be careful with this since it is recursive and if you have a circular referencing scheme, it will never return. It does handle if a table references itself though.
Andy