您的位置:首页 > 数据库

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

2009-11-22 22:17 399 查看
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

这里实现是是从上向下查,也可以从下往上查,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: