tags:

views:

64

answers:

2

I have the following folders in the table 'Folders' in my database:

  • Folder1
  • Folder2
  • Folder3
  • Folder4

The path of the folders - Folder1\Folder2\Folder3\Folder4

When i click on Folder3,i have to get the path as - Folder1\Folder2\Folder3.For this i am passing the folderID of Folder3.

How can i get this result ?

table structure

FolderiD FolderName ParentID

1 Folder1 0

2 Folder2 1

3 Folder3 2

4 Folder4 3

+1  A: 

You can use a recursive CTE for this.

/*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
Martin Smith
it will work in sql 2000?
Adu
@Adu - Nope. You would need to use a `WHILE` loop for that or recursively call a table valued function.
Martin Smith
A: 

Here's the answer I gave when this question was repeated here: 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
Joe Stefanelli