SQL SERVER 2005 公用表表达式(CTE)处理递归(父子关系) 收藏
CTE 一个突出优点就是处理递归的时候简单明了,让人一看就懂。这个是sql server 2005的新特性。
用with来实现这样的功能:
先看一个例子
在这个例子中orgunitid=1的记录是orgunitid=2的父类。
用with就能很轻松的实现这样的递归
with prodgroup
as
(select orgunitid,[type],shortname,orgunitparent from organizationunit where type=0 and rgunitid=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
这里实现是是从上向下查,也可以从下往上查,
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/wobuwei/archive/2009/11/22/4853343.aspx
如下是在oracle 中实现递归
SELECT * FROM user_tables;
SELECT * FROM emp;
select * from emp
start with mgr IS NULL
connect by prior empno = mgr;
TRUNCATE TABLE test_parent;
TRUNCATE TABLE test_child;
INSERT INTO test_parent VALUES(1,'p_name1');
INSERT INTO test_child VALUES(10,1,'c_name10');
INSERT INTO test_parent VALUES(10,'p_name2');
INSERT INTO test_child VALUES(100,10,'c_name100');
SELECT tp.id,tp.p_name,tc.c_name,tc.p_id p_id FROM test_parent tp,test_child tc WHERE tp.id=tc.p_id;
SELECT * FROM test_parent tp,test_child tc
start with tp.p_name='p_name1' connect by prior tp.id=tc.id;
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/183242/viewspace-680835/ ,如需转载,请注明出处,否则将追究法律责任。