已经有很多朋友分享过了,自己亲身操作过,随便记录下来是给自己备忘,以后用到时不用乱找。
WITH cet_depart AS ( SELECT depart_id, depart_name FROM dbo.Depart WHERE depart_id = '004' --入口 UNION ALL --递归时必要 SELECT d.depart_id, d.depart_name FROM depart d INNER JOIN cet_depart c ON CAST (c.depart_id AS INT) = d.upper_depart_id --递归条件 ) SELECT * FROM cet_depart OPTION (MAXRECURSION 20) --最大递归次数
结果集: