Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How to convert this Oracle code structure to SQL Server:

SELECT LEVEL, EMPNO, ENAME, JOB, MGR FROM EMP
CONNECT BY MGR = PRIOR EMPNO
START WITH MGR IS NULL
ORDER BY LEVEL;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
132 views
Welcome To Ask or Share your Answers For Others

1 Answer

SQL Server does not have CONNECT BY. You need to use a recursive CTE.

Place the START WITH in the WHERE filter of the anchor part (the first part of the CTE).

In the recursive part (the second half), rejoin the CTE to EMP with the CONNECT BY condition.

WITH cte AS (
    SELECT
        LEVEL = 1,
        e.EMPNO,
        e.ENAME,
        e.JOB,
        e.MGR
    FROM EMP e
    WHERE e.MGR IS NULL

    UNION ALL

    SELECT
        cte.LEVEL + 1,
        e.EMPNO,
        e.ENAME,
        e.JOB,
        e.MGR
    FROM EMP e
    JOIN cte ON e.MGR = cte.EMPNO
)

SELECT
    cte.LEVEL,
    cte.EMPNO,
    cte.ENAME,
    cte.JOB,
    cte.MGR
FROM cte
ORDER BY cte.LEVEL;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...