你这样的找法太过复杂,数据库找上下级的数据就不是这样来存储的

解决方案 »

  1.   


    Create table Org
    (OrgID int primary key identity(1,1),
     ParentID int default 0,
     OrgName nvarchar(50))
     
    insert into Org(ParentID,OrgName) select 0,'机构一'
    union all select 0,'机构二'
    union all select 1,'机构一一'
    union all select 1,'机构一二'
    union all select 3,'机构一一一'
    with t as
    (select OrgID 'x',OrgID 'y' from Org where ParentID=0
     union all
     select a.x,b.OrgID
      from t a
      inner join Org b on a.y=b.ParentID)
    select a.x 'UserID',
           stuff((select ','+rtrim(b.y)
                  from t b 
                  where b.x=a.x 
                  for xml path('')),1,1,'') 'UserSubOrgID'
     from t a
     group by a.x/*
    UserID      UserSubOrgID
    ----------- -------------------
    1           1,3,4,5
    2           2(2 row(s) affected)
    */