There is often a business scenario where the current ID is known, how to obtain its child node data? How to get the data of the parent node? The following code shows the simplest example:
/*Create an employee table*/ CREATE TABLE [dbo].[Employee]( [ID] [uniqueidentifier] NOT NULL,--user ID [ParentGUID] [uniqueidentifier] NOT NULL,--superior ID [ECode] [nvarchar](50) NOT NULL,--employee number [EName] [nvarchar](200) NOT NULL--employee name CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
/* Insert some basic data */
INSERT [dbo].[Employee] ([ID], [ParentGUID], [ECode], [EName]) VALUES (N'CF06903A-1D9B-4896-916E-56E4B8CB1955', N'00000000-0000-0000-0000- 000000000000', N'SG001', N'Chairman') INSERT [dbo].[Employee] ([ID], [ParentGUID], [ECode], [EName]) VALUES (N'DD994FDA-1703-4616-AF1B-165164DF710E', N'CF06903A-1D9B-4896-916E-56E4B8CB1955', N'SG0012', N'经理') INSERT [dbo].[Employee] ([ID], [ParentGUID], [ECode], [EName]) VALUES (N'138C93C0-387B-4582-8A56-E036056A97F2', N'DD994FDA-1703-4616-AF1B-165164DF710E', N'SG0013', N'部长') INSERT [dbo].[Employee] ([ID], [ParentGUID], [ECode], [EName]) VALUES (N'88F1D9F7-CC02-4449-BA0A-8717142FFB4D', N'138C93C0-387B-4582-8A56-E036056A97F2', N'SG0014', N'主管') INSERT [dbo].[Employee] ([ID], [ParentGUID], [ECode], [EName]) VALUES (N'166FA95A-0425-40E3-8CB9-2A4C97CA4CC6', N'88F1D9F7-CC02-4449-BA0A-8717142FFB4D', N'SG00141', N'邵工') INSERT [dbo].[Employee] ([ID], [ParentGUID], [ECode], [EName]) VALUES (N'6E94AA52-700A-4415-BB8A-34345605E13D', N'88F1D9F7-CC02-4449-BA0A-8717142FFB4D', N'SG00142', N'李工') INSERT [dbo].[Employee] ([ID], [ParentGUID], [ECode], [EName]) VALUES (N'C5E537D4-0994-43E2-A1AB-3F736B4E22D3', N'88F1D9F7-CC02-4449-BA0A-8717142FFB4D', N'SG00143', N'高工') INSERT [dbo].[Employee] ([ID], [ParentGUID], [ECode], [EName]) VALUES (N'61F79EAF-DB86-425E-A61C-4228265EEC28', N'88F1D9F7-CC02-4449-BA0A-8717142FFB4D', N'SG00144', N'卜工') INSERT [dbo].[Employee] ([ID], [ParentGUID], [ECode], [EName]) VALUES (N'34C26725-3726-4C45-90C0-440C91EF34B8', N'88F1D9F7-CC02-4449-BA0A-8717142FFB4D', N'SG00145', N'苏工')
/* Get all supervisors of the supervisor */ ;WITH cteTemp AS ( SELECT [ID], [ParentGUID], [ECode], [EName] FROM [Employee] WHERE ID = '88F1D9F7-CC02-4449-BA0A-8717142FFB4D'/*主管ID*/ UNION ALL SELECT A.[ID], A.[ParentGUID], A.[ECode], A.[EName] FROM [Employee] A INNER JOIN cteTemp B ON A.[ID] = B.[ParentGUID] ) SELECT * FROM cteTemp
/* Get all the subordinates of the supervisor */ ;WITH cteTemp AS ( SELECT [ID], [ParentGUID], [ECode], [EName] FROM [Employee] WHERE ID = '88F1D9F7-CC02-4449-BA0A-8717142FFB4D'/*主管ID*/ UNION ALL SELECT A.[ID], A.[ParentGUID], A.[ECode], A.[EName] FROM [Employee] A INNER JOIN cteTemp B ON A.[ParentGUID] = B.[ID] ) SELECT * FROM cteTemp