我有以下两个表:
SELECT [AM_ID]
,[AMI_ID]
,[Parent_AMI_ID]
,[AMI_Code]
FROM [Reporting].[dbo].[DIM_AM]
;
此表包含层次结构(37行)
SELECT [AMI_ID]
,[AMI_Name]
FROM [Reporting].[dbo].[DIM_AMI]
;
此表包含实体(AMI_Name)。
我必须使用MS SQL中的递归函数创建一个表,它将返回以下内容:
SELECT
Level
,AMI_Code
,AMI_Name
FROM...
如何使用递归函数以此格式生成hierarhy? 如何在MS SQL中使用递归函数编写递归查询? 请给我一些建议。
答案 0 :(得分:1)
这是一个小例子:
DECLARE @DIM_AM TABLE([AM_ID] INT, [AMI_ID] int, [Parent_AMI_ID] INT, [AMI_Code] VARCHAR(20))
DECLARE @DIM_AMI TABLE([AMI_ID] INT, [AMI_Name] VARCHAR(20))
INSERT INTO @DIM_AMI VALUES
(1, 'AMI1'),
(2, 'AMI2'),
(3, 'AMI3'),
(4, 'AMI4')
INSERT INTO @DIM_AM VALUES
(1, 1, NULL, 'CODE_AMI1'),
(2, 2, 1, 'CODE_AMI2'),
(3, 3, 1, 'CODE_AMI3'),
(4, 4, 3, 'CODE_AMI4')
;WITH cte AS(SELECT *, 0 AS Level FROM @DIM_AM WHERE Parent_AMI_ID IS NULL
UNION ALL
SELECT d.*, c.Level + 1 FROM cte c
JOIN @DIM_AM d ON c.AMI_ID = d.Parent_AMI_ID)
SELECT c.Level, c.AMI_Code, d.AMI_Name FROM cte c
JOIN @DIM_AMI d ON d.AMI_ID = c.AMI_ID
输出:
Level AMI_Code AMI_Name
0 CODE_AMI1 AMI1
1 CODE_AMI2 AMI2
1 CODE_AMI3 AMI3
2 CODE_AMI4 AMI4
这是递归公用表表达式(cte):
;WITH cte AS(SELECT *, 0 AS Level FROM @DIM_AM WHERE Parent_AMI_ID IS NULL
UNION ALL
SELECT d.*, c.Level + 1 FROM cte c
JOIN @DIM_AM d ON c.AMI_ID = d.Parent_AMI_ID)
第一部分是选择顶级元素(WHERE Parent_AMI_ID IS NULL
)的起点:
SELECT *, 0 AS Level FROM @DIM_AM WHERE Parent_AMI_ID IS NULL
然后通过语法,您需要union all
。
然后是递归部分,选择前一个选择的孩子:
SELECT d.*, c.Level + 1 FROM cte c
JOIN @DIM_AM d ON c.AMI_ID = d.Parent_AMI_ID