WITH Ancestors AS
             (SELECT @ParentTaskId AS [Id]
UNION ALL
SELECT p.[ParentTaskId]
FROM [dbo].[ParentTaskExecutions] p
    INNER JOIN Ancestors a
ON a.[Id] = p.[ChildTaskId])
SELECT CASE
           WHEN @ChildTaskId = @ParentTaskId THEN 1
           WHEN EXISTS (SELECT 1
                        FROM Ancestors
                        WHERE [Id] = @ChildTaskId) THEN 1
           ELSE 0 END OPTION (MAXRECURSION 100);
