CTE 一个突出优点就是处理递归的时候简单明了,让人一看就懂。这个是sql server 2005的新特性。
用with来实现这样的功能:
先看一个例子
在这个例子中orgunitid=1的记录是orgunitid=2的父类。
用with就能很轻松的实现这样的递归
with prodgroup
as
(select orgunitid,[type],shortname,orgunitparent from organizationunit where type=0 and orgunitid=1
union all
select a.orgunitid,a.[type],a.shortname,a.orgunitparent from organizationunit a inner join prodgroup b
on a.orgunitparent=b.orgunitid
)
select * from prodgroup
这里实现是是从上向下查,也可以从下往上查,