首页 > 开发 > 综合 > 正文

sql如何根据父集编号查询多集子集

2024-07-21 02:51:16
字体:
来源:转载
供稿:网友

这里用到了一个函数with

WITH CategoryInfo AS(	SELECT StuId,StuName,StuParent FROM dbo.Class WHERE StuId = id	UNION ALL	SELECT a.StuId,a.StuName,a.StuParent FROM dbo.Class AS a,CategoryInfo AS b WHERE a.StuId = b.pid	)select * from CategoryInfo

这样就可以取到你想要的包括父集和子集了

你要是想根据查出来的内容做一些比如修改等操作可以这样写

declare @StuIds varchar(max);                         WITH CategoryInfo AS(	SELECT StuId,StuName,StuParent FROM dbo.Class WHERE StuId = id	UNION ALL	SELECT a.StuId,a.StuName,a.StuParent FROM dbo.Class AS a,CategoryInfo AS b WHERE a.StuId = b.pid	)select @StuIds=ISNULL(@StuIds+',','')+convert(varchar,StuId) from CategoryInfoset @StuIds='UPDATE StuName from dbo.Class where StuId in('+@StuIds+')'exec(@CompanyCodeIn)


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表