How to query hierarchical information with SQL-Server 2000?

烂漫一生 提交于 2019-12-12 18:37:35

问题


I've got a table Folders with hierarchical information about folders:

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

For Folder4 I would like to get the parent folders in the following format:

Folder1\Folder2\Folder3\

Note: I have asked this before, but I cannot use CTE because I am using SQL-Server 2000.


回答1:


I've written a SQL function that should return what you're looking for.

/* 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


来源:https://stackoverflow.com/questions/3863401/how-to-query-hierarchical-information-with-sql-server-2000

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!