首先创建表:
CREATE TABLE [dbo].[tbUser](
[UserId] [int] NOT NULL,
[ParentUserId] [int] NOT NULL
) ON [PRIMARY]
往表内添加以下数据:
UserId ParentUserId
1 0
2 11
3 2
4 1
5 3
6 4
7 2
8 2
10 1
11 1
12 1
13 10
14 13
15 14
16 15
17 16
18 17
19 18
20 19
现要列出属于UserId=1的所有下级成员:
DECLARE @UserId INT
SET @UserId = 1
;WITH b
AS
(
SELECT * FROM tbUser WHERE UserId = @UserId
UNION ALL
SELECT a.* FROM b JOIN tbUser a ON b.UserId = a.ParentUserId
)
SELECT * FROM b ORDER BY UserId ASC