Guest User

Untitled

a guest
Jul 20th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. /dir1
  2. /file1
  3. /dir2
  4. /dir2/dir3
  5. /dir2/dir3/file2
  6.  
  7. /*
  8. Setup:
  9. - Create the table to hold the files
  10. - nodeDepth is identifier of the depth for readability
  11. - fullpath is the full path of the file or directory
  12. - nodePath is the HierarchyID
  13. - nodePath identifies the row within the tree
  14. */
  15.  
  16. DECLARE @t TABLE (
  17. nodeID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
  18. nodeDepth VARCHAR(10) NOT NULL,
  19. fullPath VARCHAR(20) NOT NULL,
  20. nodePath HIERARCHYID NOT NULL
  21. )
  22.  
  23. /*
  24. Load the nodePath value with the Parse command:
  25. - The root node has a single /
  26. - Every nodePath must begin and end with /
  27. - /1/2/ the second item on level 2
  28. */
  29.  
  30. INSERT @t (fullPath, nodeDepth, nodePath) VALUES
  31. ('/','1',HIERARCHYID::Parse('/')),
  32. ('/dir1','1.1',HIERARCHYID::Parse('/1/1/')),
  33. ('/file1','1.2',HIERARCHYID::Parse('/1/2/')),
  34. ('/dir2','1.3',HIERARCHYID::Parse('/1/3/')),
  35. ('/dir2/dir3','1.3.1',HIERARCHYID::Parse('/1/3/1/')),
  36. ('/dir2/dir3/file2','1.3.1.1',HIERARCHYID::Parse('/1/3/1/1/'))
  37.  
  38. SELECT *
  39. FROM @t
  40.  
  41. nodeID nodeDepth fullPath nodePath
  42. ----------- ---------- -------------------- --------
  43. 1 1 / 0x
  44. 2 1.1 /dir1 0x5AC0
  45. 3 1.2 /file1 0x5B40
  46. 4 1.3 /dir2 0x5BC0
  47. 5 1.3.1 /dir2/dir3 0x5BD6
  48. 6 1.3.1.1 /dir2/dir3/file2 0x5BD6B0
  49.  
  50. SELECT *
  51. FROM @t
  52. WHERE nodePath =
  53. (SELECT nodePath.GetAncestor(1)
  54. FROM @t
  55. WHERE fullPath = '/dir2/dir3/file2')
  56.  
  57. nodeID nodeDepth fullPath nodePath
  58. ----------- ---------- -------------------- ---------
  59. 5 1.3.1 /dir2/dir3 0x5BD6
  60.  
  61. SELECT *
  62. FROM @t
  63. WHERE nodePath.IsDescendantOf(
  64. (SELECT nodePath
  65. FROM @t
  66. WHERE fullPath = '/dir2')) = 1
  67. AND fullPath <> '/dir2' /* Parent is considered its own descendant */
  68.  
  69. nodeID nodeDepth fullPath nodePath
  70. ----------- ---------- -------------------- --------
  71. 5 1.3.1 /dir2/dir3 0x5BD6
  72. 6 1.3.1.1 /dir2/dir3/file2 0x5BD6B0
  73.  
  74. SELECT *
  75. FROM @t
  76. WHERE nodePath = HIERARCHYID::GetRoot()
  77.  
  78. nodeID nodeDepth fullPath nodePath
  79. ----------- ---------- -------------------- --------
  80. 1 1 / 0x
  81.  
  82. SELECT nodePath.GetLevel() AS level
  83. FROM @t
  84. WHERE fullPath = '/dir2/dir3/file2'
  85.  
  86. level
  87. ------
  88. 4
Add Comment
Please, Sign In to add comment