Wrong order in Table valued Function(keep “order” of a recursive CTE)

后端 未结 3 1577
鱼传尺愫
鱼传尺愫 2021-01-21 07:39

a few minutes ago i asked here how to get parent records with a recursive CTE. This works now, but I get the wrong order(backwards, ordered by the PK idData) when i create a Tab

3条回答
  •  轮回少年
    2021-01-21 08:09

    The correct way to do your ORDERing is to add an ORDER BY clause to your outermost select. Anything else is relying on implementation details that may change at any time (including if the size of your database/tables goes up, which may allow more parallel processing to occur).

    If you need something convenient to allow the ordering to take place, look at Example D in the examples from the MSDN page on WITH:

    WITH DirectReports(ManagerID, EmployeeID, Title, EmployeeLevel) AS 
    (
        SELECT ManagerID, EmployeeID, Title, 0 AS EmployeeLevel
        FROM dbo.MyEmployees 
        WHERE ManagerID IS NULL
        UNION ALL
        SELECT e.ManagerID, e.EmployeeID, e.Title, EmployeeLevel + 1
        FROM dbo.MyEmployees AS e
            INNER JOIN DirectReports AS d
            ON e.ManagerID = d.EmployeeID 
    )
    

    Add something similay to the EmployeeLevel column to your CTE, and everything should work.

提交回复
热议问题