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

后端 未结 3 1536
鱼传尺愫
鱼传尺愫 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 07:55

    There is no ORDER BY anywhere in sight - neither in the table-valued function, nor in the SELECT from that TVF.

    Any "ordering" will be totally arbitrary and coincidental.

    If you want a specific order, you need to specify an ORDER BY.

    So why can't you just add an ORDER BY to your SELECT:

     SELECT * FROM dbo._previousClaimsByFiData(16177344) 
     ORDER BY (whatever you want to order by)....
    

    or put your ORDER BY into the TVF:

    INSERT INTO @retPreviousClaims
        SELECT idData FROM PreviousClaims
        ORDER BY idData DESC (or whatever it is you want to order by...)
    
    0 讨论(0)
  • 2021-01-21 08:04

    I think the impression that the CTE is creating an ordering is wrong. It's a coincidence that the rows are coming out in order (possibly due to how they were originally inserted into tabData). Regardless, the TVF is returning a table so you have to explicitly add an ORDER BY to the SELECT you're using to call it if you want to guarantee ordering:

    select * from dbo._previousClaimsByFiData(16177344) order by idData
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题