AS
BEGIN
SET NOCOUNT ON


IF OBJECT_ID('dbo.cacheEZViewer_Usage_DDCL') IS NOT NULL  DROP TABLE dbo.cacheEZViewer_Usage_DDCL 
SELECT    Id, ddclElemName, CreateDate, UpdateDate,
	     pth1.PathStr AS ddclPath,		
		StartRow, StartCol, EndRow, EndCol, Description, DdsTypeId,
		PropertyName, PropertyId, pth1.PathStr AS PropertyPath,
		PropertyStartRow, PropertyStartCol, PropertyEndRow, PropertyEndCol, IsIDMSX
INTO dbo.cacheEZViewer_Usage_DDCL
FROM(
		  SELECT  DISTINCT
		          core.Id,
				core.ddclElemName,
				core.CreateDate,
				core.UpdateDate,
				core.StartRow,
				core.StartCol,
				core.EndRow,
				core.EndCol,
				core.Description,
				core.DdsTypeId,
				CASE WHEN core.Flag1 = 1 AND t.ElementName IS NOT NULL THEN  1
				     ELSE 0
					END AS IsIDMSX, 
			    DDCLProperty.Name AS PropertyName,
			    DDCLProperty.Id AS PropertyId,
			    PropertySourceInfo.StartRow AS PropertyStartRow,
			    PropertySourceInfo.StartCol AS PropertyStartCol,
			    PropertySourceInfo.EndRow AS PropertyEndRow,
			    PropertySourceInfo.EndCol AS PropertyEndCol,
			    prog.PathID
		  FROM ( 
				SELECT  -- core data 
							DDCLElement.Id,
							DDCLElement.Name AS ddclElemName,
							DDCLVersionInfo.CreateDate,
							DDCLVersionInfo.UpdateDate,
							DDCLSourceInfo.StartRow,
							DDCLSourceInfo.StartCol,
							DDCLSourceInfo.EndRow,
							DDCLSourceInfo.EndCol,
							DDCLDdsType.Description,
							DDCLElement.DdsTypeId,
							CASE WHEN  DDCLElement.DdsTypeId IN (3, 10) THEN 1
							     ELSE 0
                                   END AS Flag1, 
                                   DDCLSourceInfo.ProgramId
					   FROM dbo.DDCLElement
						   INNER JOIN dbo.DDCLVersionInfo ON DDCLElement.VersionInfoId = DDCLVersionInfo.Id
						   INNER JOIN dbo.DDCLSourceInfo ON DDCLElement.SourceInfo = DDCLSourceInfo.Id
						   INNER JOIN dbo.DDCLDdsType ON DDCLElement.DdsTypeId = DDCLDdsType.Id
					   WHERE DDCLElement.islocal = 'false'
			   )core
			    INNER JOIN ( -- programs
						       SELECT p.ProgramID, occ.PathID 
							  FROM dbo.Occurrences occ
								   INNER JOIN dbo.Programs p ON p.OccurID = occ.OccurID 
							  WHERE occ.PathID IS NOT NULL
						) prog ON core.ProgramId = prog.ProgramID  
			   LEFT OUTER JOIN dbo.DDCLProperty ON DDCLProperty.ElementId = core.Id
	             LEFT OUTER JOIN dbo.DDCLSourceInfo AS PropertySourceInfo ON DDCLProperty.SourceInfo = PropertySourceInfo.Id
			   LEFT OUTER JOIN (SELECT ElementName FROM dbo.EZViewer_IDMSX_View GROUP BY ElementName) t ON t.ElementName = core.ddclElemName
		  )c
		   LEFT OUTER JOIN  dbo.Paths pth1 ON pth1.PathID = c.PathID

 
END