树形表结构:
id | parentID | isDel |
1 | 0 | 0 |
2 | 1 | 0 |
3 | 1 | 1 |
4 | 2 | 0 |
5 | 2 | 0 |
一)根据父级ID查找所有子级ID,并将所有ID用逗号隔开返回
ID=,需要返回的结果(条件为isDel=0,含本身ID):
1,2,4,5
SQL语句如下:
with cteCopy as
(
select * from [table] where id=
union all
select a.* from [table] a join cteCopy b on a.parentID=b.id and a.IsDel=0
)
SELECT STUFF(( SELECT ',' +convert(VARCHAR, id) FROM cteCopy FOR XML PATH('')), 1, 1, '') AS ids
返回
ids |
1,2,4,5 |
二)根据子级ID查找所有父级ID,并将所有ID用逗号隔开返回
ID=,需要返回的结果(条件为isDel=0,不含本身ID):
1,2
SQL语句如下:
with cteCopy as
(
select * from [table] where id=5
union all
select a.* from [table] a join cteCopy b on a.id=b.parentID and a.IsDel=0
)
SELECT STUFF(( SELECT ',' +convert(VARCHAR, id) FROM cteCopy where id<> FOR XML PATH('')), 1, 1, '') AS ids
返回
ids |
1,2 |