AS
BEGIN
SET NOCOUNT ON

  							     
 IF OBJECT_ID('tempdb..#prg') IS NOT NULL DROP TABLE #prg
  SELECT p.ProgramId, pth.PathStr
  INTO #prg
  FROM  dbo.Programs p
        INNER JOIN dbo.Occurrences occ ON p.OccurID = occ.OccurID
        INNER JOIN dbo.Paths pth ON occ.PathID = pth.PathID


IF OBJECT_ID('dbo.cacheEZViewer_Usage_FilesInDDCL') IS NOT NULL  DROP TABLE dbo.cacheEZViewer_Usage_FilesInDDCL 
SELECT FileName, FileID, FileStartRow, FileEndRow, FileStartCol, FileEndCol, ddclfilePath, ddclElemName,
       Id, StartRow, EndRow, StartCol, EndCol, Description, DdsTypeId, ddclPath, 
	  PropertyName, PropertyID, PropertyPath, PropertyStartRow, PropertyStartCol, PropertyEndRow, PropertyEndCol
INTO   dbo.cacheEZViewer_Usage_FilesInDDCL
FROM
(
    SELECT DDCLValue.referencename AS FileName,
		 DDCLElement_1.Id AS FileID,
		 DDCLFileInfo.StartRow AS FileStartRow,
		 DDCLFileInfo.EndRow AS FileEndRow,
		 DDCLFileInfo.StartCol AS FileStartCol,
		 DDCLFileInfo.EndCol AS FileEndCol,
		 PrgForDDCLFile.PathStr AS ddclfilePath,
		 DDCLElement.name AS ddclElemName,
		 DDCLElement.Id,
		 DDCLElementInfo.StartRow,
		 DDCLElementInfo.EndRow,
		 DDCLElementInfo.StartCol,
		 DDCLElementInfo.EndCol,
		 DDCLElemType.Description,
		 DDCLElement.DdsTypeId,
		 PrgForDDCLElem.PathStr AS ddclPath,
		 DDCLProperty.name AS PropertyName,
		 DDCLProperty.Id AS PropertyID,
		 PrgForDDCLElem.PathStr AS PropertyPath,
		 PropertySourceInfo.StartRow AS PropertyStartRow,
		 PropertySourceInfo.StartCol AS PropertyStartCol,
		 PropertySourceInfo.EndRow AS PropertyEndRow,
		 PropertySourceInfo.EndCol AS PropertyEndCol
    FROM dbo.DDCLElement
	    INNER JOIN dbo.DDCLProperty ON DDCLElement.id = DDCLProperty.elementid
	    INNER JOIN dbo.DDCLValue ON DDCLProperty.id = DDCLValue.propertyid       
	    INNER JOIN dbo.DDCLSourceInfo AS DDCLElementInfo ON DDCLElement.SourceInfo = DDCLElementInfo.Id
	    INNER JOIN dbo.DDCLDdsType AS DDCLElemType ON DDCLElemType.Id = DDCLElement.DdsTypeId
	    LEFT OUTER JOIN dbo.DDCLSourceInfo AS PropertySourceInfo ON DDCLProperty.SourceInfo = PropertySourceInfo.Id
	    LEFT OUTER JOIN dbo.DDCLElement AS DDCLElement_1 ON DDCLElement_1.DdsTypeId = DDCLValue.referenceddstypeid
												 AND DDCLValue.ReferenceName = DDCLElement_1.Name
	    LEFT OUTER JOIN dbo.DDCLSourceInfo AS DDCLFileInfo ON DDCLElement_1.SourceInfo = DDCLFileInfo.Id
	    LEFT OUTER JOIN #prg AS PrgForDDCLFile ON DDCLFileInfo.ProgramId = PrgForDDCLFile.ProgramID
	    LEFT OUTER JOIN #prg AS PrgForDDCLElem ON DDCLElementInfo.ProgramId = PrgForDDCLElem.ProgramID
    WHERE DDCLElement.islocal = 'false'
		AND DDCLElement.DdsTypeId IN (27, 28)
		AND DDCLValue.referenceddstypeid = 12
		AND DDCLValue.ValueTypeId IN (2, 4)
)s

 
END