SQL SERVER: CTE RECURSIVE QUERY TO GET PARENT CHILD HIERARCHY WITH LEVELS

SQL SERVER: CTE RECURSIVE QUERY TO GET PARENT CHILD HIERARCHY WITH LEVELS
Introduction: In this article I am going to explain how to create parent-child hierarchy(Continent-> Country-> State-> City) with levels using recursive common table expression (CTE).

In previous articles i have explained How to use CTE recursive query to get employee manager hierarchy with level and Using CTE to get all dates between two specified dates and Multiple sql server queries to get all dates between two dates and Check column existence before adding new column in table and Row_number(), rank(), dense_rank(), ntile() ranking functions

Description: While working with database we often store parent and child id in same table. For example category id and sub category Id, employee id and his manager id etc.

Here in this article I am taking an example where continents and their countries and state of that countries and cities of that states are stored in same table. And suppose it is required to get all of them in hierarchy e.g. Continent-> Country-> State-> City, then CTE is very useful in such case because of its recursive capability.

Implementation: Let’s understand by an example: Create a dummy table using the script below:

IF OBJECT_ID(‘tempdb.dbo.#tbHierarchy’, ‘U’) IS NOT NULL
DROP TABLE #tbHierarchy;

GO
CREATE TABLE #tbHierarchy
(
Id INT
,[Name] VARCHAR(20)
,ParentId INT
)
Insert some dummy data using the script below:
GO
INSERT INTO #tbHierarchy(Id, [Name], ParentId)
VALUES
(1, ‘Europe’, NULL)
,(2, ‘Asia’, NULL)
,(3, ‘Africa’, NULL)
,(4, ‘France’, 1)
,(5, ‘India’, 2)
,(6, ‘China’, 2)
,(7, ‘Zimbabwe’, 3)
,(8, ‘Hong Kong’, 6)
,(9, ‘Beijing’, 6)
,(10, ‘Shanghai’,6)
,(11, ‘Chandigarh’, 5)
,(12, ‘Mumbai’, 5)
,(13, ‘Delhi’, 5)
,(14, ‘Haryana’, 5)
,(15, ‘Gurgaon’, 14)
,(16, ‘Panchkula’, 14)
,(17, ‘Paris’, 4)
,(18, ‘Marseille’, 4)
,(19, ‘Harare’, 7)
,(20, ‘Bulawayo’, 7);

Check table data
在这里插入图片描述

Recursive CTE query to get Continent-> Country-> State-> City relationship hierarchy with levels.

;WITH MyCTE
AS
(
– anchor
SELECT Id, [Name], ParentId,1 AS [Level],
CAST(([Name]) AS VARCHAR(MAX)) AS Hierarchy
FROM #tbHierarchy t1
WHERE ParentId IS NULL
UNION ALL
–recursive member
SELECT t2.id, t2.[Name], t2.ParentID,M.[level] + 1 AS [Level],
CAST((M.Hierarchy + ‘->’ + t2.Name) AS VARCHAR(MAX)) AS Hierarchy
FROM #tbHierarchy AS t2
JOIN MyCTE AS M ON t2.ParentId = M.Id
)

SELECT * FROM MyCTE
在这里插入图片描述

Explanation: The base record for the CTE is obtained by the first select query above UNION ALL. It gets all the ParentIds which don’t have ParentId i.e. NULL value. This means they are the continents so their Level is set to 1.

Second select query below UNION ALL is executed recursively to get results and it will continue until it returns no rows. Countries will be assigned Level 2, States will be assigned Level 3 and Cities will be assigned Level 4 and hierarchy is created as you can see in the final output.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值