SQL SERVER 2005 公用表表达式(CTE)处理递归(父子关系)

来源:互联网 发布:手机淘宝怎么关闭订单 编辑:程序博客网 时间:2024/05/22 10:36

     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

这里实现是是从上向下查,也可以从下往上查,

 

原创粉丝点击