Oracle对树形数据的递归查询使用Connect子句,例如:
以下内容为程序代码:
SELECT ID, PARENTID, Level
FROM TREENODE
Start With ID = 'A2'
Connect By Prior ID = ParentId
FROM TREENODE
Start With ID = 'A2'
Connect By Prior ID = ParentId
在DB2和最新的MS SQL Server 2005中也支持递归查询。SQL Server 2005和DB 2语法是相似的。
如上的SQL在DB 2中应为:
WITH SUB_TABLE (ID, PARENTID, Level)
AS (
SELECT ID, PARENTID, 0 FROM TREENODE WHERE ID = 'A2'
UNION ALL
SELECT PRIOR_TAB.ID, PRIOR_TAB.PARENTID, KSQL_SUB_TABLE.Level + 1
FROM (SELECT ID, PARENTID, Level FROM TREENODE) PRIOR_TAB, SUB_TABLE
WHERE SUB_TABLE.ID = PRIOR_TAB.ParentId
)
SELECT ID, PARENTID, Level FROM SUB_TABLE
AS (
SELECT ID, PARENTID, 0 FROM TREENODE WHERE ID = 'A2'
UNION ALL
SELECT PRIOR_TAB.ID, PRIOR_TAB.PARENTID, KSQL_SUB_TABLE.Level + 1
FROM (SELECT ID, PARENTID, Level FROM TREENODE) PRIOR_TAB, SUB_TABLE
WHERE SUB_TABLE.ID = PRIOR_TAB.ParentId
)
SELECT ID, PARENTID, Level FROM SUB_TABLE
DB2中递归查询使用起来,比Oracle的麻烦。Oracle中引入了Prior关键字,使得递归查询变得简单。
MS SQL Server在最新2005的版本中,终于支持递归查询了,相比起Oracle和DB2,落后了好多年哟!!