如何使用SQL-Server 2000查询分层信息?

时间:2010-10-05 12:00:59

标签: sql sql-server sql-server-2000

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

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

对于Folder4我想以下列格式获取父文件夹:

Folder1\Folder2\Folder3\

注意:我问了这个before,但我不能使用CTE,因为我使用的是SQL-Server 2000.

1 个答案:

答案 0 :(得分:1)

我编写了一个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