ALTER FUNCTION [dbo].[ftCanReadKnowledge](@userId int)
RETURNS @retTable TABLE
(
	SectionId int NULL,
	ArticleId int NOT NULL
)
AS
BEGIN
	DECLARE @RightsTable TABLE (SectionId INT)
	INSERT INTO @RightsTable
		SELECT liHdSectionManagerHdSectionId AS SectionId FROM vHdSectionManager vsa
		WHERE liHdSectionManagerPersonId = @userId
		UNION
		SELECT liHdSectionOperatorHdSectionId AS SectionId FROM vHdSectionOperator vsa
		WHERE liHdSectionOperatorPersonId = @userId
		UNION
		SELECT liHdSectionSolverHdSectionId AS SectionId FROM vHdSectionSolver vsa
		WHERE liHdSectionSolverPersonId = @userId
		UNION
		SELECT SectionId AS SectionId FROM vHdSectionExceptionalSolver vsa
		WHERE PersonId = @userId
		UNION
		SELECT SectionId FROM vHdSectionReader vsa
		WHERE PersonId = @userId

	INSERT INTO @retTable
		SELECT ahs.SectionId, ahs.ArticleId 
		FROM @RightsTable AS KbManagedSections
		LEFT JOIN dbo.ArticleHdSection as ahs ON ahs.SectionId = KbManagedSections.SectionId
		WHERE ahs.ArticleId IS NOT NULL

		UNION

		SELECT ahs.SectionId, ahs.ArticleId 
		FROM (
			SELECT liSlaAccessHdSectionId as SectionId FROM vSlaAccess vsa
			WHERE liSlaAccessPersonId = @userId
		) AS KbManagedSections
		LEFT JOIN dbo.ArticleHdSection as ahs ON ahs.SectionId = KbManagedSections.SectionId
		LEFT JOIN tArticle AS article ON article.iArticleId = ahs.ArticleId
		WHERE ahs.ArticleId IS NOT NULL
			AND article.Published = 1
	
	IF (EXISTS(SELECT SectionId FROM @RightsTable))
		INSERT INTO @retTable
		SELECT DISTINCT NULL as SectionId, iArticleId as ArticleId 
		FROM tArticle 
		WHERE iArticleId NOT IN (select ArticleId from ArticleHdSection) 
			OR iArticleId IN (select ArticleId from ArticleHdSection where SectionId IS NULL)
	
	RETURN
END;