Can you create nested WITH clauses for Common Table Expressions?

后端 未结 7 1199
花落未央
花落未央 2020-12-12 10:42
WITH y AS (
    WITH x AS (
        SELECT * FROM MyTable
    )
    SELECT * FROM x
)
SELECT * FROM y

Does something like this work? I tried it ear

7条回答
  •  醉话见心
    2020-12-12 11:07

    These answers are pretty good, but as far as getting the items to order properly, you'd be better off looking at this article http://dataeducation.com/dr-output-or-how-i-learned-to-stop-worrying-and-love-the-merge

    Here's an example of his query.

    WITH paths AS ( 
        SELECT 
            EmployeeID, 
            CONVERT(VARCHAR(900), CONCAT('.', EmployeeID, '.')) AS FullPath 
        FROM EmployeeHierarchyWide 
        WHERE ManagerID IS NULL
    
        UNION ALL
    
        SELECT 
            ehw.EmployeeID, 
            CONVERT(VARCHAR(900), CONCAT(p.FullPath, ehw.EmployeeID, '.')) AS FullPath 
        FROM paths AS p 
            JOIN EmployeeHierarchyWide AS ehw ON ehw.ManagerID = p.EmployeeID 
    ) 
    SELECT * FROM paths order by FullPath
    

提交回复
热议问题