22,209
社区成员
发帖
与我相关
我的任务
分享
select m.id,m.name,m.pid from
(
select 1 as num,id as nid,id,name,parentid as pid from
部门结构
union all
select 2 as num,departid as nid,id,name,departid as pid from
用户结构
) m
order by nid,num
/*
*************************************
* T-MAC 小编 *
* -->努力成长中 *
* -->梦想DBA *
*************************************
*/
if OBJECT_ID('部门结构') is not null
drop table 部门结构
go
create table 部门结构 (Id int,name varchar(10) ,parentId int)
insert 部门结构 select
1, '人事部' ,0 union select
2, '开发部' ,1 union select
3, '服务部', 1
go
if OBJECT_ID('用户结构') is not null
drop table 用户结构
go
create table 用户结构 (Id int,name varchar(10) ,departId int)
insert 用户结构 select
101, '张三', 2 union select
102, '李四', 2 union select
103, '王五', 3
go
with cte as
(
select * from 部门结构
union
select * from 用户结构
)
,cte2 as
(
select *,rn=CAST(id as varchar(100)) from cte where parentId=0
union all
select cte.Id,cte.name,cte.parentId,cast( rn+RTRIM(cte.id) as varchar(100)) from cte join cte2 on cte.parentId=cte2.Id
)
select Id,name,parentId
from cte2
order by rn
/*
Id name parentId
----------- ---------- -----------
1 人事部 0
2 开发部 1
101 张三 2
102 李四 2
3 服务部 1
103 王五 3
*/