大马资讯论坛 - 马来西亚中文资讯平台

 找回密码
 注册
搜索
打印 上一主题 下一主题

[教学]SQL Server从子节点取出所有的父节点,select all parent node

[复制链接]
跳转到指定楼层
1#
发表于 2012-7-4 20:24:33 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
[教学]SQL Server从子节点取出所有的父节点,select all parent node from child node

Sample 1 Order By Depth
  1. DECLARE @ItemCategory TABLE
  2. (
  3.     ChildId INT NOT NULL,
  4.     Name varchar(50) NOT NULL,
  5.     ParentId int NULL
  6. )

  7. INSERT INTO @ItemCategory SELECT 1, 'Toys', null
  8. INSERT INTO @ItemCategory SELECT 2, 'Computers', null
  9. INSERT INTO @ItemCategory SELECT 3, 'Consoles', 2
  10. INSERT INTO @ItemCategory SELECT 4, 'PlayStation 3', 3
  11. INSERT INTO @ItemCategory SELECT 5, 'Xbox 360', 2
  12. INSERT INTO @ItemCategory SELECT 6, 'Games', 1
  13. INSERT INTO @ItemCategory SELECT 7, 'Puzzles', 6
  14. INSERT INTO @ItemCategory SELECT 8, 'Mens Wear', null
  15. INSERT INTO @ItemCategory SELECT 9, 'Mens Clothing', 8
  16. INSERT INTO @ItemCategory SELECT 10, 'Jackets', 9
  17. INSERT INTO @ItemCategory SELECT 11, 'Rain Coats', 10

  18. DECLARE @ChildID INT = 11

  19. ;WITH c
  20. AS
  21. (
  22.     SELECT ChildId, ParentId, Name, 1 AS Depth
  23.     FROM @ItemCategory
  24.     WHERE ChildId = @ChildID

  25.     UNION ALL

  26.     SELECT t.ChildId, t.ParentId, t.Name, c.Depth + 1 AS 'Level'
  27.     FROM @ItemCategory T  
  28.     INNER JOIN c ON t.ChildId = c.ParentId
  29. )
  30. SELECT *
  31. FROM c
复制代码
Sample 2 Order By Depth DESC
  1. DECLARE @ItemCategory TABLE
  2. (
  3.     ChildId INT NOT NULL,
  4.     Name varchar(50) NOT NULL,
  5.     ParentId int NULL
  6. )

  7. INSERT INTO @ItemCategory SELECT 1, 'Toys', null
  8. INSERT INTO @ItemCategory SELECT 2, 'Computers', null
  9. INSERT INTO @ItemCategory SELECT 3, 'Consoles', 2
  10. INSERT INTO @ItemCategory SELECT 4, 'PlayStation 3', 3
  11. INSERT INTO @ItemCategory SELECT 5, 'Xbox 360', 2
  12. INSERT INTO @ItemCategory SELECT 6, 'Games', 1
  13. INSERT INTO @ItemCategory SELECT 7, 'Puzzles', 6
  14. INSERT INTO @ItemCategory SELECT 8, 'Mens Wear', null
  15. INSERT INTO @ItemCategory SELECT 9, 'Mens Clothing', 8
  16. INSERT INTO @ItemCategory SELECT 10, 'Jackets', 9
  17. INSERT INTO @ItemCategory SELECT 11, 'Rain Coats', 10

  18. DECLARE @ChildID INT = 11

  19. ;WITH c
  20. AS
  21. (
  22.     SELECT ChildID, ParentId, Name, 1 AS Depth
  23.     FROM @ItemCategory
  24.     WHERE ChildID = @ChildID

  25.     UNION ALL

  26.     SELECT t.ChildID, t.ParentId, t.Name, c.Depth + 1 AS 'Level'
  27.     FROM @ItemCategory T  
  28.     INNER JOIN c ON t.ChildID = c.ParentId
  29. )
  30. SELECT ChildID,
  31.        ParentID,
  32.        Name,
  33.        MAX(Depth) OVER() - Depth + 1 AS InverseDepth
  34. FROM c
复制代码

手机版|大马资讯论坛  

GMT+8, 2024-12-1 14:35 , Processed in 0.023704 second(s), 11 queries , File On.

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表