CTE可以用来取递归,网上资料很多,这里就不再叙述了,今天遇到的需求是要限制只取2级,然后加了个临时的lev
with tree as
(
select [CustomerID],[CustomerName],[PositionParentID],[PositionValus],[Status],[MemberLevelID],Lev=1 from [MallCustomer] where [PositionParentID] = '0017556dece149919af4b91442cf2117'
union all
select a.[CustomerID],a.[CustomerName],a.[PositionParentID],a.[PositionValus],a.[Status],a.[MemberLevelID],Lev+1 Lev from [MallCustomer] a,tree b where a.PositionParentID=b.CustomerID and Lev<=1
)
select a.[CustomerID],a.[CustomerName],a.[PositionParentID],a.[PositionValus],a.[Status],b.[MemberLevelName] from tree a,MallMemberLevel b where a.MemberLevelID=b.MemberLevelID
这里是层数限制
lev<=1
结果图