樹形結構的儲存與查詢

taogchan發表於2014-01-09
資料庫設計中常常會遇到需要儲存樹形結構,比如員工關係表、組織結構表,等等。

點選(此處)摺疊或開啟

  1. --測試資料

  2. CREATE TABLE #Employees(
  3.     EmployeeCode varchar(20) NOT NULL PRIMARY KEY CLUSTERED,
  4.     ReportToCode varchar(20) NULL)
  5. GO
  6. INSERT INTO #Employees VALUES(\'A\',NULL)
  7. INSERT INTO #Employees VALUES(\'B\',\'A\')
  8. INSERT INTO #Employees VALUES(\'C\',\'A\')
  9. INSERT INTO #Employees VALUES(\'D\',\'A\')
  10. INSERT INTO #Employees VALUES(\'E\',\'B\')
  11. INSERT INTO #Employees VALUES(\'F\',\'B\')
  12. INSERT INTO #Employees VALUES(\'G\',\'C\')
  13. INSERT INTO #Employees VALUES(\'H\',\'D\')
  14. INSERT INTO #Employees VALUES(\'I\',\'D\')
  15. INSERT INTO #Employees VALUES(\'J\',\'D\')
  16. INSERT INTO #Employees VALUES(\'K\',\'J\')
  17. INSERT INTO #Employees VALUES(\'L\',\'J\')
  18. INSERT INTO #Employees VALUES(\'M\',\'J\')
  19. INSERT INTO #Employees VALUES(\'N\',\'K\')
  20. GO
  21. /*
  22. 可能遇到的查詢問題:
  23. 1. 員工\'D\'的所有直接下屬
  24. 2. 員工\'D\'的所有2級以內的下屬(包括直接下屬和直接下屬的下屬)
  25. 3. 員工\'N\'的所有上級(按報告線順序列出)
  26. 4. 員工@EmployeeCode的所有@LevelDown級以內的下屬(@EmployeeCode和@LevelDown以變數傳入)
  27. DECLARE @EmployeeCode varchar(20), @LevelDown int;
  28. SET @EmployeeCode = \'D\';
  29. SET @LevelDown = 2;
  30. 5. 員工@EmployeeCode的所有@LevelUp級以內的上級(@EmployeeCode和@LevelUp以變數傳入)
  31. DECLARE @EmployeeCode varchar(20), @LevelUp int;
  32. SET @EmployeeCode = \'N\';
  33. SET @LevelUp = 2;
  34. */
  35. --用遞迴CTE實現員工樹形關係表

  36. WITH CTE AS(
  37.     SELECT
  38.         EmployeeCode,
  39.         ReportToCode,
  40.         ReportToDepth = 0,
  41.         ReportToPath = CAST(\'/\' + EmployeeCode + \'/\' AS varchar(200))
  42.     FROM #Employees
  43.     WHERE ReportToCode IS NULL
  44.     UNION ALL
  45.     SELECT
  46.         e.EmployeeCode,
  47.         e.ReportToCode,
  48.         ReportToDepth = mgr.ReportToDepth + 1,
  49.         ReportToPath = CAST(mgr.ReportToPath + e.EmployeeCode + \'/\' AS varchar(200))
  50.     FROM #Employees e
  51.     INNER JOIN CTE mgr
  52.     ON e.ReportToCode = mgr.EmployeeCode
  53. )
  54. SELECT * FROM CTE ORDER BY ReportToPath

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22392018/viewspace-1068778/,如需轉載,請註明出處,否則將追究法律責任。

相關文章