I just can't wrap my head around this... I have 3 related tables in SQL Server:
FileIds
Id
FileName
FolderIds
Id
ParentId
FolderName
FileInfo
Id
FolderId
FileId
FileAuthorId
FileClientId
Sample data:
FileIds
1, Gartner
2, Parker
3, Stepp
FolderIds
1, null, Georgia
2, 1, Atlanta
3, 2, Terminus
4, 3, Suite 1500
5, 4, David Williams
6, 4, Lisa Davidson
7, 2, LaGrange
8, 7, Dena Pressley
FileInfo
1, 8, 1, null, null
2, 5, 2, null, null
3, 6, 3, null null
Sample output from view:
Georgia.Atlanta.LaGrange.Dena Pressley:Gartner, null, null
Georgia.Atlanta.Terminus.Suite 1500.David Williams:Parker, null, null
Georgia.Atlanta.Terminus.Suite 1500.Lisa Davidson:Stepp, null, null
While this is not for a file directory, it is laid out like one (replace .'s and :'s with \\'s) and I need to create a view that shows the full path... It is easy to put the pieces together in code such as C#, but I can't seem to figure out how to do it in SQL. I have looked up SQL Server's recursive CTE and I'm just not getting it.
This should allow you to start using recursive CTE:
In here I'm only adding the folders, but you can do exactly the same, in another CTE to add the files
WITH folders (Id, ParentId, FolderName)
AS (
-- In here you select the first LEVEL
SELECT Id, ParentId, FolderName FROM FolderIds
WHERE ParentId IS NULL
UNION ALL
-- In here you join the previous LEVEL with new relative LEVELS
SELECT b.Id, b.ParentId, a.FolderName CONCAT ' ' CONCAT b.FolderName
FROM folders a
INNER JOIN FolderIds b
ON a.Id = b.ParentId
)
SELECT *
FROM folders
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.