For simplicity my schema:
Folders table (FolderId, ParentFolderId)
DeviceFolderProperties table (FolderId, LogDataRetentionDaysEvent)
Not every folder has a retention day. However this is an inherited value. How can you write something in SQL to return every folder and its retention day and if that is null its inherited value.
There are multiple levels to inheritance, so it will need to walk the tree.
This is what I have tried:
;
WITH [cte]
AS
(
SELECT f.FolderId, f.ParentFolderId, dfp.LogDataRetentionDaysEvent
FROM [Folders] f
LEFT JOIN DeviceFolderProperties dfp
ON f.FolderId = dfp.FolderId
),
[cte_collapse]
AS --recurse where r days is null
(
SELECT c.FolderId, c.ParentFolderId, c.LogDataRetentionDaysEvent
FROM [cte] c
WHERE c.LogDataRetentionDaysEvent IS NULL
UNION ALL
SELECT c.FolderId, c.ParentFolderId, ISNULL(c.LogDataRetentionDaysEvent, cc.LogDataRetentionDaysEvent)
FROM [cte] c
JOIN [cte_collapse] cc ON cc.FolderId = c.ParentFolderId
)
SELECT
*
FROM
[cte_collapse]