sql递归

--单表递归  由于项目中经常用到  , 随笔以作下次使用  

例如:找ProductType表 下ID为1的分类的所有子级

with result as    --result为别名

select * from TB_ProductType where Id=1  --查询ID为1 的数据
union all 
select TB_ProductType.* from tb_productType, result where result.ID = TB_ProductType.ParentID  ---递归--找到ID为1的分类的所有下级

 select * from result  --注意 上面只是获取了递归的对象 所以这里必须要查询一次

--递归删除  / 更新

with result as 

select * from TB_ProductType where Id=1 
union all 
select TB_ProductType.* from tb_productType, result where result.ID = TB_ProductType.ParentID

update TB_ProductType set name = '' where id in ( select id from result)  -- 

今日事今日毕
原文地址:https://www.cnblogs.com/gjack/p/8717309.html