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

SELECT 
	- 1 AS ResourceID, 
	'NA' AS Name, 
	Statements.Description, 
	OccurrencesStmt.StatementType, 
	pa.ProgramName, 
	OccurrencesStmt.StartRow, 
	OccurrencesStmt.StartCol, 
	OccurrencesStmt.EndRow, 
	OccurrencesStmt.EndCol, 
	Paths.PathStr, 
	OccurrencesStmt.OccurID, 
	pa.ProgramID, 
	Paragraphs.ParaID, 
	Paragraphs.ParaName 
FROM #programWithAlias pa 
	INNER JOIN OccurrencesStmt ON pa.ProgramID = OccurrencesStmt.ProgID 
	
	INNER JOIN Statements ON OccurrencesStmt.StatementType = Statements.StatementType
	
	INNER JOIN Paths ON OccurrencesStmt.PathID = Paths.PathID 
	
	INNER JOIN Paragraphs ON OccurrencesStmt.ParaID = Paragraphs.ParaID 
WHERE (pa.ProgramTypeID = 1) 
	AND (pa.ProgramName in (Select * from #string_param_temp))
	AND (OccurrencesStmt.StatementType IN (1838, 1839)) 
	AND (OccurrencesStmt.OccurID NOT IN (SELECT OccurID 
						FROM StatementReference 
						WHERE (ResourceType = 101)))

UNION 

SELECT 
	StatementReference.ResourceID, 
	Resources.Name, 
	Statements.Description, 
	OccurrencesStmt.StatementType, 
	pa.ProgramName, 
	StatementReference.StartRow, 
	StatementReference.StartCol, 
	StatementReference.StartRow AS EndRow, 
	StatementReference.StartCol AS EndCol, 
	Paths.PathStr, 
	OccurrencesStmt.OccurID, 
	pa.ProgramID, 
	Paragraphs.ParaID, 
	Paragraphs.ParaName 
FROM #programWithAlias pa 
	INNER JOIN OccurrencesStmt ON pa.ProgramID = OccurrencesStmt.ProgID 
	
	INNER JOIN StatementReference ON OccurrencesStmt.OccurID = StatementReference.OccurID 
	
	INNER JOIN Statements ON StatementReference.StatementType = Statements.StatementType 
	
	INNER JOIN Resources ON StatementReference.ResourceID = Resources.ResourceID 

	INNER JOIN Paths ON OccurrencesStmt.PathID = Paths.PathID 
	
	INNER JOIN Paragraphs ON OccurrencesStmt.ParaID = Paragraphs.ParaID 
WHERE (pa.ProgramTypeID = 1) 
	AND (pa.ProgramName in (Select * from #string_param_temp))
	AND (OccurrencesStmt.StatementType IN (1838, 1839))
	AND (StatementReference.ResourceType = 101) 						