CTE创建对象树

时间:2012-06-20 15:01:37

标签: recursion common-table-expression

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

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

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

1 个答案:

答案 0 :(得分: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