22,209
社区成员
发帖
与我相关
我的任务
分享
--测试脚本
If not object_id('[category]') is null
Drop table [category]
Go
Create table [category]([id] int,[name] nvarchar(3),[pid] int)
Insert category
Select 1,'c1',0 union all
Select 2,'c2',0 union all
Select 3,'c3',0 union all
Select 4,'c11',1 union all
Select 5,'c21',2 union all
Select 6,'c22',2 union all
Select 7,'c31',3 union all
Select 8,'c32',3
Go
with EmpsCte as
(
select pid,id,[name] From dbo.category where id=2
union all
select ec.pid,ec.id,ec.[name] from EmpsCte ec join dbo.category as cg
on ec.id=cg.pid
)
select * from EmpsCte;
If not object_id('[category]') is null
Drop table [category]
Go
Create table [category]([id] int,[name] nvarchar(3),[pid] int)
Insert category
Select 1,'c1',0 union all
Select 2,'c2',0 union all
Select 3,'c3',0 union all
Select 4,'c11',1 union all
Select 5,'c21',2 union all
Select 6,'c22',2 union all
Select 7,'c31',3 union all
Select 8,'c32',3
Go
with EmpsCte as
(
select *From dbo.category where id=2
union all
select cg.* from EmpsCte ec join dbo.category as cg
on ec.id=cg.pid
)
select * from EmpsCte;
----------- ---- -----------
2 c2 0
5 c21 2
6 c22 2
(3 行受影响)
with EmpsCte as
(
select pid,id,[name] From dbo.category where id=2
union all
select ec.pid,ec.id,ec.[name] from EmpsCte ec join dbo.category as cg
on ec.pid=cg.pid
)
select * from EmpsCte;