AS 
set NOCOUNT ON;
IF OBJECT_ID('tempdb..#programWithAlias') IS NOT NULL DROP TABLE #programWithAlias
			 SELECT Programs.ProgramID, pa.AliasName AS ProgramName, Programs.ProgramTypeID, Programs.OccurID
			 INTO #programWithAlias 
			 FROM  dbo.Programs INNER JOIN dbo.ProgramAliases pa  ON Programs.ProgramID = pa.ProgramId and pa.AliasType = 0
			 	AND (pa.ProgramID IN (Select * from #numeric_param_temp))

SELECT     pa.ProgramID, pa.ProgramName, dbo.Paths.PathStr, Occurrences_1.StartRow, 
                      CASE WHEN dbo.Paths.PathID = Occurrences_1.PathID THEN 0 ELSE - 1 END AS IsCopy
FROM         dbo.ProgramElements INNER JOIN
                      dbo.Occurrences AS Occurrences_1 ON dbo.ProgramElements.OccurId = Occurrences_1.OccurID INNER JOIN
                      #programWithAlias pa ON dbo.ProgramElements.ProgId = pa.ProgramID INNER JOIN
                      dbo.Paths ON Occurrences_1.PathID = dbo.Paths.PathID INNER JOIN
                      dbo.Occurrences ON pa.OccurID = dbo.Occurrences.OccurID
WHERE     (dbo.ProgramElements.ElementType IN (1, 2, 3, 4)) AND (pa.ProgramID IN (Select * from #numeric_param_temp)) AND (Occurrences_1.StartCol <> 8)
UNION
SELECT     DISTINCT pa.ProgramID, pa.ProgramName, dbo.Paths.PathStr, dbo.Occurrences.StartRow, 
                      CASE WHEN dbo.Paths.PathID = Occurrences_1.PathID THEN 0 ELSE - 1 END AS IsCopy
FROM         dbo.Paths INNER JOIN
                      dbo.Occurrences ON dbo.Paths.PathID = dbo.Occurrences.PathID INNER JOIN
                      #programWithAlias pa INNER JOIN
                      dbo.Sections ON pa.ProgramID = dbo.Sections.ProgramID INNER JOIN
                      dbo.Occurrences AS Occurrences_1 ON pa.OccurID = Occurrences_1.OccurID ON dbo.Occurrences.OccurID = dbo.Sections.OccurID
WHERE     (pa.ProgramID IN (Select * from #numeric_param_temp)) AND (dbo.Occurrences.StartCol <> 8)
UNION
SELECT DISTINCT 
                      TOP (100) PERCENT pa.ProgramID, pa.ProgramName, dbo.Paths.PathStr, dbo.Occurrences.StartRow, 
                      CASE WHEN dbo.Paths.PathID = Occurrences_1.PathID THEN 0 ELSE - 1 END AS IsCopy
FROM         dbo.Paths INNER JOIN
                      dbo.Occurrences ON dbo.Paths.PathID = dbo.Occurrences.PathID INNER JOIN
                      dbo.Paragraphs ON dbo.Occurrences.OccurID = dbo.Paragraphs.OccurID INNER JOIN
                      dbo.Occurrences AS Occurrences_1 INNER JOIN
                      #programWithAlias pa ON Occurrences_1.OccurID = pa.OccurID ON dbo.Paragraphs.ProgramID = pa.ProgramID
WHERE     (pa.ProgramID IN (Select * from #numeric_param_temp)) AND (dbo.Occurrences.StartCol <> 8) AND (dbo.Paragraphs.ParaName NOT LIKE '%_FIRST_SENTENCES')
ORDER BY pa.ProgramName, dbo.Paths.PathStr, Occurrences_1.StartRow
 