开发者

ORACLE Connect by clause equivalent in SQL Server

开发者 https://www.devze.com 2022-12-18 22:38 出处:网络
Is there a equivalent clause to CONNECT BY of Oracle in SQL Server. The requirement to build a category tree using a parentId f开发者_JS百科ield.The SQL Server 2005+ equivalent of Oracle\'s CONNECT BY

Is there a equivalent clause to CONNECT BY of Oracle in SQL Server. The requirement to build a category tree using a parentId f开发者_JS百科ield.


The SQL Server 2005+ equivalent of Oracle's CONNECT BY hierarchical query syntax is to use a recursive CTE. SQL Server 2008 added HierarchyID. Here's an example of a recursive CTE:

WITH EmployeeHierarchy (EmployeeID, LastName, FirstName, ReportsTo, HierarchyLevel) AS (
   SELECT EmployeeID,
          LastName,
          FirstName,
          ReportsTo,
          1 as HierarchyLevel
     FROM Employees
    WHERE ReportsTo IS NULL
   UNION ALL
   -- Recursive step
   SELECT e.EmployeeID,
          e.LastName,
          e.FirstName,
          e.ReportsTo,
          eh.HierarchyLevel + 1 AS HierarchyLevel
     FROM Employees e
     JOIN EmployeeHierarchy eh ON e.ReportsTo = eh.EmployeeID)
  SELECT *
    FROM EmployeeHierarchy
ORDER BY HierarchyLevel, LastName, FirstName 

Googling "hierarchical CTE" and/or "recursive CTE" will turn up numerous results. I took the example query from the 4GuysFromRolla.com.

Recursive CTEs are now ANSI standard - the syntax wasn't supported until Oracle 11g as I understand.


There's HierarchyID data type in MS SQL Server 2008, which can make your life easier.

0

精彩评论

暂无评论...
验证码 换一张
取 消