■ CTE 재귀 호출을 사용하는 방법을 보여준다.
▶ 예제 코드 (SQL)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
CREATE TABLE MENU ( ID INT ,PARENT_ID INT ,NAME VARCHAR(50) ); INSERT INTO MENU VALUES (1, 0, '메뉴'); INSERT INTO MENU VALUES (2, 0, '메뉴'); INSERT INTO MENU VALUES (3, 1, '메뉴'); INSERT INTO MENU VALUES (4, 1, '메뉴'); INSERT INTO MENU VALUES (5, 1, '메뉴'); INSERT INTO MENU VALUES (6, 5, '메뉴'); INSERT INTO MENU VALUES (7, 2, '메뉴'); INSERT INTO MENU VALUES (8, 2, '메뉴'); WITH CTE(ID, PARENT_ID, NAME, DISPLAY_ORDER, TREE_PATH) AS ( SELECT ID ,PARENT_ID ,NAME ,CONVERT(VARCHAR(4000), ID ) AS DISPLAY_ORDER ,CONVERT(VARCHAR(4000), NAME) AS TREE_PATH FROM MENU WHERE PARENT_ID = 0 UNION ALL SELECT A.ID ,A.PARENT_ID ,A.NAME ,CONVERT(VARCHAR(4000), B.DISPLAY_ORDER + ' > ' + CONVERT(VARCHAR(4000), A.ID)) AS DISPLAY_ORDER ,CONVERT(VARCHAR(4000), B.TREE_PATH + ' > ' + A.NAME ) AS TREE_PATH FROM MENU AS A, CTE AS B WHERE A.PARENT_ID = B.ID ) SELECT NAME ,TREE_PATH FROM CTE ORDER BY DISPLAY_ORDER; |