获取文件夹的树结构

时间:2010-09-30 11:13:09

标签: sql-server

我的数据库“文件夹”表中有以下文件夹:

  • Folder1中
  • FOLDER2
  • Folder3
  • Folder4

文件夹的路径 - Folder1 \ Folder2 \ Folder3 \ Folder4

当我点击Folder3时,我必须得到路径为 - Folder1 \ Folder2 \ Folder3.为此我传递了Folder3的folderID。

我怎样才能得到这个结果?

表结构

FolderiD FolderName ParentID

1 Folder1 0

2 Folder2 1

3 Folder3 2

4 Folder4 3

2 个答案:

答案 0 :(得分:1)

您可以使用递归CTE。

/*Test Data*/
SELECT *
INTO #Folders FROM 
(SELECT 1 AS FolderId, 0 AS ParentId, 'Folder1' AS FolderName UNION ALL
SELECT 2 AS FolderId, 1 AS ParentId, 'Folder2' AS FolderName UNION ALL
SELECT 3 AS FolderId, 2 AS ParentId, 'Folder3' AS FolderName UNION ALL
SELECT 4 AS FolderId, 3 AS ParentId, 'Folder4' AS FolderName ) F


/*Query*/    
;WITH fl AS
     ( SELECT 1 AS Level,
             FolderId   ,
             ParentId   ,
             FolderName ,
             CAST(FolderName AS nvarchar(MAX)) AS F
     FROM    #Folders
     WHERE   FolderId = 3

     UNION ALL

     SELECT Level +1    ,
            f.FolderId  ,
            f.ParentId  ,
            f.FolderName,
            CAST(f.FolderName + '/' + fl.F AS nvarchar(MAX))
     FROM   fl
            JOIN #Folders f
            ON     fl.ParentId = f.FolderId
     )
SELECT   top (1) F
FROM     fl
ORDER BY Level DESC

drop table #Folders

答案 1 :(得分:0)

以下是我在此处重复此问题时给出的答案:How to query hierarchical information with SQL-Server 2000?

/* Set up test data */
create table Folders (
    FolderID int,
    FolderName varchar(10),
    ParentID int
)

insert into Folders
    (FolderID, FolderName, ParentID)
    select 1,'Folder1',0 union all
    select 2,'Folder2',1 union all
    select 3,'Folder3',2 union all
    select 4,'Folder4',3        
go

/* Create function */
create function dbo.CreateFolderPath (@FolderID int)
returns varchar(1000)
as
begin
    declare @ParentID int
    declare @FolderPath varchar(1000)
    set @FolderPath = ''

    select @ParentID = ParentID
        from Folders
        where FolderID = @FolderID

    while @ParentID<>0 begin
        select @FolderPath = FolderName + '\' + @FolderPath, @ParentID = ParentID
            from Folders
            where FolderID = @ParentID
    end /* while */

    return @FolderPath
end /* function */
go

/* Demo the function */
select dbo.CreateFolderPath(4)

/* Clean up after demo */
drop function dbo.CreateFolderPath
drop table Folders