表1:User
Create table User
(
UserID int primary key identity(1,1),
UserParentID nvarchar(100), ------- 上级用户ID组 :1,3,5
OrgID int default 0 ------------------- 用户所属机构ID
)
insert into User(UserParentID,OrgID) select '1,3,5',1
union all select '2,4,6',2
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,'机构一一一'
最终结果:
UserID UserSubOrgID
1 1,3,4,5
2 2
即找出该用户所属机构ID和下属所有的ID
------解决方案--------------------
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)
*/