У меня есть две таблицы
CREATE TABLE [dbo].[Folder](
[FolderID] [int] IDENTITY(1,1) NOT NULL,
[FolderName] [varchar](50) NOT NULL,
[ParentFolderID] [int] NULL
)
и
CREATE TABLE [dbo].[FolderSubscription](
[UserID] [int] NOT NULL,
[FolderID] [int] NOT NULL,
[IncludeSubfolders] [bit] NOT NULL
)
Поле [IncludeSubfolders]
означает, что если пользователь также подписан на подпапки.
Моя цель - узнать, подписался ли пользователь на определенную папку.
Я попробовал следующий рекурсивный запрос.но не повезло
DECLARE @FolderID INT=2,
@UserID INT= 1
WITH SubFolderS_CTE (FolderID,ParentFolderID,FolderSubscription)
AS
(
SELECT
Folder.FolderID,
Folder.ParentFolderID,
DMSsubscription.IncludeSubfolders
FROM
FolderSubscription
INNER JOIN
Folder
ON
Folder.FolderID = FolderSubscription.FolderID
WHERE
FolderSubscription.FolderID = @FolderID AND FolderSubscription.UserID = @UserID
UNION ALL
SELECT
folder.FolderID,
folder.ParentFolderID
,sub.IncludeSubfolders
FROM
FolderSubscription sub
INNER JOIN
Folder folder
ON folder.FolderID = sub.FolderID
INNER JOIN
SubFolderS_CTE
ON folder.FolderID = SubFolderS_CTE.ParentFolderID
)
SELECT * FROM SubFolderS_CTE
Данные ..
FolderID | FolderName | ParentFolderID
----------------------------------------
1 | Po | NULL
2 | Tigress | 1
3 | Mantis | 2
Подписка ..
UserID | FolderID | IncludeChildren
----------------------------------------
1 | 2 | 1