■ 계층적 테이블을 조회하는 방법을 보여준다.
▶ 계층적 테이블 조회하기 예제 (SQL)
1 2 3 |
SELECT * FROM GetTreeTable(18); |
▶ 계층적 테이블 조회하기 (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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
CREATE FUNCTION [dbo].[GetTreeTable] ( @ParentID INT -- 부모 ID ) RETURNS @ResultTree TABLE ( ID INT ,Name NVARCHAR(50) ,ParentID INT ,TreeLevel INT ,TreePath VARCHAR(2000) ) AS BEGIN DECLARE @TreeLevel INT; SELECT @TreeLevel = 0; INSERT INTO @ResultTree SELECT ---------------------------------------- ID = A.ID -- ID ,Name = A.Name -- 명칭 ,ParentID = A.ParentID -- 부모 ID ---------------------------------------- ,TreeLevel = @TreeLevel ,TreePath = RIGHT('00000000' + CAST(A.ID AS VARCHAR(8)), 8) FROM Menu AS A WITH(NOLOCK) WHERE A.ID = @ParentID; WHILE @@ROWCOUNT > 0 BEGIN SELECT @TreeLevel = @TreeLevel + 1; INSERT INTO @ResultTree SELECT ---------------------------------------- ID = A.ID -- ID ,Name = A.Name -- 명칭 ,ParentID = A.ParentID -- 부모ID ---------------------------------------- ,TreeLevel = @TreeLevel ,TreePath = B.TreePath + '/' + RIGHT('00000000' + CAST(A.ID AS VARCHAR(8)), 8) FROM Menu AS A WITH(NOLOCK) INNER JOIN @ResultTree AS B ON B.ID = A.ParentID WHERE EXISTS ( SELECT B.* FROM @ResultTree AS B WHERE B.ID = A.ParentID ) AND NOT EXISTS ( SELECT C.* FROM @ResultTree AS C WHERE C.ID = A.ID ); END; RETURN; END GO |