繁体   English   中英

在DB中表示文件系统(在SQL Server 2008中使用hierarchyid)

[英]Represent File System in DB (using hierarchyid in SQL Server 2008)

我没有找到任何具体的例子,但我有兴趣使用hierarchyid数据类型来表示具有更新等的整个目录结构。 这是为hierarchyid引用的常见用例,但我找不到构建这样一个示例的任何文章。

我只想表示一个完整的目录结构,例如:

/dir1
/file1
/dir2
/dir2/dir3
/dir2/dir3/file2

**我不是想与磁盘上的文件系统同步。 它纯粹通过数据库表示。 **

以下是通过hierarchyid表示文件系统的示例

/*
Setup:
 - Create the table to hold the files
 - nodeDepth is identifier of the depth for readability
 - fullpath is the full path of the file or directory
 - nodePath is the HierarchyID
 - nodePath identifies the row within the tree
*/

DECLARE @t TABLE (
  nodeID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
  nodeDepth VARCHAR(10) NOT NULL,
  fullPath VARCHAR(20) NOT NULL,
  nodePath HIERARCHYID NOT NULL
) 

加载数据:

/*
Load the nodePath value with the Parse command: 
 - The root node has a single /
 - Every nodePath must begin and end with /
 - /1/2/ the second item on level 2
*/

INSERT @t (fullPath, nodeDepth, nodePath) VALUES  
('/','1',HIERARCHYID::Parse('/')),
('/dir1','1.1',HIERARCHYID::Parse('/1/1/')),
('/file1','1.2',HIERARCHYID::Parse('/1/2/')),
('/dir2','1.3',HIERARCHYID::Parse('/1/3/')),
('/dir2/dir3','1.3.1',HIERARCHYID::Parse('/1/3/1/')),
('/dir2/dir3/file2','1.3.1.1',HIERARCHYID::Parse('/1/3/1/1/'))

显示路径:

SELECT *
FROM @t 

nodeID      nodeDepth  fullPath             nodePath
----------- ---------- -------------------- --------
1           1          /                    0x
2           1.1        /dir1                0x5AC0
3           1.2        /file1               0x5B40
4           1.3        /dir2                0x5BC0
5           1.3.1      /dir2/dir3           0x5BD6
6           1.3.1.1    /dir2/dir3/file2     0x5BD6B0

获取file2的祖先(上一层):

SELECT * 
FROM @t 
WHERE nodePath = 
  (SELECT nodePath.GetAncestor(1)
   FROM @t 
   WHERE fullPath = '/dir2/dir3/file2')

nodeID      nodeDepth  fullPath             nodePath
----------- ---------- -------------------- ---------
5           1.3.1      /dir2/dir3           0x5BD6

得到dir2的所有下降:

SELECT *
FROM @t 
WHERE nodePath.IsDescendantOf(
  (SELECT nodePath 
   FROM @t 
   WHERE fullPath = '/dir2')) = 1
AND fullPath <> '/dir2' /* Parent is considered its own descendant */

nodeID      nodeDepth  fullPath             nodePath
----------- ---------- -------------------- --------
5           1.3.1      /dir2/dir3           0x5BD6
6           1.3.1.1    /dir2/dir3/file2     0x5BD6B0

获取根路径:

SELECT * 
FROM @t 
WHERE nodePath = HIERARCHYID::GetRoot()

nodeID      nodeDepth  fullPath             nodePath
----------- ---------- -------------------- --------
1           1          /                    0x

获取file2的级别:

SELECT nodePath.GetLevel() AS level
FROM @t 
WHERE fullPath = '/dir2/dir3/file2'

level
------
4

参考文献:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM