--------------所有子集数据包括自己--------------------- CREATE PROCEDURE ALLSON @ID INT AS BEGIN WITH CTE AS ( SELECT ID,PID,NAME,0 AS LVL FROM TEST1 WHERE ID = @ID UNION ALL SELECT D.ID,D.PID,D.NAME,LVL+1 FROM CTE C INNER JOIN TEST1 D ON C.ID = D.PID ) SELECT * FROM CTE END ------------------所有父级数据------------------- CREATE PROCEDURE ALLFATHER @ID INT AS BEGIN WITH CTE AS ( SELECT ID,PID,NAME,0 AS LVL FROM TEST1 WHERE ID = @ID UNION ALL SELECT D.ID,D.PID,D.NAME,LVL+1 FROM CTE C INNER JOIN TEST1 D ON C.PID = D.ID ) SELECT * FROM CTE END --FATHER EXEC ALLFATHER 6
如果本文对你有所帮助,请打赏——1元就足够感动我:)
联系邮箱:intdb@qq.com
我的GitHub: https://github.com/vipstone
联系邮箱:intdb@qq.com
我的GitHub: https://github.com/vipstone
关注公众号:
作者: 王磊
出处: http://vipstone.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,请标明出处。