2011-08-22 51 views
9

我還沒有找到任何具體的例子,但我有興趣使用hierarchyid數據類型來表示整個目錄結構的更新等。這是hierarchyid引用的常見用例,但我找不到任何構建這樣一個示例的文章。在數據庫中表示文件系統(在SQL Server 2008中使用hierarchyid)

我只是想代表整個目錄結構如:

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

**我不是想與磁盤上的文件系統進行同步此。它純粹通過數據庫來表示。 **

+2

您希望保留的表結構同步與文件怎麼辦系統?如果我在/ dir2中添加一個文件,表格應該多快知道它?立即,一些延遲,從來沒有?在運行時只讀目錄結構是否更有意義?這不會真的需要hierarchyid。 –

+0

謝謝,我沒有試圖保持數據庫與文件系統同步。它基本上將作爲自己的文件系統(文件節點將指向磁盤上的文件,但不會有目錄結構)。我真正需要幫助的只是這一部分。謝謝。 – user8790899800

+0

爲什麼@Aaron Bertrand的評論在不是真正相關的時候被上調了?似乎很奇怪。 – user8790899800

回答

7

這裏是通過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 

獲取文件2的祖先(上一級):

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的所有descentants:

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 

獲取等級升文件2的:

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

level 
------ 
4 

參考文獻:

相關問題