declare @a table (TC_Id int,TC_PID int,TC_Name varchar(200))
insert @a values(1,0,'中国')
insert @a values(2,0,'美国')
insert @a values(3,0,'加拿大')
insert @a values(4,1,'北京')
insert @a values(5,1,'上海')
insert @a values(6,1,'江苏')
insert @a values(7,6,'苏州')
insert @a values(8,7,'常熟')
insert @a values(9,6,'南京')
insert @a values(10,6,'无锡')
insert @a values(11,2,'纽约')
insert @a values(12,2,'旧金山')declare @tmp1 table (TC_Id int,TC_PID int,TC_Name varchar(200),lev int)
insert @tmp1 select *,1 from @a where tc_ID=1
while exists(select 1 from @a a,@tmp1 b where a.tc_pid=b.tc_ID and a.tc_ID not in (select tc_ID from @tmp1))
  insert @tmp1 select a.*,1 from  @a a,@tmp1 b where a.tc_pid=b.tc_ID and a.tc_ID not in (select tc_ID from @tmp1)
select * from @tmp1

解决方案 »

  1.   

    create  table  tree    (  node  int,  child  int,  weight  int)
      

  2.   

    table(son_id,parent_id,name)---这个方法比较好ortable
    id          name
    001          省级总公司
    001001       市级公司1
    001002       市级公司2
    001003       市级公司3
    001001001    市级1下面有县级1
    001002001    市级2下面有县级1
    001002002    市级2下面有县级2
      

  3.   

    TABLE( ID,parentID,NAME)当为根结点时,将PARENTID设为一个固定值,如“0”