我的数据库的“文件夹”表中有以下文件夹:
文件夹的路径 - Folder1\Folder2\Folder3\Folder4
当我单击 Folder3 时,我必须将路径设为 - Folder1\Folder2\Folder3。为此,我传递了 Folder3 的 folderID。
我怎样才能得到这个结果?
1 Folder1 0
2 Folder2 1
3 Folder3 2
4 Folder4 3
这是我在这里重复这个问题时给出的答案:
/* 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