WITH n(lev,ID, NAME, PORGID, ORG_ID_TREE) AS
(SELECT 0,ID, NAME, PORGID, CAST(ID AS VARCHAR(1024))
FROM CPM_GDSBA
WHERE ID = ‘00001‘
UNION ALL
SELECT n.lev +1, nplus1.ID, nplus1.NAME, nplus1.PORGID, n.ORG_ID_TREE || ‘,‘ || nplus1.ID
FROM CPM_GDSBA as nplus1, n
WHERE n.ID = nplus1.PORGID)
SELECT lev as LEVEL,ID, NAME, PORGID, ORG_ID_TREE FROM n
其中,n代表第一次查询结果,即根数据,然后递归往下找父为该数据的记录,在递归过程中ORG_ID_TREE记录递归的路径,也就是拼接从根一直到当前最后的叶子节点的路径。
lev代表递归的深度,初始值由UNION ALL前面的初始查询语句决定,后续递归动作在n.lev基础上加1
这个递归对应oracle的CONNECT BY PRIOR关键词,oracle的SYS_CONNECT_BY_PATH关键词对应的 CAST(ID AS VARCHAR(1024))这种形式
更多的解释可参照:
http://blog.csdn.net/suliqiang/article/details/47746395
https://www.ibm.com/developerworks/cn/data/library/techarticles/dm-1010liush/