admin

如何使用SQL-Server 2000查询层次结构信息?

sql

我有一张表,Folders其中包含有关文件夹的层次结构信息:

FolderID     FolderName     ParentID
1            Folder1        0
2            Folder2        1
3            Folder3        2
4            Folder4        3

因为Folder4我想以以下格式获取父文件夹:

Folder1\Folder2\Folder3\

注意:之前已经问过这个问题,但是由于使用SQL-Server 2000,所以不能使用CTE。


阅读 171

收藏
2021-07-01

共1个答案

admin

我编写了一个SQL函数,该函数应返回您要查找的内容。

/* 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
2021-07-01