1

我有两个表:文件夹,文件。每个表有 4 个字段:ParentID、ID、Name、Type

我需要创建一个 CTE 以便使用 T-SQL 一次性检索整个树。到目前为止,这就是我所做的,但递归尚未激活。

我忘了提到一个文件夹内可能有一个或多个文件夹/文件。

4

1 回答 1

2

假设您正在使用根目录中NULL的项目,则以下内容应该可以工作:ParentID

WITH FilesAndFolders AS (
    SELECT ID AS FileID, 
           CAST(NULL AS int) AS FolderID, 
           ParentID, 
           Name, 
           [Type]
    FROM File
    UNION ALL
    SELECT CAST(NULL AS int),
           ID, 
           ParentID, 
           Name, 
           [Type]
    FROM Folder
),
Tree AS (
    SELECT FileID, 
           FolderID, 
           Name, 
           [Type], 
           CAST('' AS nvarchar(MAX)) AS [Path]
    FROM FilesAndFolders
    WHERE ParentID IS NULL
    UNION ALL 
    SELECT FF.FileID, 
           FF.FolderID, 
           FF.Name, 
           FF.[Type], 
           T.[Path]+T.[Name]+'/'
    FROM FilesAndFolders FF
    JOIN Tree T ON T.FolderID = FF.ParentID
)
SELECT FileID, FolderID, [Path]+[Name] FullName, [Type]
FROM Tree
于 2012-06-20T15:18:03.957 回答