Dưới đây là một ví dụ về đại diện cho một hệ thống tập tin thông qua 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
)
tải dữ liệu:
/*
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/'))
Hiện các đường dẫn:
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
Nhận tổ tiên của file2 (lên một cấp):
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
Nhận tất cả descentants của 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
Lấy đường dẫn gốc:
SELECT *
FROM @t
WHERE nodePath = HIERARCHYID::GetRoot()
nodeID nodeDepth fullPath nodePath
----------- ---------- -------------------- --------
1 1 / 0x
Lấy leve l file2:
SELECT nodePath.GetLevel() AS level
FROM @t
WHERE fullPath = '/dir2/dir3/file2'
level
------
4
Tài liệu tham khảo:
Làm thế nào để bạn mong đợi để giữ cấu trúc bảng đồng bộ với tập tin hệ thống? Nếu tôi thêm một tệp vào/dir2, bảng sẽ biết nhanh về nó như thế nào? Ngay lập tức, một chút chậm trễ, không bao giờ? Nó sẽ không có ý nghĩa hơn để chỉ đọc trong cấu trúc thư mục tại thời gian chạy? Sẽ không thực sự cần phân cấp cho điều đó. –
Cảm ơn, tôi không cố gắng giữ cho DB đồng bộ với hệ thống tệp. Về cơ bản nó sẽ hoạt động như hệ thống tập tin riêng của nó (các nút tập tin sẽ trỏ đến các tập tin trên đĩa nhưng sẽ không có cấu trúc thư mục). Tất cả những gì tôi thực sự cần giúp đỡ chỉ là một phần của nó. Cảm ơn. – user8790899800
Tại sao nhận xét của @Aaron Bertrand lại được bình chọn khi nó không thực sự có liên quan? Có vẻ kỳ quặc. – user8790899800