sqlserver 递归查询

2024-12-12 14:41:33
推荐回答(2个)
回答1:

CREATE TABLE #tb1(stuId INT,stuName VARCHAR(30),teaId INT);
INSERT INTO #tb1 (stuId,stuName,teaId)
VALUES(1,'zhou',0),(2,'kong',0),(3,'hong',2),(4,'zhang',1),(5,'liu',4),
(6,'zhao',5),(7,'zheng',6),(8,'wei',7)
;WITH cte AS (
SELECT t.stuId,t.stuName,t.teaId FROM #tb1 AS t
WHERE t.stuId=8
UNION ALL
SELECT t.stuId,t.stuName,t.teaId FROM cte AS c
JOIN #tb1 AS t ON c.teaId=t.stuId
)
SELECT * FROM cte

回答2:

select * from 表 where stuID<8 order by stuID desc