
PRINT N'Altering Procedure [sAlert].[pAlertLogAdd]...';


GO
CREATE OR ALTER PROCEDURE [sAlert].[pAlertLogAdd]  
   
 @rXML nvarchar(max),  
 @rOrgId smallint  
   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
--BEGIN TRY  
   
 --BEGIN TRANSACTION  
 DECLARE @loXML XML;  
  
  SET @rXML=REPLACE(@rXML,'&','AND');  
 SET @loXML = CAST(@rXML AS XML);  
  
 DECLARE @lCount INT  
 DECLARE @lInterrorCode INT  
 --  @intDoc INT  
 --EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXML  
   
 DECLARE @lNextNumber BIGINT    
 DECLARE @lFromNextNumber BIGINT    
 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAlert.tAlertLog', 0, 1, 1,@outNextNumber = @lNextNumber output  
   
 SET @lFromNextNumber=@lNextNumber-1  
 INSERT INTO sAlert.tAlertLog  
  (  
   Id,  
   ContactId,  
   AlertMessage,  
   AlertSubject,  
   StatusId,  
   ResultMessage,  
   SMSType,  
   SourceEvent,  
   EventId,  
   EventName,  
   AlertModeId,  
   OrgId,  
   CreatedUserId,  
   CreatedDateTime,  
   UserId,  
   IsDaily,  
   IsWeekly,  
   IsMonthly,  
   ProviderAppointmentId , 
   ClaimIntimationDetailId
  )  
 SELECT  
   @lFromNextNumber + ROW_NUMBER() OVER(ORDER BY T.c.value('ContactId[1]','nvarchar(50)')),  
   T.c.value('ContactId[1]','nvarchar(500)') AS ContactId,  
   [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('AlertMessage[1]','nvarchar(max)')) AS AlertMessage,  
   [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('AlertSubject[1]','nvarchar(255)')) AS AlertSubject,  
   T.c.value('StatusId[1]','int') AS StatusId,  
   [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('ResultMessage[1]','nvarchar(255)')) AS ResultMessage,  
   T.c.value('SMSType[1]','nvarchar(50)') AS SMSType,  
   T.c.value('SourceEvent[1]','nvarchar(50)') AS SourceEvent,  
   T.c.value('EventId[1]','int') AS EventId,   
   [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('EventName[1]','nvarchar(100)')) AS EventName,  
   T.c.value('AlertModeId[1]','tinyint') AS AlertModeId,  
   @rOrgId,  
   CASE WHEN T.c.value('CreatedUserId[1]','bigint') = 1 THEN sCommon.fGetBigIntIdForOrg(T.c.value('CreatedUserId[1]','bigint'),@rOrgId) ELSE T.c.value('CreatedUserId[1]','bigint') END,  
     
   sCommon.fGetDate(),  
   T.c.value('UserId[1]','bigint') AS UserId,  
   case when T.c.value('Flag[1]','int') = 1 then 1 ENd,  
   case when T.c.value('Flag[1]','int') = 2 then 1 ENd,  
   case when T.c.value('Flag[1]','int') = 3 then 1 ENd,  
     T.c.value('ProviderAppointmentId[1]','bigint') AS ProviderAppointmentId  ,
	  T.c.value('ClaimIntimationDetailId[1]','bigint') AS ClaimIntimationDetailId  

    
 FROM  
  @loXML.nodes('/Table/AlertLog')T(c)  
 -- OPENXML (@intDoc, '/Table/AlertLog', 1)  
 --WITH  
 --(  
 -- ContactId nvarchar(50) 'ContactId',  
 -- AlertMessage nvarchar(255) 'AlertMessage',  
 -- AlertSubject nvarchar(255) 'AlertSubject',  
 -- StatusId int 'StatusId',  
 -- ResultMessage nvarchar(255) 'ResultMessage',  
 -- SMSType nvarchar(50) 'SMSType',  
 -- SourceEvent nvarchar(50) 'SourceEvent',  
 -- EventId int 'EventId',  
 -- AlertModeId tinyint 'AlertModeId',  
 -- CreatedUserId bigint 'CreatedUserId'  
 --)  
  
 SELECT @lCount = COUNT(1)  
  FROM   
  @loXML.nodes('/Table/AlertLog')T(c)  
  --OPENXML (@intDoc, '/Table/AlertLog', 1)  
  --   WITH ( ContactId nvarchar(50))  
  SET @lNextNumber  = @lCount + @lFromNextNumber   
    
  EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sAlert.tAlertLog', @rCurrentNumber = @lNextNumber   
    
  --EXEC sp_xml_removedocument @intDoc  
    
  SELECT 1 AS Result,@lFromNextNumber+1 AS FromId,@lNextNumber AS ToId  
   
 -- COMMIT TRANSACTION  
    
 --END TRY  
   
 --BEGIN CATCH   
 -- ROLLBACK TRANSACTION  
 -- SELECT -1 AS Result  
 --END CATCH  
END
GO
PRINT N'Altering Procedure [sSupport].[pAHCCounsellingListGet]...';


GO

CREATE OR ALTER PROCEDURE [sSupport].[pAHCCounsellingListGet]
 @rOrgId smallint,      
 @rProviderId bigint = 0,      
 @rRoundGroupId bigint = 0,      
 @rHealthIndicatorId bigint = 0,      
 @rEmployeeCode nvarchar(100) = '',      
 @rEmployeeName nvarchar(100) = '',      
 @rStatusId int = 0,      
 @rSectorId varchar(100) = '',        
 @rVerticalId varchar(100) = '',        
 @rCompanyGroupId varchar(100) = '',        
 @rEmployeeCompanyId varchar(100) = '',        
 @rLocationMainGroupId varchar(100) = '',        
 @rLocationSubGroupId varchar(100) = '',        
 @rLocationId varchar(100) = '',        
 @rFunctionId varchar(100) = '',        
 @rDepartmentGroupId varchar(100) = '',        
 @rDepartmentId varchar(100) = '',        
 @rEmployeeTypeId varchar(100) = '',        
 @rGradeId varchar(100) = '',      
 @rTargetGroupId varchar(100) = '',      
 @rEmployeeDesignationId varchar(100) = '',      
 @rSectorIdEntity nvarchar(max)= '',      
 @rVerticalIdEntity nvarchar(max)= '',      
 @rCompanyGroupIdEntity nvarchar(max)= '',      
 @rCompanyIdEntity nvarchar(max)= '',       
 @rGradeIdEntity nvarchar(max)= '',      
 @rFunctionIdEntity nvarchar(max)= '',      
 @rStoreLocationIdEntity nvarchar(max)= '',      
 @rEmployeeTypeGroupId int = 0,      
 @rDoctorId bigint = 0,    
 @rCode NVARCHAR(MAX) = ''     
AS      
SET NOCOUNT ON      
BEGIN
 declare @lAbnormalFindingsOrHealthIndicatorConfigVal varchar(5); 
            
 select @lAbnormalFindingsOrHealthIndicatorConfigVal = sConfig.fConfigurationValueGet('Provider.AbnormalFindingsOrHealthIndicatorParam',@rOrgId,0,0,0);

  WITH LatestAlertLog AS     (           
   SELECT ProviderAppointmentId, CreatedDateTime as CreatedDate, ROW_NUMBER() OVER (PARTITION BY ProviderAppointmentId   
   ORDER BY CreatedDateTime DESC) AS RowNum           
   FROM sAlert.tAlertLog       
 )  
 SELECT PA.Id,EM.Id as EmployeeId,EM.Code as EmployeeCode,SCT.Id as BusinessSectorId,      
 ISNull(EM.FirstName, '') + ' ' + ISNull(EM.MiddleName, '') + ' ' + ISNull(EM.LastName, '') as EmployeeName,      
 MobileNumber = ISNULL(ECD.MobileNumber, ''),Department = ISNULL(ODM.Title, ''), ECD.CompanyEmail, EXM.ExaminationDate,    
 PA.AppointmentNumber, PA.AppointmentDate, PA.ProviderId, PM.Title as ProviderName,      
 PA.StatusId, SM.Title as Status, PA.RejectReason, AD.name as FileName, AD.configid as configId, ISNULL(PA.IsExcelUploaded, 0) as IsExcelUploaded,      
 Details.[SONOGRAPHY] as Sonography, Details.[XRAY] as Xray, Details.[ECG] as ECG, Details.[ECHO] as Echo, Details.[TMT] as TMT,      
 CASE WHEN @lAbnormalFindingsOrHealthIndicatorConfigVal = 'True' THEN AF.AbnormalFindingHtml
      ELSE [dbo].[fGetDiagnosisDetailsofExamination](EXM.Id) END AS AbnormalFindings, 
 SCT.Title as Business, LM.Id as LocationId, LM.Title as [Location], SLM.Title as [ExaminationStoreLocation],     
 PA.CounsellingRemark as CounsellingRemark, PA.CounsellingRemarkId as CounsellingRemarkId, PA.CounsellingDate as CounsellingDate,PA.NonPathoParameters as CSVNonPathoParameters,      
 ISNULL(EMM.FirstName, '') + ' ' + ISNULL(EMM.LastName, '') AS AssignByDoctorName,PA.AssignDate, EJD.EmployeeStoreLocationId, ISNULL(PA.DocumentReuploadRemark, '') as DocumentReuploadRemark,    
 PA.PatientSourceId,PA.SetupId,MT.Title as ExaminationType,AL.CreatedDate,ISNULL(EMM1.FirstName, '') + ' ' + ISNULL(EMM1.LastName, '') AS AssignToDoctorName,ISNULL(ECD1.ExtensionNo,'') as DoctorExtensionNo
 FROM [sSupport].[tProviderAppointment] PA WITH (NOLOCK)      
 INNER JOIN [sExamination].[tExamination] EXM WITH (NOLOCK) ON EXM.ParticipantSourceId = PA.PatientSourceId AND EXM.SetupId = PA.SetupId      
 INNER JOIN sIp.tStoreLocationMaster SLM WITH (NOLOCK) ON SLM.Id = EXM.StoreLocationId    
 LEFT JOIN [sExamination].[tDiagnosis] DIA WITH (NOLOCK) ON DIA.SourceId = EXM.Id      
 INNER JOIN [sHrm].[tEmployeeMaster] EM WITH (NOLOCK) ON EM.Id = PA.PatientSourceId    
 INNER JOIN [sExamination].[tSetupMaster] SEM WITH (NOLOCK) ON SEM.Id = PA.SetupId    
 INNER JOIN sExamination.tSetupEmployee SE ON SE.EmployeeId = PA.PatientSourceId and SE.SetupId = PA.SetupId    
 LEFT JOIN sExamination.tSubTypeMaster ST on SEM.SubTypeId = ST.Id  LEFT JOIN sExamination.tMainTypeMaster MT on ST.MainTypeId = MT.Id    
 LEFT JOIN [sHrm].[tEmployeeMaster] EMM WITH (NOLOCK) ON EMM.Id = PA.AssignByDoctorId      
 LEFT JOIN [sHrm].[tEmployeeMaster] EMM1 WITH (NOLOCK) ON EMM1.Id = PA.AssignToDoctorId      
 LEFT JOIN [sSupport].[tProviderAppointmentDocument] AD WITH (NOLOCK) ON AD.ProviderAppointmentId = PA.Id      
 INNER JOIN [sSupport].[tProviderMaster] PM WITH (NOLOCK) ON PM.Id = PA.ProviderId      
 INNER JOIN sHrm.tEmployeeJobDetail EJD WITH (NOLOCK) ON EM.Id = EJD.EmployeeId      
 INNER JOIN [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id = EJD.EmployeeTypeId       
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id = EJD.EmployeeCompanyId      
 INNER JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id = ECM.CompanyGroupId      
 INNER JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID = CGM.VerticalId      
 INNER JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id = VTM.SectorId      
 INNER JOIN sCommon.tLocationMaster LM WITH (NOLOCK) ON LM.Id = EJD.EmployeeLocationId      
 LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LM.LocationSubGroupId          
 LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId      
 LEFT JOIN sCommon.tStatusMaster SM WITH (NOLOCK) ON SM.Id = PA.StatusId      
 LEFT JOIN sHrm.tEmployeeCommunications AS ECD WITH (NOLOCK) ON ECD.EmployeeId = EM.Id      
 LEFT JOIN sHrm.tEmployeeCommunications AS ECD1 WITH (NOLOCK) ON ECD1.EmployeeId = EMM1.Id      
 LEFT JOIN sCommon.tOrganizationDepartmentMaster AS ODM WITH (NOLOCK) ON ODM.Id = EJD.OrganizationDepartmentId      
 LEFT JOIN sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id      
 LEFT JOIN LatestAlertLog AL ON AL.ProviderAppointmentId = PA.Id AND AL.RowNum = 1   
 OUTER APPLY [dbo].[fAbnormalFindingsHealthIndicator](EXM.Id) AF
 LEFT JOIN      
 (      
  SELECT ExaminationId, [R.B.C. COUNT], [MCV], [F B S], [CHOLESTEROL], [TRIGLYCERIDE], [LDL], [HDL],        
    [SGPT], [ECG], [SONOGRAPHY], [TMT], [ECHO], [HB], [SERUM CREATININE], [SERUM URIC ACID], [HBA1C], [R B S], [P P B S],       
    [Waist Circumference], [TSH], [PSA], [XRAY]      
  FROM      
  (      
   SELECT SPM.Title, TR.SourceId [ExaminationId], LTRIM(RTRIM(TRD.Remark)) as Remark
   FROM sOrderEntry.tStaticTestParameterMaster AS SPM        
   INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id        
   INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id        
   INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id        
   INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId        
   WHERE SPM.Id in (3, 5, 19, 20, 21, 25, 31, 32, 33, 34, 38, 107, 104, 105, 109, 108, 2, 27, 49, 166, 54, 58)      
  )      
  d PIVOT      
  (      
   MIN(Remark) FOR Title IN        
   (      
    [R.B.C. COUNT], [MCV], [F B S], [CHOLESTEROL], [TRIGLYCERIDE], [LDL], [HDL], [SGPT],        
    [ECG], [SONOGRAPHY], [TMT], [ECHO], [HB], [SERUM CREATININE], [SERUM URIC ACID], [HBA1C], [R B S], [P P B S],       
    [Waist Circumference], [TSH], [PSA], [XRAY]      
   )      
  ) piv      
 ) AS Details ON Details.ExaminationId = EXM.Id      
 WHERE PA.OrgId = @rOrgId       
 AND (PA.StatusId = @rStatusId OR ISNULL(@rStatusId, 0) = 0)      
 AND (PA.ProviderId = @rProviderId OR ISNULL(@rProviderId, 0) = 0)      
 AND (PA.AssignToDoctorId = @rDoctorId OR ISNULL(@rDoctorId, 0) = 0)      
 AND (SEM.SetUpGroupId = @rRoundGroupId OR ISNULL(@rRoundGroupId, 0) = 0)      
 AND (PA.HealthIndicatorId = @rHealthIndicatorId OR ISNULL(@rHealthIndicatorId, 0) = 0)      
 AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')      
 AND ((ISNull(EM.FirstName, '') + ' ' + ISNull(EM.MiddleName, '') + ' ' + ISNull(EM.LastName, '')) like '%' + @rEmployeeName + '%'      
 OR ISNULL(@rEmployeeName,'') = '')      
      
 AND ((VTM.SectorId  IN(SELECT item FROM sCommon.fnsplit(@rSectorId,','))) OR (ISNULL(@rSectorId,'') = ''))        
 AND ((LMG.Id  IN(SELECT item FROM sCommon.fnsplit(@rLocationMainGroupId,','))) OR (ISNULL(@rLocationMainGroupId,'') = ''))        
 AND ((CGM.VerticalId  IN(SELECT item FROM sCommon.fnsplit(@rVerticalId,','))) OR (ISNULL(@rVerticalId,'') = ''))        
 AND ((ECM.CompanyGroupId  IN(SELECT item FROM sCommon.fnsplit(@rCompanyGroupId,','))) OR (ISNULL(@rCompanyGroupId,'') = ''))        
 AND ((EJD.EmployeeCompanyId  IN(SELECT item FROM sCommon.fnsplit(@rEmployeeCompanyId,','))) OR (ISNULL(@rEmployeeCompanyId,'') = ''))        
 AND ((LSG.Id  IN(SELECT item FROM sCommon.fnsplit(@rLocationSubGroupId,','))) OR (ISNULL(@rLocationSubGroupId,'') = ''))        
 AND ((LM.Id  IN(SELECT item FROM sCommon.fnsplit(@rLocationId,','))) OR (ISNULL(@rLocationId,'') = ''))        
 AND ((DGM.FunctionId  IN(SELECT item FROM sCommon.fnsplit(@rFunctionId,','))) OR (ISNULL(@rFunctionId,'') = ''))        
 AND ((ODM.DepartmentGroupId  IN(SELECT item FROM sCommon.fnsplit(@rDepartmentGroupId,','))) OR (ISNULL(@rDepartmentGroupId,'') = ''))        
 AND ((EJD.OrganizationDepartmentId  IN(SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))        
 AND ((EJD.EmployeeTypeId  IN(SELECT item FROM sCommon.fnsplit(@rEmployeeTypeId,','))) OR (ISNULL(@rEmployeeTypeId,'') = ''))        
 AND ((EJD.GradeId  IN(SELECT item FROM sCommon.fnsplit(@rGradeId,','))) OR (ISNULL(@rGradeId,'') = ''))        
 AND ((EJD.EmployeeDesignationId  IN(SELECT item FROM sCommon.fnsplit(@rEmployeeDesignationId,','))) OR (ISNULL(@rEmployeeDesignationId,'') = ''))        
 AND ((EXM.TargetGroupId  IN(SELECT item FROM sCommon.fnsplit(@rTargetGroupId,','))) OR (ISNULL(@rTargetGroupId,'') = ''))      
      
 AND (ISNULL(SCT.Id,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rSectorIdEntity,''),','))OR ISNULL(@rSectorIdEntity,'')='')      
 AND (ISNULL(VTM.Id,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalIdEntity,''),','))OR ISNULL(@rVerticalIdEntity,'')='')      
 AND (ISNULL(ECM.CompanyGroupId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyGroupIdEntity,''),','))OR ISNULL(@rCompanyGroupIdEntity,'')='')      
 AND (ISNULL(EJD.EmployeeCompanyId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyIdEntity,''),','))OR ISNULL(@rCompanyIdEntity,'')='')      
 AND (ISNULL(EJD.GradeId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rGradeIdEntity,''),','))OR ISNULL(@rGradeIdEntity,'')='')      
 AND (ISNULL(DGM.FunctionId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rFunctionIdEntity,''),','))OR ISNULL(@rFunctionIdEntity,'')='')      
 AND (ISNULL(EXM.StoreLocationId,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rStoreLocationIdEntity,''),','))OR ISNULL(@rStoreLocationIdEntity,'')='')     
 AND (ETM.EmployeeTypeGroupId = @rEmployeeTypeGroupId OR @rEmployeeTypeGroupId = 0) 
   AND EM.Code like @rEmployeeCode + '%'   
 AND       
(      
   EXISTS   
    (  
        SELECT 1  
        FROM sCommon.fnsplit(@rCode, ',') AS SplitValues  
        WHERE   
            (CHARINDEX(',', @rCode) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists  
            OR   
            (CHARINDEX(',', @rCode) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists  
    )  
    OR ISNULL(@rCode, '') = ''  )
 Order by EXM.ExaminationDate ASC
END
GO
PRINT N'Altering Procedure [sAppointment].[pTimeSlotSetupAdd]...';


GO
CREATE OR ALTER PROCEDURE [sAppointment].[pTimeSlotSetupAdd]
        @rId int,
        @rOrgId smallint,
        @rStoreLocationId int,        
        @rCode nvarchar(100)=null,
		@rTitle nvarchar(100)=null,	
		@rSourceTypeId int,
		@rMainTypeId int,
		@rSetupId int=0,	    
		@rDoctorEmployeeId bigint=0,         
        @rCreatedUserId bigint,
        @rUpdatedUserId bigint,        		
		@rIsOnline bit=0,
		@rIsOffline bit=0,
		@rIsObsolete bit=0,
		@rServiceId bigint = 0
 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	IF(@rId = 0)	
	BEGIN
		IF(@rMainTypeId = 10)
		BEGIN
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND MainTypeId = 10)
				BEGIN
				select -104 as Result
				RETURN
			END
		END
		ELSE
		BEGIN 
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND UPPER(Code)=UPPER(@rCode) AND MainTypeId=@rMainTypeId)
				BEGIN
					SELECT -102 AS Result
				RETURN
			END 
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND UPPER(Title)=UPPER(@rTitle) AND MainTypeId=@rMainTypeId)
				BEGIN
					SELECT -106 AS Result
				RETURN
			END 
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND DoctorEmployeeId=@rDoctorEmployeeId AND IsOnline=@rIsOnline AND @rIsOnline <> 0 AND MainTypeId=@rMainTypeId)
				BEGIN
					SELECT -107 AS Result
				RETURN
			END
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND DoctorEmployeeId=@rDoctorEmployeeId AND IsOffline=@rIsOffline AND @rIsOffline <> 0 AND MainTypeId=@rMainTypeId)
				BEGIN
					SELECT -108 AS Result
				RETURN
			END
		END
	END
	ELSE
	BEGIN
		IF(@rMainTypeId = 10)
		BEGIN
			If EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND MainTypeId = 10 AND Id<>@rId)
				BEGIN
					SELECT -104 AS Result
				RETURN
			END
		END
		ELSE
		BEGIN 
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND UPPER(Code)=UPPER(@rCode) AND MainTypeId=@rMainTypeId AND Id<>@rId)
				BEGIN
					SELECT -102 AS Result
				RETURN
			END 
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND UPPER(Title)=UPPER(@rTitle) AND MainTypeId=@rMainTypeId AND Id<>@rId)
				BEGIN
					SELECT -106 AS Result
				RETURN
			END 
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND DoctorEmployeeId=@rDoctorEmployeeId AND IsOnline=@rIsOnline AND @rIsOnline <> 0 AND MainTypeId=@rMainTypeId AND Id<>@rId)
				BEGIN
					SELECT -107 AS Result
				RETURN
			END
			IF EXISTS(SELECT Id FROM [sAppointment].[tTimeSlotSetup] WHERE OrgId=@rOrgId AND StoreLocationId=@rStoreLocationId AND DoctorEmployeeId=@rDoctorEmployeeId AND IsOffline=@rIsOffline AND @rIsOffline <> 0 AND MainTypeId=@rMainTypeId AND Id<>@rId)
				BEGIN
					SELECT -108 AS Result
				RETURN
			END
		END
	END
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT
 
	IF(@rId = 0)	
	BEGIN
		--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sSupport.tVaccineDoseMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO   [sAppointment].[tTimeSlotSetup] 		(			 			Code,Title,SourceTypeId,MainTypeId,SetupId,DoctorEmployeeId,StoreLocationId,OrgId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,IsOnline,IsOffline,ServiceId 		) 		VALUES 		(			
			@rCode,@rTitle,@rSourceTypeId,@rMainTypeId,@rSetupId,@rDoctorEmployeeId,@rStoreLocationId,@rOrgId,@rIsObsolete,@rCreatedUserId,sCommon.fGetDate(),@rUpdatedUserId,sCommon.fGetDate(),@rIsOnline,@rIsOffline,@rServiceId 		)
		 SELECT 1 AS Result			
	END	
 
ELSE
	 BEGIN	 
	    UPDATE  [sAppointment].[tTimeSlotSetup]
	    SET
			Code=@rCode,	         			Title=@rTitle,	 			SourceTypeId= @rSourceTypeId, 			MainTypeId=@rMainTypeId, 			SetupId=@rSetupId, 			DoctorEmployeeId=@rDoctorEmployeeId,      			UpdatedUserId=@rUpdatedUserId, 			UpdatedDateTime=sCommon.fGetDate(),						
			IsObsolete=@rIsObsolete,
			IsOnline = @rIsOnline,	      
			IsOffline = @rIsOffline,
			ServiceId = @rServiceId
	      WHERE Id = @rId
	      SELECT 11 AS Result
	 END  	
 
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		SELECT ERROR_MESSAGE() AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sCwb].[pDoctorMasterModify]...';


GO

CREATE OR ALTER PROCEDURE [sCwb].[pDoctorMasterModify]
	@rOrgId int,
	@rId [bigint],
	@rEmployeeId [bigint],
    @rMedicalRegistrationNo nvarchar(50),	 
	@rCreatedByUserId [bigint],
	@rDoctorSign varbinary(max),
	@rIsWellness bit = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

 declare  @countnew  int = 0
 select @countnew = count(*) FROM sCwb.tDoctorMaster WHERE  MedicalRegistrationNo=@rMedicalRegistrationNo and EmployeeId not in(@rEmployeeId)

 if(@countnew = 0)
 BEGIN 
	 UPDATE sCwb.tDoctorMaster
		SET
 
			EmployeeId = @rEmployeeId,
			MedicalRegistrationNo = @rMedicalRegistrationNo,
			UpdatedUserId = @rCreatedByUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			DoctorSignature = @rDoctorSign,
			IsWellness = @rIsWellness
	  WHERE (Id = @rId)
	  
	  BEGIN 
			SELECT @rEmployeeId AS Result
	  END	
 END	    
 ELSE
	BEGIN
		SELECT -100 AS RESULT 
	END
END
GO
PRINT N'Altering Procedure [dbo].[prc_getInjuriesRegistered_DrReaddy]...';


GO

CREATE OR ALTER PROCEDURE [dbo].[prc_getInjuriesRegistered_DrReaddy]
	@FromDate datetime = null,
	@ToDate datetime = null,
	@ReportTypeId bigint = 0,
	@SubLocationId bigint = 0,
	@EmployeeCode nvarchar(50) = null,
	@EmployeeName nvarchar(50) = null,
	@CodeLike nvarchar(100) = null,
	@DepartmentId bigint = 0,
	@BodyPartId bigint = 0,      
	@DesignationId bigint =0,
	@EmployeeTypeId bigint = 0,     	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',   
	@orgid int,
	@VisitPurpose int = 0,
	@UserId bigint,
	@Company int=0
	as
	BEGIN     
	BEGIN TRY
	BEGIN TRANSACTION
	IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
	BEGIN
	DROP TABLE #TableOne
	END
	if exists (Select 1 FROM 
				sExamination.tAccidentLog a
				inner join sExamination.tExamination b on b.Id = a.ExaminationId
				LEFT join sHrm.tEmployeeMaster e on e.id = b.ParticipantSourceId and b.ParticipantSourceTypeId = 95
				LEFT join  sHrm.tEmployeePersonalDetail ep on ep.EmployeeId = e.Id
				LEFT join  sHrm.tEmployeeJobDetail ej on ej.EmployeeId = e.Id
				left join sHrm.tEmployeeDesignationMaster ed on ed.Id = ej.EmployeeDesignationId
				left join sCommon.tOrganizationDepartmentMaster od on od.Id= ej.OrganizationDepartmentId
				left join sHrm.tEmployeeTypeMaster et on et.Id = ej.EmployeeTypeId
				left join sIp.tStoreLocationMaster sl on sl.Id = ej.EmployeeStoreLocationId
				LEFT JOIN sSafety.tIncidentTypeMaster ITM ON ITM.Id=a.IncidentTypeId
				LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id=b.DoctorEmployeeId
				LEFT JOIN sSecurity.tUser Users on Users.Id = E.CreatedUserId
				LEFT JOIN sHrm.tLocationDepartmentHead LDH ON LDH.OrganizationDepartmentId = b.OrganizationDepartmentId 
				Left join sHrm.tEmployeeMaster e1 on e1.id = LDH.HeadEmployeeId
				left join sHrm.tEmployeeCompanyMaster ECM on ECM.Id=b.EmployeeCompanyId
				left join sHrm.tEmployeeLegalEntitymaster LEM On LEM.Id=b.LegalEntityId
				LEFT JOIN sExamination.tAccidentLogField EAF ON EAF.AccidentLogId = a.Id 
				LEFT JOIN sSafety.tIncidentSetup SIS ON SIS.Id = EAF.IncidentSetupId and SIS.IsShowInReport = 1
				LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on b.ParticipantSourceId = EFD.Id and b.ParticipantSourceTypeId = 1001
				LEFT JOIN sHrm.tCsrBenefiterMaster BM on b.ParticipantSourceId = BM.Id and b.ParticipantSourceTypeId = 1009
				LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id	
				left join sExamination.vExtEmployeeExaminationDetail EED ON b.Id = EED.ExaminationId
				where
				isnull(b.iscancel,0) = 0 and isnull(SIS.CauseId, 0) = 0
				and (b.StoreLocationId =@SubLocationId or (
					@SubLocationId = 0
					AND
					b.StoreLocationId IN (
							select LM.Id from sIp.tStoreLocationMaster LM 
							INNER JOIN [sSecurity].[tUserLocation] UL ON UL.StoreLocationId = LM.Id 
							where IsObsolete = 0 AND OrgId = @orgid AND UL.UserId = @UserId 
						)
					)
				)
				AND 
				(
					(e.Code = @EmployeeCode AND b.ParticipantSourceTypeId = 95)
					OR
					(EM2.Code = @EmployeeCode AND b.ParticipantSourceTypeId = 1001)
					OR
					(BM.Code = @EmployeeCode AND b.ParticipantSourceTypeId = 1009)
					OR
					@EmployeeCode = ''
				)
				and (ej.OrganizationDepartmentId =@DepartmentId or @DepartmentId = 0)
				AND (
					@BodyPartId = 0
					OR ',' + a.BodyPartIds + ',' LIKE '%,' + CAST(@BodyPartId AS NVARCHAR(10)) + ',%'
				)
				and (ej.EmployeeTypeId =@EmployeeTypeId or @EmployeeTypeId = 0)
				AND ((a.IncidentDate >= @FromDate) OR (ISNULL(@FromDate,'') = ''))
				AND ((a.IncidentDate <= @ToDate) OR (ISNULL(@ToDate,'') = ''))
				and (ej.EmployeeDesignationId =@DesignationId or @DesignationId = 0)
				and (a.EmployeeCompanyid= @Company or @Company=0)							
				and ((EED.ParticipantName Like @EmployeeName +'%' ) or (ISNULL(@EmployeeName,'') = ''))
				and 
				(	
					exists (
						SELECT 1 FROM sCommon.fnsplit(@CodeLike, ',') AS SplitValues 
						WHERE LTRIM(RTRIM(ISNULL(SplitValues.item, ''))) <> '' 
						AND e.Code = LTRIM(RTRIM(SplitValues.item))
					)
					or ISNULL(@CodeLike, '') = ''
				)
				and ((b.CauseId = @VisitPurpose) OR @VisitPurpose = 0)
				)
	BEGIN
		CREATE TABLE #TableOne
		(
			AccidentLogId bigint,
			AccidentLogFieldResponse nvarchar(max),
			Id bigint,
			FieldRemark nvarchar(max),
			Value nvarchar(max),
			[Sr.No.] int,
			OPDNo varchar(30),
			Entity varchar(50),
			[Time of Incident] varchar(15),
			DateofIncident varchar(50),
			DateofIncident1 date,
			MonthName nvarchar(50),
			Year nvarchar(50),
			[Date of visited to OHC] nvarchar(2000),
			GenderId varchar(20),
			[Time of visited to OHC] nvarchar(2000),
			Name nvarchar(2000),
			Code nvarchar(2000),
			[Contact Details] VARCHAR(1000),
			[Please mention if the IP is- Employee/ Contract Employee/ Visitor] varchar(2000),
			[Description How it occur] nvarchar(2000),
			[Nature of the injury] nvarchar(2000),
			[BodyPart] nvarchar(2000),
			[If Two or more  body part please provide details of body part] nvarchar(2000),
			[Category of Injury] nvarchar(2000),
			[Location of injury Inside] nvarchar(2000),
			[Medical Treatment given] nvarchar(2000),
			[Please mention if the medical treatment involved the prescription medication - Yes/ No] varchar(2000),
			[If Yes- Please give the details - name, active ingredient with the dosage and the duration prescribed (Attach the prescription)] nvarchar(2000),
			MedicineName varchar(2000),
			Dosage varchar(2000),
			DoseFrequency varchar(2000),
			[Further Action] varchar(2000),
			[If Yes- Please provide the reason for Further Action-] nvarchar(2000),
			[If Yes- Please provide the reason for hospital reference-] nvarchar(2000),
			[Name of Hospital with contact details of treating doctor] nvarchar(2000),
			Department nvarchar(2000),
			Category nvarchar(2000),
			Age nvarchar(20),
			StoreLocation nvarchar(100),
			EmployeeStoreLocationId bigint,
			OrganizationDepartmentId bigint,
			BodyPartId bigint,
			EmployeeDesignationId bigint,
			EmployeeTypeId bigint ,
			fromDate Date,
			ToDate Date,
			TreatmentRemark nvarchar(max),
			PlaceofIncident nvarchar(max),
			SubLocation nvarchar(max),
			[Type of Injury] nvarchar(max),
			[Paramedics Name] nvarchar(max),
			[Treating Doctor Name] nvarchar(max),
			ExaminationNumber varchar(max), --Mantis:0040291 on (04/02/2025) by shivam
			[How Patient came to OHC] nvarchar(max),
			[How Patient left OHC] nvarchar(max),
			[Activity during Injury (As narrated by Patient/ co worker)] nvarchar(max),
		)
			INSERT INTO #TableOne
				SELECT 
				a.Id As AccidentLogId, 
				EAF.AccidentLogFieldResponse, 
				SIS.Id ,
				SIS.FieldRemark,
				CONVERT(nvarchar(2000),EAF.Id) As Value,
				ROW_NUMBER() OVER (PARTITION BY Datepart(YYYY,IncidentDate) ORDER BY IncidentDate asc )[Sr.No.],
				Isnull(b.examinationNumber,'') As OPDNo ,
				isnull(VMB.Title,'') as Entity,
				a.IncidentTime as [Time of Incident],
				convert(varchar,a.IncidentDate,103) as DateofIncident,
				IncidentDate as DateofIncident1,
				datename(mm,IncidentDate) as 'MonthName',
				datename(yyyy,IncidentDate) as 'Year',
				isnull(convert(varchar,b.ExaminationDate),'') as [Date of visited to OHC],
				case when Isnull(ep.GenderId,0)=1 then 'Male' when Isnull(ep.GenderId,0)=2 then 'Female' else 'Not Known' end GenderId,
				OP.OPDTime as [Time of visited to OHC],
				Name = CASE b.ParticipantSourceTypeId WHEN 95 THEN e.FirstName + ' ' + isnull(e.LastName,'')
				WHEN 1001 THEN EFD.Name WHEN 1009 THEN CASE WHEN isnull(OP.OtherName,'') <> '' THEN OP.OtherName ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END,
				Code = CASE b.ParticipantSourceTypeId WHEN 95 THEN e.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
				[Contact Details] = CONVERT(VARCHAR(1000),
				CASE b.ParticipantSourceTypeId
					WHEN 95 THEN isnull(EC.CompanyEmail,'')
					WHEN 1009 THEN isnull(BM.EmailId,'')
				END),
				CASE b.ParticipantSourceTypeId WHEN 95 THEN isnull(et.Title,'') 
					 WHEN 1009 THEN isnull(OTY.Title,'') END as [Please mention if the IP is- Employee/ Contract Employee/ Visitor],
				isnull(a.IncidentRemark,'') as [Description How it occur],
				isnull(a.NatureAndExtant,'') as [Nature of the injury],
				STUFF((
					SELECT ',' + ISNULL(BPM.Title, '')
					FROM sSafety.tBodyPartMaster BPM
					WHERE ',' + a.BodyPartIds + ',' LIKE '%,' + CAST(BPM.Id AS NVARCHAR(10)) + ',%'
					FOR XML PATH ('')
				), 1, 1, '') AS [BodyPart],
				Isnull(BSM.Title,'') as [If Two or more  body part please provide details of body part],
				isnull(ITM.Title,'') as [Category of Injury],
				isnull(a.PlaceofIncident,'') as [Location of injury Inside],
				isnull(a.TreatmentRemark,'') as [Medical Treatment given],
				CASE WHEN ISNULL(pd.PrescriptionId, 0) = p.Id THEN 'Yes'ELSE 'No'END AS [Please mention if the medical treatment involved the prescription medication - Yes/ No],				
				ISNULL(SIM.Title, '') 
				+ ', ' + Convert(varchar, ISNULL(PD.Dosage, 0)) 
				+ ', ' + ISNULL(DDFM.Title, '')
				As [If Yes- Please give the details - name, active ingredient with the dosage and the duration prescribed (Attach the prescription)],
				STUFF((
						SELECT  ',' +(ISNULL(SIM.Title, '')) 
						FROM sIp.tStockItemMaster SIM
						INNER JOIN sExamination.tPrescriptionDetail PD ON SIM.Id = PD.StockItemId 
						INNER JOIN sExamination.tPrescription P ON PD.PrescriptionId = P.Id
						WHERE P.SourceId = b.Id
						FOR XML PATH ('')
					), 	1, 1, '') as MedicineName,
				STUFF((	SELECT  ',' + Convert(varchar, ISNULL(PD.Dosage, 0)) 
						FROM sExamination.tPrescriptionDetail PD
						INNER JOIN   sIp.tStockItemMaster SIM ON SIM.Id = PD.StockItemId 
						INNER JOIN sExamination.tPrescription P ON PD.PrescriptionId = P.Id
						WHERE P.SourceId = b.Id
						FOR XML PATH ('')
					), 1, 1, ''	) as Dosage,
				STUFF((	SELECT  ',' + ISNULL(DDFM.Title, '')  
						FROM sIp.tDrugDosageFrequencyMaster DDFM 
						inner Join sExamination.tPrescriptionDetail PD on DDFM.Id = PD.DrugDosageFrequencyId
						INNER JOIN sExamination.tPrescription P ON PD.PrescriptionId = P.Id
						WHERE P.SourceId = b.Id
						FOR XML PATH ('')
					), 	1, 1, '') as DoseFrequency,
				Case FAM.IsHospitalDoctor when 1 THEN 'Yes'ELSE 'No'END AS [Further Action],
				ISNULL(FAM.Title, '') AS [If Yes- Please provide the reason for Further Action-],
				OP.FurtherActionRemark as [If Yes- Please provide the reason for hospital reference-],
				IsNull(AFM.Title,'') + '<br/> -'+ isnull(AFM.PhoneNumberOffice,'') as [Name of Hospital with contact details of treating doctor],
				od.Title as 'Department',
				et.Title as 'Category',
				Age = Convert(varchar,(DATEDIFF(YEAR, ep.DateOfBirth, a.IncidentDate))),
				sl.Title as 'StoreLocation',
				@SubLocationId as EmployeeStoreLocationId,
				@DepartmentId as OrganizationDepartmentId,
				@BodyPartId as BodyPartId,
				@DesignationId as EmployeeDesignationId,
				@EmployeeTypeId as EmployeeTypeId,
				ISNULL(@FromDate,'') as fromDate,
				@ToDate as ToDate,
				a.TreatmentRemark,
				a.PlaceofIncident,
				sl1.Title as SubLocation,
				isnull(Cm.Title,'') AS [Type of Injury],
				Case WHEN (PARUSR.SourceId = b.DoctorEmployeeId AND ISNULL(DM.Id,0) > 0) THEN '' ELSE LTRIM(RTRIM(isnull(PAREMP.FirstName,'') + ' ' + isnull(PAREMP.LastName,''))) end as [Paramedics Name],
				Case WHEN ISNULL(DM.Id,0) = 0 THEN '' ELSE LTRIM(RTRIM(isnull(EM1.EmployeePrefix, '') + ' ' + isnull(EM1.FirstName,'') + ' ' + isnull(EM1.LastName,''))) end as [Treating Doctor Name],
				b.ExaminationNumber, TTOOHC.Title, TFOOHC.Title, a.ActivityWAccident
				FROM 
				sExamination.tAccidentLog a
				inner join sExamination.tExamination b on b.Id = a.ExaminationId
				LEFT join sHrm.tEmployeeMaster e on e.id = b.ParticipantSourceId and b.ParticipantSourceTypeId = 95
				LEFT join sHrm.tEmployeePersonalDetail ep on ep.EmployeeId = e.Id
				LEFT join sHrm.tEmployeeJobDetail ej on ej.EmployeeId = e.Id
				LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on b.ParticipantSourceId = EFD.Id and b.ParticipantSourceTypeId = 1001
				LEFT JOIN sHrm.tCsrBenefiterMaster BM on b.ParticipantSourceId = BM.Id and b.ParticipantSourceTypeId = 1009
				LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id	
				left join sHrm.tEmployeeDesignationMaster ed on ed.Id = ej.EmployeeDesignationId
				LEFT JOIN sHrm.tEmployeeJobDetail EJD on e.Id = EJD.EmployeeId
				LEFT JOIN sHrm.tEmployeeDesignationMaster EDM on EJD.EmployeeDesignationId = EDM.Id 
				LEFT JOIN sHrm.tEmployeeCompanyMaster ECM1 on EJD.EmployeeCompanyId= ECM1.Id 
				left join sHrm.tEmployeeCommunications EC on EC.EmployeeId = e.Id
				left join sHrm.tCompanyGroupMaster CGM on CGM.Id = ECM1.CompanyGroupId
				left join sHrm.tVerticalMaster VMB on VMB.Id = CGM.VerticalId
				left join sCommon.tOrganizationDepartmentMaster od on od.Id= ej.OrganizationDepartmentId
				left join sHrm.tEmployeeTypeMaster et on et.Id = ej.EmployeeTypeId
				left join sHrm.tCsrBenefiterTypeMaster OTY on OTY.Id = BM.CSRBenefiterTypeId
				left join sIp.tStoreLocationMaster sl on sl.Id = ej.EmployeeStoreLocationId
				left join sIp.tStoreLocationMaster sl1 on sl1.Id = b.StoreLocationId
				LEFT JOIN sSafety.tIncidentTypeMaster ITM ON ITM.Id=a.IncidentTypeId
				LEFT JOIN sSafety.tTransportationMaster TTOOHC ON TTOOHC.Id=a.TransportationToOhcId
				LEFT JOIN sSafety.tTransportationMaster TFOOHC ON TFOOHC.Id=a.TransportationFromOhcId
				LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id=b.DoctorEmployeeId
				LEFT JOIN sCwb.tDoctorMaster DM ON DM.EmployeeId = b.DoctorEmployeeId
				LEFT JOIN sSecurity.tUser PARUSR on PARUSR.Id = b.CreatedUserId
				Left join sHrm.tEmployeeMaster PAREMP on PAREMP.id = PARUSR.SourceId and SourceTypeId = 95
				LEFT JOIN sSecurity.tUser Users on Users.Id = E.CreatedUserId
				LEFT JOIN sHrm.tLocationDepartmentHead LDH ON LDH.OrganizationDepartmentId = b.OrganizationDepartmentId 
				Left join sHrm.tEmployeeMaster e1 on e1.id = LDH.HeadEmployeeId
				left join sHrm.tEmployeeCompanyMaster ECM on ECM.Id=b.EmployeeCompanyId
				left join sHrm.tEmployeeLegalEntitymaster LEM On LEM.Id=b.LegalEntityId
				LEFT JOIN sExamination.tAccidentLogField EAF ON EAF.AccidentLogId = a.Id 
				LEFT JOIN sSafety.tIncidentSetup SIS ON SIS.Id = EAF.IncidentSetupId and SIS.IsShowInReport = 1
				LEFT JOIN sExamination.tOPD OP ON OP.ExaminationId = b.Id
				left join sSafety.tBodySideMaster BSM on BSM.Id = a.BodySideId
				left join sSafety.tLegalPointMaster LPM on LPM.Id = a.LegalPointId
				left JOIN sExamination.tPrescription P ON P.SourceId= b.Id
				left JOIN sExamination.tPrescriptionDetail PD ON PD.PrescriptionId=P.Id AND PD.IsObsolete=0
				left Join sIp.tDrugDosageFrequencyMaster DDFM on DDFM.Id = PD.DrugDosageFrequencyId
				left JOIN sIp.tStockItemMaster SIM ON SIM.Id = PD.StockItemId 
				left join sSafety.tFurtherActionMaster FAM on FAM.Id = OP.FurtherActionId and FAM.IsHospitalDoctor = 1
				left join sExamination.tReferral R on R.SourceId = b.Id
				left join sCommon.tClinicMaster AFM on AFM.Id = R.ReferToClinicId
				left join sSafety.tCauseMaster CM on CM.Id  = a.causeId				
				left join sExamination.vExtEmployeeExaminationDetail EED ON b.Id = EED.ExaminationId
				where 
				isnull(b.iscancel,0) = 0 and isnull(SIS.CauseId, 0) = 0
				and (b.StoreLocationId =@SubLocationId or (
					@SubLocationId = 0
					AND
					b.StoreLocationId IN (
							select LM.Id from sIp.tStoreLocationMaster LM 
							INNER JOIN [sSecurity].[tUserLocation] UL ON UL.StoreLocationId = LM.Id 
							where IsObsolete = 0 AND OrgId = @orgid AND UL.UserId = @UserId 
						)
					)
				)
				and (e.Code = @EmployeeCode or @EmployeeCode = '')
				and (ej.OrganizationDepartmentId =@DepartmentId or @DepartmentId = 0)
				AND (
					@BodyPartId = 0
					OR ',' + a.BodyPartIds + ',' LIKE '%,' + CAST(@BodyPartId AS NVARCHAR(10)) + ',%'
				)
				and (ej.EmployeeTypeId =@EmployeeTypeId or @EmployeeTypeId = 0)
				AND ((a.IncidentDate >= @FromDate) OR (ISNULL(@FromDate,'') = ''))
				AND ((a.IncidentDate <= @ToDate) OR (ISNULL(@ToDate,'') = ''))
				and (ej.EmployeeDesignationId =@DesignationId or @DesignationId = 0)
				and (a.EmployeeCompanyid= @Company or @Company=0)				
				and ((EED.ParticipantName Like @EmployeeName +'%' ) or (ISNULL(@EmployeeName,'') = ''))
				and 
				(	
					exists (
						SELECT 1 FROM sCommon.fnsplit(@CodeLike, ',') AS SplitValues 
						WHERE LTRIM(RTRIM(ISNULL(SplitValues.item, ''))) <> '' 
						AND e.Code = LTRIM(RTRIM(SplitValues.item))
					)
					or ISNULL(@CodeLike, '') = ''
				)
				and ((b.CauseId = @VisitPurpose) OR @VisitPurpose = 0)
				
				order by IncidentDate

					DECLARE @Count int = 0
					DECLARE @FieldRemarkNameTable TABLE
					(
					tId int IDENTITY (1, 1), FieldRemarkName nvarchar(250),FieldOrder int
					)
					INSERT INTO @FieldRemarkNameTable
					SELECT DISTINCT SIS.FieldRemark,SIS.FieldOrder FROM sSafety.tIncidentSetup SIS WHERE SIS.Id IN  
					(
					SELECT DISTINCT  Id FROM #TableOne
					) AND SIS.IsShowInReport = 1 and SIS.FieldGroup = 'Injury' order by FieldOrder desc
					SELECT @Count = COUNT(0) FROM @FieldRemarkNameTable
					--SELECT * FROM #TableOne						
						
						
					DECLARE @query nvarchar(max)='',@query1 nvarchar(max)='',@query2 nvarchar(max)=''
					SELECT @Count = COUNT(0) FROM @FieldRemarkNameTable  
					WHILE (@Count <> 0)  
					BEGIN  
						SELECT @query = @query + '[' + ISNULL(UPPER(FieldRemarkname), '') + '],'  
						FROM @FieldRemarkNameTable WHERE tId = @Count  

						SELECT @query1 = @query1 + 'Isnull([' + ISNULL(UPPER(FieldRemarkname), '') + '],'''')'
						+ Replace(QUOTENAME(UPPER(SUBSTRING(FieldRemarkname, 1, 128))) + (case When LEN(FieldRemarkname) > 128 THEN QUOTENAME(UPPER(SUBSTRING(FieldRemarkname, 129, 256))) ELSE '' END), '][', '') + ','  
						FROM @FieldRemarkNameTable WHERE tId = @Count

						SELECT @query2 = @query2 + 'STUFF(( select distinct Isnull([' + ISNULL(UPPER(FieldRemarkname), '') + '],'''') From #tmppivot as t where t.OPDNo=t1.OPDNo FOR XML PATH('''')), 1, 0, '''')'
						+ Replace(QUOTENAME(UPPER(SUBSTRING(FieldRemarkname, 1, 128))) + (case When LEN(FieldRemarkname) > 128 THEN QUOTENAME(UPPER(SUBSTRING(FieldRemarkname, 129, 256))) ELSE '' END), '][', '') + ','  
						FROM @FieldRemarkNameTable WHERE tId = @Count
				
						SET @Count = @Count - 1  
					END  

					SET @query = SUBSTRING(@query, 0, LEN(@query))  
					SET @query1 = SUBSTRING(@query1, 0, LEN(@query1))  
					SET @query2 = SUBSTRING(@query2, 0, LEN(@query2))  

					--PRINT @query
					--print @query1
					--print @query2
					DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)

					SET @DynamicPivotQuery = '
							SELECT DISTINCT 
								OPDNo,
								Entity,
								DateofIncident1,
								ISNULL(DateofIncident,'''') AS [Date of Incident],
								[Date of visited to OHC],
								[Time of Incident],
								[Time of visited to OHC],
								Name,
								Code,
								[Contact Details],
								[Please mention if the IP is- Employee/ Contract Employee/ Visitor],
								SubLocation AS Site,
								[Type of Injury],
								[Treating Doctor Name],
								[Paramedics Name],
								[Description How it occur],
								[Nature of the injury],
								[BodyPart],
								[If Two or more  body part please provide details of body part],
								[Category of Injury],
								[Location of injury Inside],
								[Medical Treatment given],
								[Please mention if the medical treatment involved the prescription medication - Yes/ No],
								MedicineName + '', '' + Dosage + '', '' + DoseFrequency as
								[If Yes- Please give the details - name, active ingredient with the dosage and the duration prescribed (Attach the prescription)],
								[Further Action],[If Yes- Please provide the reason for Further Action-],
								[If Yes- Please provide the reason for hospital reference-],
								[Name of Hospital with contact details of treating doctor],
								[How Patient came to OHC],[How Patient left OHC],
								[Activity during Injury (As narrated by Patient/ co worker)]
							INTO #tmppivot 
							FROM (
								SELECT DISTINCT 
									value, 
									FieldRemark,
									AccidentLogId,
									OPDNo,
									Entity,
									MonthName,
									Year,
									[Date of visited to OHC],
									[Time of Incident],
									[Description How it occur],
									[Nature of the injury],
									[BodyPart],
									[If Two or more  body part please provide details of body part],
									[Category of Injury],
									[Time of visited to OHC],
									DateofIncident1,
									DateofIncident,
									Name,
									Code,
									[Contact Details],
									[Please mention if the IP is- Employee/ Contract Employee/ Visitor],
									[Location of injury Inside],
									[Medical Treatment given],
									[Please mention if the medical treatment involved the prescription medication - Yes/ No],
									MedicineName, Dosage ,DoseFrequency,
									[Further Action],[If Yes- Please provide the reason for Further Action-],
									[If Yes- Please provide the reason for hospital reference-],
									[Name of Hospital with contact details of treating doctor],
									Department,
									Category,
									StoreLocation,
									EmployeeStoreLocationId,
									OrganizationDepartmentId,
									EmployeeDesignationId,
									EmployeeTypeId,
									fromDate,
									ToDate,
									PlaceofIncident,SubLocation,
									[Type of Injury],
									[Treating Doctor Name],
									[Paramedics Name],
									ExaminationNumber,
									ISNULL(
										CASE 
											WHEN ISDATE(REPLACE(LEFT(AccidentLogFieldResponse,16),''T'','' '')) = 1 
											THEN CONVERT(VARCHAR(20), CONVERT(DATETIME, REPLACE(LEFT(AccidentLogFieldResponse,16),''T'','' ''), 120), 103)
												 + '' '' + RIGHT(CONVERT(VARCHAR(20), CONVERT(DATETIME, REPLACE(LEFT(AccidentLogFieldResponse,16),''T'','' ''), 120), 100), 7)
											ELSE AccidentLogFieldResponse
										END, ''''
									) AS AccidentLogFieldResponse,
									[How Patient came to OHC],[How Patient left OHC],
									[Activity during Injury (As narrated by Patient/ co worker)]
								FROM #TableOne) AS Tab1

							SELECT DISTINCT 
								DateofIncident1,
								Entity,
								[Date of Incident],
								[Date of visited to OHC],
								[Time of Incident],
								[Time of visited to OHC],
								Name,
								Code,
								[Contact Details],
								[Please mention if the IP is- Employee/ Contract Employee/ Visitor],
								Site,
								[Type of Injury],
								[Treating Doctor Name],
								[Paramedics Name],
								[Description How it occur],
								[Nature of the injury],
								[BodyPart],
								[If Two or more  body part please provide details of body part],
								[Category of Injury],
								[Location of injury Inside],
								[Medical Treatment given],
								[Please mention if the medical treatment involved the prescription medication - Yes/ No],							
								[If Yes- Please give the details - name, active ingredient with the dosage and the duration prescribed (Attach the prescription)],
								[Further Action],
								[If Yes- Please provide the reason for Further Action-],
								[If Yes- Please provide the reason for hospital reference-],
								[Name of Hospital with contact details of treating doctor],
								[How Patient came to OHC],[How Patient left OHC],
								[Activity during Injury (As narrated by Patient/ co worker)]
							INTO #tmpfinalpivot 
							FROM #tmppivot AS t1 

							SELECT 
								ROW_NUMBER() OVER (
									--PARTITION BY DATEPART(YYYY,DateofIncident1)
									ORDER BY DateofIncident1 ASC
								) AS [Sr.No.],
								Entity,
								Site,
								[Date of Incident],
								[Time of Incident],
								[Treating Doctor Name],
								[Paramedics Name],
								[Date of visited to OHC],
								[Time of visited to OHC],
								Name,
								Code,
								[Contact Details],
								[How Patient came to OHC],
								[Please mention if the IP is- Employee/ Contract Employee/ Visitor],
								[Description How it occur],
								[Location of injury Inside],
								[Activity during Injury (As narrated by Patient/ co worker)],
								[Nature of the injury],
								[Type of Injury],
								ISNULL(
								[BodyPart] + 
									CASE 
										WHEN [BodyPart] <> '''' AND [BodyPart] IS NOT NULL 
											THEN '' - '' + [If Two or more  body part please provide details of body part] 
										ELSE '''' 
									END,
									''''
								) AS [Affected Body Part],
								[Category of Injury],
								[Medical Treatment given],
								[Please mention if the medical treatment involved the prescription medication - Yes/ No],							
								[If Yes- Please give the details - name, active ingredient with the dosage and the duration prescribed (Attach the prescription)],
								[Further Action],
								[If Yes- Please provide the reason for Further Action-],
								[How Patient left OHC]
							FROM #tmpfinalpivot 
							ORDER BY DateofIncident1'

					--PRINT @DynamicPivotQuery
					
					EXECUTE (@DynamicPivotQuery)
	END
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
	SELECT -1 AS Result,ERROR_MESSAGE()
END CATCH
end
GO
PRINT N'Altering Procedure [sCwb].[pDoctorMasterAdd]...';


GO

CREATE OR ALTER PROCEDURE [sCwb].[pDoctorMasterAdd]
    @rOrgId int,
	@rEmployeeId [bigint],
	@rMedicalRegistrationNo nvarchar(50),	 
	@rCreatedByUserId [bigint],
	@rDoctorSign varbinary(max),
	@rIsWellness bit = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

DECLARE @lNextNumber BIGINT
	EXECUTE sCommon.pTableRowIdGet @rOrgId,'sCWB.tDoctorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

IF NOT EXISTS (SELECT 1 FROM sCwb.tDoctorMaster WHERE EmployeeId=@rEmployeeId or MedicalRegistrationNo=@rMedicalRegistrationNo) 
BEGIN
	INSERT INTO sCwb.tDoctorMaster
		(
			Id,
			EmployeeId,
			MedicalRegistrationNo,		 
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId,
			DoctorSignature,
			IsWellness
		)
	VALUES
		(
			@lNextNumber,
			@rEmployeeId,
			@rMedicalRegistrationNo, 
			@rCreatedByUserId,
			sCommon.fGetDate(),
			@rCreatedByUserId,
			sCommon.fGetDate(),
			@rOrgId,
			@rDoctorSign,
			@rIsWellness
		)
 
			SELECT @rEmployeeId AS Result
 
END
ELSE
	BEGIN
		SELECT -100 AS RESULT 
	END
		
END
GO
PRINT N'Altering Procedure [sCwb].[pDoctorMasterGet]...';


GO

CREATE OR ALTER PROCEDURE [sCwb].[pDoctorMasterGet]
	@rId [bigint] = 0,
	@rDoctorName [nvarchar](300) = '',
	@rDepartmentId [smallint] = 0,
	@rSpecialityId [smallint] = 0,
	@rIsSearch [bit] = 0,
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF @rIsSearch = 1
	BEGIN
		SET @rDoctorName = sCommon.fSearchStringGet(@rDoctorName)
	END

	SELECT DM.Id AS DoctorId,
	DM.EmployeeId AS DoctorEmployeeId,
	vEDM.EmployeeCode AS DoctorCode,
	vEDM.FirstName AS FirstName,
	vEDM.MiddleName AS MiddleName,
	vEDM.LastName AS LastName,
	vEDM.DoctorName AS DoctorName,
	DM.MedicalRegistrationNo As MedicalregistrationNo,
	isnull(DM.IsWellness,0) as IsWellness
	FROM sCwb.tDoctorMaster DM
	INNER JOIN sCwb.vExtDoctorMaster vEDM ON DM.EmployeeId = vEDM.EmployeeId
	WHERE ((DM.EmployeeId = @rId) OR (@rId = 0))
	AND ((vEDM.DoctorName LIKE @rDoctorName) OR (@rDoctorName = ''))
	AND DM.OrgId = @rOrgId
	ORDER BY vEDM.DoctorName ASC	
END
GO
PRINT N'Altering Procedure [sExamination].[pExaminationStatusDetail]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pExaminationStatusDetail]
	@rStoreLocationId int = 0,
	@rParticipantTypeId int = 0 ,
	@rCaseCauseId int = 0,
	@rLocationId int = 0,
	@rFunctionId int = 0,
	@rDepartmentGroupId int = 0,
	@rDepartmentId int = 0,
	@rGradeId int = 0,
	@rDesignationId int = 0,
	@rJobTitleId int=0,
	@rCompanyId int=0,
	@rContractorId int = 0,
	@rGenderId smallint=0,
	@rStatusId smallint=0,
	@rAgeFrom int=0,
	@rAgeTo int=100,
	@rFromDate date = null,
	@rToDate date = null,
	@rOrgId int,
	@rEmployeeCode nvarchar(50)='',
	@rUserId bigint = 0,
	@rSectorId bigint = 0,
	@rVerticalId bigint = 0,
	@rCompnayGroupId bigint = 0,
	@rRoundGroupId bigint = 0,
	@rRoundId bigint = 0,
	@rEmployeeTypeGoupId bigint = 0,
	@rEmployeeTypeId bigint = 0,
	@rEmployeeSubTypeId bigint = 0,
	@rTargetGroupId int=0,

	--@rHealthIndexParameterId NVARCHAR(MAX) = '',
	@rHealthIndicatorId INT = 0,
	@rLocationMainGroupId INT = 0,
	@rLocationSubGroupId INT = 0,
	@rFromPercentage DEcimal(10,2)= -1,
	@rToPercentage DEcimal(10,2) = -1,
	@rMaINTypeId int = 1,
	@rCompanyGroupId int = 0,
	@rEmployeeCompanyId int = 0,
	@PageIndex int = 1
AS
BEGIN	
	
	IF OBJECT_ID('tempdb..#TEMPTableMain') IS NOT NULL
	DROP TABLE #TEMPTableMain

	Create TABLE #TEMPTableMain  (tid int Identity(1,1), StorelocationId int, Storelocation nvarchar(200),TotalFeezCnt int,TotalInProgressCnt int,TotalCompletedCnt int,TotalClosedCnt int,TotalNotStartedCnt int
	 ,OrgId int,VeryPoor decimal(10,2),Poor decimal(10,2),Fair decimal(10,2),Good decimal(10,2),Excellent decimal(10,2),Generated int,NotGenerated int,IndicatorName nvarchar(200),Percentage decimal(10,2),ClassicWell decimal(10,2),
	 ColorCode nvarchar(50), ColorCode1 nvarchar(50), ColorCode2 nvarchar(50), ColorCode3 nvarchar(50), ColorCode4 nvarchar(50), ColorCode5 nvarchar(50), ColorCode6 nvarchar(50))

	INSERT INTO #TEMPTableMain (StorelocationId,Storelocation,TotalFeezCnt,TotalInProgressCnt,TotalCompletedCnt,TotalClosedCnt,TotalNotStartedCnt)
	select SLM.Id,SLM.Title ,		
	isnull(a.TotalFeezCnt,0),
	isnull(b.[TotalInProgressCnt],0) ,
	isnull(c.[TotalCompletedCnt],0) ,
	isnull(d.[TotalClosedCnt],0)  ,
	isnull(f.[TotalNotStartedCnt],0)	
	
	from sIp.tStoreLocationMaster SLM
	inner JOIN sSecurity.tUserLocation UL ON  UL.StoreLocationId = SLM.Id and UL.UserId = @rUserId
	left join(	
	(select SL.ID,count(*) as TotalFeezCnt 
	from sExamination.tSetupEmployee SE
	inner join sExamination.tSetupMaster SM	on SE.SetupId = SM.Id
	inner join sHrm.vEmployeeCommonDetail EM on SE.EmployeeId = EM.EmployeeId
	left join sHrm.tEmployeeJobDetail JD on EM.EmployeeId = JD.EmployeeId	
	left join sExamination.tExamination E on E.ParticipantSourceId = SE.EmployeeId and E.SetupId = SM.Id
	inner join sIp.tStoreLocationMaster SL on SL.Id = SM.StoreLocationId
	left join sCommon.tOrganizationDepartmentMaster OD on JD.OrganizationDepartmentId = OD.Id	
	left join sHrm.tEmployeeCompanyMaster ECM on JD.EmployeeCompanyId = ECM.Id
	left join sHrm.tCompanyGroupMaster CG on ECM.CompanyGroupId = CG.Id
	left join sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = E.CauseId 
	LEFT JOIN sSecurity.tUser U ON U.Id = E.CreatedUserId 
	inner JOIN sSecurity.tUserLocation UL ON  UL.StoreLocationId = SL.Id and UL.UserId = @rUserId
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON EM.DepartmentGroupId = DGM.Id 		
	LEFT JOIN sCommon.tFunctionMaster FM  ON DGM.FunctionId= FM.Id
	where 
	SM.SubTypeId in (1,2)  And SM.IsObsolete='0'
	and EM.OrgId = @rOrgId 
	and (SM.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)	
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND(E.GradeId=@rGradeId OR @rGradeId=0)
	AND((E.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))
	and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)
	and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)
	and (VM.SectorId = @rSectorId or @rSectorId = 0)
	AND(E.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND (FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND(EM.GenderId = @rGenderId OR @rGenderId=0)
	AND ((EM.Code =  @rEmployeeCode ) OR (@rEmployeeCode = '')) and SL.IsActiveHealth =1 
	AND (Jd.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND (Jd.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	AND (Jd.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)
	AND (SE.SetupId = @rRoundId OR @rRoundId = 0)
	AND (SM.SetupGroupId = @rRoundGroupId OR @rRoundGroupId = 0)
	and SL.IsActiveHealth =1 
	group by SL.ID)
	) a on a.id = SLM.Id
	left join(
	(select SL.ID,count(*) as TotalInProgressCnt from sExamination.tSetupEmployee SE
	inner join sExamination.tSetupMaster SM	on SE.SetupId = SM.Id
	inner join sHrm.vEmployeeCommonDetail EM on SE.EmployeeId = EM.EmployeeId
	inner join sHrm.tEmployeeJobDetail JD on EM.EmployeeId = JD.EmployeeId	
	inner join sExamination.tExamination E on E.ParticipantSourceId = SE.EmployeeId and E.SetupId = SM.Id
	inner join sIp.tStoreLocationMaster SL on SL.Id = SM.StoreLocationId
	left join sCommon.tOrganizationDepartmentMaster OD on JD.OrganizationDepartmentId = OD.Id	
	left join sHrm.tEmployeeCompanyMaster ECM on JD.EmployeeCompanyId = ECM.Id
	left join sHrm.tCompanyGroupMaster CG on ECM.CompanyGroupId = CG.Id
	left join sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = E.CauseId 
	LEFT JOIN sSecurity.tUser U ON U.Id = E.CreatedUserId 
	inner JOIN sSecurity.tUserLocation UL ON  UL.StoreLocationId = SL.Id and UL.UserId = @rUserId
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON EM.DepartmentGroupId = DGM.Id 		
	LEFT JOIN sCommon.tFunctionMaster FM  ON DGM.FunctionId= FM.Id
	where 
	E.StatusId = 1 and
	SM.SubTypeId in (1,2)  And SM.IsObsolete='0'
	and EM.OrgId = @rOrgId 
	and (SM.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)	
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND(E.GradeId=@rGradeId OR @rGradeId=0)
	AND((E.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))
	and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)
	and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)
	and (VM.SectorId = @rSectorId or @rSectorId = 0)
	AND(E.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND (FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND(EM.GenderId = @rGenderId OR @rGenderId=0)
	AND ((EM.Code =  @rEmployeeCode ) OR (@rEmployeeCode = '')) and SL.IsActiveHealth =1 
	AND (Jd.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND (Jd.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	AND (Jd.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)
	AND (SE.SetupId = @rRoundId OR @rRoundId = 0)
	AND (SM.SetupGroupId = @rRoundGroupId OR @rRoundGroupId = 0)
	and SL.IsActiveHealth =1 
	group by SL.ID)
	) as b on b.Id = SLM.Id
	left join(
	(select SL.ID,count(*) as TotalCompletedCnt from sExamination.tSetupEmployee SE
	inner join sExamination.tSetupMaster SM	on SE.SetupId = SM.Id
	inner join sHrm.vEmployeeCommonDetail EM on SE.EmployeeId = EM.EmployeeId
	inner join sHrm.tEmployeeJobDetail JD on EM.EmployeeId = JD.EmployeeId	
	inner join sExamination.tExamination E on E.ParticipantSourceId = SE.EmployeeId and E.SetupId = SM.Id
	inner join sIp.tStoreLocationMaster SL on SL.Id = SM.StoreLocationId
	left join sCommon.tOrganizationDepartmentMaster OD on JD.OrganizationDepartmentId = OD.Id	
	left join sHrm.tEmployeeCompanyMaster ECM on JD.EmployeeCompanyId = ECM.Id
	left join sHrm.tCompanyGroupMaster CG on ECM.CompanyGroupId = CG.Id
	left join sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = E.CauseId 
	LEFT JOIN sSecurity.tUser U ON U.Id = E.CreatedUserId 
	inner JOIN sSecurity.tUserLocation UL ON  UL.StoreLocationId = SL.Id and UL.UserId = @rUserId
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON EM.DepartmentGroupId = DGM.Id 		
	LEFT JOIN sCommon.tFunctionMaster FM  ON DGM.FunctionId= FM.Id
	where 
	E.StatusId in (3,4) and
	SM.SubTypeId in (1,2)  And SM.IsObsolete='0'
	and EM.OrgId = @rOrgId 
	and (SM.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)	
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND(E.GradeId=@rGradeId OR @rGradeId=0)
	AND((E.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))
	and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)
	and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)
	and (VM.SectorId = @rSectorId or @rSectorId = 0)
	AND(E.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND (FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND(EM.GenderId = @rGenderId OR @rGenderId=0)
	AND ((EM.Code =  @rEmployeeCode ) OR (@rEmployeeCode = '')) and SL.IsActiveHealth =1 
	AND (Jd.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND (Jd.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	AND (Jd.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)
	AND (SE.SetupId = @rRoundId OR @rRoundId = 0)
	AND (SM.SetupGroupId = @rRoundGroupId OR @rRoundGroupId = 0)
	and SL.IsActiveHealth =1 
	group by SL.ID)
	) as c on c.Id = SLM.id
	left join(
	(select SL.ID,count(*) as TotalClosedCnt from sExamination.tSetupEmployee SE
	inner join sExamination.tSetupMaster SM	on SE.SetupId = SM.Id
	inner join sHrm.vEmployeeCommonDetail EM on SE.EmployeeId = EM.EmployeeId
	inner join sHrm.tEmployeeJobDetail JD on EM.EmployeeId = JD.EmployeeId	
	inner join sExamination.tExamination E on E.ParticipantSourceId = SE.EmployeeId and E.SetupId = SM.Id
	inner join sIp.tStoreLocationMaster SL on SL.Id = SM.StoreLocationId
	left join sCommon.tOrganizationDepartmentMaster OD on JD.OrganizationDepartmentId = OD.Id	
	left join sHrm.tEmployeeCompanyMaster ECM on JD.EmployeeCompanyId = ECM.Id
	left join sHrm.tCompanyGroupMaster CG on ECM.CompanyGroupId = CG.Id
	left join sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = E.CauseId 
	LEFT JOIN sSecurity.tUser U ON U.Id = E.CreatedUserId 
	inner JOIN sSecurity.tUserLocation UL ON  UL.StoreLocationId = SL.Id and UL.UserId = @rUserId
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON EM.DepartmentGroupId = DGM.Id 		
	LEFT JOIN sCommon.tFunctionMaster FM  ON DGM.FunctionId= FM.Id
	where 
	E.StatusId in (5,6) and
	SM.SubTypeId in (1,2)  And SM.IsObsolete='0'
	and EM.OrgId = @rOrgId 
	and (SM.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)	
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND(E.GradeId=@rGradeId OR @rGradeId=0)
	AND((E.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))
	and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)
	and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)
	and (VM.SectorId = @rSectorId or @rSectorId = 0)
	AND(E.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND (FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND(EM.GenderId = @rGenderId OR @rGenderId=0)
	AND ((EM.Code =  @rEmployeeCode ) OR (@rEmployeeCode = '')) and SL.IsActiveHealth =1 
	AND (Jd.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND (Jd.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	AND (Jd.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)
	AND (SE.SetupId = @rRoundId OR @rRoundId = 0)
	AND (SM.SetupGroupId = @rRoundGroupId OR @rRoundGroupId = 0)
	and SL.IsActiveHealth =1 
	group by SL.ID)
	) as d on d.Id = SLM.id
	left join(
	(select SL.ID,count(*) as TotalNotStartedCnt from sExamination.tSetupEmployee SE
	inner join sExamination.tSetupMaster SM	on SE.SetupId = SM.Id
	inner join sHrm.vEmployeeCommonDetail EM on SE.EmployeeId = EM.EmployeeId
	inner join sHrm.tEmployeeJobDetail JD on EM.EmployeeId = JD.EmployeeId	
	left join sExamination.tExamination E on E.ParticipantSourceId = SE.EmployeeId and E.SetupId = SM.Id
	inner join sIp.tStoreLocationMaster SL on SL.Id = SM.StoreLocationId
	left join sCommon.tOrganizationDepartmentMaster OD on JD.OrganizationDepartmentId = OD.Id	
	left join sHrm.tEmployeeCompanyMaster ECM on JD.EmployeeCompanyId = ECM.Id
	left join sHrm.tCompanyGroupMaster CG on ECM.CompanyGroupId = CG.Id
	left join sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = E.CauseId 
	LEFT JOIN sSecurity.tUser U ON U.Id = E.CreatedUserId 
	inner JOIN sSecurity.tUserLocation UL ON  UL.StoreLocationId = SL.Id and UL.UserId = @rUserId
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON EM.DepartmentGroupId = DGM.Id 		
	LEFT JOIN sCommon.tFunctionMaster FM  ON DGM.FunctionId= FM.Id
	where 
	( E.Id is null or E.StatusId=101) and
	SM.SubTypeId in (1,2)  And SM.IsObsolete='0'
	and EM.OrgId = @rOrgId 
	and (SM.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)	
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND(E.GradeId=@rGradeId OR @rGradeId=0)
	AND((E.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))
	and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)
	and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)
	and (VM.SectorId = @rSectorId or @rSectorId = 0)
	AND(E.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND (FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND(EM.GenderId = @rGenderId OR @rGenderId=0)
	AND ((EM.Code =  @rEmployeeCode ) OR (@rEmployeeCode = '')) and SL.IsActiveHealth =1 
	AND (Jd.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND (Jd.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	AND (Jd.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)
	AND (SE.SetupId = @rRoundId OR @rRoundId = 0)
	AND (SM.SetupGroupId = @rRoundGroupId OR @rRoundGroupId = 0)
	and SL.IsActiveHealth =1 
	group by SL.ID)
	) as f on f.Id = SLM.id
	
	where (SLM.Id = @rStoreLocationId or @rStoreLocationId = 0) and
	SLM.IsObsolete=0 and SLM.IsActiveHealth='1' and SLM.OrgId=@rOrgId

	---------------------------------------------------------START------------------------------------------------------------------

	--SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)

   IF OBJECT_ID('tempdb..#HealthIndicatorStatus') IS NOT NULL
	DROP TABLE #HealthIndicatorStatus

   IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
	DROP TABLE #TableOne


        DECLARE @count int = 0

        DECLARE @HealthIndicatorId TABLE (HealthIndicatorId int, OrgId int, ColorCode nvarchar(50))

        DECLARE @HealthIndicatorCount TABLE (Id int IDENTITY (1, 1),OrgId int)

        Create TABLE #HealthIndicatorStatus  (OrgId int,VeryPoor int,Poor int,Fair int,Good int,Excellent int,ClassicWell int,
		ColorCode1 nvarchar(50), ColorCode2 nvarchar(50), ColorCode3 nvarchar(50), ColorCode4 nvarchar(50), ColorCode5 nvarchar(50), ColorCode6 nvarchar(50))

        INSERT INTO @HealthIndicatorId
		Select t.HealthIndicatorId, t.Id, HIM.ColorCode from (
            SELECT (SELECT id FROM [sExamination].[tHealthIndicatorMaster]
            WHERE RangeTo >= CONVERT(decimal(18, 2), ((SUM(CONVERT(decimal(18, 2), DIA.EarnedHealthPoints)) * 100) / SUM(CONVERT(decimal(18, 2), DIA.TotalHealthPoints))))
            AND CONVERT(decimal(18, 2), ((SUM(CONVERT(decimal(18, 2), DIA.EarnedHealthPoints)) * 100) / SUM(CONVERT(decimal(18, 2), DIA.TotalHealthPoints)))) > RangeFrom)
            AS HealthIndicatorId,
            SLM.Id
            FROM sExamination.tExamination AS EXM
            INNER JOIN [sExamination].[tDiagnosis] AS DIA ON EXM.Id = DIA.SourceId
            INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID = EXM.SetupId
            INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
            INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID = EXM.ParticipantSourceId
            INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id = EXM.StoreLocationId
            INNER JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id = SLM.LocationId
            INNER JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID = EMP.OrgId
            INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id
			--Change By Nidhi Pandey due to Health index location wise count mismatch; dt - 18/04/2022  (make below joins from INNER -> LEFT)
            LEFT JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId = EMP.ID
            LEFT JOIN [sExamination].[tHealthIndicatorMaster] AS HIM ON HIM.Id = DIA.HealthIndicatorId
            LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id = EXM.EmployeeCompanyId
            LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id = ECM.CompanyGroupId
            LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID = CGM.VerticalId
            LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id = VTM.SectorId
            LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id = EXM.OrganizationDepartmentId
            LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id = DPT.DepartmentGroupId
            LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id = DPG.FunctionId
            LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EMP.Id = EPD.EmployeeId	  	     
			WHERE EXM.ParticipantSourceTypeId = 95
            AND EXM.OrgId = @rOrgId
            AND DIA.TotalHealthPoints > 0
            AND SSM.MainTypeId in (1,2)
			AND UL.UserId=@rUserId
            AND ((STM.SetupGroupId = @rRoundGroupId) OR (@rRoundGroupId = 0))
            AND ((EXM.SetupId = @rRoundId) OR (@rRoundId = 0))
            AND ((VTM.SectorId = @rSectorId) OR (@rSectorId = 0))
            AND ((CGM.VerticalId = @rVerticalId) OR (@rVerticalId = 0))
            AND ((ECM.CompanyGroupId = @rCompnayGroupId) OR (@rCompnayGroupId = 0))
            AND ((EJD.EmployeeCompanyId = @rCompanyId) OR (@rCompanyId = 0))
            --AND ((SLM.LocationId = @rLocationId) OR (@rLocationId = 0))
            AND ((EXM.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
            AND ((DPG.FunctionId = @rFunctionId) OR (@rFunctionId = 0))
            AND ((DPT.DepartmentGroupId = @rDepartmentGroupId) OR (@rDepartmentGroupId = 0))
            AND ((EXM.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
            AND ((EMP.Code = @rEmployeeCode) OR (@rEmployeeCode = ''))
			AND ((EXM.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
			AND ((EXM.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))                                    
			AND ((EPD.GenderId = @rGenderId) OR (@rGenderId = 0))			                                    
            AND ((EXM.GradeId = @rGradeId) OR (@rGradeId = 0))			                                    
			AND ((EXM.TargetGroupId = @rTargetGroupId) OR (@rTargetGroupId = 0))			                                    
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR @rEmployeeTypeId = 0)
			AND ((EJD.EmployeeGroupId = @rEmployeeTypeGoupId) OR (@rEmployeeTypeGoupId = 0))
			AND ((EJD.EmployeeSubTypeId = @rEmployeeSubTypeId) OR (@rEmployeeSubTypeId = 0))
			GROUP BY EMP.ID, SLM.Id
			) t
			INNER JOIN [sExamination].[tHealthIndicatorMaster] HIM ON HIM.Id = t.HealthIndicatorId
			option(Recompile)
        INSERT INTO @HealthIndicatorCount 
		SELECT OrgId FROM @HealthIndicatorId GROUP BY OrgId

        SELECT @count = COUNT(0) FROM @HealthIndicatorCount

        WHILE (@count <> 0)
        BEGIN
            DECLARE @myOrgId bigint = 0
            SELECT @myOrgId = OrgId
            FROM @HealthIndicatorCount
            WHERE id = @count
            INSERT INTO #HealthIndicatorStatus

                SELECT @myOrgId, (SELECT COUNT(0) FROM @HealthIndicatorId WHERE HealthIndicatorId = 1 AND OrgId = @myOrgId)
                , (SELECT COUNT(0) FROM @HealthIndicatorId WHERE HealthIndicatorId = 2 AND OrgId = @myOrgId)
                , (SELECT COUNT(0) FROM @HealthIndicatorId WHERE HealthIndicatorId = 3 AND OrgId = @myOrgId)
                , (SELECT COUNT(0) FROM @HealthIndicatorId WHERE HealthIndicatorId = 4 AND OrgId = @myOrgId)
                , (SELECT COUNT(0) FROM @HealthIndicatorId WHERE HealthIndicatorId = 5 AND OrgId = @myOrgId)
				, (SELECT COUNT(0) FROM @HealthIndicatorId WHERE HealthIndicatorId = 6 AND OrgId = @myOrgId)
				, (SELECT top 1 ISNULL(ColorCode, '') FROM @HealthIndicatorId WHERE HealthIndicatorId = 1 AND OrgId = @myOrgId)
				, (SELECT top 1 ISNULL(ColorCode, '') FROM @HealthIndicatorId WHERE HealthIndicatorId = 2 AND OrgId = @myOrgId)
				, (SELECT top 1 ISNULL(ColorCode, '') FROM @HealthIndicatorId WHERE HealthIndicatorId = 3 AND OrgId = @myOrgId)
				, (SELECT top 1 ISNULL(ColorCode, '') FROM @HealthIndicatorId WHERE HealthIndicatorId = 4 AND OrgId = @myOrgId)
				, (SELECT top 1 ISNULL(ColorCode, '') FROM @HealthIndicatorId WHERE HealthIndicatorId = 5 AND OrgId = @myOrgId)
				, (SELECT top 1 ISNULL(ColorCode, '') FROM @HealthIndicatorId WHERE HealthIndicatorId = 6 AND OrgId = @myOrgId)

            SET @count = @count - 1
        END


        Create TABLE #TableOne (tid int IDENTITY (1, 1),RowID nvarchar(50),OrgId bigint,OrganizationName nvarchar(250),TotalPoints decimal(10, 2),EarnedPoints decimal(10, 2),Percentage decimal(10, 2),IndicatorName nvarchar(250),TotalEmployee int, ColorCode nvarchar(50))
        INSERT INTO #TableOne
		select P.RowID, P.OrgId, P.OrganizationName, P.TotalPoints, P.EarnedPoints, P.Percentage, 
		(CASE WHEN ISNULL(HIM.HealthIndicatorLabel, '') != '' and HIM.IsObsolete = 0 THEN HIM.HealthIndicatorLabel ELSE HIM.Title END) as IndicatorName, 
		P.TotalEmployee, HIM.ColorCode from (
            SELECT CONVERT(nvarchar(50), REPLACE(NEWID(), '-', '')) AS RowID
            , SLM.Id AS OrgId
            , SLM.Title AS OrganizationName
            , SUM(DIA.TotalHealthPoints) TotalPoints
            , SUM(DIA.EarnedHealthPoints) EarnedPoints
            , CONVERT(decimal(18, 2), ((SUM(CONVERT(decimal(18, 2), DIA.EarnedHealthPoints)) * 100) / SUM(CONVERT(decimal(18, 2), DIA.TotalHealthPoints)))) AS Percentage
            , ISNULL((
				SELECT Id FROM [sExamination].[tHealthIndicatorMaster] 
				WHERE RangeTo >= CONVERT(decimal(18, 2), ((SUM(CONVERT(decimal(18, 2), DIA.EarnedHealthPoints)) * 100) / SUM(CONVERT(decimal(18, 2), DIA.TotalHealthPoints))))
				AND CONVERT(decimal(18, 2), ((SUM(CONVERT(decimal(18, 2), DIA.EarnedHealthPoints)) * 100) / SUM(CONVERT(decimal(18, 2), DIA.TotalHealthPoints)))) > RangeFrom
				),'')
            AS IndicatorId
            , COUNT(0) AS TotalEmployee
            FROM sExamination.tExamination AS EXM
            INNER JOIN [sExamination].[tDiagnosis] AS DIA ON EXM.Id = DIA.SourceId
            INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID = EXM.SetupId
            INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
            INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID = EXM.ParticipantSourceId
            INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id = EXM.StoreLocationId
            INNER JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id = SLM.LocationId
            INNER JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID = EMP.OrgId
			INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id
			--Change By Nidhi Pandey due to Health index location wise count mismatch; dt - 18/04/2022  (make below joins from INNER -> LEFT)
            LEFT JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId = EMP.ID
            LEFT JOIN [sExamination].[tHealthIndicatorMaster] AS HIM ON HIM.Id = DIA.HealthIndicatorId
            LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id = EXM.EmployeeCompanyId
            LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id = ECM.CompanyGroupId
            LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID = CGM.VerticalId
            LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id = VTM.SectorId
            LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id = EXM.OrganizationDepartmentId
            LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id = DPT.DepartmentGroupId
            LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id = DPG.FunctionId
            LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EMP.Id = EPD.EmployeeId	  	 
			WHERE EXM.ParticipantSourceTypeId = 95
            AND EXM.OrgId = @rOrgId
            AND DIA.TotalHealthPoints > 0
            AND SSM.MainTypeId in (1,2)
			AND UL.UserId=@rUserId
            AND ((STM.SetupGroupId = @rRoundGroupId) OR (@rRoundGroupId = 0))
            AND ((EXM.SetupId = @rRoundId) OR (@rRoundId = 0))
            AND ((VTM.SectorId = @rSectorId) OR (@rSectorId = 0))
            AND ((CGM.VerticalId = @rVerticalId) OR (@rVerticalId = 0))
            AND ((ECM.CompanyGroupId = @rCompnayGroupId) OR (@rCompnayGroupId = 0))
            AND ((EJD.EmployeeCompanyId = @rCompanyId) OR (@rCompanyId = 0))
            --AND ((SLM.LocationId = @rLocationId) OR (@rLocationId = 0))
            AND ((EXM.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
            AND ((DPG.FunctionId = @rFunctionId) OR (@rFunctionId = 0))
            AND ((DPT.DepartmentGroupId = @rDepartmentGroupId) OR (@rDepartmentGroupId = 0))
            AND ((EXM.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
            AND ((EMP.Code = @rEmployeeCode) OR (@rEmployeeCode = ''))
            AND ((EXM.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
			AND ((EXM.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
			AND ((EPD.GenderId = @rGenderId) OR (@rGenderId = 0))			                                    
            AND ((EXM.GradeId = @rGradeId) OR (@rGradeId = 0))	
			AND ((EXM.TargetGroupId = @rTargetGroupId) OR (@rTargetGroupId = 0))
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR @rEmployeeTypeId = 0)
			AND ((EJD.EmployeeGroupId = @rEmployeeTypeGoupId) OR (@rEmployeeTypeGoupId = 0))
			AND ((EJD.EmployeeSubTypeId = @rEmployeeSubTypeId) OR (@rEmployeeSubTypeId = 0))			                                    
			GROUP BY SLM.Id, SLM.Title
			) P
			INNER JOIN [sExamination].[tHealthIndicatorMaster] HIM ON HIM.Id = P.IndicatorId
            ORDER BY P.OrgId
			option(Recompile)

			--select * from #TableOne
			--select * from #HealthIndicatorStatus
  --      DECLARE @lReslutGridOrganization varchar(max) = ''

		--SELECT @lReslutGridOrganization = @lReslutGridOrganization + '<tr>
		--	<td style="width: 20%;">' + ISNULL(OrganizationName, '') + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(TotalEmployee, 0)) + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(Percentage, 0)) + '</td>
		--	<td style="width: 10%; ">' + ISNULL(IndicatorName, '') + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Excellent * 100) / CONVERT(decimal(18, 2), TotalEmployee)), 0)) + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Good * 100) / CONVERT(decimal(18, 2), TotalEmployee)), 0)) + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Fair * 100) / CONVERT(decimal(18, 2), TotalEmployee)), 0)) + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Poor * 100) / CONVERT(decimal(18, 2), TotalEmployee)), 0)) + '</td>
		--	<td style="width: 10%; text-align: right;">' + CONVERT(varchar, ISNULL(CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.VeryPoor * 100) / CONVERT(decimal(18, 2), TotalEmployee)), 0)) + '</td>
		--	</tr>'
  --      FROM #TableOne AS t 
		--INNER JOIN #HealthIndicatorStatus S ON t.OrgId = s.OrgId
		--order by OrganizationName
		--option(Recompile)


		--IF (@lReslutGridOrganization <> '')
		--BEGIN
			
		--	Declare @Header nvarchar(max)=' <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 98%; border-collapse: collapse;"><thead>
  --                                          <tr>
  --                                              <td>Sub Location</td>
  --                                              <td style="text-align: right;">Total Employee</td>
  --                                              <td style="text-align: right;">Health Index (%)</td>
  --                                              <td>Indicator</td>
  --                                              <td style="text-align: right;">Very Healthy (%)</td>
  --                                              <td style="text-align: right;">Healthy (%)</td>
  --                                              <td style="text-align: right;">Low Risk (%)</td>
  --                                              <td style="text-align: right;">Moderate Risk (%)</td>
  --                                              <td style="text-align: right;">High Risk (%)</td>
  --                                          </tr></thead>'
			


		--	SELECT @Header+''+@lReslutGridOrganization +'</table>' AS ResultGrid
		--END
		--ELSE
		--BEGIN
		--	SELECT '' AS ResultGrid
		--END
		
		--DECLARE @MainCount int = (Select count(*) from #TEMPTableMain)
		--Declare @lStoreLocationId int = '';
		--While(@MainCount < 0)
		--BEGIN
		--	Select @lStoreLocationId = StoreLocationId from #TEMPTableMain where tid = @MainCount

		--	if Exists(Select 1 from #TableOne AS t
		--	INNER JOIN #HealthIndicatorStatus S ON t.OrgId = s.OrgId where t.OrgId = @lStoreLocationId)
		--	BEGIN
		--		Update #TEMPTableMain set  
				
		--		Excellent = CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Excellent * 100) / CONVERT(decimal(18, 2), TotalEmployee)),
		--		Good = CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Good * 100) / CONVERT(decimal(18, 2), TotalEmployee)),
		--		Fair = CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Fair * 100) / CONVERT(decimal(18, 2), TotalEmployee)),
		--		Poor = CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Poor * 100) / CONVERT(decimal(18, 2), TotalEmployee)),
		--		VeryPoor = CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.VeryPoor * 100) / CONVERT(decimal(18, 2), TotalEmployee))
		--		FROM #TableOne AS t
		--		INNER JOIN #HealthIndicatorStatus S ON t.OrgId = s.OrgId where t.OrgId  = @lStoreLocationId
		--	END
			

		--	Set @MainCount = @MainCount - 1
		--END

		Update #TEMPTableMain
		Set Excellent = ISNULL(tExcellent,0), Good = ISNULL(tGood,0) , Fair = ISNULL(tFair,0), Poor = ISNULL(tPoor,0), VeryPoor = ISNULL(tVeryPoor,0),
		IndicatorName = ISNULL(t1.IndicatorName,''),Percentage = ISNULL(t1.Percentage,0),OrgId = ISNULL(t1.OrgId,0),ClassicWell = ISNULL(t1.tClassicWell,0),
		ColorCode = ISNULL(t1.ColorCode,0), ColorCode1 = ISNULL(t1.ColorCode1,0), ColorCode2 = ISNULL(t1.ColorCode2,0), ColorCode3 = ISNULL(t1.ColorCode3,0), 
		ColorCode4 = ISNULL(t1.ColorCode4,0), ColorCode5 = ISNULL(t1.ColorCode5,0), ColorCode6 = ISNULL(t1.ColorCode6,0)
		From (
		Select t.*, CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Excellent * 100) / CONVERT(decimal(18, 2), TotalEmployee)) as tExcellent,
				 CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Good * 100) / CONVERT(decimal(18, 2), TotalEmployee)) as tGood,
				 CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Fair * 100) / CONVERT(decimal(18, 2), TotalEmployee)) as tFair ,
				 CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.Poor * 100) / CONVERT(decimal(18, 2), TotalEmployee)) as tPoor ,
				 CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.VeryPoor * 100) / CONVERT(decimal(18, 2), TotalEmployee)) as tVeryPoor,				 
				 CONVERT(decimal(18, 2), CONVERT(decimal(18, 2), s.ClassicWell * 100) / CONVERT(decimal(18, 2), TotalEmployee)) as tClassicWell,
				 CONVERT(nvarchar(50), ISNULL(s.ColorCode1, '')) as ColorCode1,
				 CONVERT(nvarchar(50), ISNULL(s.ColorCode2, '')) as ColorCode2,
				 CONVERT(nvarchar(50), ISNULL(s.ColorCode3, '')) as ColorCode3,
				 CONVERT(nvarchar(50), ISNULL(s.ColorCode4, '')) as ColorCode4,
				 CONVERT(nvarchar(50), ISNULL(s.ColorCode5, '')) as ColorCode5,
				 CONVERT(nvarchar(50), ISNULL(s.ColorCode6, '')) as ColorCode6
				FROM #TableOne AS t
				INNER JOIN #HealthIndicatorStatus S ON t.OrgId = s.OrgId ) as t1 where t1.OrgId  = #TEMPTableMain.StoreLocationId

	    

        --option(Recompile)
			
  Drop table #HealthIndicatorStatus   
  Drop table #TableOne


	--------------------------------------------------------- END -------------------------------------------------------------------
	
	
	--------------------------------------------------------- Start -------------------------------------------------------------------

	

	IF(@rToDate='')
	BEGIN
		SET @rToDate='01/06/2050'
	END
	

	DECLARE @EmployeeCode nVarchar(100)=''
	DECLARE @lReslutGridOrganization varchar(max)='',@lpaging varchar(max)=''
	DECLARE	@PageSize INT=50

	Select Distinct EXM.ID,EXM.SetupId,EXM.ParticipantSourceId,EXM.EmployeeCompanyId,EXM.StoreLocationId,
	EXM.OrganizationDepartmentId,EXM.ParticipantSourceTypeId,EXM.OrgId,EXM.ExaminationDate,EXM.GradeId
	 INto #tmp 
	FROM sExamination.tExamination AS EXM
	INNER JOIN sExamination.tHealthIndex AS HI ON HI.ExaminationId=EXM.Id
	--INNER JOIN [sExamination].[tHealthIndexParameterMaster] AS HIP ON HIP.ID = HI.HealthIndexParameterId	
	INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId
	INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId
	INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId
	INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID
	INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD on EMP.Id = EPD.EmployeeId	
	LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=EXM.EmployeeCompanyId
	LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId
	LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId
	LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId
	LEFT JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId
	LEFT JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId
	LEFT JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId
	LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId
	LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId
	LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId
	LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId
	LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId
	LEFT JOIN sHrm.tGradeMaster GRD on EJD.GradeId = GRD.Id
	INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	CROSS APPLY (
		SELECT TOP 1 HIM.Id
		FROM sExamination.tHealthIndicatorMaster AS HIM
		WHERE (HI.EarnedPoints * 100.0 / NULLIF(HI.TotalPoints,0)) > HIM.RangeFrom
			AND (HI.EarnedPoints * 100.0 / NULLIF(HI.TotalPoints,0)) <= HIM.RangeTo
	) AS HIA
	WHERE EXM.ParticipantSourceTypeId=95 AND EXM.OrgId=@rOrgId
	AND HI.TotalPoints>0 AND SSM.MaINTypeId=@rMaINTypeId
	--AND (((SELECT Id FROM [sExamination].[tHealthIndicatorMaster] WHERE RangeTo >=CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))
	--AND CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))>RangeFrom) =@rHealthIndicatorId) OR (@rHealthIndicatorId=0))
	AND (HIA.Id = @rHealthIndicatorId OR @rHealthIndicatorId=0)
	AND ((STM.SetupGroupId=@rRoundGroupId) OR (@rRoundGroupId=0))
	AND ((EXM.SetupId=@rRoundId) OR (@rRoundId=0))
	AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))
	AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))
	--AND ((HIP.ID in ((select Item from dbo.fSplitStr(@rHealthIndexParameterId,',') where Item <> ''))) OR (@rHealthIndexParameterId=''))
	AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))
	AND ((EJD.EmployeeCompanyId=@rCompanyId) OR (@rCompanyId=0))
	AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))
	AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))
	AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))
	AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((EMP.Code LIKE @rEmployeeCode) OR (@rEmployeeCode  = ''))
	AND ((CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) >= @rFromPercentage) OR (@rFromPercentage = -1))
	AND ((CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) <= @rToPercentage) OR (@rToPercentage = -1))
	AND ((LSG.Id=@rLocationSubGroupId ) OR (@rLocationSubGroupId  = 0 ))
	AND ((LMG.Id=@rLocationMainGroupId) OR (@rLocationMainGroupId = 0 ))
	AND UL.UserId = @rUserId 
	--AND ((EXM.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	--AND ((EXM.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='')
	AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)

	DECLARE @GeneratedCountSQL NVARCHAR(MAX) = N'';

	SET @GeneratedCountSQL = N'
	UPDATE TM
	SET Generated = t.GeneratedCount
	FROM #TEMPTableMain AS TM
	INNER JOIN (
		SELECT 
			COUNT(1) AS GeneratedCount,
			SLM.Id AS StoreLocationId
		FROM #tmp AS EXM
		INNER JOIN sExamination.tHealthIndex AS HI 
			ON HI.ExaminationId = EXM.Id
		CROSS APPLY (
			SELECT 
				CAST(
					(CAST(HI.EarnedPoints AS DECIMAL(18,2)) * 100.0) /
					NULLIF(CAST(HI.TotalPoints AS DECIMAL(18,2)),0)
				AS DECIMAL(18,2)) AS Percentage
		) AS P
		INNER JOIN sExamination.tSetupMaster AS STM 
			ON STM.ID = EXM.SetupId
		INNER JOIN sExamination.tSetupGroupMaster AS SGM 
			ON SGM.Id = STM.SetupGroupId
		INNER JOIN sExamination.tSubTypeMaster AS SSM 
			ON SSM.Id = STM.SubTypeId
		INNER JOIN sHrm.tEmployeeMaster AS EMP 
			ON EMP.ID = EXM.ParticipantSourceId
		INNER JOIN sHrm.tEmployeeJobDetail AS EJD 
			ON EJD.EmployeeId = EMP.ID
		INNER JOIN sHrm.tEmployeePersonalDetail AS EPD 
			ON EMP.Id = EPD.EmployeeId
		LEFT JOIN sHrm.tEmployeeCompanyMaster AS ECM 
			ON ECM.Id = EXM.EmployeeCompanyId
		LEFT JOIN sHrm.tCompanyGroupMaster AS CGM 
			ON CGM.Id = ECM.CompanyGroupId
		LEFT JOIN sHrm.tVerticalMaster AS VTM 
			ON VTM.ID = CGM.VerticalId
		LEFT JOIN sHrm.tSectorMaster AS SCT 
			ON SCT.Id = VTM.SectorId
		LEFT JOIN sCommon.tCompanyInformation AS CMP 
			ON CMP.ID = SCT.OrgId
		LEFT JOIN sIp.tStoreLocationMaster AS SLM 
			ON SLM.Id = EXM.StoreLocationId
		LEFT JOIN sCommon.tLocationMaster AS LMN 
			ON LMN.Id = SLM.LocationId
		LEFT JOIN sCommon.tOrganizationDepartmentMaster AS DPT 
			ON DPT.Id = EXM.OrganizationDepartmentId
		LEFT JOIN sCommon.tDepartmentGroupMaster AS DPG 
			ON DPG.Id = DPT.DepartmentGroupId
		LEFT JOIN sCommon.tFunctionMaster AS FCN 
			ON FCN.Id = DPG.FunctionId
		LEFT JOIN sCommon.tLocationSubGroupMaster AS LSG 
			ON LSG.Id = LMN.LocationSubGroupId
		LEFT JOIN sCommon.tLocationMainGroupMaster AS LMG 
			ON LMG.Id = LSG.LocationMainGroupId
		LEFT JOIN sHrm.tGradeMaster AS GRD 
			ON EJD.GradeId = GRD.Id
		INNER JOIN sSecurity.tUserLocation AS UL 
			ON EXM.StoreLocationId = UL.StoreLocationId
		LEFT JOIN sExamination.tHealthIndicatorMaster AS HIM
			ON P.Percentage BETWEEN HIM.RangeFrom AND HIM.RangeTo
		WHERE ((EXM.ParticipantSourceTypeId = 0) OR (0=0))  
		  AND EXM.OrgId = @rOrgId
		  AND HI.TotalPoints > 0 
		  AND SSM.MainTypeId = @rMainTypeId';

	-- Only add filters if parameters are set
	IF @rHealthIndicatorId <> 0
		SET @GeneratedCountSQL += ' AND HIM.Id = @rHealthIndicatorId';

	IF @rRoundGroupId <> 0
		SET @GeneratedCountSQL += ' AND STM.SetupGroupId = @rRoundGroupId';

	IF @rRoundId <> 0
		SET @GeneratedCountSQL += ' AND EXM.SetupId = @rRoundId';

	IF @rSectorId <> 0
		SET @GeneratedCountSQL += ' AND VTM.SectorId = @rSectorId';

	IF @rVerticalId <> 0
		SET @GeneratedCountSQL += ' AND CGM.VerticalId = @rVerticalId';

	IF @rCompanyGroupId <> 0
		SET @GeneratedCountSQL += ' AND ECM.CompanyGroupId = @rCompanyGroupId';

	IF @rEmployeeCompanyId <> 0
		SET @GeneratedCountSQL += ' AND EJD.EmployeeCompanyId = @rEmployeeCompanyId';

	IF @rLocationId <> 0
		SET @GeneratedCountSQL += ' AND SLM.LocationId = @rLocationId';

	IF @rStoreLocationId <> 0
		SET @GeneratedCountSQL += ' AND EXM.StoreLocationId = @rStoreLocationId';

	IF @rFunctionId <> 0
		SET @GeneratedCountSQL += ' AND DPG.FunctionId = @rFunctionId';

	IF @rDepartmentGroupId <> 0
		SET @GeneratedCountSQL += ' AND DPT.DepartmentGroupId = @rDepartmentGroupId';

	IF @rDepartmentId <> 0
		SET @GeneratedCountSQL += ' AND EXM.OrganizationDepartmentId = @rDepartmentId';

	IF @rEmployeeCode <> ''
		SET @GeneratedCountSQL += ' AND EMP.Code = @rEmployeeCode';

	IF @rFromPercentage <> -1
		SET @GeneratedCountSQL += ' AND P.Percentage >= @rFromPercentage';

	IF @rToPercentage <> -1
		SET @GeneratedCountSQL += ' AND P.Percentage <= @rToPercentage';

	IF @rLocationSubGroupId <> 0
		SET @GeneratedCountSQL += ' AND LSG.Id = @rLocationSubGroupId';

	IF @rLocationMainGroupId <> 0
		SET @GeneratedCountSQL += ' AND LMG.Id = @rLocationMainGroupId';

	IF ISNULL(@rFromDate,'') <> ''
		SET @GeneratedCountSQL += ' AND EXM.ExaminationDate >= @rFromDate';

	IF ISNULL(@rToDate,'') <> ''
		SET @GeneratedCountSQL += ' AND EXM.ExaminationDate <= @rToDate';

	IF @rGradeId <> 0
		SET @GeneratedCountSQL += ' AND EXM.GradeId = @rGradeId';

	IF @rGenderId <> 0
		SET @GeneratedCountSQL += ' AND EPD.GenderId = @rGenderId';

	IF @rEmployeeTypeId <> 0
		SET @GeneratedCountSQL += ' AND EJD.EmployeeTypeId = @rEmployeeTypeId';

	IF @rEmployeeTypeGoupId <> 0
		SET @GeneratedCountSQL += ' AND EJD.EmployeeGroupId = @rEmployeeTypeGoupId';

	IF @rEmployeeSubTypeId <> 0
		SET @GeneratedCountSQL += ' AND EJD.EmployeeSubTypeId = @rEmployeeSubTypeId';

	SET @GeneratedCountSQL += '
		  AND UL.UserId = @rUserId
		GROUP BY SLM.Id
	) AS t
	ON TM.StoreLocationId = t.StoreLocationId
	';

	-- Execute
	EXEC sp_executesql 
    @GeneratedCountSQL,
    N'@rStoreLocationId INT, @rParticipantTypeId INT, @rCaseCauseId INT, 
      @rLocationId INT, @rFunctionId INT, @rDepartmentGroupId INT, 
      @rDepartmentId INT, @rGradeId INT, @rDesignationId INT, 
      @rJobTitleId INT, @rCompanyId INT, @rContractorId INT, 
      @rGenderId SMALLINT, @rStatusId SMALLINT, 
      @rAgeFrom INT, @rAgeTo INT, @rFromDate DATE, @rToDate DATE, 
      @rOrgId INT, @rEmployeeCode NVARCHAR(50), 
      @rUserId BIGINT, @rSectorId INT, @rVerticalId INT, 
      @rCompnayGroupId INT, @rRoundGroupId INT, 
      @rRoundId INT, @rEmployeeTypeGoupId INT, 
      @rEmployeeTypeId INT, @rEmployeeSubTypeId INT, 
      @rTargetGroupId INT, @rHealthIndicatorId INT, 
      @rLocationMainGroupId INT, @rLocationSubGroupId INT, 
      @rFromPercentage DECIMAL(10,2), @rToPercentage DECIMAL(10,2), 
      @rMaINTypeId INT, @rCompanyGroupId INT, 
      @rEmployeeCompanyId INT, @PageIndex INT',
    @rStoreLocationId, @rParticipantTypeId, @rCaseCauseId, 
    @rLocationId, @rFunctionId, @rDepartmentGroupId, 
    @rDepartmentId, @rGradeId, @rDesignationId, 
    @rJobTitleId, @rCompanyId, @rContractorId, 
    @rGenderId, @rStatusId, 
    @rAgeFrom, @rAgeTo, @rFromDate, @rToDate, 
    @rOrgId, @rEmployeeCode, 
    @rUserId, @rSectorId, @rVerticalId, 
    @rCompnayGroupId, @rRoundGroupId, 
    @rRoundId, @rEmployeeTypeGoupId, 
    @rEmployeeTypeId, @rEmployeeSubTypeId, 
    @rTargetGroupId, @rHealthIndicatorId, 
    @rLocationMainGroupId, @rLocationSubGroupId, 
    @rFromPercentage, @rToPercentage, 
    @rMaINTypeId, @rCompanyGroupId, 
    @rEmployeeCompanyId, @PageIndex;

	

	--update #TEMPTableMain set 
	--Generated = t.GeneratedCount from (
	--Select Count(1) as GeneratedCount,SLM.Id as StoreLocationId 
	--FROM #tmp AS EXM
	----INNER JOin #tmp E On E.id=EXM.id
	--INNER JOIN sExamination.tHealthIndex AS HI ON HI.ExaminationId=EXM.Id
	----INNER JOIN [sExamination].[tHealthIndexParameterMaster] AS HIP ON HIP.ID = HI.HealthIndexParameterId	
	--INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId
	--INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId
	--INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
	--INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId
	--INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID
	--INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD on EMP.Id = EPD.EmployeeId	
	--LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=EXM.EmployeeCompanyId
	--LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId
	--LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId
	--LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId
	--LEFT JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId
	--LEFT JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId
	--LEFT JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId
	--LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId
	--LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId
	--LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId
	--LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId
	--LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId
	--LEFT JOIN sHrm.tGradeMaster GRD on EJD.GradeId = GRD.Id
	--INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	--WHERE ((EXM.ParticipantSourceTypeId = 0) OR (0=0))  AND EXM.OrgId=@rOrgId
	--AND HI.TotalPoints>0 AND SSM.MaINTypeId=@rMaINTypeId
	--AND (((SELECT Id FROM [sExamination].[tHealthIndicatorMaster] WHERE RangeTo >=CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))
	--AND CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints)))>RangeFrom) =@rHealthIndicatorId) OR (@rHealthIndicatorId=0))
	--AND ((STM.SetupGroupId=@rRoundGroupId) OR (@rRoundGroupId=0))
	--AND ((EXM.SetupId=@rRoundId) OR (@rRoundId=0))
	--AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))
	--AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))
	----AND ((HIP.ID in ((select Item from dbo.fSplitStr(@rHealthIndexParameterId,',') where Item <> ''))) OR (@rHealthIndexParameterId=''))
	--AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))
	--AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))
	--AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))
	--AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	--AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))
	--AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))
	--AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	--AND ((EMP.Code = @rEmployeeCode) OR (@rEmployeeCode  = ''))
	--AND ((CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) >= @rFromPercentage) OR (@rFromPercentage = -1))
	--AND ((CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) <= @rToPercentage) OR (@rToPercentage = -1))
	--AND ((LSG.Id=@rLocationSubGroupId ) OR (@rLocationSubGroupId  = 0 ))
	--AND ((LMG.Id=@rLocationMainGroupId) OR (@rLocationMainGroupId = 0 ))
	
	--AND ((EXM.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	--AND ((EXM.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))	
	--AND(EXM.GradeId=@rGradeId OR @rGradeId=0)
	--AND(EPD.GenderId = @rGenderId OR @rGenderId=0)
	--AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	--AND (EJD.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	--AND (EJD.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)
	--AND UL.UserId = @rUserId
	--Group By SLM.Id
	--) as t where #TEMPTableMain.StorelocationId = t.StorelocationId
	----Group by SLM.Id, SLM.Title

	Drop Table #tmp

	--------------------------------------------------------- END -------------------------------------------------------------------		
	
	
	--------------------------------------------------------- Start -------------------------------------------------------------------		
	

	DECLARE @GeneralCols varchar(max) = '', @GeneralCols1 varchar(max) = '', @lQueryExisting varchar(max), @GeneralCols2 varchar(max)
    SELECT @GeneralCols = STUFF((SELECT
        ',' + QUOTENAME(sCommon.fGetIntIdForOrg(Id, @rOrgId))
    FROM sExamination.tStaticHealthIndexParameterMaster
    WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17)
    ORDER BY Id
    FOR xml PATH (''), TYPE)
    .value('.', 'NVARCHAR(MAX)'), 1, 1, '')


	print '1'

    SELECT @GeneralCols1 = STUFF((SELECT
        ',' + QUOTENAME(Code) + ' varchar(300)'
    FROM sExamination.tStaticHealthIndexParameterMaster
    WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17)
    ORDER BY Id
    FOR xml PATH (''), TYPE)
    .value('.', 'NVARCHAR(MAX)'), 1, 1, '')


	print '1'

    SELECT @GeneralCols2 = STUFF((SELECT
        ',' + QUOTENAME(Code)
    FROM sExamination.tStaticHealthIndexParameterMaster
    WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17)
    ORDER BY Id
    FOR xml PATH (''), TYPE)
    .value('.', 'NVARCHAR(MAX)'), 1, 1, '')

    DECLARE @Header nvarchar(max) = '<tr style="background-color: #f9f9f9;"><th>Code</th><th>Name</th><th>Grade</th><th>Total Points</th><th>Earned Points</th><th>HealthIndex</th><th>Indicator</th>'
    SELECT @Header = @Header + '<th>' + code + '</th>'
    FROM sExamination.tStaticHealthIndexParameterMaster
    WHERE Id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17)
    ORDER BY Id
    SELECT @Header = @Header + '</tr>'


    IF OBJECT_ID('tempdb..#tblExamination') IS NOT NULL
        DROP TABLE #tblExamination


    CREATE TABLE #tblExamination (tid int IDENTITY (1, 1),ExaminationId bigint,EarnedPoints int,HealthIndexParameterId int,Code varchar(100))

    INSERT INTO #tblExamination
        SELECT H.ExaminationId, EarnedPoints, HealthIndexParameterId, HM.Code
        FROM sExamination.tHealthIndexPartial H
        INNER JOIN sExamination.tHealthIndexParameterMaster HM ON H.HealthIndexParameterId = HM.Id
        INNER JOIN sExamination.tStaticHealthIndexParameterMaster AS s ON s.Id = hm.StaticHealthIndexParameterId
        INNER JOIN sExamination.tExamination AS EXM ON H.ExaminationId = EXM.Id
        INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID = EXM.SetupId
        INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id = STM.SetupGroupId
        INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
        INNER JOIN sExamination.tDiagnosisPartial AS DIA ON EXM.Id = DIA.ExaminationId
        INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId
	INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID
	INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD on EMP.Id = EPD.EmployeeId	
	LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=EXM.EmployeeCompanyId
	LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId
	LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId
	LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId
	LEFT JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId
	LEFT JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId
	LEFT JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId
	LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId
	LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId
	LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId
	LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId
	LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId
	LEFT JOIN sHrm.tGradeMaster GRD on EJD.GradeId = GRD.Id
	INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	
        WHERE EXM.ParticipantSourceTypeId=95 AND EXM.OrgId=@rOrgId
	AND SSM.MaINTypeId=@rMaINTypeId	
	AND ((STM.SetupGroupId=@rRoundGroupId) OR (@rRoundGroupId=0))
	AND ((EXM.SetupId=@rRoundId) OR (@rRoundId=0))
	AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))
	AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))
	
	AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))
	AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))
	AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))
	AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))
	AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))
	AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((EMP.Code = @rEmployeeCode) OR (@rEmployeeCode  = ''))
	
	AND ((LSG.Id=@rLocationSubGroupId ) OR (@rLocationSubGroupId  = 0 ))
	AND ((LMG.Id=@rLocationMainGroupId) OR (@rLocationMainGroupId = 0 ))
	AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)  -- Nidhi Pandey; Mantis id = 22911, DT - 16/01/2023
	AND UL.UserId = @rUserId 
        AND s.Id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17)
	


    IF OBJECT_ID('tempdb..##tblMainTableStatus') IS NOT NULL
        DROP TABLE ##tblMainTableStatus

    SELECT @lQueryExisting = 'create table ##tblMainTableStatus(tid int identity(1,1),d_ExamId bigint,' + @GeneralCols1 + ')'
    EXEC (@lQueryExisting)

    SELECT @lQueryExisting = '
    insert into ##tblMainTableStatus	
	select ExaminationId,' + @GeneralCols2 + '
	from
	(
		select ExaminationId,EarnedPoints,Code from #tblExamination
	) src 
	pivot
	(
	  max(EarnedPoints) for Code in (' + @GeneralCols2 + ')
	) piv;'

	print @lQueryExisting
    EXEC (@lQueryExisting)

	UPDATE #TEMPTableMain set 
	NotGenerated = ISNULL(t.NotGeneratedCount,0)
	from 
	(Select Count(1) as NotGeneratedCount,SLM.Id as StoreLocationId 
	
    FROM ##tblMainTableStatus AS m
    INNER JOIN sExamination.tExamination AS EXM ON m.d_ExamId = EXM.Id
    INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID = EXM.SetupId
    INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id = STM.SetupGroupId
    INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId
    INNER JOIN [sExamination].[tDiagnosisPartial] AS DIA ON EXM.Id = DIA.ExaminationId
    INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId
	INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID
	INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD on EMP.Id = EPD.EmployeeId	
	LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=EXM.EmployeeCompanyId
	LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId
	LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId
	LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId
	LEFT JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId
	LEFT JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId
	LEFT JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId
	LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId
	LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId
	LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId
	LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId
	LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId	
	LEFT JOIN sHrm.tGradeMaster GRD on EJD.GradeId = GRD.Id
	INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
    LEFT JOIN [sExamination].[tHealthIndicatorMaster] AS HIM ON HIM.Id = DIA.HealthIndicatorId
    WHERE ((EXM.ParticipantSourceTypeId = 0) OR (0=0))
    --AND SSM.MaINTypeId=@rMaINTypeId	
	AND ((STM.SetupGroupId=@rRoundGroupId) OR (@rRoundGroupId=0))
	AND ((EXM.SetupId=@rRoundId) OR (@rRoundId=0))
	AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))
	AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))
	
	AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))
	AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))
	AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))
	AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))
	AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))
	AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))
	AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	AND ((EMP.Code = @rEmployeeCode) OR (@rEmployeeCode  = ''))
	AND ((LSG.Id=@rLocationSubGroupId ) OR (@rLocationSubGroupId  = 0 ))
	AND ((LMG.Id=@rLocationMainGroupId) OR (@rLocationMainGroupId = 0 ))
	
	AND ((EXM.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EXM.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND(EXM.GradeId=@rGradeId OR @rGradeId=0)
	AND(EPD.GenderId = @rGenderId OR @rGenderId=0)
	AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND (EJD.EmployeeGroupId = @rEmployeeTypeGoupId OR @rEmployeeTypeGoupId = 0)
	AND (EJD.EmployeeSubTypeId = @rEmployeeSubTypeId OR @rEmployeeSubTypeId = 0)	
	AND UL.UserId = @rUserId 
    Group By SLM.Id) as t where #TEMPTableMain.StorelocationId = t.StorelocationId

	DECLARE @sql NVARCHAR(MAX);
	Declare @rHighRiskLabel nvarchar(20), @rModerateRiskLabel nvarchar(20), @rLowRiskLabel nvarchar(20), 
	@rHealthyLabel nvarchar(20), @rVeryHealthyLabel nvarchar(20), @rClassicWellLabel nvarchar(20);
	set @rHighRiskLabel = (select (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 
									from sExamination.tHealthIndicatorMaster where Code = '1') + ' (%)'
	set @rModerateRiskLabel = (select (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 
									from sExamination.tHealthIndicatorMaster where Code = '2') + ' (%)'
	set @rLowRiskLabel = (select (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 
									from sExamination.tHealthIndicatorMaster where Code = '3') + ' (%)'
	set @rHealthyLabel = (select (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 
									from sExamination.tHealthIndicatorMaster where Code = '4') + ' (%)'
	set @rVeryHealthyLabel = (select (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 
									from sExamination.tHealthIndicatorMaster where Code = '5') + ' (%)'
	set @rClassicWellLabel = (select (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 
									from sExamination.tHealthIndicatorMaster where Code = '6') + ' (%)'

	SET @sql = N'
    SELECT  
        Storelocation AS [Sub Location],
        TotalFeezCnt AS [Total Freezed Employee],
        TotalInProgressCnt AS [InProgress],
        TotalCompletedCnt AS Completed,
        TotalClosedCnt AS Closed,
        TotalNotStartedCnt AS [Not Started],
        Generated,
        NotGenerated AS [Not Generated],
        Percentage AS [Health Index (%)],
        IndicatorName AS Indicator,
        ClassicWell AS ' + QUOTENAME(@rClassicWellLabel) + ',
        Excellent AS ' + QUOTENAME(@rVeryHealthyLabel) + ',
        Good AS ' + QUOTENAME(@rHealthyLabel) + ',
        Fair AS ' + QUOTENAME(@rLowRiskLabel) + ',
        Poor AS ' + QUOTENAME(@rModerateRiskLabel) + ',
        VeryPoor AS ' + QUOTENAME(@rHighRiskLabel) + N'
    FROM #TEMPTableMain;';

	EXEC sp_executesql @sql;

	 Select ColorCode,
	 ColorCode1,
	 ColorCode2,
	 ColorCode3,
	 ColorCode4,
	 ColorCode5,
	 ColorCode6
	 from #TEMPTableMain

	Drop table #TEMPTableMain
	IF OBJECT_ID('tempdb..##tblMainTableStatus') IS NOT NULL
        DROP TABLE ##tblMainTableStatus
	--------------------------------------------------------- END -------------------------------------------------------------------		
END
GO
PRINT N'Altering Procedure [sExamination].[pSaveAllExaminationDatas]...';


GO

ALTER proc [sExamination].[pSaveAllExaminationDatas]     
@rVital varchar(max),                
@rAppointments varchar(max),                
@rDisese varchar(max),                
@rDiseaseDetails varchar(max),                
@rPrescription varchar(max),                
@rPrescriptionDetail varchar(max),                
@rComplaint varchar(max),                
@rTests varchar(max),                
@rReferrals varchar(max),                
@rOthers varchar(max),                
@rHabits varchar(max),                
@rLSDTests varchar(max),  
@rGroupItemPrescription varchar(max),
@rIsonSugarMedication bit=0,       
@rIsonBPMedication bit=0,             
@rIsNewLSD bit=0,
@rIsDataEntryTemplateModal bit=0
as                
begin                 
SET NOCOUNT ON                
--SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED                
--SET XACT_ABORT ON                
                
 --SELECT -1 AS RESULT                
 --return                
 declare @trancount int;                
                    
 declare @error int, @message varchar(4000), @xstate int,@errorCount int, @errorLine int;                
                
 declare @lOrgId int,@lNextNumber bigint,@lFromNextNumber bigint,@lCount int,@rStoreLocationId int,@lExaminationId bigint,@lStorelocationId bigint                
 declare @lAppointmentid bigint,@rReferSourceId bigint,@i int,@tParticipantSourceId bigint,@lAppointmentType tinyint                
 declare @loNextNumber varchar(20),@lAppointmentDate varchar(50),@lAutoDispense varchar(50)                
                 
 declare @lxmlVital xml,@lxmlAppointment xml,@lxmlDisease xml,@lxmlDiseaseDetail xml,                
 @lxmlPrescription xml,@lxmlPrescriptionDetail xml,@lxmlCmplaint xml,@lxmlTests xml,                
 @lxmlReferral xml,@lxmlOthers xml,@lxmlGroupItemPrescription xml             
                 
 declare @exceptiondetail nvarchar(max),@rUserId bigint,@username nvarchar(200)                 
 BEGIN TRY                       
 set @lxmlVital = CAST(@rVital AS xml)                
 set @lxmlAppointment = CAST(@rAppointments AS xml)                
 set @lxmlDisease = CAST(@rDisese AS xml)                
 set @lxmlDiseaseDetail = CAST(@rDiseaseDetails AS xml)                
 set @lxmlPrescription = CAST(@rPrescription AS xml)                
 set @lxmlPrescriptionDetail = CAST(@rPrescriptionDetail AS xml)                
 set @lxmlCmplaint = CAST(@rComplaint AS xml)                
 set @lxmlTests = CAST(@rTests AS xml)                
 set @lxmlReferral = CAST(@rReferrals AS xml)                
 set @lxmlOthers = CAST(@rOthers AS xml)    
 set @lxmlGroupItemPrescription = CAST(@rGroupItemPrescription AS xml)
                  
 declare @tblVital table(tid int identity(1,1),v_ExamId bigint,v_OrgId int,v_TypeId int,v_Pulse varchar(50),v_Temp varchar(50),                
 v_BPSys varchar(50),v_BPDia varchar(50),v_Height varchar(50),v_BodyWeight varchar(50),v_Id bigint,v_CreatedUserId bigint,v_Remark varchar(max),            
 a_providerId int,v_Spo2 varchar(50))       
    
 insert into @tblVital                
 select T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@SourceTypeId','int') as SourceTypeId,                
 T.c.value('@Pulse','varchar(50)') as Pulse,                
 T.c.value('@Temprature','varchar(50)') as Temprature,                
 T.c.value('@BPSys','varchar(50)') as BPSys,                
 T.c.value('@BPDia','varchar(50)') as BPDia,                
 T.c.value('@Height','varchar(50)') as Height,                
 T.c.value('@BodyWaight','varchar(50)') as BodyWaight,null,                
 T.c.value('@CreatedUserId','bigint') as CreatedUserId,                
 T.c.value('@Remark','varchar(max)') as Remark,            
 T.c.value('@ProviderId','int') as ProviderId,    
 T.c.value('@SPO2','varchar(50)') as v_Spo2        
 from @lxmlVital.nodes('/Vitals/vital')T(c)                
      -- select * from @tblVital
              
 set @rUserId = (Select Top 1 v_CreatedUserId from @tblVital)                
 set @username =(select Top 1 ISNULL(LoginTitle,'') from sSecurity.tUser where id=ISNULL(@rUserId,0))  

 update w set w.v_Id = v.Id from @tblVital w inner join sExamination.tVital v on w.v_ExamId = v.SourceId 
 
 select @lOrgId = v_OrgId,@lExaminationId=v_ExamId from @tblVital           
 select @tParticipantSourceId =ParticipantSourceId,@lStorelocationId=isnull(storelocationid,0) from sExamination.tExamination where Id=@lExaminationId               
 
  Declare @rOPDNumber nvarchar(50)='';
  set @rOPDNumber = (select ExaminationNumber from sExamination.tExamination where Id = @lExaminationId);

  Declare @rProviderAppointmentId BIGINT = 0;
  set @rProviderAppointmentId = (select top 1 ISNULL(a_providerId, 0) from @tblVital);
  IF (@rProviderAppointmentId > 0)
  BEGIN
		update sSupport.tProviderAppointment set StatusId = 591 Where Id = @rProviderAppointmentId;
		
		Insert into sSupport.tProviderAppointmentlog
		select Id, 591, @rUserId, sCommon.fGetDate(),@rOPDNumber
		FROM [sSupport].[tProviderAppointment]
		Where Id = @rProviderAppointmentId
  END
 
 --Developer: Deval, Added Configuration for Dispence Qty.            
 declare @lEnableDispenseConfigVal varchar(5), @lAutoDispenseConfigVal varchar(5);            
            
 select @lEnableDispenseConfigVal = sConfig.fConfigurationValueGet('OPD.IsEnableDispenseInPrescription',@lOrgId,@lStoreLocationId,0,0)            
 select @lAutoDispenseConfigVal = sConfig.fConfigurationValueGet('Examination.IsAutoDispense',@lOrgId,@lStoreLocationId,0,0)            
 --Developer: Deval, Added Configuration for Dispence Qty.            
 BEGIN TRY                
 --begin transaction                
                 
 --BEGIN                
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tVital', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --END                
                
 --select * from @tblVital                 
 --return                
                
 MERGE sExamination.tVital AS Target USING                 
 (                
  SELECT Id,v_Id,v_ExamId,v_OrgId,v_TypeId,v_Pulse,v_Temp,v_BPSys,                
  v_BPDia,v_Height,v_BodyWeight,v_CreatedUserId,v_Remark,tid ,v_Spo2               
  FROM @tblVital TT LEFT JOIN sExamination.tVital T with(nolock) ON TT.v_id = T.Id                
 ) AS Source ON Target.Id = Source.v_Id                
 WHEN MATCHED THEN                
  UPDATE SET Pulse = case when isnull(Source.v_pulse,'') <> '' then Source.v_pulse else null end,                
  BloodPressureSystolic = case when isnull(Source.v_BPSys,'') <> '' then Source.v_BPSys else null end,                
  BloodPressureDiastolic = case when isnull(Source.v_BPDia,'') <> '' then Source.v_BPDia else null end,         
  SPo2 = case when isnull(Source.v_Spo2,'') <> '' then Source.v_Spo2 else null end,        
  Temperature = case when isnull(Source.v_Temp,'') <> '' then Source.v_Temp else null end,                  
  Height = case when isnull(Source.v_Height,'') <> '' then Source.v_Height else null end,                
  BodyWeight = case when isnull(Source.v_BodyWeight,'') <> '' then Source.v_BodyWeight else null end,                
  BMI = case when isnull(Source.v_Height,'') <> '' and isnull(Source.v_BodyWeight,'') <> '' then                
  ROUND((CASE WHEN (Source.v_Height) = 0 THEN 0                
  ELSE CONVERT(DECIMAL(14, 6), ((Source.v_BodyWeight) / CAST(SQUARE((CASE WHEN (Source.v_Height) <= 0 THEN 1                
  ELSE CAST((Source.v_Height) AS DECIMAL(9, 6)) END)/ 100) AS DECIMAL(9, 6)))) END), 3) else BMI end,                  
  Remark = left([sSetup].[fPortalXMLTagsReplaceReverse](v_Remark),600),                
  UpdatedDateTime=sCommon.fGetDate()                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceId,SourceTypeId,Pulse,Temperature,BloodPressureSystolic,BloodPressureDiastolic,Height,                
   BodyWeight,BMI,IsObsolete,CreatedUserId,CreatedDateTime,OrgId,Remark ,SPo2               
  )                
  VALUES                
  (                
   v_ExamId,v_ExamId,v_TypeId,                
   case when isnull(v_pulse,'') = '' then null else v_pulse end,                
   case when isnull(v_Temp,'')='' then null else v_Temp end,                
   case when isnull(v_BPSys,'')='' then null else v_BPSys end,                
   case when isnull(v_BPDia,'')='' then null else v_BPDia end,         
   case when isnull(v_Height,'')='' then null else v_Height end,                
   case when isnull(v_BodyWeight,'')='' then null else v_BodyWeight end,                
   case when isnull(v_Height,'') <> '' and isnull(v_BodyWeight,'') <> '' then           
   ROUND((CASE WHEN (v_height) = 0 THEN 0 ELSE CONVERT(DECIMAL(14, 2),((v_BodyWeight) / CAST(SQUARE((CASE WHEN (v_height) <= 0 THEN 1                 
   ELSE CAST((v_height) AS DECIMAL(9,2)) END)/ 100) AS DECIMAL(9,2)))) END), 3) else 0 end,                
   0,v_CreatedUserId,sCommon.fGetDate(),v_OrgId,  
   left([sSetup].[fPortalXMLTagsReplaceReverse](v_Remark),600),  
   case when isnull(v_Spo2,'')='' then null else v_Spo2 end  
  );                
 --begin                
 --select @lCount = COUNT(1) FROM @tblVital                 
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tVital', @rCurrentNumber = @lNextNumber                
 --end                
 --commit tran;                
 END TRY          
 BEGIN CATCH                 
  select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                 
                  
  --set @trancount = @@trancount;                
                
  --if @xstate = -1                
  --          rollback;           
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran ;                
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @lOrgId,'OPD_Vital_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 1              
 END CATCH                
 declare @tblAppointments table(tid int identity(1,1),a_AppointmentId bigint,a_ExamId bigint,a_doctorId bigint,a_EmpId bigint,                
 a_obsolete bit,a_PatientSourceTypeId bigint,a_OrgId int,a_AppointmentDate varchar(50),a_StoreLocationId int,                
 a_FollowupRemark varchar(max),a_SetupId int,a_CauseId int,a_CreatedUserId bigint,a_SubTypeId int,                
 a_AppointNumber varchar(200),a_OtherName varchar(200),a_age int,a_VaccineId int,a_AppointmentType tinyint,a_genderId int, a_riskCategoryChecked int)            
 insert into @tblAppointments                
 select T.c.value('@AppointmentId','bigint') as AppointmentId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@DoctorEmployeeId','bigint') as DoctorEmployeeId,                
 T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,                
 T.c.value('@IsObsolete','bit') as IsObsolete,                
 T.c.value('@PatientSourceTypeId','int') as PatientSourceTypeId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@AppointmentDate','varchar(50)') as AppointmentDate,                
 T.c.value('@StoreLocationId','int') as StoreLocationId,   
 T.c.value('@FollowupRemark','varchar(max)') as FollowupRemark,                
 T.c.value('@SetupId','int') as SetupId,                
 T.c.value('@CauseId','int') as CauseId,                
 T.c.value('@CreatedUserId','bigint') as CreatedUserId,null,'',                
 T.c.value('@OtherName','varchar(200)') as OtherName,null as age,                
 T.c.value('@VaccineId','int') as VaccineId,                
 T.c.value('@AppointmentType','tinyint') as AppointmentType, null as genderId,            
 T.c.value('@RiskCategoryChecked','int') as RiskCategoryChecked            
 from @lxmlAppointment.nodes('/Appointments/Appointment')T(c)            
                
--select * from @tblAppointments --m            
            
 update w set w.a_SubTypeId = s.SubTypeId from @tblAppointments w inner join sExamination.tSetupMaster s on s.Id = w.a_SetupId                
                  
 update @tblAppointments set a_AppointmentId = IsNull(Id,0) from sAppointment.tAppointment where a_ExamId = ReferSourceId               
                 
 update a set a_age = case when a.a_PatientSourceTypeId = 1009 then                
 case when CS.DateOfBirth = '1900-01-01' then 0 else datediff(yy,CS.DateOfBirth,getdate()) end                
 when a.a_PatientSourceTypeId = 1001 then                
 case when EFD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EFD.DateOfBirth,getdate()) end else                
 case when EP.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EP.DateOfBirth,getdate()) end end                
 From @tblAppointments as a                
 left join sHrm.tEmployeeMaster EM on a.a_EmpId = EM.Id and a.a_PatientSourceTypeId = 95                
 left join sHrm.tEmployeePersonalDetail EP on a.a_EmpId = EP.EmployeeId and a.a_PatientSourceTypeId = 95                
 left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = a.a_EmpId and a.a_PatientSourceTypeId = 1001                
 left join sHrm.tCsrBenefiterMaster CS on a.a_EmpId = CS.Id and a.a_PatientSourceTypeId = 1009                
            
  update a set a_genderId = case when a.a_PatientSourceTypeId = 1009 then CS.GenderId                
 when a.a_PatientSourceTypeId = 1001 then EFD.GenderId else EP.GenderId end            
 From @tblAppointments as a                
 left join sHrm.tEmployeeMaster EM on a.a_EmpId = EM.Id and a.a_PatientSourceTypeId = 95                
 left join sHrm.tEmployeePersonalDetail EP on a.a_EmpId = EP.EmployeeId and a.a_PatientSourceTypeId = 95                
 left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = a.a_EmpId and a.a_PatientSourceTypeId = 1001                
 left join sHrm.tCsrBenefiterMaster CS on a.a_EmpId = CS.Id and a.a_PatientSourceTypeId = 1009                
                
  Declare @lExamid bigint = 0, @lFollowUpRemark varchar(max), @lEmpId bigint, @lRiskCategoryChecked bit;            
  select @lAppointmentid = ISNULL(a_AppointmentId,0),@lAppointmentType = ISNULL(a_AppointmentType,0), @lExamid = ISNULL(a_ExamId,0),            
  @lFollowUpRemark = ISNULL(a_FollowupRemark,''), @lEmpId = ISNULL(a_EmpId,0), @lRiskCategoryChecked = ISNULL(a_riskCategoryChecked, 0) from @tblAppointments            
            
  IF(@lRiskCategoryChecked = 1)            
  BEGIN            
   INSERT INTO [sExamination].[tLSDTrackerEmployee] (ParticipantSourceId, ParticipantSourceTypeId)              
  SELECT EXM.ParticipantSourceId, EXM.ParticipantSourceTypeId             
  FROM sExamination.tExamination EXM            
  WHERE EXM.Id = @lExamid            
  AND NOT EXISTS (            
   SELECT 1             
   FROM [sExamination].[tLSDTrackerEmployee] T            
   WHERE T.ParticipantSourceId = EXM.ParticipantSourceId            
   AND T.ParticipantSourceTypeId = EXM.ParticipantSourceTypeId            
  );            
    update [sExamination].[tLSDTrackerEmployee] set RiskCategoryId = 1            
    where ParticipantSourceId = @lEmpId and ParticipantSourceTypeId = 95            
            
    update [sExamination].[tExamination] set RiskCategoryId = 1 Where Id = @lExamid            
  END            
  ELSE            
  BEGIN            
         update [sExamination].[tLSDTrackerEmployee] set RiskCategoryId = 0           
    where ParticipantSourceId = @lEmpId and ParticipantSourceTypeId = 95         
   update [sExamination].[tExamination] set RiskCategoryId = 0 Where Id = @lExamid            
  END            
            
  if(ISNULL(@lAppointmentid,0)>0 and ISNULL(@lFollowUpRemark,'') != '')            
  BEGIN            
  update sAppointment.tAppointment set FollowupRemark = @lFollowUpRemark where Id = ISNULL(@lAppointmentid,0)            
  END            
                
  if(ISNULL(@lAppointmentid,0)>0)              
  begin               
  if exists (select 1 from  sAppointment.tAppointment where Id = ISNULL(@lAppointmentid,0) and ISNULL(@lAppointmentType,0) <> 1 and ISNULL(@lExamid,0) <> ReferSourceId)                 
  begin               
                
  update sAppointment.tAppointment set ApprovalStatusId = 550 where Id = ISNULL(@lAppointmentid,0) and ISNULL(@lAppointmentType,0) <> 1              
  end                
 end               
 set @lAppointmentid = 0                
 select @rStoreLocationId = a_StoreLocationId,@lAppointmentid = a_AppointmentId,                
 @lAppointmentDate = a_AppointmentDate,@rReferSourceId = a_ExamId from @tblAppointments 
 --where isnull(a_AppointmentId,0) = 0                
                  
 --if @lAppointmentid > 0      
 --begin                 
 -- update sAppointment.tAppointment set ReferSourceId = @rReferSourceId,IsRegister = 1 where Id = @lAppointmentid                
 --end                
 update E set E.VaccineDoseId=Isnull(t.a_VaccineId,0)                
 from sExamination.tExamination E                 
 inner join @tblAppointments t on t.a_ExamId=E.Id                
                
 if exists(Select 1 from @tblAppointments t inner join sExamination.tCauseMaster CM on CM.Id=t.a_CauseId where CM.CauseTypeId=4 and isnull(a_VaccineId,0)>0 and a_PatientSourceTypeId=95)                
  begin                
   Insert into [sSupport].[tVaccineLog](Orgid,SourceTypeId,SourceId,ParticipantSourceTypeId,ParticipantSourceId,VaccineDate,VaccineDoseId,StoreLocationId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime)                
   Select a_OrgId,1002,a_ExamId,a_PatientSourceTypeId,a_EmpId,E.ExaminationDate,a_VaccineId,a_StoreLocationId,0,a_CreatedUserId,sCommon.fGetDate(),a_CreatedUserId,sCommon.fGetDate()                
   From @tblAppointments t                
   inner join sExamination.tExamination E on E.id=t.a_ExamId                
   where a_ExamId not in (select SourceId from [sSupport].[tVaccineLog] where SourceTypeId=1002)              
                
   Declare @rVaccineId int=0                
    select @rVaccineId = Isnull(VM.Id,0)                
    From sSupport.tVaccineMaster VM                
    inner join sSupport.tVaccineDoseMaster VDM on VDM.VaccineId=VM.Id                
    where VDM.Id in (select Distinct a_VaccineId from @tblAppointments) and Isnull(VDM.IsCompleted,0)=1            
    print @rVaccineId                
    if(@rVaccineId>0)                
    begin                
    Insert into sHrm.tEmployeeVaccine (OrgId,EmployeeId,VaccineId,LastVaccineDate,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime)                
    Select a_OrgId,a_EmpId,@rVaccineId,E.ExaminationDate,0,a_CreatedUserId,sCommon.fGetDate(),a_CreatedUserId,sCommon.fGetDate()                
    From @tblAppointments t                
    inner join sExamination.tExamination E on E.id=t.a_ExamId                
    where t.a_EmpId not in (select EmployeeId From sHrm.tEmployeeVaccine where VaccineId=@rVaccineId)                 
                
    update EV set EV.LastVaccineDate=E.ExaminationDate,UpdatedUserId=a_CreatedUserId,UpdatedDateTime=sCommon.fGetDate()                
    From shrm.tEmployeeVaccine EV                
    inner join @tblAppointments t on t.a_EmpId=ev.EmployeeId      
    inner join sExamination.tExamination E on E.id=t.a_ExamId                
    where ev.VaccineId=@rVaccineId and t.a_EmpId in (select EmployeeId From sHrm.tEmployeeVaccine where VaccineId=@rVaccineId)                
              
 --Declare @rValidDateForNextDoseForSameVaccine datetime = '';              
 --  select @rValidDateForNextDoseForSameVaccine = dateadd(MM,Isnull(VTD.FrequencyDays,0),E.ExaminationDate)              
 --   from @tblAppointments VL               
 --   Inner join sSupport.tVaccineDoseMaster VDM on VDM.Id = VL.a_VaccineId              
 --   Inner join sSupport.tVaccineTypeDetail VTD on VTD.Id = VDM.VaccineTypeDetailId              
 --   inner join sSupport.tVaccineTypeMaster VTM on VTM.Id = VTD.VaccineTypeMasterId              
 --   inner join sSupport.tVaccineMaster VM on VM.Id = VTM.VaccineMasterId              
 --   inner join sExamination.tExamination E on E.id = VL.a_ExamId              
 --   where VL.a_OrgId=@lOrgId AND VL.a_EmpId = @tParticipantSourceId AND E.Id = @lExaminationId AND VM.Id = @rVaccineId              
              
 --update VL set VL.VaccineDueDate = @rValidDateForNextDoseForSameVaccine,UpdatedUserId=a_CreatedUserId,UpdatedDateTime=sCommon.fGetDate()                
 --   From [sSupport].[tVaccineLog] VL               
 --   inner join @tblAppointments t on t.a_EmpId = VL.ParticipantSourceId              
 --Where t.a_ExamId = @lExaminationId              
                
    end           
  end                
               
 if @lAppointmentDate <> ''                
 begin                
   IF NOT EXISTS (SELECT 1 FROM sAppointment.tAppointment WHERE ReferSourceId = @lExamid)
   BEGIN    
  exec sCommon.pPrefixSetupNextNumberGet @rOrgId = @lOrgId,@rPrefixFunctionalityId = 8,@rStoreLocationId = @rStoreLocationId,                
  @rNextNumber = @loNextNumber output                
                  
  update @tblAppointments set a_AppointNumber = @loNextNumber                
  begin try                
  --begin tran                
  begin                
                
  exec sCommon.pTableRowIdGet @lOrgId, 'sAppointment.tAppointment', 0, 1, 1,@outNextNumber = @lNextNumber output                 
  SET @lFromNextNumber = @lNextNumber - 1                
  end                
  --MERGE sAppointment.tAppointment AS Target USING                 
  --(                
  -- SELECT Id,a_AppointmentId,a_ExamId,a_doctorId,a_EmpId,a_obsolete,a_PatientSourceTypeId,                
  -- a_OrgId,a_AppointmentDate,a_StoreLocationId,a_FollowupRemark,a_SetupId,a_CauseId,                
  -- a_CreatedUserId,a_AppointNumber,a_OtherName,tid,Isnull(a_age,0) as a_age, Isnull(a_genderId, 0) as a_genderId            
  -- FROM @tblAppointments TT LEFT JOIN sAppointment.tAppointment T with(nolock) ON TT.a_AppointmentId = T.Id                
  --) AS Source ON Target.Id = Source.a_AppointmentId                 
  --WHEN NOT MATCHED THEN                
  -- INSERT                
  -- (                
  --  Id,PatientSourceId,PatientSourceTypeId,AppointmentDate,                
  --  AppointmentNumber,DoctorEmployeeId,FromTime,ToTime,IsRegister,                
  --  IsObsolete,OrgId,StatusId,ReferSourceId,ReferSourceTypeId,                
  --  StoreLocationId,SetupId,CauseId,OtherName,FollowupRemark,age,ApprovalStatusId, GenderId               
  -- )                
  -- VALUES                
  -- (                
  --  @lFromNextNumber + tid,a_EmpId,a_PatientSourceTypeId,                
  --  case when len(a_AppointmentDate) = 10 then convert(Datetime, a_AppointmentDate, 104) else CONVERT(VARCHAR(11), a_AppointmentDate) end,                
  --  a_AppointNumber,case when a_doctorId > 0 then a_doctorId else null end,                
  --  null,null,0,a_obsolete,a_OrgId,1,a_ExamId,0,a_StoreLocationId,a_SetupId,a_CauseId,                
  --  case when a_OtherName <> '' then a_OtherName else null end,left(a_FollowupRemark,200),case when Isnull(a_age,0)=0 then null else a_age end,548, a_genderId               
  -- );        

    DECLARE @AppointmentFlag VARCHAR(50);

    IF EXISTS(Select 1 from @tblAppointments t inner join sExamination.tCauseMaster CM on CM.Id=t.a_CauseId where CM.CauseTypeId=8)
	BEGIN
	     SET @AppointmentFlag = 'AHC Followup Appointment'; --AHC Consultation Follow-up Appointment
	END
	ELSE
	BEGIN
	     SET @AppointmentFlag = 'Followup Appointment'; --Normal Follow-up Appointment
	END
    INSERT INTO sAppointment.tAppointment               
   (                
    Id,PatientSourceId,PatientSourceTypeId,AppointmentDate,                
    AppointmentNumber,DoctorEmployeeId,FromTime,ToTime,IsRegister,                
    IsObsolete,OrgId,StatusId,ReferSourceId,ReferSourceTypeId,                
    StoreLocationId,SetupId,CauseId,OtherName,FollowupRemark,age,ApprovalStatusId, GenderId,AppointmentFlag               
   )                
  SELECT                             
    @lFromNextNumber + tid,a_EmpId,a_PatientSourceTypeId,                
    case when len(a_AppointmentDate) = 10 then convert(Datetime, a_AppointmentDate, 104) else CONVERT(VARCHAR(11), a_AppointmentDate) end,                
    a_AppointNumber,case when a_doctorId > 0 then a_doctorId else null end,                
    null,null,0,a_obsolete,a_OrgId,1,a_ExamId,0,a_StoreLocationId,a_SetupId,a_CauseId,                
    case when a_OtherName <> '' then a_OtherName else null end,left(a_FollowupRemark,200),case when Isnull(a_age,0)=0 then null else a_age end,548, a_genderId,@AppointmentFlag            
   FROM @tblAppointments TT;     
  begin                
  select @lCount = COUNT(1) FROM @tblAppointments                 
  SET @lNextNumber  = @lCount + @lFromNextNumber                 
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sAppointment.tAppointment', @rCurrentNumber = @lNextNumber                
  end                
  --commit tran;                
  end try                
  BEGIN CATCH                  
  select @error = ERROR_NUMBER(),                
      @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
  --set @trancount = @@trancount;                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran ;                
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)             
  Select @lOrgId,'OPD_tAppointment_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 2              
 END CATCH     
 END
 end                
 declare @tblDisease table(tid int identity(1,1),d_ExaminDiseaseId bigint,d_OrgId int,d_ExamId bigint,d_SourceTypeId int)                
 insert into @tblDisease                
 select T.c.value('@ExaminDiseaseId','bigint') as ExaminDiseaseId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@SourceTypeId','int') as SourceTypeId                
 from @lxmlDisease.nodes('/ExaminDisease/Disease')T(c)                
                 
 update w set w.d_ExaminDiseaseId = d.Id from @tblDisease w inner join sExamination.tExaminDisease d                
 on d.SourceId = w.d_ExamId                
 BEGIN TRY                 
 --begin tran                
 --begin                
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tExaminDisease', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --end                
 MERGE sExamination.tExaminDisease AS Target USING                 
 (                
  SELECT Id,d_ExaminDiseaseId,d_OrgId,d_ExamId,d_SourceTypeId,tid                
  FROM @tblDisease TT LEFT JOIN sExamination.tExaminDisease T with(nolock) ON TT.d_ExaminDiseaseId = T.Id                
 ) AS Source ON Target.Id = Source.d_ExaminDiseaseId                 
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceTypeId,SourceId,Remark,OrgId,IsObsolete                
  )                
  VALUES                
  (                
   d_ExamId,d_SourceTypeId,d_ExamId,'',d_OrgId,0                
  );                
 --begin                
 --select @lCount = COUNT(1) FROM @tblDisease                 
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tExaminDisease', @rCurrentNumber = @lNextNumber               
 --end                
 --commit tran                
 END TRY                
 BEGIN CATCH                
 select @error = ERROR_NUMBER(),     
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
 --set @trancount = @@trancount;                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran;                
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @lorgid,'OPD_ExaminDisease_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 3              
 END CATCH                
 update w set w.d_ExaminDiseaseId = d.Id from @tblDisease w inner join sExamination.tExaminDisease d                
 on d.SourceId = w.d_ExamId                
                  
 declare @tblDiseaseDetail table(tid int identity(1,1),dd_ExaminDiseaseId bigint,dd_OrgId int,dd_ExaminDiseaseDetailId bigint,                
 dd_DiseaseId int,dd_Remark varchar(max),dd_IsObsolete bit,dd_ExaminationId bigint)                
 insert into @tblDiseaseDetail                
 select T.c.value('@ExaminDiseaseId','bigint') as ExaminDiseaseId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@ExaminDiseaseDetailId','bigint') as ExaminDiseaseDetailId,                
 T.c.value('@DiseaseId','int') as DiseaseId,                
 T.c.value('@Remark','varchar(max)') as Remark,                
 T.c.value('@IsObsolete','bit') as IsObsolete,                
 T.c.value('@ExaminationId','bigint') as ExaminationId                
 from @lxmlDiseaseDetail.nodes('/ExaminDiseaseDetail/DiseaseDetail')T(c)                
                 
 update w set w.dd_ExaminDiseaseId = d.d_ExaminDiseaseId from @tblDiseaseDetail w inner join @tblDisease d                
 on w.dd_ExaminationId = d.d_ExamId                
                 
 update w set w.dd_ExaminDiseaseDetailId = d.Id from @tblDiseaseDetail w inner join sExamination.tExaminDiseaseDetail d                
 on w.dd_ExaminDiseaseId = d.ExaminDiseaseId and w.dd_DiseaseId = d.DiseaseId                
                
                 
                
 begin try                
 --begin tran                
                  
 --begin                 
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tExaminDiseaseDetail', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --end                
 MERGE sExamination.tExaminDiseaseDetail AS Target USING                 
 (                
  SELECT Id,dd_ExaminDiseaseId,dd_OrgId,dd_ExaminDiseaseDetailId,dd_DiseaseId,                
  dd_Remark,dd_IsObsolete,dd_ExaminationId,tid                
  FROM @tblDiseaseDetail TT LEFT JOIN sExamination.tExaminDiseaseDetail T with(nolock) ON TT.dd_ExaminDiseaseDetailId = T.Id                
 ) AS Source ON Target.Id = Source.dd_ExaminDiseaseDetailId                 
 WHEN MATCHED THEN                
  UPDATE SET Remark = left([sSetup].[fPortalXMLTagsReplaceReverse](dd_Remark),600)                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   ExaminDiseaseId,DiseaseId,Remark,OrgId,IsObsolete                
  )                
  VALUES                
  (                
   dd_ExaminDiseaseId,dd_DiseaseId,left([sSetup].[fPortalXMLTagsReplaceReverse](dd_Remark),600),dd_OrgId,dd_IsObsolete                
  );                
                 
 update w set w.IsObsolete = 1 from sExamination.tExaminDiseaseDetail w                
 inner join sExamination.tExaminDisease ED on w.ExaminDiseaseId = ED.Id                
 inner join @tblDiseaseDetail dd on ED.Id = dd.dd_ExaminDiseaseId                
 inner join @tblDisease d on ED.SourceId = d.d_ExamId                
 where w.Id not in                
 (                
  select dd_ExaminDiseaseDetailId from @tblDiseaseDetail                
 )                
 and DiseaseId not in                
 (                
  select dd_DiseaseId from @tblDiseaseDetail                
 )                
 --begin                
 --select @lCount = COUNT(1) FROM @tblDiseaseDetail                 
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tExaminDiseaseDetail', @rCurrentNumber = @lNextNumber                
 --end                
 --commit tran;                
 end try                
 BEGIN CATCH                
 select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
           @xstate = XACT_STATE();                
 --set @trancount = @@trancount;                
                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran;                
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @lorgid,'OPD_ExaminDiseaseDetail_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 4              
 END CATCH                
 declare @tblPrescription table(tid int identity(1,1),p_PrescriptionId bigint,p_OrgId int,p_DoctorId bigint,p_SourceTypeId int,                
 p_ExaminationId bigint,p_Remark varchar(max),p_CreatedUserId bigint,p_IsAutoDispense bit,p_IsDirect bit,p_IsDispense bit)                
 insert into @tblPrescription                
 select T.c.value('@PrescriptionId','bigint') as PrescriptionId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@DoctorId','bigint') as DoctorId,                
 T.c.value('@SourceTypeId','int') as SourceTypeId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@Remark','varchar(max)') as IsObsolete,                
 T.c.value('@CreatedUserId','bigint') as CreatedUserId,                
 T.c.value('@IsAutoDispense','bit') as IsAutoDispense,                
 T.c.value('@IsDirect','bit') as IsDirect,                
 T.c.value('@IsDispense','bit') as IsDispense                
 from @lxmlPrescription.nodes('/ExaminPrescription/Prescription')T(c)                
                 
 update w set w.p_PrescriptionId = p.Id from @tblPrescription w inner join sExamination.tPrescription p on w.p_ExaminationId = p.SourceId                
 begin try                
 --begin tran                
                 
 --begin                
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tPrescription', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --end                
 MERGE sExamination.tPrescription AS Target USING                 
 (                
  SELECT Id,p_PrescriptionId,p_OrgId,p_DoctorId,p_SourceTypeId,p_ExaminationId,                
  p_Remark,p_CreatedUserId,p_IsAutoDispense,p_IsDirect,tid                
  FROM @tblPrescription TT LEFT JOIN sExamination.tPrescription T with(nolock) ON TT.p_PrescriptionId = T.Id                
 ) AS Source ON Target.Id = Source.p_PrescriptionId                
 WHEN MATCHED THEN                
  UPDATE SET Remark = left([sSetup].[fPortalXMLTagsReplaceReverse](p_Remark),200),IsObsolete = 0,                
  CreatedUserId = p_CreatedUserId,UpdatedUserId=p_CreatedUserId                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceTypeId,SourceId,DoctorEmployeeId,Number,IsObsolete,CreatedUserId,CreatedDateTime,                
   IsDispensed,UpdatedDateTime,UpdatedUserId,Remark,OrgId,IsDirect                
  )                
  VALUES                
  (                
   p_ExaminationId,p_SourceTypeId,p_ExaminationId,p_CreatedUserId,p_ExaminationId,                
   0,p_CreatedUserId,sCommon.fGetDate(),0,sCommon.fGetDate(),p_CreatedUserId,left([sSetup].[fPortalXMLTagsReplaceReverse](p_Remark),200),                
   p_OrgId,p_IsDirect                
  );                
 --begin                
 --select @lCount = COUNT(1) FROM @tblPrescription                 
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tPrescription', @rCurrentNumber = @lNextNumber                
 --end                
 --commit tran                
 --end try                
 --BEGIN CATCH                
 --select @error = ERROR_NUMBER(),                
 --              @message = ERROR_MESSAGE(),                 
 --              @xstate = XACT_STATE();                
 --set @trancount = @@trancount;                
                
 -- --if @xstate = -1             
 -- --          rollback;                
 -- --      if @xstate = 1 and @trancount = 0                
 -- --          rollback                
 -- --      if @xstate = 1 and @trancount > 0                
 --           rollback tran;                
 --set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
 -- <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
 -- <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
 -- <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
 -- <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
 -- <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
 -- </Table>'                
                
 -- insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
 -- Select @lorgid,'OPD_Prescription_DBError',5000,@exceptiondetail,getdate()                
 -- Set @errorCount=-1                
 --END CATCH                
 update w set w.p_PrescriptionId = p.Id from @tblPrescription w inner join sExamination.tPrescription p on w.p_ExaminationId = p.SourceId                
               
 declare @tblPrescriptionDetail_temp table(tid int identity(1,1),pp_PrescriptionId bigint,pp_OrgId int,pp_PrescriptionDetailId bigint,                
 pp_StockItemId int,pp_DrugFrequencyId int,pp_DrugQuantity varchar(50),pp_Dosage varchar(50),pp_DrugFrequencyText varchar(200),                
 pp_DrugInstruction varchar(200),pp_DrugScheduleId int,pp_ExaminationId bigint,pp_StockRemark varchar(max),                
 pp_Duration varchar(50),pp_Total varchar(50),pp_IsAllowDirectIssue bit,pp_IsNotInStore bit,pp_IsDispensed bit,                
 pp_CreatedUserId bigint,pp_StoreLocationId int,pp_SourceTypeId int,pp_DispensedQty varchar(50),pp_QueueTypeId int,                
 pp_Isobsolete bit,pp_IsBatchWise bit,pp_StockBatchId int,pp_DispenseId bigint,pp_RemainQty decimal(12,2),                
 pp_AverageCost decimal(12,2),pp_InwardValue decimal(12,2),pp_DispenseBatchId bigint,pp_LocationId int,pp_ConsumeUOM varchar(100),pp_IsNew bit)                
              
 declare @tblPrescriptionDetail table(tid int identity(1,1),pp_PrescriptionId bigint,pp_OrgId int,pp_PrescriptionDetailId bigint,                
 pp_StockItemId int,pp_DrugFrequencyId int,pp_DrugQuantity varchar(50),pp_Dosage varchar(50),pp_DrugFrequencyText varchar(200),                
 pp_DrugInstruction varchar(200),pp_DrugScheduleId int,pp_ExaminationId bigint,pp_StockRemark varchar(max),                
 pp_Duration varchar(50),pp_Total varchar(50),pp_IsAllowDirectIssue bit,pp_IsNotInStore bit,pp_IsDispensed bit,                
 pp_CreatedUserId bigint,pp_StoreLocationId int,pp_SourceTypeId int,pp_DispensedQty varchar(50),pp_QueueTypeId int,                
 pp_Isobsolete bit,pp_IsBatchWise bit,pp_StockBatchId int,pp_DispenseId bigint,pp_RemainQty decimal(12,2),                
 pp_AverageCost decimal(12,2),pp_InwardValue decimal(12,2),pp_DispenseBatchId bigint,pp_LocationId int,pp_ConsumeUOM varchar(100),pp_IsNew bit)                
 insert into @tblPrescriptionDetail                
 select T.c.value('@PrescriptionId','bigint') as PrescriptionId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@PrescriptionDetailId','bigint') as PrescriptionDetailId,                
 T.c.value('@StockItemId','int') as StockItemId,                
 T.c.value('@DrugFrequencyId','int') as DrugFrequencyId,                
 T.c.value('@DrugQuantity','varchar(50)') as DrugQuantity,                
 T.c.value('@Dosage','varchar(50)') as Dosage,                
 T.c.value('@DrugFrequencyText','varchar(200)') as PrescriptionId,                
 T.c.value('@DrugInstruction','varchar(200)') as DrugInstruction,                
 T.c.value('@DrugScheduleId','int') as DrugScheduleId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@StockRemark','varchar(max)') as StockRemark,                
 T.c.value('@Duration','varchar(50)') as Duration,                
 T.c.value('@Total','varchar(50)') as Total,                
 T.c.value('@IsAllowDirectIssue','bit') as IsAllowDirectIssue,                
 T.c.value('@IsNotInStore','bit') as IsNotInStore,                
 T.c.value('@IsDispensed','bit') as IsDispensed,                
 T.c.value('@CreatedUserId','bigint') as CreatedUserId,                
 T.c.value('@StoreLocationId','int') as StoreLocationId,                
 T.c.value('@SourceTypeId','int') as SourceTypeId,                
 T.c.value('@DispensedQty','varchar(50)') as DispensedQty,                
 T.c.value('@QueueTypeId','int') as QueueTypeId,                
 T.c.value('@Isobsolete','bit') as Isobsolete,null,                
 T.c.value('@StockItemId','int') as StockItemId,null,null,null,null,null,                
 T.c.value('@LocationId','int') as LocationId,                
 T.c.value('@ConsumeUOM','varchar(100)') as ConsumeUOM ,0               
 from @lxmlPrescriptionDetail.nodes('/ExaminPrescriptionDetail/Prescription')T(c)                
                 
 update w set w.pp_PrescriptionId = p.p_PrescriptionId from @tblPrescriptionDetail w inner join @tblPrescription p                
 on w.pp_ExaminationId = p.p_ExaminationId                
               
 update @tblPrescriptionDetail set pp_IsNew = 1 where pp_PrescriptionDetailId = 0              
              
--Developer: Deval, Added IF Codition For Visit Purpose Type Daycare            
 IF NOT EXISTS(Select 1 from @tblAppointments t inner join sExamination.tCauseMaster CM on CM.Id=t.a_CauseId where CM.CauseTypeId=6)            
 BEGIN            
  update w set w.pp_PrescriptionDetailId = p.Id from @tblPrescriptionDetail w inner join sExamination.tPrescriptionDetail p                
  on w.pp_PrescriptionId = p.PrescriptionId and w.pp_StockItemId = p.StockItemId                
 END            
--Developer: Deval, Added IF Codition For Visit Purpose Type Daycare            
            
 update w set w.pp_IsBatchWise = p.IsBatchWiseTracking from @tblPrescriptionDetail w inner join sIp.tStockItemMaster p                
 on w.pp_StockItemId = p.Id                
                 
 update w set w.pp_StockBatchId = p.Id from @tblPrescriptionDetail w inner join sProcurement.tStockBatch p                
 on w.pp_StockItemId = p.StockItemId and p.StoreLocationId = w.pp_StoreLocationId and p.OrgId = w.pp_OrgId                
 and isnull(p.Number,'') = ''                
                 
 update w set w.IsObsolete = 1 from sExamination.tPrescriptionDetail w inner join @tblPrescriptionDetail                
 on w.PrescriptionId = pp_PrescriptionId                
 where Id not in (select pp_PrescriptionDetailId from @tblPrescriptionDetail)                
 --begin try                 
 --begin tran                
                 
 begin                
            
 Declare @rBatchAvl int = 0, @rUpDateBatchAvl int = 0; --Developer: Deval            
            
 Set @rBatchAvl = (select count(*) from @tblPrescriptionDetail Where pp_IsBatchWise = 1) --Developer: Deval            
            
 exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tPrescriptionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 SET @lFromNextNumber = @lNextNumber - 1                
 end                
 MERGE sExamination.tPrescriptionDetail AS Target USING                 
 (                
  SELECT Id,pp_PrescriptionId,pp_OrgId,pp_PrescriptionDetailId,                
  pp_StockItemId,pp_DrugFrequencyId,pp_DrugQuantity,pp_Dosage,pp_DrugFrequencyText,                
  pp_DrugInstruction,pp_DrugScheduleId,pp_ExaminationId,pp_StockRemark,                
  pp_Duration,pp_Total,pp_IsAllowDirectIssue,pp_IsNotInStore,pp_IsDispensed, pp_DispensedQty,            
  pp_CreatedUserId,pp_StoreLocationId,pp_SourceTypeId,pp_QueueTypeId,pp_Isobsolete,pp_ConsumeUOM,tid                
  FROM @tblPrescriptionDetail TT LEFT JOIN sExamination.tPrescriptionDetail T with(nolock) ON TT.pp_PrescriptionDetailId = T.Id                
 ) AS Source ON Target.Id = Source.pp_PrescriptionDetailId                 
 WHEN MATCHED THEN                
  UPDATE SET Remark = left([sSetup].[fPortalXMLTagsReplaceReverse](pp_StockRemark),400),IsObsolete = 0,Duration = pp_Duration,                
  PrescribedQuantity = pp_Total,CreatedUserId = pp_CreatedUserId,UpdatedUserId = pp_CreatedUserId,                
  IsDirectIssue = pp_IsAllowDirectIssue,IsNotInStore = pp_IsNotInStore,DrugInstruction = pp_DrugInstruction,                
  Dosage = pp_Dosage,DurgDosageQty = pp_Dosage,DrugDosageFrequencyId = pp_DrugFrequencyId,                
  DrugDosageScheduleId = pp_DrugScheduleId,ConsumeUOM = pp_ConsumeUOM             
  --DispensedQuantity = (Case When (@rBatchAvl > 0 and ISNULL(@lAutoDispenseConfigVal,'False') = 'True' and ISNULL(pp_IsDispensed,0) = 0) Then 0 Else pp_DispensedQty END) --Developer: Deval, Added Case            
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,PrescriptionId,StockItemId,DrugInstruction,Duration,Remark,                
  PrescribedQuantity,IsDirectIssue,IsObsolete,CreateduserId,UpdatedUserId,                
   IsDispensed,UpdatedDateTime,OrgId,DispensedQuantity,IsNotInStore,Dosage,                
   DurgDosageQty,DrugDosageFrequencyId,DrugDosageScheduleId,ConsumeUOM                
  )                
  VALUES                
  (                
   @lFromNextNumber + tid,pp_PrescriptionId,pp_StockItemId,pp_DrugInstruction,pp_Duration,                
   left([sSetup].[fPortalXMLTagsReplaceReverse](pp_StockRemark),400),                
   pp_Total,pp_IsAllowDirectIssue,0,pp_CreatedUserId,pp_CreatedUserId,0,                
   sCommon.fGetDate(),pp_OrgId,pp_DispensedQty,pp_IsNotInStore,pp_Dosage,pp_Dosage,pp_DrugFrequencyId,pp_DrugScheduleId,pp_ConsumeUOM                
  ); --Developer: Deval, Added Case Statement for @rBatchAvl            
 begin                
 select @lCount = COUNT(1) FROM @tblPrescriptionDetail                 
 SET @lNextNumber  = @lCount + @lFromNextNumber                 
 exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tPrescriptionDetail', @rCurrentNumber = @lNextNumber                
 end                
 --commit tran                
 end try                
 BEGIN CATCH                
 select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
  --set @trancount = @@trancount;                
  --if @xstate = -1                
 --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --  if @xstate = 1 and @trancount > 0                
            --rollback tran;                
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @lorgid,'OPD_PrescriptionDetail_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 5              
 END CATCH  
 
 BEGIN TRY
 BEGIN
	 declare @tblGroupItemPrescriptionData table(tid int identity(1,1),pp_PrescriptionDetailId bigint,pp_GroupItemId int,
	 pp_StockBatchId int,pp_Quantity varchar(50),pp_OrgId int,pp_CreatedUserId bigint)                
	 insert into @tblGroupItemPrescriptionData                
	 select              
	 T.c.value('@PrescriptionDetailId','bigint') as PrescriptionDetailId, 
	 T.c.value('@GroupItemId','int') as GroupItemId,
	 T.c.value('@StockBatchId','int') as StockBatchId,     
	 T.c.value('@Quantity','varchar(50)') as Quantity,
	 T.c.value('@OrgId','int') as OrgId,
	 T.c.value('@CreatedUserId','bigint') as CreatedUserId
	 from @lxmlGroupItemPrescription.nodes('/GroupItemPrescriptionData/GroupItem')T(c)  
	 
	 --Delete If Unchecked From Group Item Tray
	 DELETE OGIT from sExamination.tOPDGroupItemTrack OGIT
	INNER JOIN sExamination.tPrescriptionDetail T ON T.Id = OGIT.PrescriptionDetailId     
	INNER JOIN sExamination.tPrescription PRE ON PRE.Id = T.PrescriptionId
	Where PRE.SourceId = @lExaminationId
		  AND NOT EXISTS (
			SELECT 1
			FROM @tblGroupItemPrescriptionData TMP
			WHERE TMP.pp_StockBatchId = OGIT.StockBatchId
			  AND TMP.pp_GroupItemId = OGIT.GroupItemId
	  )

	exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tOPDGroupItemTrack', 0, 1, 1,@outNextNumber = @lNextNumber output                 
	 SET @lFromNextNumber = @lNextNumber - 1                
 END               
 MERGE sExamination.tOPDGroupItemTrack AS Target USING
 (                
  SELECT tid, T.Id as PrescriptionDetailId, pp_GroupItemId, pp_StockBatchId, pp_Quantity, pp_OrgId, pp_CreatedUserId 
  FROM @tblGroupItemPrescriptionData TT 
  LEFT JOIN sExamination.tPrescriptionDetail T with(nolock) ON T.StockItemId = TT.pp_GroupItemId      
  LEFT JOIN sExamination.tPrescription PRE ON PRE.Id = T.PrescriptionId
  WHERE PRE.SourceId = @lExaminationId
 ) AS Source ON Target.PrescriptionDetailId = Source.PrescriptionDetailId and Target.StockBatchId = Source.pp_StockBatchId          
 WHEN MATCHED THEN                
  UPDATE SET Target.Quantity=pp_Quantity, UpdatedUserId=pp_CreatedUserId, UpdatedDateTime=sCommon.fGetDate()
 WHEN NOT MATCHED THEN
  INSERT                
  (                
   Id,PrescriptionDetailId,GroupItemId,StockBatchId,Quantity,OrgId,IsObsolete,
   CreateduserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime           
  )                
  VALUES                
  (                
   @lFromNextNumber + tid,Source.PrescriptionDetailId,pp_GroupItemId,pp_StockBatchId,pp_Quantity,pp_OrgId,0,             
   pp_CreatedUserId, sCommon.fGetDate(), pp_CreatedUserId, sCommon.fGetDate()          
  );     
 begin                
 select @lCount = COUNT(1) FROM @tblGroupItemPrescriptionData          
 SET @lNextNumber  = @lCount + @lFromNextNumber
 exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tOPDGroupItemTrack', @rCurrentNumber = @lNextNumber
 end
 END TRY
 BEGIN CATCH                
 select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @lorgid,'OPD_OPDGroupItemTrack_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 13           
 END CATCH
            
 --Developer: Deval, Added IF Codition For Visit Purpose Type Daycare            
 IF NOT EXISTS(Select 1 from @tblAppointments t inner join sExamination.tCauseMaster CM on CM.Id=t.a_CauseId where CM.CauseTypeId=6)            
 BEGIN            
  update w set w.pp_PrescriptionDetailId = p.Id from @tblPrescriptionDetail w inner join sExamination.tPrescriptionDetail p                
  on w.pp_PrescriptionId = p.PrescriptionId and w.pp_StockItemId = p.StockItemId                
 END            
 ELSE            
  BEGIN            
  update w set w.pp_PrescriptionDetailId = p.Id from @tblPrescriptionDetail w inner join sExamination.tPrescriptionDetail p                
  on w.pp_PrescriptionId = p.PrescriptionId and w.pp_StockItemId = p.StockItemId Where p.Id = @lFromNextNumber + tid            
 END            
 --Developer: Deval, Added IF Codition For Visit Purpose Type Daycare            
                 
 select top 1 @lAutoDispense = p_IsAutoDispense from @tblPrescription                
                
 IF @lAutoDispense <> '0' and (select count(*) from @tblPrescriptionDetail where pp_IsBatchWise = 0) > 0 and (select count(*) from @tblPrescriptionDetail where pp_IsBatchWise = 1 AND isnull(pp_IsNotInStore,0) = 1) > 0            
 BEGIN  --Developer: Deval, Date: 19/10/1023            
  UPDATE P SET P.IsDispensed = 1                
  FROM sExamination.tPrescription P with(ROWLOCK) inner join @tblPrescription w on P.Id = w.p_PrescriptionId            
 END            
            
 IF @lAutoDispense <> '0' and (select count(*) from @tblPrescriptionDetail where pp_IsBatchWise = 0) > 0 and (select count(*) from @tblPrescriptionDetail where pp_IsBatchWise = 1) = 0 -- 0019030; Nidhi Pandey; DT- 18/05/2022              
 begin               
              
 -- Delete from @tblPrescriptionDetail where pp_IsNew = 0              
              
   -- *** insert data into temp table for temporary to set proper tid value ***---              
                
 insert into @tblPrescriptionDetail_temp (pp_PrescriptionId ,pp_OrgId ,pp_PrescriptionDetailId , pp_StockItemId ,pp_DrugFrequencyId ,pp_DrugQuantity ,pp_Dosage ,              
 pp_DrugFrequencyText , pp_DrugInstruction ,pp_DrugScheduleId ,pp_ExaminationId ,pp_StockRemark , pp_Duration ,pp_Total ,pp_IsAllowDirectIssue ,pp_IsNotInStore ,              
 pp_IsDispensed , pp_CreatedUserId ,pp_StoreLocationId ,pp_SourceTypeId ,pp_DispensedQty,pp_QueueTypeId ,                
  pp_Isobsolete ,pp_IsBatchWise ,pp_StockBatchId ,pp_DispenseId ,pp_RemainQty,  pp_AverageCost ,pp_InwardValue ,pp_DispenseBatchId ,pp_LocationId ,pp_ConsumeUOM,pp_IsNew)              
   select pp_PrescriptionId , pp_OrgId ,pp_PrescriptionDetailId , pp_StockItemId ,pp_DrugFrequencyId ,pp_DrugQuantity ,pp_Dosage ,pp_DrugFrequencyText , pp_DrugInstruction ,pp_DrugScheduleId ,pp_ExaminationId ,pp_StockRemark , pp_Duration ,pp_Total ,    
  
    
      
        
          
pp_IsAllowDirectIssue ,pp_IsNotInStore ,pp_IsDispensed , pp_CreatedUserId ,pp_StoreLocationId ,pp_SourceTypeId ,pp_DispensedQty,pp_QueueTypeId ,                
  pp_Isobsolete ,pp_IsBatchWise ,pp_StockBatchId ,pp_DispenseId ,pp_RemainQty,  pp_AverageCost ,pp_InwardValue ,pp_DispenseBatchId ,pp_LocationId ,pp_ConsumeUOM,pp_IsNew from              
  @tblPrescriptionDetail where pp_IsNew = 1              
              
   -- *** insert data into temp table for temporary to set proper tid value ***---              
                
  UPDATE P SET P.IsDispensed = p_IsDispense                
  FROM sExamination.tPrescription P inner join @tblPrescription w on P.Id = w.p_PrescriptionId                
  inner join @tblPrescriptionDetail_temp wt ON wt.pp_PrescriptionId = w.p_PrescriptionId Where isnull(wt.pp_IsNotInStore,0) = 0 --Developer: Deval, Date: 19/10/1023            
                  
  UPDATE PD SET PD.DispensedQuantity = case when isnull(pp_IsNotInStore,0) = 0 then             
  (case When (@lAutoDispenseConfigVal = 'True' and @lEnableDispenseConfigVal = 'True') then PD.DispensedQuantity Else pp_Total END) --Developer: Deval            
  else 0 end            
  FROM sExamination.tPrescriptionDetail PD inner join @tblPrescriptionDetail_temp w ON PD.Id = w.pp_PrescriptionDetailId                
                  
  UPDATE P SET P.DirectIssuedCount = 1 + P.DirectIssuedCount                
  FROM sExamination.tPrescriptionDirect P INNER JOIN sExamination.tPrescriptionDirectDetail PD                
  ON P.Id = PD.PrescriptionDirectId inner join @tblPrescriptionDetail_temp w ON PD.Id = w.pp_PrescriptionDetailId                
  where pp_QueueTypeId = 2 and pp_Isobsolete = 1                
                  
  UPDATE e SET e.StatusId = 4 from sExamination.tExamination e inner join                
  @tblPrescription w on w.p_ExaminationId = e.Id                
                  
  update w set w.pp_DispenseId = p.Id from @tblPrescriptionDetail_temp w inner join sPharmacy.tDispense p                
  on w.pp_PrescriptionDetailId = p.PrescriptionDetailId                
  begin try                
  --begin tran                
                  
begin                
  exec sCommon.pTableRowIdGet @lOrgId, 'sPharmacy.tDispense', 0, 1, 1,@outNextNumber = @lNextNumber output                 
  SET @lFromNextNumber = @lNextNumber - 1               
  print @lNextNumber              
  end                
  MERGE sPharmacy.tDispense AS Target USING                 
  (                
   SELECT T.Id,pp_PrescriptionDetailId,pp_CreatedUserId,pp_OrgId,pp_IsNotInStore,tid                
   FROM @tblPrescriptionDetail_temp TT LEFT JOIN sPharmacy.tDispense T with(nolock) ON TT.pp_DispenseId = T.Id AND isnull(TT.pp_IsNotInStore,0) = 0                
  ) AS Source ON Target.Id = Source.Id AND isnull(Source.pp_IsNotInStore,0) = 0    --Developer: Deval, Date: 01/01/2024            
  WHEN MATCHED THEN            
   UPDATE SET PrescriptionDetailId = pp_PrescriptionDetailId            
  WHEN NOT MATCHED THEN                
   INSERT                
   (                
    Id,PrescriptionDetailId,CreatedUserId,CreatedDateTime,OrgId                
   )                
   VALUES                
   (                
    @lFromNextNumber + tid,pp_PrescriptionDetailId,pp_CreatedUserId,sCommon.fGetDate(),pp_OrgId                
   );                
  begin                 
  select @lCount = COUNT(1) FROM @tblPrescriptionDetail_temp                 
  SET @lNextNumber  = @lCount + @lFromNextNumber                 
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sPharmacy.tDispense', @rCurrentNumber = @lNextNumber                
  end                
  --commit tran                
  end try                
  BEGIN CATCH                
 select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
  --set @trancount = @@trancount;                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran;                
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @lorgid,'OPD_Dispense_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 6              
 END CATCH                
  update w set w.pp_DispenseId = p.Id from @tblPrescriptionDetail_temp w inner join sPharmacy.tDispense p                
  on w.pp_PrescriptionDetailId = p.PrescriptionDetailId                
                  
  update w set w.pp_RemainQty = case when isnull(pp_IsNotInStore,0) = 0 then                
  (isnull(p.PrescribedQuantity,0) - isnull(p.DispensedQuantity,0)) else 0 end                
  from @tblPrescriptionDetail_temp w inner join sExamination.tPrescriptionDetail p on w.pp_PrescriptionDetailId = p.Id                
                  
  update w set w.pp_AverageCost = case when isnull(pp_IsNotInStore,0) = 0 then WeightedAverageCost else 0 end from @tblPrescriptionDetail_temp w                
  inner join sIp.tStockItemPlanning p on w.pp_StockItemId = p.StockItemId and w.pp_StoreLocationId = p.StoreLocationId                
                  
  update @tblPrescriptionDetail_temp set pp_InwardValue = case when isnull(pp_IsNotInStore,0) = 0 then (pp_AverageCost * pp_RemainQty) else 0 end                
                  
  update w set w.pp_DispenseBatchId = p.Id from @tblPrescriptionDetail_temp w inner join sPharmacy.tDispenseBatch p                
  on w.pp_DispenseId = p.DispenseId                
  begin try                
  --begin tran                
                  
  begin                
  exec sCommon.pTableRowIdGet @lOrgId, 'sPharmacy.tDispenseBatch', 0, 1, 1,@outNextNumber = @lNextNumber output                 
  SET @lFromNextNumber = @lNextNumber - 1                
  end                
  MERGE sPharmacy.tDispenseBatch AS Target USING                 
  (                
   SELECT Id,pp_StockBatchId,pp_DispenseId,pp_RemainQty,pp_Total,pp_AverageCost,                
   pp_OrgId,pp_IsNotInStore,tid                
   FROM @tblPrescriptionDetail_temp TT  LEFT JOIN sPharmacy.tDispenseBatch T with (nolock) ON TT.pp_DispenseBatchId = T.Id and TT.pp_IsNotInStore = 0                 
  ) AS Source ON Target.Id = Source.Id and Source.pp_IsNotInStore = 0    --Developer: Deval, Date: 01/01/2024            
  WHEN MATCHED THEN                
   UPDATE SET DispenseId = pp_DispenseId                
  WHEN NOT MATCHED THEN                
   INSERT                
   (                
    Id,DispenseId,StockBatchId,Quantity,UnitCost,OrgId,ReturnQuantity                
   )                
   VALUES                
   (                
    @lFromNextNumber + tid,pp_DispenseId,pp_StockBatchId,              pp_Total,pp_AverageCost,pp_OrgId,0                
   );                
  begin                 
  select @lCount = COUNT(1),@i = 1 FROM @tblPrescriptionDetail_temp                 
  SET @lNextNumber  = @lCount + @lFromNextNumber                 
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sPharmacy.tDispenseBatch', @rCurrentNumber = @lNextNumber                
  end                
  --commit tran                
  end try                
  BEGIN CATCH                
 select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
 --set @trancount = @@trancount;                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran;                
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @lorgid,'OPD_DispenseBatch_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 7              
END CATCH                
  update w set w.pp_DispenseBatchId = p.Id from @tblPrescriptionDetail_temp w inner join sPharmacy.tDispenseBatch p                
  on w.pp_DispenseId = p.DispenseId                
           
               
      
  select @lCount = COUNT(1),@i = 1 FROM @tblPrescriptionDetail_temp                
                 
  while @i <= @lCount                
  begin                
   declare @rOrgId int,@rSourceTypeId int,@rSourceId bigint,@rItemSourceTypeId int,@rItemSourceId int,                
   @rQuantity decimal(12,2),@rValue decimal(12,2),@rCreatedUserId bigint,@rLocationId int,@rItemBatchId int,                
   @rIsNotInStore bit               
                 
                   
   select @rOrgId = pp_OrgId,@rSourceTypeId = 48,@rSourceId = pp_DispenseBatchId,@rItemSourceId = pp_StockItemId,@rItemSourceTypeId = 34,            
   @rQuantity = (case When (@lAutoDispenseConfigVal = 'True' and @lEnableDispenseConfigVal = 'True') then pp_DispensedQty Else pp_Total END),            
   @rValue = pp_InwardValue,@rCreatedUserId = pp_CreatedUserId,                
   @rStoreLocationId = pp_StoreLocationId,@rLocationId = pp_LocationId,@rItemBatchId = pp_StockBatchId,            
   @rIsNotInStore = isnull(pp_IsNotInStore,0)                
   from @tblPrescriptionDetail_temp where tid = @i                
                 
   if @rIsNotInStore = 0                
   begin               
 print 'DispenseBatchId -' + Cast(@rSourceId as varchar(200)) + '@rStoreLocationId -' + Cast(@rStoreLocationId as varchar(200)) + '@rItemSourceId -'+ Cast(@rItemSourceId as varchar(200))              
    Exec sIp.pWeightedAverageCostLogAdd_New @rOrgId =@rOrgId,@rSourceTypeId=@rSourceTypeId,@rSourceId=@rSourceId,                
    @rItemSourceTypeId = @rItemSourceTypeId,@rItemSourceId=@rItemSourceId,@rQuantity=@rQuantity ,@rValue=@rValue ,@rIsReceipt=0,                
    @rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rStoreLocationId ,@rLocationId=@rLocationId,@rItemBatchId = @rItemBatchId,                
    @rItemName =''                
   end                
   else                
   begin               
                 
    UPDATE P SET P.IsDispensed = 1                
    FROM sExamination.tPrescription P with(ROWLOCK) inner join @tblPrescription w on P.Id = w.p_PrescriptionId                
   end                
   select @i = @i + 1                
  end                
 end                 
               
 delete P from sExamination.tPrescription P with(ROWLOCK) inner join @tblPrescription t on P.Id = t.p_PrescriptionId                
 where P.Id not in (select PrescriptionId from sExamination.tPrescriptionDetail with(nolock))                
                 
 declare @tblComplaint table(tid int identity(1,1),c_ComplaintId bigint,c_OrgId int,c_ExaminationId bigint,c_SourceTypeId int,                
 c_Remark varchar(max))                
 insert into @tblComplaint                 
 select T.c.value('@ComplaintId','bigint') as ComplaintId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@SourceTypeId','int') as SourceTypeId,                
 T.c.value('@Remark','varchar(max)') as Remark                
 from @lxmlCmplaint.nodes('/ExaminComplaint/Complaint')T(c)                
                 
 update c set c.c_ComplaintId = cc.Id from @tblComplaint c inner join sExamination.tComplaint cc                
 on c.c_ExaminationId = cc.SourceId                
 begin try                
 --begin tran                
                 
 --begin                
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tComplaint', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --end                
 MERGE sExamination.tComplaint AS Target USING                 
 (                
  SELECT Id,c_ComplaintId,c_OrgId,c_ExaminationId,c_SourceTypeId,c_Remark,tid                
  FROM @tblComplaint TT LEFT JOIN sExamination.tComplaint T with(NOLOCK) ON TT.c_ComplaintId = T.Id                
 ) AS Source ON Target.Id = Source.c_ComplaintId                 
 WHEN MATCHED THEN                
  UPDATE SET Remark = left([sSetup].[fPortalXMLTagsReplaceReverse](c_Remark),1000)                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceTypeId,SourceId,Remark,OrgId,IsObsolete                
  )                
  VALUES             
  (                
   c_ExaminationId,c_SourceTypeId,c_ExaminationId,left([sSetup].[fPortalXMLTagsReplaceReverse](c_Remark),1000),c_OrgId,0                
  );                
 --begin                
 --select @lCount = COUNT(1) FROM @tblComplaint                 
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tComplaint', @rCurrentNumber = @lNextNumber                
 --end                
 --commit tran;                
 end try                
 BEGIN CATCH                
 select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
 --set @trancount = @@trancount;                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran;                
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                              
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @lorgid,'OPD_Complaint_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 8              
 END CATCH                
                 
 declare @tblTests table(tid int identity(1,1),t_AreaId int,t_AreaTypeId int,t_ExaminationId bigint,                
 t_OrgId int,t_ParameterId int,t_ServiceValue nvarchar(500),t_Remark varchar(max),t_IsReferred bit,t_ClinicalId bigint,t_IsDone bit,                
 t_ParticipantAreaId bigint,t_TestRequestId bigint,t_TestDetailId int,t_TestRequestDetailId bigint,t_IsPackageValue varchar(10))                
 insert into @tblTests                
select T.c.value('@AreaId','int') as AreaId,                
 T.c.value('@AreaTypeId','int') as AreaTypeId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                 
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@ParameterId','int') as ParameterId,            
 T.c.value('@ServiceValue','nvarchar(500)') as ServiceValue,      
 T.c.value('@Remark','varchar(max)') as Remark,                
 T.c.value('@IsReferred','bit') as IsReferred,                
 T.c.value('@ClinicalId','bigint') as ClinicalId,                
 T.c.value('@IsDone','bit') as IsDone,                 
 null,null,null,null,                
 T.c.value('@IsPackageValue','varchar(10)') as IsPackageValue                
 from @lxmlTests.nodes('/ExaminTest/Tests')T(c)                
                  
 update t set t.t_TestRequestId = p.Id from @tblTests t inner join sExamination.tTestRequest p                
 on t.t_AreaId = p.TestId and t.t_ExaminationId = p.SourceId                
                 
 update t set t.t_TestDetailId = p.Id from @tblTests t inner join sOrderEntry.tTestDetail p                
 on t.t_AreaId = p.TestId and t.t_ParameterId = p.TestParameterId                
                 
 declare @tblTestsNew table(tid int identity(1,1),tt_TestId int,tt_ExaminationId bigint,tt_OrgId int,                
 tt_ParticipantAreaId bigint,tt_TestRequestId bigint,tt_IsPackageValue varchar(10))                
 insert into @tblTestsNew                
 select distinct t_AreaId,t_ExaminationId,t_OrgId,t_ParticipantAreaId,t_TestRequestId,t_IsPackageValue from @tblTests                
 BEGIN TRY                
 --begin tran                
                 
 begin                
 exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequest', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 SET @lFromNextNumber = @lNextNumber - 1                
 end                 
 MERGE sExamination.tTestRequest AS Target USING                 
 (                
  SELECT Id,tt_TestRequestId,tt_TestId,tt_OrgId,tt_ExaminationId,tid,tt_IsPackageValue                
  FROM @tblTestsNew TT LEFT JOIN sExamination.tTestRequest T with(NOLOCK) ON TT.tt_TestRequestId = T.Id                
 ) AS Source ON Target.Id = Source.tt_TestRequestId                 
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceId,TestId,SourceTypeId,OrgId,IsObsolete,IsPackage                
  )                
  VALUES                
  (                
   @lFromNextNumber + tid,tt_ExaminationId,tt_TestId,1002,tt_OrgId,0,case when upper(tt_IsPackageValue)='Y' then 1 else 0 end                
  );                
 begin                
 select @lCount = COUNT(1) FROM @tblTestsNew                 
 SET @lNextNumber  = @lCount + @lFromNextNumber                 
 exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tTestRequest', @rCurrentNumber = @lNextNumber                
 end                
 --commit tran;                
 --END TRY                
 --BEGIN CATCH                
 -- select @error = ERROR_NUMBER(),                
 --              @message = ERROR_MESSAGE(),                 
 --              @xstate = XACT_STATE();                
 --set @trancount = @@trancount;                
 -- --if @xstate = -1                
 -- --          rollback;                
 -- --      if @xstate = 1 and @trancount = 0                
 -- --          rollback                
 -- --      if @xstate = 1 and @trancount > 0                
 --           rollback tran;                
 --set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
 -- <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
 -- <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
 -- <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
 -- <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
 -- <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
 -- </Table>'                
                
 -- insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
 -- Select @lorgid,'OPD_TestRequest_DBError',5000,@exceptiondetail,getdate()                
 -- Set @errorCount=-1                
 --END CATCH                
                 
 update t set t.t_TestRequestId = p.Id from @tblTests t inner join sExamination.tTestRequest p                
 on t.t_AreaId = p.TestId and t.t_ExaminationId = p.SourceId                
                 
 update t set t.t_TestRequestDetailId = p.Id from @tblTests t inner join sExamination.tTestRequestDetail p                
 on t.t_TestDetailId = p.TestDetailId and t.t_TestRequestId = p.TestRequestId                
                 
--Developer: Deval, Mantis Id: 0025977              
 --delete w from sExamination.tTestRequestDetail w inner join @tblTests on w.TestRequestId = t_TestRequestId                
 --where Id not in (select t_TestRequestDetailId from @tblTests)                
              
 Declare @TestCount int, @TestDetailNewCount int, @TestDetailOldCount int, @TestDetailCount int;              
 set @TestCount = (select Count(*) from @tblTests);              
 set @TestDetailNewCount = (select Count(*) from @tblTests Where t_IsPackageValue = 'false')              
 set @TestDetailOldCount = (select Count(*) from @tblTests Where t_IsPackageValue = 'true')              
 set @TestDetailCount = (select Count(*) from sExamination.tTestRequestDetail w              
      inner join sExamination.tTestRequest TR on TR.Id = w.TestRequestId               
      Where TR.SourceId = @lExaminationId)              
 IF(@TestCount > 0)              
 BEGIN              
  IF(@TestDetailNewCount = 0)              
  BEGIN              
              
  delete w from sExamination.tTestRequestDetail w               
   inner join sExamination.tTestRequest TR on TR.Id = w.TestRequestId              
   where TR.SourceId = @lExaminationId AND w.Id not in (select t_TestRequestDetailId from @tblTests)              
              
     delete TR from sExamination.tTestRequest TR              
     Where TR.SourceId = @lExaminationId AND             
     TR.Id Not in               
 (select Distinct TRD.TestRequestId from sExamination.tTestRequestDetail TRD               
 inner join sExamination.tTestRequest TRE on TRE.Id = TRD.TestRequestId              
 Where TRE.SourceId = @lExaminationId)              
               
  END              
  ELSE IF(@TestDetailCount > @TestDetailOldCount and @TestDetailNewCount > 0)              
  BEGIN              
   delete w from sExamination.tTestRequestDetail w               
    inner join sExamination.tTestRequest TR on TR.Id = w.TestRequestId              
    where TR.SourceId = @lExaminationId AND            
 w.Id not in (select t_TestRequestDetailId from @tblTests Where t_IsPackageValue = 'true')                     
              
   delete TR from sExamination.tTestRequest TR              
   Where TR.SourceId = @lExaminationId AND            
   TR.Id not in (select Distinct TES.t_TestRequestId from @tblTests TES)              
               
  END              
 END              
 ELSE              
 BEGIN              
   exec [sExamination].[pSettingsForTestDetails] @lExaminationId              
 END              
 --Mantis Id: 0025977              
              
 --BEGIN TRY                
 --begin tran                
                  
 --begin                
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --end                
                 
 declare @tblTestsM table(tid int identity(1,1),t_AreaId int,t_AreaTypeId int,t_ExaminationId bigint,                
 t_OrgId int,t_ParameterId int,t_ServiceValue nvarchar(500),t_Remark varchar(400),t_IsReferred bit,t_ClinicalId bigint,t_IsDone bit,                
 t_ParticipantAreaId bigint,t_TestRequestId bigint,t_TestDetailId int,t_TestRequestDetailId bigint)                
 insert into @tblTestsM      
 select t_AreaId,t_AreaTypeId,t_ExaminationId,t_OrgId,t_ParameterId,t_ServiceValue,t_Remark,t_IsReferred,t_ClinicalId,t_IsDone,                
 t_ParticipantAreaId,t_TestRequestId,t_TestDetailId,t_TestRequestDetailId from @tblTests where t_TestDetailId is not null        
                
IF(@rIsDataEntryTemplateModal = 1)      
BEGIN      
 MERGE sExamination.tTestRequestDetail AS Target USING      
 (                
  SELECT Id,t_TestRequestId,t_TestDetailId,t_OrgId,t_ExaminationId,t_TestRequestDetailId,tid,t_ServiceValue,t_Remark      
  FROM @tblTestsM TT LEFT JOIN sExamination.tTestRequestDetail T with(NOLOCK) ON TT.t_TestRequestDetailId = T.Id                
 ) AS Source ON Target.Id = Source.t_TestRequestDetailId                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   TestRequestId,TestDetailId,OrgId,ServiceValue,Remark           
  )                
  VALUES                
  (                
   t_TestRequestId,t_TestDetailId,t_OrgId,t_ServiceValue,t_Remark      
  )      
  WHEN MATCHED THEN UPDATE SET ServiceValue=t_ServiceValue, Remark=t_Remark;      
END      
ELSE      
BEGIN      
 MERGE sExamination.tTestRequestDetail AS Target USING      
 (                
  SELECT Id,t_TestRequestId,t_TestDetailId,t_OrgId,t_ExaminationId,t_TestRequestDetailId,tid      
  FROM @tblTestsM TT LEFT JOIN sExamination.tTestRequestDetail T with(NOLOCK) ON TT.t_TestRequestDetailId = T.Id                
 ) AS Source ON Target.Id = Source.t_TestRequestDetailId                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   TestRequestId,TestDetailId,OrgId        
  )                
  VALUES                
  (                
   t_TestRequestId,t_TestDetailId,t_OrgId      
  );      
END      
 --begin                
 --select @lCount = COUNT(1) FROM @tblTestsM                
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tTestRequestDetail', @rCurrentNumber = @lNextNumber                
 --end                
 --commit tran;                
 END TRY                
 BEGIN CATCH                
  select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
  --set @trancount = @@trancount;                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran;                
                    
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @lOrgid,'OPD_TestRequestDetail_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 9              
 END CATCH                
 declare @tblReferral table(tid int identity(1,1),r_ReferralId bigint,r_OrgId int,r_ExaminationId bigint,                
 r_StoreLocationId int,r_ReferToClinicId int,r_ContactPerson varchar(200),r_CreatedUserId bigint)                
 insert into @tblReferral                
 select T.c.value('@ReferralId','bigint') as ReferralId,                
 T.c.value('@OrgId','int') as OrgId,                
 T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@StoreLocationId','int') as StoreLocationId,                
 T.c.value('@ReferToClinicId','int') as ReferToClinicId,                
 T.c.value('@ContactPerson','varchar(200)') as ContactPerson,                
 T.c.value('@CreatedUserId','bigint') as CreatedUserId                
 from @lxmlReferral.nodes('/ExaminReferral/Referral')T(c)                
                 
 update q set q.r_ReferralId = Id from @tblReferral q inner join sExamination.tReferral on q.r_ExaminationId = SourceId                
               
 begin try                
 --begin tran                
                 
 --begin                
 --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tReferral', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 --SET @lFromNextNumber = @lNextNumber - 1                
 --end                
 delete Ref from sExamination.tReferral Ref             
 inner join @tblReferral q on q.r_ReferralId = Ref.Id            
 Where q.r_ReferToClinicId <= 0 and q.r_ExaminationId = SourceId            
             
 delete from @tblReferral where r_ReferToClinicId <= 0                
                 
 MERGE sExamination.tReferral AS Target USING                 
 (                
  SELECT Id,r_ReferralId,r_OrgId,r_ExaminationId,r_StoreLocationId,r_ReferToClinicId,r_ContactPerson,                
  r_CreatedUserId,tid                
  FROM @tblReferral TT LEFT JOIN sExamination.tReferral T with(nolock) ON TT.r_ReferralId = T.Id and TT.r_ReferToClinicId > 0                
 ) AS Source ON Target.Id = Source.r_ReferralId and Source.r_ReferToClinicId > 0                
 WHEN MATCHED THEN                
  UPDATE SET ReferToClinicId = r_ReferToClinicId,ContactPerson = r_ContactPerson,                
  UpdatedUserId = r_CreatedUserId,UpdatedDateTime = sCommon.fGetDate()                
 WHEN NOT MATCHED THEN                
  INSERT                
  (                
   Id,SourceId,ReferToClinicId,Remark,ContactPerson,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,                
   StoreLocationId,OrgId,HistoryOf,TreatmentDetail,Diagnosis                
  )                
  VALUES                
  (                
   r_ExaminationId,r_ExaminationId,r_ReferToClinicId,'',r_ContactPerson,r_CreatedUserId,sCommon.fGetDate(),                
   r_CreatedUserId,sCommon.fGetDate(),r_StoreLocationId,r_OrgId,'','',''                
  );                
                 
 delete from sExamination.tReferral where ReferToClinicId < 0                
 --begin                
 --select @lCount = COUNT(1) FROM @tblReferral                
 --SET @lNextNumber  = @lCount + @lFromNextNumber                 
 --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tReferral', @rCurrentNumber = @lNextNumber                
 --end                
 --commit tran;                
 end try                
 BEGIN CATCH                
 select @error = ERROR_NUMBER(),                
  @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
 --set @trancount = @@trancount;                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran;                
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)         
  Select @lorgid,'OPD_Referral_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 10              
END CATCH                
 declare @tblOthers table(tid int identity(1,1),o_ExaminationId bigint,o_ReferenceEmployeeId bigint,o_IsWaive bit,                
 o_OutSideMedicine varchar(max),o_OutSideTest varchar(max),o_OtherName varchar(300),o_OtherAge varchar(20),                
 o_OtherAgeMonth varchar(20),o_OtherGenderId varchar(10),o_NursingRemark varchar(max),o_IsPediatric bit,                
 o_ParticipantSourceTypeId int,o_FurterActionId int,o_FurtherActionRemark varchar(250),o_Time varchar(100),                
 o_OutTime varchar(100),o_IsFit int,o_FitnessStatus smallint,OutSidePrescriptionId bigint, o_OtherSubGroupId int,             
 o_ReferToDoctorId BIGINT, o_UnfitListingId BIGINT, o_UniqueIdType nvarchar(50), o_UniqueIdTypeOther nvarchar(100), o_UniqueId nvarchar(16),o_OtherEmail nvarchar(100),v_VendorCompanyName nvarchar(100),r_ReferenceOPDId bigint,m_MobileNumber nvarchar(20))            
 insert into @tblOthers                
 select T.c.value('@ExaminationId','bigint') as ExaminationId,                
 T.c.value('@ReferenceEmployeeId','bigint') as ReferenceEmployeeId,                
 T.c.value('@IsWaive','bit') as IsWaive,                
 T.c.value('@OutSideMedicine','varchar(max)') as OutSideMedicine,                
 T.c.value('@OutSideTest','varchar(max)') as OutSideTest,                
 T.c.value('@OtherName','varchar(300)') as OtherName,                
 T.c.value('@OtherAge','varchar(20)') as OtherAge,                
 T.c.value('@OtherAgeMonth','varchar(20)') as OtherAgeMonth,                
 case when T.c.value('@OtherGenderId','varchar(10)') = '-1' then null else T.c.value('@OtherGenderId','varchar(10)') end as OtherGenderId,                
 T.c.value('@NursingRemark','varchar(max)') as NursingRemark,                
 T.c.value('@IsPediatric','bit') as IsPediatric,null,                
 T.c.value('@FurtherActionId','int') as FurtherActionId,                
 left(T.c.value('@FurtherActionRemark','varchar(250)'),250) as FurtherActionRemark,                
 left(T.c.value('@OPDTime','varchar(100)'),100) as OPDTime,                
 left(T.c.value('@OPDOutTime','varchar(100)'),100) as OPDOutTime,                
 T.c.value('@IsFit','int') as IsFit,                
 T.c.value('@FitnessStatus','smallint') as FitnessStatus,                
 T.c.value('@OutSidePrescriptionId','bigint') as OutSidePrescriptionId,              
 T.c.value('@OtherSubGroupId','int') as OtherSubGroupId,            
 T.c.value('@ReferToDoctorId','bigint') as ReferToDoctorId,            
 T.c.value('@UnfitListingId','bigint') as UnfitListingId,      
 T.c.value('@UniqueIdType','nvarchar(50)') as UniqueIdType,      
 T.c.value('@UniqueIdTypeOther','nvarchar(100)') as UniqueIdTypeOther,      
 T.c.value('@UniqueId','nvarchar(16)') as UniqueId,      
 T.c.value('@OtherEmail','nvarchar(100)') as UniqueId,  
 T.c.value('@vendorCompanyName','nvarchar(100)') as VendorCompanyName,  
 T.c.value('@ReferenceOPDId','bigint') as ReferenceOPDId, 
 T.c.value('@MobileNumber','nvarchar(20)') as MobileNumber  
 from @lxmlOthers.nodes('/ExaminOther/OhterDetail')T(c)      
                 
 update w set w.o_ParticipantSourceTypeId = E.ParticipantSourceTypeId from @tblOthers w inner join sExamination.tExamination E                
 on w.o_ExaminationId = E.Id                
                 
 update OSP set OSP.SourceId=w.o_ExaminationId ,UpdatedDateTime=sCommon.fGetDate(),UpdatedUserId=@rUserId from sExamination.tOutSidePrescription OSP                
 inner join @tblOthers w on w.OutSidePrescriptionId=OSP.id                
 where Isnull(w.OutSidePrescriptionId,0) >0                
          declare  @Fitnessstatus int , @ReferenceOPdId bigint, @ReferenceOPdIdNew bigint,@ExaminationId bigint      
  set @Fitnessstatus = (select o_FitnessStatus from  @tblOthers )    
  set @ReferenceOPdId = (select r_ReferenceOPDId from  @tblOthers )    
  set @ExaminationId = (select o_ExaminationId from  @tblOthers )    
  if (@Fitnessstatus != -1)
  begin
	  if(@ReferenceOPdId > 0)
	  set @ReferenceOPdIdNew = @ReferenceOPdId
	  else
	  set @ReferenceOPdIdNew = @ExaminationId
  end
 MERGE sExamination.tOPD AS Target USING                 
 (                
  SELECT ExaminationId,o_ExaminationId,o_ReferenceEmployeeId,o_IsWaive,o_OutSideMedicine,o_OutSideTest,o_OtherName,                
  o_OtherAge,o_NursingRemark,o_OtherAgeMonth,o_OtherGenderId,o_IsPediatric,o_ParticipantSourceTypeId,                
  o_FurterActionId,o_FurtherActionRemark,o_Time,o_OutTime,o_IsFit,o_FitnessStatus, o_OtherSubGroupId, o_ReferToDoctorId, tid,      
  o_UniqueIdType, o_UniqueIdTypeOther, o_UniqueId, o_OtherEmail,v_VendorCompanyName,r_ReferenceOPDId,m_MobileNumber      
  FROM @tblOthers TT LEFT JOIN sExamination.tOPD T with(nolock) ON TT.o_ExaminationId = T.ExaminationId                
 ) AS Source ON Target.ExaminationId = Source.o_ExaminationId                
 WHEN MATCHED THEN                
  UPDATE SET ReferenceEmployeeId = o_ReferenceEmployeeId,IsWaiveOff = o_IsWaive,                
  OutsideMedicine = left([sSetup].[fPortalXMLTagsReplaceReverse](o_OutSideMedicine),1000),                
  OutsideTest = left([sSetup].[fPortalXMLTagsReplaceReverse](o_OutSideTest),1000),                
  NursingRemark = left([sSetup].[fPortalXMLTagsReplaceReverse](o_NursingRemark),200),                
  Age = o_OtherAge,OtherName = o_OtherName,Months = o_OtherAgeMonth,                
  GenderId = case when o_OtherGenderId = '-1' then null else o_OtherGenderId end,                
  IsPediatric = case when o_ParticipantSourceTypeId in (1001,1009) then o_IsPediatric else null end,                
  FurtherActionId = o_FurterActionId,FurtherActionRemark = [sSetup].[fPortalXMLTagsReplaceReverse](o_FurtherActionRemark),                
  OPDTime = [sSetup].[fPortalXMLTagsReplaceReverse](o_Time),                
  OPDOutTime = [sSetup].[fPortalXMLTagsReplaceReverse](o_OutTime),                
  IsFit = case when o_IsFit = 1 then 1 else 0 end,                
  FitnessStatus = o_FitnessStatus,              
  OtherSubGroupId = o_OtherSubGroupId, ReferToDoctorId = o_ReferToDoctorId,       
  UniqueIdType = o_UniqueIdType, UniqueIdTypeOther = o_UniqueIdTypeOther, UniqueId = o_UniqueId ,OtherEmail = o_OtherEmail  ,VendorCompanyName = v_VendorCompanyName  ,ReferenceOPDId = r_ReferenceOPDId,MobileNumber = m_MobileNumber
 WHEN NOT MATCHED THEN      
  INSERT                
  (                
   ExaminationId,ReferenceEmployeeId,IsWaiveOff,OutsideMedicine,OutsideTest,OtherName,                
   NursingRemark,Age,Months,GenderId,IsPediatric,FurtherActionId,FurtherActionRemark,OPDTime,                
   OPDOutTime,IsFit,FitnessStatus,OtherSubGroupId,ReferToDoctorId, UniqueIdType, UniqueIdTypeOther, UniqueId ,OtherEmail  ,VendorCompanyName,ReferenceOPDId,MobileNumber  
  )                
  VALUES                
  (                
   o_ExaminationId,o_ReferenceEmployeeId,o_IsWaive,left([sSetup].[fPortalXMLTagsReplaceReverse](o_OutSideMedicine),1000),                
   left([sSetup].[fPortalXMLTagsReplaceReverse](o_OutSideTest),1000),                
   o_OtherName,left([sSetup].[fPortalXMLTagsReplaceReverse](o_NursingRemark),200),                
   o_OtherAge,o_OtherAgeMonth,case when o_OtherGenderId = -1 then null else o_OtherGenderId end,                
   case when o_ParticipantSourceTypeId in (1001,1009) then o_IsPediatric else null end,o_FurterActionId,                
   [sSetup].[fPortalXMLTagsReplaceReverse](o_FurtherActionRemark),[sSetup].[fPortalXMLTagsReplaceReverse](o_Time),                
   [sSetup].[fPortalXMLTagsReplaceReverse](o_OutTime),case when o_IsFit = 1 then 1 else 0 end,o_FitnessStatus,o_OtherSubGroupId,o_ReferToDoctorId,      
   o_UniqueIdType, o_UniqueIdTypeOther, o_UniqueId,o_OtherEmail, v_VendorCompanyName,@ReferenceOPdIdNew,m_MobileNumber  
  );      
            
  Declare @rCauseId int = 0, @rIsTrackIncidentLog bit = 0, @rIsTrackForFitness bit = 0, @rIsFit bit = 0, @rUnfitListingId bigint = 0;            
  set @rCauseId = (select top 1 a_CauseId from @tblAppointments);            
  set @rIsTrackIncidentLog = (select IsTrackIncidentLog from sExamination.tCauseMaster where Id = @rCauseId);            
  set @rIsTrackForFitness = (select IsTrackForFitness from sExamination.tCauseMaster where Id = @rCauseId);            
  set @rIsFit = (select (case when o_IsFit = 1 then 1 else 0 end) from @tblOthers);            
  set @rUnfitListingId = (select ISNULL(o_UnfitListingId, 0) from @tblOthers);            
            
  IF ((ISNULL(@rIsTrackIncidentLog, 0) = 0 AND ISNULL(@rIsTrackForFitness, 0) = 1) OR @rUnfitListingId > 0)            
  BEGIN            
  IF(ISNULL(@rIsFit, 0) = 0 AND @rUnfitListingId = 0)            
  BEGIN            
    DECLARE @lNextNumberIsFit bigint;            
    EXEC sCommon.pTableRowIdGet @lOrgId, 'sExamination.tOPDUnfitListing', 0, 1, 1,@outNextNumber = @lNextNumberIsFit output            
            
    Insert Into [sExamination].[tOPDUnfitListing]            
    Values(@lNextNumberIsFit, @lExaminationId, 0, @rUserId, sCommon.fGetDate())            
  END            
  ELSE IF (ISNULL(@rIsFit, 0) = 1 AND @rUnfitListingId > 0)            
  BEGIN       
   Declare @runfitExaminationId BIGINT, @runfitEmployeeId BIGINT, @runfitSourceTypeId INT;
   set @runfitExaminationId = (select ExaminationId from [sExamination].[tOPDUnfitListing] Where Id = @rUnfitListingId);
   set @runfitEmployeeId = (select ParticipantSourceId from sExamination.tExamination Where Id = @runfitExaminationId);
   set @runfitSourceTypeId = (select ParticipantSourceTypeId from sExamination.tExamination Where Id = @runfitExaminationId);

   Update OUL set IsFit = 1 FROM [sExamination].[tOPDUnfitListing] OUL
   INNER JOIN sExamination.tExamination EXM ON EXM.Id = OUL.ExaminationId
   Where EXM.ParticipantSourceId = @runfitEmployeeId and EXM.ParticipantSourceTypeId = @runfitSourceTypeId;   
  END            
  END            
            
  update sExamination.tExamination set IsonSugarMedication=@rIsonSugarMedication,IsonBPMedication=@rIsonBPMedication,IsNewLSD=@rIsNewLSD                
  where Id=@lExaminationId                
              
  -- othername issue in importopd medicine by Nidhi Pandey              
 UPDATE [sExamination].[tExamination] SET OPDOtherName = ISNULL(c.OtherName,'')                
 FROM  [sExamination].[tExamination] t  INNER JOIN sExamination.tOPD c    ON t.Id = c.ExaminationId where t.Id=@lExaminationId                
   -- othername issue in importopd medicine by Nidhi Pandey               
  if(Len(@rHabits)>17)                
  begin                
   select @rHabits = Replace(Replace(Replace(@rHabits,'ExTobacco',''),'ExSmoker',''),'ExAlcohol','')                
   exec sExamination.pSaveHabitHygineDetailsN @lOrgId,@lExaminationId,@tParticipantSourceId,1002,@rHabits                
  end                
  if(Len(@rLSDTests)>15)                
  begin                
   exec [sExamination].[pCreateTestResultsByIdN] @lExaminationId,@lOrgId,@rLSDTests,1002                
   -- for genrating disnosis for test results                
   DECLARE @tbltmpTestDetail TABLE (tid int IDENTITY (1, 1),t_TestParameterId int,t_ServiceValue nvarchar(500),t_DateOfBirth date,t_GenderId int,t_ParameterValueTypeId int,t_ListValueTypeId int,t_TestType int,t_Age int,t_DetailId bigint,                
   t_ExaminationId bigint,t_StaticTestParameterId int)                
   DECLARE @tbltmpDiagnosis TABLE (tid int IDENTITY (1, 1),d_DiagnosisRemark varchar(max),d_Recommendation varchar(max),d_DetailId bigint,d_Type int,d_MainId bigint,d_ExaminationId bigint,d_StaticTestParameterId int)                
                
   INSERT INTO @tbltmpTestDetail                
    SELECT TPM.Id, TRD.ServiceValue, EP.DateOfBirth, EP.GenderId, TPM.ParameterValueTypeId, TPM.ListValueTypeId, 1,                
    DATEDIFF(yy, EP.DateOfBirth, GETDATE()), TRD.Id, ED.Id,TPM.StaticTestParameterId                
    FROM sExamination.tExamination ED                
    INNER JOIN sHrm.tEmployeePersonalDetail EP ON ED.ParticipantSourceId = EP.EmployeeId                
    INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId                
    INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId                
    INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id                
    INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id                
    WHERE ED.Id =@lExaminationId                
    AND TPM.ParameterValueTypeId IN (1, 2)                
    AND TPM.IsObsolete = 0                
    AND ISNULL(TRD.ServiceValue, '') <> ''                
    ORDER BY TPM.ParameterValueTypeId                
                
    INSERT INTO @tbltmpDiagnosis                
     SELECT ISNULL(TPD.Diagnosis, ''), ISNULL(TPD.Recommendation, ''), TPD.Id, t_TestType, t_DetailId, t_ExaminationId,t_StaticTestParameterId                
     FROM sOrderEntry.tTestParameterDetail TPD                
     INNER JOIN @tbltmpTestDetail TD ON TPD.TestParameterId = TD.t_TestParameterId                
     WHERE TPD.GenderId = TD.t_GenderId                
     AND t_Age BETWEEN TPD.AgeFrom AND TPD.AgeTo                
     AND ISNULL(TPD.IsNormal, 0) = 0                
     AND TD.t_ParameterValueTypeId = 1       
     AND t_TestType = 1                
     AND CONVERT(decimal(18, 9), t_ServiceValue) BETWEEN CAST(TPD.Minimum AS decimal(12, 4)) AND CAST(TPD.Maximum AS decimal(12, 4))                
     and ISNUMERIC(t_ServiceValue)=1                
     AND t_ServiceValue <>'+'                
     AND ISNULL(TPD.Diagnosis, '')<>''                 
    INSERT INTO @tbltmpDiagnosis                
     SELECT ISNULL(DiagnosisRemark, ''), ISNULL(RecommendationRemark, ''), TLS.Id, t_TestType, t_DetailId, t_ExaminationId,0                
     FROM sExamination.tTestListTypeSetup TLS                
     INNER JOIN @tbltmpTestDetail TD ON TLS.TestParameterId = TD.t_TestParameterId                
     INNER JOIN sOrderEntry.tListValueTypeMaster LVTM ON LVTM.Id = TD.t_ListValueTypeId                
     INNER JOIN sOrderEntry.tListValueMaster LV ON LV.ListValueTypeId = LVTM.Id AND LV.Id = TLS.ListValueId                
     WHERE TLS.IsNormal = 0                
     AND LV.Title LIKE TD.t_ServiceValue                
     AND TD.t_ParameterValueTypeId = 2                
     AND t_TestType = 1                
     AND ISNULL(DiagnosisRemark, '')<>''                
                
    UPDATE TRD SET TRD.Diagnosis = t.d_DiagnosisRemark,TRD.Recommendation = t.d_Recommendation,TRD.IsAbnormal = 1                
    FROM sExamination.tTestRequestDetail AS TRD                
    INNER JOIN @tbltmpDiagnosis AS t ON TRD.Id = d_MainId                
    WHERE t.d_Type = 1                
  end                
  declare @rSetupId int                 
  if(Len(@rHabits)>17 or Len(@rLSDTests)>15 or @rIsNewLSD='true')                
  begin                
   print 'Lsd started'                
   select @rSetupId=[sCommon].[fGetIntIdForOrg](8,@lOrgId)                   
   -- For Dianosis Tracker                
   EXEC [sExamination].[pDiagnosisTrackerEmployeeUpdateOPD] @lOrgId,@rSetupId,@lStorelocationId,@lExaminationId                
                
   update sExamination.tDiagnosisTrackerEmployee set IsonSugarMedication=@rIsonSugarMedication,IsonBPMedication=@rIsonBPMedication,                
   DiabeticExisting=case when Isnull(@rIsonSugarMedication,0)=1 then 'Diabetic Existing' else DiabeticExisting end,                
  HypertensionExisting = case when isnull(@rIsonBPMedication,1)=1 then 'Hypertension Existing' else HypertensionExisting end                
   where ExaminationId=@lExaminationId                   
                
   --For LSD Tracker                
   exec [sExamination].[pLSDTrackerEmployeeUpdateALL] @lOrgId,@rSetupId,@lStorelocationId,@lExaminationId,8,@rSetupId                
  end                
                
  if(@rIsNewLSD='true' and Len(@rHabits)<=17)                
  begin                
                   
   UPDATE DTE SET DTE.Tobacco = 0,                
   DTE.Smoker = 0,                
   DTE.Alcohol = 0,                
   DTE.ExTobacco=case when  Isnull(LTE.Tobacco,0)=1 then 1 else DTE.ExTobacco end,                
   DTE.ExSmoker=case when  Isnull(LTE.Smoker,0)=1 then 1 else DTE.ExSmoker end,                
   DTE.ExAlcohol=case when Isnull(LTE.Alcohol,0)=1 then 1 else DTE.ExAlcohol end                
   --DTE.AlcoholSocial = Details.[Alcohol-Social],                
   --DTE.Drug = Details.Drugs                
   FROM sExamination.tDiagnosisTrackerEmployee AS DTE                
   INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId                
   INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId                
   --INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId                
   --INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId                
   INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId                
   LEFT JOIN [sExamination].[tLSDTrackerEmployee] AS LTE ON EXM.ParticipantSourceId=LTE.ParticipantSourceId and EXM.ParticipantSourceTypeId=LTE.ParticipantSourceTypeId                
   WHERE EXM.ParticipantSourceTypeId=95                
   AND EXM.OrgId=@lOrgId                
   AND ((EXM.Id = @lExaminationId))                
   --AND SSM.MaINTypeId=@rMaINTypeId                
   --AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))                
   AND ((EXM.SetupId=@rSetupId))                
   AND ((EXM.StoreLocationId=@lStorelocationId))                
                
                
   UPDATE DTE SET DTE.Tobacco = 0,                
   DTE.Smoker = 0,                
   DTE.Alcohol = 0,                
   DTE.ExTobacco=case when Isnull(DTE.Tobacco,0)=1 then 1  else DTE.ExTobacco end,                
   DTE.ExSmoker=case when  Isnull(DTE.Smoker,0)=1 then 1 else DTE.ExSmoker end,                
   DTE.ExAlcohol=case when Isnull(DTE.Alcohol,0)=1 then 1 else DTE.ExAlcohol end                
   --DTE.AlcoholSocial = Details.[Alcohol-Social],                
   --DTE.Drug = Details.Drugs                
   FROM [sExamination].[tLSDTrackerEmployee] AS DTE                
   INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId=DTE.ParticipantSourceId and EXM.ParticipantSourceTypeId=DTE.ParticipantSourceTypeId                
   INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId                
   INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId                
   INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId                
   INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId                
   WHERE EXM.ParticipantSourceTypeId=95                
   AND EXM.OrgId=@lOrgId                
   AND ((EXM.Id = @lExaminationId))                
   AND SSM.MaINTypeId=8                
   AND ((STM.SetupGroupId=@rSetupId))                
   AND ((EXM.SetupId=@rSetupId))                
   AND ((EXM.StoreLocationId=@lStorelocationId))                
                
  end                
 END TRY                
  BEGIN CATCH                  
  select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
                     
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)                
  Select @lOrgId,'OPD_DBError',5000,@exceptiondetail,getdate(),@rUserId                  
  Set @errorCount=-1                
  SET @errorLine = 11              
 END CATCH                  
 --print 'LifeStyleDisease Auto Insert start'                
 -- LifeStyleDisease Auto Insert start                
 declare @lConfValue varchar(100)                
 SELECT @lConfValue=ISNULL(cm.ItemValue,pm.ItemValue) FROM sConfig.tConfigurationMaster  AS PM                
 LEFt JOIN sConfig.tConfigurationSetup AS CM ON cm.ConfigurationId=Pm.Id AND SourceId=@lOrgId AND SourceTypeId=1016                 
 WHERE PM.Id=184                
 if(@lConfValue='True')                
 begin                
 begin try                
 --begin tran                
  declare @tblLifeStyleDisease table(tid int identity(1,1),dd_OrgId int,dd_DiseaseId int,dd_ExaminationId bigint,                
  dd_ParticipantSourceId bigint,dd_ParticipantSourceTypeId smallint,dd_RelationshipId smallint)                
                   
   insert into @tblLifeStyleDisease                
   select dd_OrgId,dd_DiseaseId,dd_ExaminationId,E.ParticipantSourceId,E.ParticipantSourceTypeId,case when EFD.id is null then 1 else EFD.RelationshipId End                
   from @tblDiseaseDetail as tDD                
   --inner join sExamination.tDiseaseMaster DM On DM.id=tDD.dd_DiseaseId and DM.StaticDiseaseId IN (7,11,13,20,25,159,190,328)                
   inner join sExamination.tDiseaseMaster DM On DM.id=tDD.dd_DiseaseId and DM.IsForOPD=1                
   inner join sExamination.tExamination E On E.id=tDD.dd_ExaminationId                
   left join sHrm.tEmployeeFamilyDetails EFD On EFD.id= E.ParticipantSourceid and E.ParticipantSourceTypeId=1001                
   --select * from @tblLifeStyleDisease                
   if((Select Count(*) from @tblLifeStyleDisease) > 0)                
   begin                
    declare @cnt int,@i1 int                
    select @cnt = count(*),@i1 = 1 from @tblLifeStyleDisease                
    while @i1 <= @cnt                
    begin                
    declare @lDiseasseid bigint,@lRelationshipid smallint                
    declare @lOrgId1 int,@lParticipantSourceId bigint,@lParticipantSourceTypeId smallint                
                
    select @lDiseasseid = dd_DiseaseId,@lRelationshipid=dd_RelationshipId,                
    @lOrgId1=dd_OrgId,@lParticipantSourceId=dd_ParticipantSourceId,@lParticipantSourceTypeId=dd_ParticipantSourceTypeId                
    from @tblLifeStyleDisease where tid=@i1                
                
    IF NOT EXISTS (select * from @tblLifeStyleDisease as tDD                
    inner join sExamination.tHistory H On H.ParticipantSourceId=tDD.dd_ParticipantSourceId and H.ParticipantSourceTypeId=tDD.dd_ParticipantSourceTypeId                
    inner join sExamination.tHistoryDetail HD On HD.HistoryId=H.Id and HD.DiseaseId= @lDiseasseid )                
    begin                
     print 'Not Exists'        
     declare @lNextNumber1 bigint                 
     
	 IF NOT EXISTS (select Id from sExamination.tHistory Where ParticipantSourceId = @lParticipantSourceId and ParticipantSourceTypeId = @lParticipantSourceTypeId)
	 BEGIN
		 exec sCommon.pTableRowIdGet @lOrgId1, 'sExamination.tHistory', 0, 1, 1,@outNextNumber = @lNextNumber1 output             
		 insert into sExamination.tHistory                
		 (                
		  Id,ParticipantSourceId,ParticipantSourceTypeId,Remark,OrgId,IsObsolete,IsSurgeryDone,SurgeryRemark                
		 )                
		 select @lNextNumber1,@lParticipantSourceId,@lParticipantSourceTypeId,'',@lOrgId1,0,0,''                
     END
	 ELSE
	 BEGIN
	    set @lNextNumber1 = (select Id from sExamination.tHistory Where ParticipantSourceId = @lParticipantSourceId and ParticipantSourceTypeId = @lParticipantSourceTypeId)
	 END
	 
     insert into sExamination.tHistoryDetail(HistoryId,DiseaseId,Remark,RelationshipId,OrgId,IsObsolete)                
     select @lNextNumber1,@lDiseasseid,'',@lRelationshipid,@lOrgId1,0                 
                
    end                
    else if not exists (select * from @tblLifeStyleDisease as tDD                
    inner join sExamination.tHistory H On H.ParticipantSourceId=tDD.dd_ParticipantSourceId and H.ParticipantSourceTypeId=tDD.dd_ParticipantSourceTypeId                
    inner join sExamination.tHistoryDetail HD On HD.HistoryId=H.Id and HD.DiseaseId= @lDiseasseid and HD.RelationshipId = @lRelationshipid)                
    begin                
     insert into sExamination.tHistoryDetail(HistoryId,DiseaseId,Remark,RelationshipId,OrgId,IsObsolete)                
     select Top 1 HD.HistoryId,tdd.dd_DiseaseId,'',@lRelationshipid,@lOrgId1,0 from @tblLifeStyleDisease as tDD                
    inner join sExamination.tHistory H On H.ParticipantSourceId=tDD.dd_ParticipantSourceId and H.ParticipantSourceTypeId=tDD.dd_ParticipantSourceTypeId                
    inner join sExamination.tHistoryDetail HD On HD.HistoryId=H.Id and HD.DiseaseId= @lDiseasseid                 
    end                
    select @i1 = @i1+ 1                
    end                
   end                
 --commit tran;                
 end try                
 BEGIN CATCH                
 select @error = ERROR_NUMBER(),                
               @message = ERROR_MESSAGE(),                 
               @xstate = XACT_STATE();                
 --set @trancount = @@trancount;                
  --if @xstate = -1                
  --          rollback;                
  --      if @xstate = 1 and @trancount = 0                
  --          rollback                
  --      if @xstate = 1 and @trancount > 0                
            --rollback tran;                
 set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >                
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @message +'</td></tr>                
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">User : </td>                
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ @username +'</td></tr>                
  </Table>'                
                
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)                
  Select @lorgid,'OPD_LifeStyleDisease_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 12              
 END CATCH                
 end                
 -- LifeStyleDisease Auto Insert end                
 --COMMIT TRANSACTION                
 if (@errorCount=-1)                
 begin                
 SELECT -1 AS RESULT,  @message as Error, @errorLine as [LineNo]              
 end                
 else                
 begin                
 SELECT 1 AS RESULT  ,  @message as Error, @errorLine as [LineNo]              
 end                
 --SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off            
end
GO
PRINT N'Altering Procedure [sExamination].[pGetAllExaminationDetails]...';


GO

ALTER proc [sExamination].[pGetAllExaminationDetails] 
@rExaminationId bigint,    
@rOrgId int,    
@rStoreLocationId int    
as    
SET NOCOUNT ON    
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED    
begin    
 declare @rParticipantId bigint,@rParticipantSourceTypeId int,@lothermedicines nvarchar(1000)    
 select @rParticipantId = ParticipantSourceId,@rParticipantSourceTypeId = ParticipantSourceTypeId    
 from sExamination.tExamination where Id = @rExaminationId    
     
 Select  @lothermedicines = COALESCE(@lothermedicines,'') + Isnull(OSPD.StockItemName,'') + '-' + Isnull(OSPD.DrugInstruction,'')    
  + '-' + Isnull(DFM.Title,'') + '-' + Isnull(DSM.Title,'') + '-' + Isnull(OSPD.Duration,'') + '-' + Isnull(OSPD.PrescribedQuantity,'') + ','    
 From sExamination.tExamination E    
 left join sExamination.tOutSidePrescription OSP on OSP.Sourceid=E.id    
 inner join sExamination.tOutSidePrescriptionDetail OSPD on OSPD.OutSidePrescriptionId=OSP.id    
 left join sIp.tDrugDosageFrequencyMaster DFM on DFM.id=OSPD.DrugDosageFrequencyId    
 left join sIp.tDrugScheduleMaster DSM on DSM.id=OSPD.DrugDosageScheduleId    
 where E.Id = @rExaminationId    
    
 print @lothermedicines    
 SET @lothermedicines = Replace(LEFT(@lothermedicines, LEN(@lothermedicines) - 1),',','/r/n')    
    
 select EE.Id as ExaminationId,    
 ParticipantName = case when EE.ParticipantSourceTypeId = 1009 then CS.FirstName + ' ' + CS.LastName    
 when EE.ParticipantSourceTypeId = 1001 then EFD.Name else EM.FirstName + ' ' + EM.LastName end,    
 ParticipantCode = case when EE.ParticipantSourceTypeId = 1009 then CS.Code    
 when EE.ParticipantSourceTypeId = 1001 then EM3.Code else EM.Code end,    
 EE.ParticipantSourceTypeId,    
 EE.ParticipantSourceId,    
 EE.ProcessTypeId,    
 EE.OrganizationDepartmentId,    
 EE.ExaminationDate,    
 EE.SetupId,    
 EE.DoctorEmployeeId,    
 isnull(C.Id,0) as CauseId,     
 isnull(C.CauseTypeId,0) as CauseTypeId, --Developer: Deval, Added CauseTypeId, Date: 19/09/2023    
 EE.CriteiraGroupId,    
 BloodGroupId = case when EE.ParticipantSourceTypeId = 1001 then EF.BloodGroupId when EE.ParticipantSourceTypeId = 95 then PD.BloodGroupId    
 else 0 end,    
 (CASE WHEN C.IsCustomLog = 1 THEN '' ELSE isnull(convert(varchar,A.FollowupDate,103),'') END) as FollowupDate,     
 (CASE WHEN C.IsCustomLog = 1 THEN isnull(CI.IsFit,0) ELSE isnull(A.IsFit,0) END) as IsFit,    
 isnull(O.FitnessStatus,0) as FitnessStatus,    
 (CASE WHEN C.IsCustomLog = 1 THEN isnull(CI.Id,0) ELSE isnull(A.Id,0) END) as AccidentId,    
 isnull(IsTrackIncidentLog,0) as IsTrackIncidentLog,    
 isnull(IsTrackForFitness,0) as IsTrackForFitness,    
 isnull(R.ReferToClinicId,-1) as ReferToClinicId,    
 isnull(R.ContactPerson,'') as ContactPersion,    
 isnull(EM.StatusId,0) as EmployeeStatusId,    
 isnull(convert(varchar,EE.ExaminationDate,103),'') as ExDate,    
 isnull(v.Id,0) as VitalId,    
 isnull(NatureOfWorkId,0) as NatureOfWorkId,    
 isnull(Pulse,0) as Pulse,    
 isnull(Temperature,0) as Temperature,    
 isnull(BloodPressureSystolic,0) as BPSys,    
 isnull(BloodPressureDiastolic,0) as BPDia,    
 isnull(Respiration,0) as Respiration,    
 isnull(V.Height,0) as Height,    
 isnull(BodyWeight,0) as BodyWeight,    
 isnull(BMI,0) as BMI,    
 isnull(V.Remark,'') as VitalRemark,    
 isnull(O.OtherName,'') as OtherName,    
 isnull(EM2.Code,'') as ReferenceCode,    
 isnull(EM2.FirstName,'') + ' ' + isnull(EM2.LastName,'') as ReferenceName,    
 isnull(O.NursingRemark,'') as NursingRemark,    
 isnull(EM2.Id,0) as ReferenceEmployeeId,    
 isnull(O.IsWaiveOff,0) as IsWaiveOff,    
 isnull(O.Age,0) as OtherAge,    
 isnull(O.Months,0) as OtherMonth,    
 isnull(O.GenderId,0) as OtherGenderId,    
 isnull(O.OutsideMedicine,'') as OutsideMedicine,    
 isnull(O.OutsideTest,'') as OutsideTest,    
 isnull(p.Id,0) as PrescriptionId,    
 isnull(p.Remark,'') as PrescriptionRemark,    
 isnull(p.IsDispensed,0) as IsDispensed,    
 isnull(ED.Id,0) as ExaminDiseaseId,    
 isnull(ED.Remark,'') as DiseaseRemark,    
 isnull(COM.Id,0) as ComplaintId,    
 isnull(COM.Remark,'') as ComplaintRemark,    
 isnull(O.IsPediatric,0) as IsPediatric, 
 isnull(CASE 
	WHEN EE.ParticipantSourceTypeId = 1009 then G2.Title
	WHEN EE.ParticipantSourceTypeId = 1001 then ''
	ELSE G.Title
 End,'') AS Gender,
 Age = case when EE.ParticipantSourceTypeId = 1009 then    
 case when CS.DateOfBirth = '1900-01-01' then 0 else datediff(yy,CS.DateOfBirth,getdate()) end    
 when EE.ParticipantSourceTypeId = 1001 then    
 case when EFD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EFD.DateOfBirth,getdate()) end else    
 case when EP.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EP.DateOfBirth,getdate()) end end,    
 isnull(EE.ExaminationNumber,'') as ExaminationNumber,    
 isnull(SA.Id,'') as AppointmentId,    
 isnull(convert(varchar,SA.AppointmentDate,103),'') as AppointmentDate,    
 isnull(SA.FollowupRemark,'') as FollowupRemark,
  isnull(SA.CompliantRemark,'') as CompliantRemark,  
 case when EM5.StatusId <> 10 then     
 EM5.FirstName + ' ' + isnull(EM5.LastName,'')     
     
 else '' end as DoctorName, --[Neha - OPD Screen - DoctorName lable Issue]    
 isnull(O.FurtherActionId,0) as FurtherActionId,    
 isnull(O.FurtherActionRemark,'') as FurtherActionRemark,    
 FAM.Code as FurtherActionCode,    
 isnull(O.OPDTime,'') as OPDTime,    
 isnull(O.OPDOutTime,'') as OPDOutTime,    
 isnull(O.IsFit,0) as IsOPDFit,    
 Isnull(OSP.Id,0) as OutsideMedicineId,    
 Isnull(@lothermedicines,'') as OutsideMedicineList,    
 Isnull(EE.VaccineDoseId,0)VaccineDoseId,    
 ISNULL(O.OtherSubGroupId,0)OtherSubGroupId,    
 ISNULL(IsonSugarMedication, 0) IsonSugarMedication,    
 ISNULL(IsonBPMedication, 0) IsonBPMedication,    
 ISNULL(ReferToDoctorId, 0) ReferToDoctorId,    
 ISNULL(OUL.Id, 0) UnfitListingId,    
 (Case When ISNULL(EE.RiskCategoryId, 0) = 1 Then 1 Else 0 END) RiskCategoryChecked, ISNULL(EE.DataEntryTemplateId, 0) as DataEntryTemplateId,    
 ISNULL(O.UniqueIdType, 0) as UniqueIdType, ISNULL(O.UniqueIdTypeOther, 0) as UniqueIdTypeOther, ISNULL(O.UniqueId, 0) as UniqueId  ,  
  isnull(V.SPo2,0) as SPO2 ,isnull(O.OtherEmail,'') as OtherEmail,isnull(O.VendorCompanyName,'') as VendorCompanyName,
  case when EE.ParticipantSourceTypeId = 1009 then CS.LocationId else EJD.EmployeeLocationId end as EmployeeLocationId,
   CASE 
    WHEN EE.ParticipantSourceTypeId = 1009 
        THEN ISNULL(CS.MobileNO, o.MobileNumber) when EE.ParticipantSourceTypeId = 1001 
        THEN ISNULL(CS.MobileNO, o.MobileNumber)
    ELSE 
        ISNULL(o.MobileNumber, EC.MobileNumber)
END AS MobileNumber --Developer: Yogesh Banwe, Added MobileNumber, Date: 12/01/2026, Mantis : 0049519
 from sExamination.tExamination EE    
 left join sHrm.tEmployeeMaster EM on EE.ParticipantSourceId = EM.Id and EE.ParticipantSourceTypeId = 95
 left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
 left join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId = EM.Id
 left join sHrm.tEmployeePersonalDetail EP on EE.ParticipantSourceId = EP.EmployeeId and EE.ParticipantSourceTypeId = 95    
 left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = EE.ParticipantSourceId and EE.ParticipantSourceTypeId = 1001    
 left join sHrm.tEmployeeMaster EM3 on EFD.EmployeeId = EM3.Id    
 left join sHrm.tCsrBenefiterMaster CS on EE.ParticipantSourceId = CS.Id and EE.ParticipantSourceTypeId = 1009    
 left join sExamination.tAccidentLog A on EE.Id = A.ExaminationId    
 left join sExamination.tCustomIncident CI on EE.Id = CI.ExaminationId    
 left join sExamination.tOPDUnfitListing OUL on OUL.ExaminationId = EE.Id    
 left join sExamination.tCauseMaster C on C.Id = EE.CauseId    
 left join sExamination.tReferral R on EE.Id = R.SourceId    
 left join sExamination.tVital V on EE.Id = V.SourceId    
 left join sExamination.tOPD O on EE.Id = O.ExaminationId    
 left join sSafety.tFurtherActionMaster FAM ON FAM.Id = O.FurtherActionId    
 left join sHrm.tEmployeeMaster EM2 on EE.ParticipantSourceTypeId = 1009 AND O.ReferenceEmployeeId = EM2.Id    
 left join sHrm.tEmployeePersonalDetail PD on EE.ParticipantSourceId = PD.EmployeeId and EE.ParticipantSourceTypeId = 95    
 left join sHrm.tEmployeeFamilyDetails EF on EE.ParticipantSourceId = EF.Id and EE.ParticipantSourceTypeId = 1001    
 left join sExamination.tPrescription P on EE.Id = P.SourceId    
 left join sExamination.tExaminDisease ED on EE.Id = ED.SourceId    
 left join sExamination.tComplaint COM on COM.SourceId = EE.Id    
 left join sAppointment.tAppointment SA on EE.Id = SA.ReferSourceId     
 left join sHrm.tEmployeeMaster EM5 on EM5.Id = EE.DoctorEmployeeId    
 --Left join sCwb.tDoctorMaster CDM on CDM.EmployeeId = EM5.Id    
 --Left join sCwb.tDoctorStoreLocation DSL on CDM.EmployeeId = DSL.EmployeeId and DSL.SubLocationId = @rStoreLocationId    
 left join sExamination.tOutSidePrescription OSP on OSP.Sourceid=EE.id    
 --left join sSupport.tVaccineDoseMaster VDM on VDM.Id=EE.VaccineDoseId 
 left join [sCommon].[tGenderMaster] G ON EP.GenderId = G.Id   
 left join [sCommon].[tGenderMaster] G2 ON CS.GenderId = G2.Id   
 where EE.Id = @rExaminationId    
 OPTION (RECOMPILE)    
    
 select ED.Id,EED.Id as DetailId,    
 isnull(ED.Remark,'') as Remark,    
 EED.DiseaseId as DiseaseId,    
 isnull(EED.Remark,'') as DieseaseRemark,    
 CTM.Title as DiseaseType,    
 EED.IsObsolete    
 from sExamination.tExaminDiseaseDetail EED    
 inner join sExamination.tExaminDisease ED on EED.ExaminDiseaseId = ED.Id    
 inner join sExamination.tDiseaseMaster CTM on EED.DiseaseId = CTM.Id    
 where ED.SourceId = @rExaminationId and EED.IsObsolete = 0    
 OPTION (RECOMPILE)    
    
 SELECT PR.Id As PrescriptionId,    
 PR.IsDispensed,    
 PRED.Id AS PrescriptiondetailId,    
 PRED.StockItemId,    
 PRED.DrugInstruction,    
 PRED.Duration,    
 CONVERT(int,ROUND(ISNULL(PRED.DispensedQuantity,0),0)) AS DispensedQuantity,    
 SIM.Title AS StockItemName,    
 PRED.Remark AS StockItemremark,    
 PRED.PrescribedQuantity as Total,    
 PRED.IsDirectIssue AS IsAllowDirectIssue,    
 PRED.IsNotInStore,    
 PRED.Dosage,    
 SIM.ItemSubGroupId as SubGroupId,    
 isnull((select Title from sIp.tItemSubGroupMaster where Id = SIM.ItemSubGroupId),'') as MedicineType,    
 PRED.DurgDosageQty as DrugFreqQty,    
 PRED.DrugDosageScheduleId as DrugScheduleId,    
 PRED.DrugDosageFrequencyId as DrugFreqId,    
 DF.DurgQuantity as DrugQty,    
 DQ.Title as DrugQtyText,    
 DF.Title as DrugFrequencyText,    
 DS.Title as DrugScheduleText,0 as IsDelete,    
 isnull(PRED.ConsumeUOM,'') as Unit,    
 PRED.UpdatedDateTime, UOM.Title as UOM, ISNULL(SIM.IsGroupItem, 0) as IsGroupItem   
 FROM sExamination.tPrescriptionDetail PRED    
 INNER JOIN sExamination.tPrescription PR ON PR.Id = PRED.PrescriptionId    
 INNER JOIN sIp.tStockItemMaster SIM ON PRED.StockItemId = SIM.ID    
 INNER JOIN sFinanceCommon.tStockUomMaster UOM ON UOM.Id = SIM.IssueStockUomId    
 INNER JOIN sIp.tDrugDosageFrequencyMaster DF on PRED.DrugDosageFrequencyId = DF.Id    
 INNER JOIN sIp.tDrugScheduleMaster DS on PRED.DrugDosageScheduleId = DS.Id    
 INNER JOIN sIp.tDrugDosageQtyMaster DQ on PRED.DurgDosageQty = DQ.DosageQty    
 WHERE PR.SourceId= @rExaminationId AND PRED.IsObsolete = 0 AND PR.IsObsolete = 0    
 AND SIM.IsDrug = 1 AND SIM.IsBlockedForIssue = 0 AND SIM.IsObsolete = 0 order by PRED.IsNotInStore    
 OPTION (RECOMPILE)      
 SELECT TM.Id,    
 AM.Id,    
 TR.Id AS TestRequestId,    
 1 AS Id,    
 1 AS RId,    
 --AM.Id AS RespectiveTestId,    
 TM.Id AS RespectiveTestId,   -- Developer: Deval, Date: 02/10/2023    
 TPM.Id as TestAreaId,    
 AM.Title AS Test1Name,    
 TPM.Title as TestName,    
 isnull(TRd.Remark,'') AS Remark,    
 ISNULL(TR.IsReferred,0) As IsReferred,    
 ISNULL(TR.ReferredClinicId,0) AS ClinicalId,    
 ISNULL(CM.Title,'') AS Clinical,AM.AreaTypeId,    
 TM.ServiceSubGroupId as SubgroupId,    
 SSM.ServiceMainGroupId as MainGroupId,    
 ISNULL(SSM.Title,'') AS SubType,    
 ISNULL(SMG.Title,'') AS MainType,    
 CASE WHEN ISNULL(TR.IsResultDone,0)=0 THEN 'Not Done' ELSE 'Done' END AS StatusName,    
 0 as TestParameterFlag,    
 case when Isnull(TR.IsPackage,0) = 0 then 'Y' else 'N' end IsPackageValue    
 FROM [sExamination].[tAreaMaster] AM    
 INNER JOIN sExamination.tAreaTypeMaster AT ON AM.AreaTypeId = AT.Id    
 INNER JOIN sExamination.tTestRequest TR ON TR.TestId = AM.Id    
 INNER JOIN sExamination.tTestRequestDetail TRD on TR.Id = TRD.TestRequestId    
 INNER JOIN sOrderEntry.tTestDetail TD on TRD.TestDetailId = TD.Id    
 INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id    
 LEFT JOIN sCommon.tClinicMaster CM ON  TR.ReferredClinicId = CM.Id     
 INNER JOIN sOrderEntry.tTestMaster TM ON TM.Id = TR.TestId AND TM.OrgId = @rOrgId    
 INNER JOIN sOrderEntry.tServiceSubGroupMaster SSM ON SSM.Id = TM.ServiceSubGroupId    
 INNER JOIN sOrderEntry.tServiceMainGroupMaster SMG ON SMG.Id = SSM.ServiceMainGroupId    
 WHERE TR.SourceId = @rExaminationId AND AM.OrgId = @rOrgId    
 AND AM.AreaTypeId IN (1,2) AND TR.IsObsolete = 0    
 order by AM.Title,TD.OrderIndex    
 OPTION (RECOMPILE)    
 SELECT ISNULL(ADT.AllergyId,0) AS AllergyId,    
 ISNULL(ADT.AllegyDetailId,0) AS AllergyDetailId,         
 ISNULL(ATM.Id,0) AS AllergyTypeId,    
 ISNULL(AllergyDetailRemark,'') AS AllergyDetailRemark,    
 ATM.Title AS AllergyType,    
 ISNULL(ADT.Duration,'') AS Number,    
 ISNULL(ADT.DurationUnitId,0) AS DurationUnitId,    
 ISNULL(ADT.IsObsolete,0) AS IsObsolete,    
 ISNull(DUM.Title,'') AS Unit,    
 CASE WHEN ADT.AllergyTypeId IS NOT NULL THEN 1 ELSE 0 END AS IsSelected    
 FROM sExamination.tAllergyTypeMaster ATM    
 LEFT JOIN                   
 (    
  SELECT AD.IsObsolete,    
  AD.Id AS AllegyDetailId,    
  AD.AllergyTypeId,A.Id AS AllergyId,    
  AD.Remark AS AllergyDetailRemark,    
  AD.Duration,    
  AD.DurationUnitId    
  FROM sExamination.tAllergyDetail AD    
  INNER JOIN sExamination.tAllergy A ON A.Id = AD.AllergyId    
  AND A.IsObsolete = 0 AND AD.IsObsolete = 0    
  AND A.ParticipantId = @rParticipantId    
  AND A.ParticipantSourceTypeId = @rParticipantSourceTypeId    
  AND A.OrgId = @rOrgId    
 ) ADT ON ADT.AllergyTypeId = ATM.Id AND ATM.IsObsolete = 0    
 LEFT JOIN sCommon.tDurationUnitMaster DUM ON ADT.DurationUnitId=DUM.ID    
 WHERE ATM.OrgId = @rOrgId    
 OPTION (RECOMPILE)     
 SELECT R.Id,    
 R.SourceId AS EmployeeId,    
 isnull(R.ReferToClinicId,-1) as ReferToClinicId,    
 CM.Title AS ClinicName,    
 R.Remark,isnull(R.ContactPerson,'') as ContactPerson,    
 ISNULL(RT.Remark,'') AS TestRemark,    
 ISNULL(TM.Id,0) AS TestId,    
 ISNULL(RT.Id,0) AS ReferralTestId,    
 ISNULL(TM.Title,'') AS Test,    
 ISNULL(TM.ServiceSubGroupId,0) AS ServiceSubGroupId,    
 ISNULL(SSM.ServiceMainGroupId,0) AS ServiceMainGroupId,    
 ISNULL(SSM.Title,'') AS ServiceSubGroup,    
 ISNULL(SMG.Title,'') AS ServiceMainGroup    
 FROM sExamination.tReferral R    
 INNER JOIN sCommon.tClinicMaster CM ON CM.Id=R.ReferToClinicId    
 LEFT JOIN sExamination.tReferralTest RT ON RT.ReferralId=R.Id    
 LEFT JOIN sOrderEntry.tTestMaster TM ON TM.Id=RT.TestId    
 LEFT JOIN sOrderEntry.tServiceSubGroupMaster SSM ON SSM.Id = TM.ServiceSubGroupId    
 LEfT JOIN sOrderEntry.tServiceMainGroupMaster SMG ON SMG.Id = SSM.ServiceMainGroupId    
 where R.SourceId = @rExaminationId AND R.StoreLocationId=@rStoreLocationId AND R.OrgId = @rOrgId    
 OPTION (RECOMPILE) 
 
 ;WITH ValidOGIT AS (
	SELECT O.*
	FROM sExamination.tOPDGroupItemTrack O
	LEFT JOIN sExamination.tPrescriptionDetail PD ON PD.Id = O.PrescriptionDetailId
	LEFT JOIN sExamination.tPrescription PRE ON PRE.Id = PD.PrescriptionId
	WHERE 
		O.PrescriptionDetailId IS NULL 
		OR PRE.SourceId = @rExaminationId
)
 select GII.Id, 
	GII.StockItemId, STM.Code as StockItemCode, STM.Title as StockItemName, 
	GII.GroupItemId,
	CASE WHEN OGIT.Quantity > 0 THEN OGIT.Quantity ELSE GII.DefaultQty END AS Quantity,
	GII.DefaultUOM, OSB.StockBatchId, ISNULL(OGIT.PrescriptionDetailId, 0) AS PrescriptionDetailId,
	CASE WHEN OGIT.Id > 0 THEN 1 ELSE 0 END AS IsChecked
	from sProcurement.tGroupItemIssue GII
	INNER JOIN sIp.tStockItemMaster STM ON STM.Id = GII.StockItemId
	INNER JOIN sProcurement.tStockBatch SB ON SB.Id = GII.StockBatchId
	INNER JOIN sProcurement.tOtherStockBatch OSB ON OSB.StockBatchId = SB.Id and OSB.OtherLocationSourceId = GII.GroupItemId
	LEFT JOIN ValidOGIT OGIT ON OGIT.GroupItemId = GII.GroupItemId AND OGIT.StockBatchId = OSB.StockBatchId
	where OSB.OtherLocationSourceTypeId = 10170
	AND GII.OrgId = @rOrgId AND GII.IsObsolete = 0
	AND GII.StoreLocationId = @rStoreLocationId
OPTION (RECOMPILE)

 SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off    
end
GO
PRINT N'Altering Procedure [sExamination].[pInjuryListingGet]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pInjuryListingGet]  
@rId [bigint] = 0,
@rEmployeeCode[nvarchar](20),
@rStoreLocationId [int],
@rUserId [bigint] = 0
AS  
SET NOCOUNT ON  
BEGIN  
 SET @rEmployeeCode=sCommon.fSearchStringGet(@rEmployeeCode);  
   
 WITH InjuredPersons AS (
    SELECT 
        II.Id AS IncidentId,

        -- InjuredPersonNames
        STUFF((
            SELECT ', ' + ED.EmployeeDetails
            FROM (
                SELECT DISTINCT
                    vd.ReportId,
                    LTRIM(RTRIM(
                        CASE
                            WHEN eem.FirstName IS NOT NULL AND eem.FirstName <> '' AND eem.FirstName <> '--'
                                 AND vd.VisitorName IS NOT NULL AND vd.VisitorName <> '' AND vd.VisitorName <> '--'
                            THEN (eem.FirstName + ' ' + eem.LastName) + ', ' + vd.VisitorName
                            WHEN eem.FirstName IS NOT NULL AND eem.FirstName <> '' AND eem.FirstName <> '--'
                            THEN (eem.FirstName + ' ' + eem.LastName)
                            WHEN vd.VisitorName IS NOT NULL AND vd.VisitorName <> '' AND vd.VisitorName <> '--'
                            THEN vd.VisitorName
                            ELSE ''
                        END
                    )) AS EmployeeDetails
                FROM [sInjury].[vVictimDetails] vd
                LEFT JOIN sHrm.tEmployeeMaster eem ON eem.Id = vd.EmployeeId
            ) ED
            WHERE ED.ReportId = II.Id
            FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS InjuredPersonNames,

        -- EmployeeCode
        STUFF((
            SELECT ', ' + ED.EmployeeCodes
            FROM (
                SELECT DISTINCT
                    vd.ReportId,
                    LTRIM(RTRIM(
                        CASE
                            WHEN eem.Code IS NOT NULL AND eem.Code <> '' AND eem.Code <> '--'
                            THEN eem.Code
                            ELSE ''
                        END
                    )) AS EmployeeCodes
                FROM [sInjury].[vVictimDetails] vd
                LEFT JOIN sHrm.tEmployeeMaster eem ON eem.Id = vd.EmployeeId
            ) ED
            WHERE ED.ReportId = II.Id
            FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS EmployeeCode

    FROM [sInjury].[vIncidentInformation] II
),
InjuredPerson2 AS(
SELECT CI.ExaminationId,EE.ExaminationNumber,
                 case ISNULL(EE.ParticipantSourceTypeId,95)
		             when  95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
                 else 
		             case 
		             when isnull(OP.OtherName,'') <> '' then OP.OtherName 
		             else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') 
		             end 
		         end 
		AS EmployeeName ,
		case isnull(EE.ParticipantSourceTypeId,95) 
		when 95 then isnull(EM.Code,'') 
		else isnull(CS.Code,'') end AS EmployeeCode
		FROM
[sExamination].[tCustomIncident] CI   
 LEFT join sExamination.tCustomIncidentStatus CIS ON CIS.Id = CI.StatusId
 INNER JOIN sExamination.tExamination EE ON CI.ExaminationId=EE.Id
 LEFT JOIN sHrm.tEmployeeMaster EM ON EE.ParticipantSourceId=EM.Id AND isnull(EE.ParticipantSourceTypeId,95) = 95 
 LEFT JOIN sHrm.tCsrBenefiterMaster CS ON EE.ParticipantSourceId=CS.Id AND EE.ParticipantSourceTypeId = 1009 
 LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  
 LEFT JOIN sExamination.tOPD OP on OP.ExaminationId = EE.Id
 UNION 
  SELECT CI.ExaminationId,EE.ExaminationNumber,case ISNULL(EE.ParticipantSourceTypeId,95)
		             when  95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
                 else 
		             case 
		             when isnull(OP.OtherName,'') <> '' then OP.OtherName 
		             else 
					 
					 isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') 
		             end 
		         end 
		AS EmployeeName,
		case isnull(EE.ParticipantSourceTypeId,95) 
		when 95 then isnull(EM.Code,'') 
		else isnull(CS.Code,'') end AS EmployeeCode
		FROM
[sExamination].[tCustomIncident] CI   
 INNER join sExamination.tCustomIncidentStatus CIS ON CIS.Id = CI.StatusId
 INNER JOIN sExamination.tArchieveExamination EE ON CI.ExaminationId=EE.Id
 LEFT JOIN sHrm.tEmployeeMaster EM ON EE.ParticipantSourceId=EM.Id AND isnull(EE.ParticipantSourceTypeId,95) = 95 
 LEFT JOIN sHrm.tCsrBenefiterMaster CS ON EE.ParticipantSourceId=CS.Id AND EE.ParticipantSourceTypeId = 1009 
 LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  
 LEFT JOIN sExamination.tOPD OP on OP.ExaminationId = EE.Id
)
SELECT * FROM( SELECT CI.Id,CI.ExaminationId,
        CASE WHEN  CI.ExaminationId IS NULL THEN IP.InjuredPersonNames
		     ELSE
                IP2.EmployeeName
		END
		AS EmployeeName,  
		CASE WHEN  CI.ExaminationId IS NULL THEN IP.EmployeeCode
		     ELSE
                IP2.EmployeeCode
		END
		AS EmployeeCode,
        case isnull(EE.ParticipantSourceTypeId,95) when 95 then EM.Id else CS.Id end AS EmployeeId,  
        isnull(EE.ParticipantSourceTypeId,95) as ParticipantSourceTypeId,
        case isnull(EE.ParticipantSourceTypeId,95) when 95 then 'Employee' ELSE 'Other' end AS ParticipantType, 
        CI.IsFit, 
		isnull(IP2.ExaminationNumber, '') as ExaminationNumber, CIS.Id as LogStatusId, 
        isnull(CIS.Title, '') as LogStatus, isnull(C.Title, '') as VisitPurpose, 
        isnull(CI.PlantId, 0) as PlantId, 
		CASE WHEN  CI.ExaminationId IS NULL THEN II.IncidentDateTime
		     ELSE
                CI.IncidentDateTime
		END
		AS IncidentDateTime,
        case when II.Id is not null then 1 else 0 end as IsFIRCreated,
        isnull(II.ReportCode, '') as ReportCode,

		CASE 
	      WHEN EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformationLog] IIL
                         WHERE IIL.ReportId = II.Id AND IIL.Status = 2 AND IIL.PartialViewId=5)
            THEN 2 --Completed
		  WHEN NOT EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformation] WHERE ExaminationId = CI.ExaminationId)
			AND NOT EXISTS(SELECT 1 FROM [sInjury].[vIncidentInformationLog] WHERE ReportId=II.Id)
            THEN 0
			ELSE 1 --Pending

	    END as RestAdviseStatus,

		CASE 
	      WHEN NOT EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformation] WHERE ExaminationId = CI.ExaminationId)
			AND NOT EXISTS(SELECT 1 FROM [sInjury].[vIncidentInformationLog] WHERE ReportId=II.Id)
            THEN 0
		  WHEN NOT EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformationLog] RAD WHERE RAD.ReportId=II.Id)
            THEN 0
			WHEN EXISTS (
					SELECT 1 
					FROM [sInjury].[vRestAdvisedByDoctor] RAD 
					WHERE RAD.ReportId = II.Id 
					  --AND RAD.InDraft = 0 
					  AND RAD.RevisitStatus =2
				) THEN 2 -- 2= Complete
		  WHEN EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformationLog] IIL
                         WHERE IIL.ReportId = II.Id AND IIL.Status = 2 AND IIL.PartialViewId=5)
            THEN 1 -- 1= Pending
				ELSE 0 
	    END as RevisitStatus,

        CASE 
	        WHEN 
	        EXISTS (SELECT  1 FROM [sInjury].[vOccupationalReportLog] ORL
                  LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
                  LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
	        LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
                  WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId) 
	        THEN 
	        (SELECT TOP 1 ORL.Id FROM [sInjury].[vOccupationalReportLog] ORL
                  LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
                  LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
	        LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
                  WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId)
	        ELSE
                  (SELECT top 1 IL.Id FROM [sInjury].[vIncidentInformationLog] IL
	        LEFT JOIN [sInjury].[vIncidentInformation] IR on IR.Id=IL.ReportId
	        where IR.[InDraft]=0 and IL.RoleId = 32 and IL.ReportId = II.Id order by IL.Id desc) 
	    END as LogId,

	    CASE 
	        WHEN 
	        EXISTS (SELECT  1 FROM [sInjury].[vOccupationalReportLog] ORL
                  LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
                  LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
	        LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
                  WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId) 
	        THEN 
	        (SELECT TOP 1 ORL.ReportId FROM [sInjury].[vOccupationalReportLog] ORL
                  LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
                  LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
	        LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
                  WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId)
	        ELSE
                  (SELECT top 1 IL.ReportId FROM [sInjury].[vIncidentInformationLog] IL
	        LEFT JOIN [sInjury].[vIncidentInformation] IR on IR.Id=IL.ReportId
	        where IR.[InDraft]=0 and IL.RoleId = 32 and IL.ReportId = II.Id order by IL.Id desc) 
	    END as ReportId,

		CASE 
		    WHEN 
		    EXISTS (SELECT  1 FROM [sInjury].[vOccupationalReportLog] ORL
               LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
               LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
		    LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
               WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId) 
		    THEN 
		    (SELECT TOP 1 PM.Id FROM [sInjury].[vOccupationalReportLog] ORL
               LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
               LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
		    LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
               WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId)
		    ELSE
               (SELECT top 1 IL.PartialViewId FROM [sInjury].[vIncidentInformationLog] IL
		    LEFT JOIN [sInjury].[vIncidentInformation] IR on IR.Id=IL.ReportId
		    where IR.[InDraft]=0 and IL.RoleId = 32 and IL.ReportId = II.Id order by IL.Id desc)
		END as PartialViewId, 

		CASE 
		    WHEN 
		    EXISTS (SELECT  1 FROM [sInjury].[vOccupationalReportLog] ORL
               LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
               LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
		    LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
               WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId) 
		    THEN 
		    (SELECT TOP 1 PM.PartialViewName FROM [sInjury].[vOccupationalReportLog] ORL
               LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
               LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
		    LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
               WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId)
		    ELSE
               (SELECT top 1 (select PartialViewName from [sInjury].[vPartialViewMaster] where Id=IL.PartialViewId)
		    FROM [sInjury].[vIncidentInformationLog] IL
		    LEFT JOIN [sInjury].[vIncidentInformation] IR on IR.Id=IL.ReportId
		    where IR.[InDraft]=0 and IL.RoleId = 32 and IL.ReportId = II.Id order by IL.Id desc) 
		END as PartialViewName, 

		CASE 
		    WHEN 
		    EXISTS (SELECT  1 FROM [sInjury].[vOccupationalReportLog] ORL
               LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
               LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
		    LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
               WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId) 
		    THEN 
		    (SELECT TOP 1 ORL.Status FROM [sInjury].[vOccupationalReportLog] ORL
               LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
               LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
		    LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id=ST.SectionId
               WHERE ORL.ReportId = II.Id AND ORL.Status = 1 AND PM.Id=15 AND ORL.UserId = @rUserId)
		    ELSE
               (SELECT top 1 IL.Status FROM [sInjury].[vIncidentInformationLog] IL
		    LEFT JOIN [sInjury].[vIncidentInformation] IR on IR.Id=IL.ReportId
		    where IR.[InDraft]=0 and IL.RoleId = 32 and IL.ReportId = II.Id order by IL.Id desc) 
		END as Status, 

        (SELECT top 1 IL.RoleId FROM [sInjury].[vIncidentInformationLog] IL
		        LEFT JOIN [sInjury].[vIncidentInformation] IR on IR.Id=IL.ReportId
		        where IR.[InDraft]=0 and IL.RoleId = 32 and IL.ReportId = II.Id order by IL.Id desc) as RoleId,

		CASE 
		    WHEN NOT EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformation] WHERE ExaminationId = CI.ExaminationId)
			AND NOT EXISTS(SELECT 1 FROM [sInjury].[vIncidentInformationLog] WHERE ReportId=II.Id)
            THEN 'FIR Generation'

	        --WHEN EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformation] WHERE Id = II.Id and InDraft = 1)
         --   THEN 'Incident Log Information'
            -- Check in IncidentInformationLog
            WHEN EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformationLog] IIL
                         WHERE IIL.ReportId = II.Id AND IIL.Status = 1)
            THEN 
                (SELECT TOP 1 PM.PartialViewName FROM [sInjury].[vIncidentInformationLog] IIL
                 LEFT JOIN [sInjury].[vPartialViewMaster] PM ON PM.Id = IIL.PartialViewId
                 WHERE IIL.ReportId = II.Id AND IIL.Status = 1)
            -- Check in ReportPreparation
            WHEN EXISTS (SELECT 1 FROM [sInjury].[vIncidentInformation] WHERE Id = II.Id and IsGenbaDone = 1 and Id Not in(select ReportId from [sInjury].[vReportPreparation]))
            THEN 'Report Preparation'
		    
	        WHEN EXISTS (SELECT 1 FROM [sInjury].[vReportPreparation] RP
            WHERE RP.ReportId = II.Id AND RP.Status IN (1, 3))
            THEN 'Report Preparation'
            -- Check in OccupationalReportLog
            WHEN EXISTS (SELECT 1 FROM [sInjury].[vOccupationalReportLog] ORL
                         WHERE ORL.ReportId = II.Id AND ORL.Status = 1)
            THEN
                (SELECT TOP 1 ST.StageName FROM [sInjury].[vOccupationalReportLog] ORL
                 LEFT JOIN [sInjury].[vStageRoles] SR ON SR.Id = ORL.StageRoleId
                 LEFT JOIN [sInjury].[vStages] ST ON ST.StageID = SR.StageID
                 WHERE ORL.ReportId = II.Id AND ORL.Status = 1)
            ELSE 'Completed'
	    END AS CurrentStageName,

		CASE 
	    WHEN EXISTS (SELECT 1 FROM [sInjury].[vReportPreparation] RP
        WHERE RP.ReportId = II.Id AND RP.Status>1)
		THEN 1
		ELSE 0
		END AS IsReportPrepDone,
		isnull(OP.ReferenceEmployeeId, '') as ReferenceOtherId, isnull(EM2.Code, '') as ReferenceCode, 
		isnull(EM2.FirstName,'') + ' ' + isnull(EM2.LastName,'') as ReferenceName,
		isnull(CI.InjuryConfirmedById, 0) as InjuryConfirmedById, isnull(EM3.FirstName,'') + ' ' + isnull(EM3.LastName,'') as InjuryConfirmedByName,
		isnull(ECOM.CompanyEmail, '') as InjuryConfirmedMailId
 From [sInjury].[vIncidentInformation] II
 FULL OUTER join [sExamination].[tCustomIncident] CI ON II.ExaminationId = CI.ExaminationId 
 LEFT join sExamination.tCustomIncidentStatus CIS ON CIS.Id = CI.StatusId
 LEFT JOIN sExamination.tExamination EE ON CI.ExaminationId=EE.Id
 LEFT JOIN sHrm.tEmployeeMaster EM ON EE.ParticipantSourceId=EM.Id AND isnull(EE.ParticipantSourceTypeId,95) = 95 
 LEFT JOIN sHrm.tCsrBenefiterMaster CS ON EE.ParticipantSourceId=CS.Id AND EE.ParticipantSourceTypeId = 1009 
 LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  
 LEFT JOIN sExamination.tOPD OP on OP.ExaminationId = EE.Id
 LEFT JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = OP.ReferenceEmployeeId
 LEFT JOIN sExamination.tCauseMaster C on C.Id = EE.CauseId
 LEFT JOIN sExamination.tCauseTypeMaster CTM on CTM.Id = C.CauseTypeId
 LEFT JOIN InjuredPersons IP ON IP.IncidentId = II.Id AND CI.ExaminationId IS NULL
 LEFT JOIN InjuredPerson2 IP2 ON IP2.ExaminationId=CI.ExaminationId
 LEFT JOIN sHrm.tEmployeeMaster EM3 ON EM3.Id = CI.InjuryConfirmedById
 LEFT JOIN sHrm.tEmployeeCommunications ECOM ON ECOM.EmployeeId = EM3.Id
 WHERE 
 (II.InDraft IS NULL OR II.InDraft <> 1)
 AND (
        ( II.InDraft = 0 AND II.LocationId = (SELECT LocationId FROM sIp.tStoreLocationMaster WHERE Id = @rStoreLocationId))
        OR
        (II.InDraft IS NULL AND EE.StoreLocationId = @rStoreLocationId)
    )
AND (
(II.InDraft = 0 AND II.IsActive=1)
OR 
(II.InDraft IS NULL)
)
AND ( 
(II.InDraft IS NULL AND CI.StatusId = 2 )
OR
(II.InDraft = 0)
)
AND ISNULL(EE.IsCancel,0)=0
)S
 WHERE ((S.EmployeeCode like @rEmployeeCode)  OR (ISNULL(@rEmployeeCode,'')=''))
 AND ((S.Id = @rId) OR (@rId = 0))
 ORDER BY S.Id DESC;
END
GO
PRINT N'Altering Procedure [sExamination].[pVisitPurposeGet]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pVisitPurposeGet]
@rId int,
@rCode nvarchar(30)='',
@rTitle nvarchar(100)='',
@rOrgId smallint =0,
@rCauseSeverityId tinyint=0,
@rCauseTypeId tinyint= 0,
@rIsSearch bit = 1
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF @rIsSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
	SELECT CM.Id,CM.Code,CM.Title,
	ISNULL(CS.Title,'') AS CauseSeverityName,
	ISNULL(CM.CauseSeverityId,0) AS CauseSeverityId,
	ISNULL(CT.Title,'') AS CauseTypeName,
	ISNULL(CM.CauseTypeID,0) AS CauseTypeID,
	ISNULL(CM.IsObsolete,0) AS IsObsolete,
	isnull(CM.IsTrackIncidentLog,0) as IsTrackIncidentLog,
	isnull(CM.IsCustomLog,0) as IsCustomLog,
	isnull(CM.IsTrackForFitness,0) as IsTrackForFitness,
	isnull(CM.IsDefault,0) as IsDefault,
	isnull(CM.DiseaseId,0) as DiseaseId,
	isnull(CM.FurtherActionId,0) as FurtherActionId,
	isnull(CM.IsFit,0) as IsFit, 
	isnull(CM.IsWellness,0) as IsWellness
	FROM sExamination.tCauseMaster CM
	LEFT JOIN sExamination.tCauseTypeMaster CT ON CT.Id=CM.CauseTypeId
	LEFT JOIN sExamination.tCauseSeverityMaster CS ON CS.ID=CM.CauseSeverityId
	WHERE ((CM.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
	AND	((CM.Id = @rId) OR (@rId = 0))
	AND ((CM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
	AND ((CM.CauseSeverityId=@rCauseSeverityId)OR(@rCauseSeverityId=0))
	AND ((CM.CauseTypeId=@rCauseTypeId)OR(@rCauseTypeId=0))
	AND ((CM.OrgId=@rOrgId))
	ORDER BY CM.CreatedDateTime desc
END
GO
PRINT N'Altering Procedure [sExamination].[pVisitPurposeMasterAdd]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pVisitPurposeMasterAdd]	 
@rId int,
@rCode nvarchar(30),
@rTitle nvarchar(100),
@rIsObsolete bit,
@rOrgId smallint,
@rCreatedUserId bigint,
@rCauseSeverityId tinyint,
@rCauseTypeId tinyint,
@rIsTrackLog bit,
@rIsCustomLog bit,
@rIsTrackFitness bit,
@rIsDefault bit,
@rDiseaseId int = null,
@rFurtherActionId int = null,
@rFit bit = null,
@rIsWellness bit = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sExamination.tCauseMaster where Code=@rCode AND OrgId=@rOrgId)
		BEGIN
			select -102 as Result
			RETURN
		END 

		If Exists(select Id from sExamination.tCauseMaster where Title=@rTitle AND OrgId=@rOrgId)
		BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sExamination.tCauseMaster where Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		
		If  Exists(select Id from sExamination.tCauseMaster where Title=@rTitle AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	IF(@rCauseTypeId=4)
	Begin
		If  Exists(select Id from sExamination.tCauseMaster where CauseTypeId=@rCauseTypeId AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -104 as Result
			RETURN
		End
	End
	IF(@rCauseTypeId=5)
	Begin
		If  Exists(select Id from sExamination.tCauseMaster where CauseTypeId=@rCauseTypeId AND OrgId=@rOrgId AND Id<>@rId)
		Begin
			select -105 as Result
			RETURN
		End
	End
	select @rDiseaseId = case when isnull(@rDiseaseId,0) in (0,-1) then null else @rDiseaseId end
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN		
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sExamination.tCauseMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sExamination.tCauseMaster
		(
			Id,Code,Title,IsObsolete,OrgId,CreatedUserId,
			CreatedDateTime,CauseSeverityId,CauseTypeId,
			IsTrackIncidentLog,IsCustomLog,IsTrackForFitness,DiseaseId,
			FurtherActionId,IsFit,IsWellness
		)
		VALUES
		(
			@lNextNumber,@rCode,@rTitle,@rIsObsolete,@rOrgId,
			@rCreatedUserId,sCommon.fGetDate(),@rCauseSeverityId,
			@rCauseTypeId,@rIsTrackLog,@rIsCustomLog,@rIsTrackFitness,@rDiseaseId,
			@rFurtherActionId,@rFit,@rIsWellness
		)
		
		--if @rIsDefault = 0
		--begin
		--	declare @cnt int
		--	select @cnt = count(*) from sExamination.tCauseMaster where OrgId = @rOrgId
		--	select @cnt = isnull(@cnt,0)
			
		--	if @cnt = 0
		--	begin
		--		update sExamination.tCauseMaster set IsDefault = 1 where Id = @lNextNumber
		--	end
		--end

		--Mantis Id: 0026655, Developer: Deval, Date: 16/08/2023
		if @rIsDefault = 1
		begin
			update sExamination.tCauseMaster set IsDefault = 0 where OrgId = @rOrgId
			update sExamination.tCauseMaster set IsDefault = 1 where Id = @lNextNumber
		end
		--Mantis Id: 0026655, Developer: Deval, Date: 16/08/2023

		SELECT 1 AS Result
	END
	ELSE
	BEGIN
		SET @lNextNumber = @rId
		UPDATE sExamination.tCauseMaster SET
		Title=@rTitle,Code=@rCode,UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=sCommon.fGetDate(),CauseSeverityId= @rCauseSeverityId,
		CauseTypeId =@rCauseTypeId,IsObsolete=@rIsObsolete,
		IsTrackIncidentLog = @rIsTrackLog,IsCustomLog = @rIsCustomLog,IsTrackForFitness = @rIsTrackFitness,
		DiseaseId = @rDiseaseId,FurtherActionId = @rFurtherActionId,IsFit = @rFit,
		IsDefault = @rIsDefault,   --Mantis Id: 0026655, Developer: Deval, Date: 16/08/2023
		IsWellness = @rIsWellness
		WHERE Id = @rId
		SELECT 11 AS Result
	END
	
	if @rIsDefault = 1
	begin
		update sExamination.tCauseMaster set IsDefault = 0 where OrgId = @rOrgId
		update sExamination.tCauseMaster set IsDefault = 1 where Id = @lNextNumber
	end	
	COMMIT TRANSACTION
END
GO
PRINT N'Altering Procedure [sExamination].[pExaminationDetaileGet]...';


GO
-- exec [sExamination].[pExaminationDetaileGet] 9999000000831,8
-- drop proc [sExamination].[pExaminationDetaileGet]
CREATE OR ALTER PROCEDURE [sExamination].[pExaminationDetaileGet]
@rId bigint,
@rMainTyepId int
AS
SET NOCOUNT ON
BEGIN
	Declare @lPreviousDate datetime = '1900/01/01',@lExaminationDate datetime
	Declare @lCriteriaGroupId int,@lTargetGroupId int
	Declare @lEmployeeId bigint
	SET @lCriteriaGroupId = (SELECT CriteiraGroupId FROM sExamination.tExamination Where Id = @rId)
	SET @lTargetGroupId = (SELECT TargetGroupId FROM sExamination.tExamination Where Id = @rId)
	SET @lEmployeeId = (SELECT ParticipantSourceId FROM sExamination.tExamination Where Id = @rId)
	SET @lExaminationDate = (SELECT ExaminationDate FROM sExamination.tExamination Where Id = @rId)
	SET @lPreviousDate = 
	(
		SELECT ExaminationDate FROM 
		(
			SELECT ExaminationDate,ROW_NUMBER() OVER(ORDER BY ExaminationDate desc) As RowNum
			FROM sExamination.tExamination E
			INNER JOIN sExamination.tSetupMaster SM ON SM.Id = E.SetupId
			INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = SM.SubTypeId
			where STM.MainTypeId = 1 AND E.ParticipantSourceId = @lEmployeeId  AND ExaminationDate < @lExaminationDate
		) As A
		WHERE A.RowNum =1
	)
	IF((@rMainTyepId != 7) AND (@rMainTyepId != 8))
	BEGIN
		SELECT E.Id AS ExaminationId,
		E.OrgId,
		ST.MainTypeId,
		MT.Title AS MainTypeName,
		E.StoreLocationId,
		SLM.Title AS StoreLocationName,
		SLM.LocationId,
		LM.Title AS LocationName,
		OrganizationDepartmentId,
		OD.Title AS DepartmentName,
		E.SetupId,
		SM.RoundNumber,
		E.StatusId,
		ExaminationDate,
		ParticipantSourceTypeId,
		ParticipantSourceId,
		ISNULL(DoctorEmployeeId,0) AS DoctorEmployeeId,
		ParticipantCode = CASE E.ParticipantSourceTypeId 
		WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
		ParticipantName = 
		CASE E.ParticipantSourceTypeId 
		WHEN 1009 THEN
		(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) 
		WHEN 95 THEN EM.FirstName + ' ' + EM.LastName 
		WHEN 1001 THEN EFD.Name END,
		
		RelationName = CASE E.ParticipantSourceTypeId WHEN  95 THEN 'SELF' WHEN 1001 THEN RM.Title WHEN 1009 THEN 'Other' END,
		GenderId = CASE E.ParticipantSourceTypeId WHEN 95 THEN EPD.GenderId
		WHEN 1001 THEN ISNULL([sCommon].[fGenderIdFromRelationIdGet](EFD.RelationshipId),'')
		WHEN 1009 THEN BM.GenderId END,
		Gender = CASE E.ParticipantSourceTypeId	WHEN 95 THEN GM.Title
		WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
		WHEN 1009 THEN GM2.Title END,
		DateOfBirth = CASE E.ParticipantSourceTypeId WHEN 95 THEN ISNULL(EPD.DateOfBirth,'')
		WHEN 1001 THEN ISNULL(EFD.DateOfBirth,'')
		WHEN 1009 THEN ISNULL(BM.DateOfBirth,'') END,
		Age = CASE E.ParticipantSourceTypeId
		WHEN 95 THEN ISNULL(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0)
		WHEN 1001 THEN ISNULL(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0)
		WHEN 1009 THEN ISNULL(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) END,
		isnull(EmployeeDesignationId,0) as EmployeeDesignationId,
		isnull(E.ProcessTypeId,0) as ProcessTypeId,
		SM.Title AS Setup,		
		isnull(Height,0) as Height,
		 CASE 
    WHEN E.ParticipantSourceTypeId = 1009 
        THEN ISNULL(BM.MobileNO, ETO.MobileNumber) when E.ParticipantSourceTypeId = 1001 
        THEN ISNULL(BM.MobileNO, ETO.MobileNumber)
    ELSE 
        ISNULL(EC.MobileNumber, ETO.MobileNumber)
END AS MobileNumber,
		CompanyEmail,
		SSM.Title as StatusName,
		ISNULL(@lPreviousDate,'1900/01/01') AS PreviousDate,
		ISNULL(@lCriteriaGroupId,0) AS CriteriaGroupId,
		isnull(@lTargetGroupId,0) AS TargetGroupId
		FROM sExamination.tExamination E
		INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
		INNER JOIN sExamination.tSubTypeMaster ST on SM.SubTypeId = ST.Id
		INNER JOIN sExamination.tMainTypeMaster MT on ST.MainTypeId = MT.Id
		INNER JOIN sIp.tStoreLocationMaster SLM on E.StoreLocationId = SLM.Id
		INNER JOIN sCommon.tLocationMaster LM on SLM.LocationId = LM.Id
		LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id
		LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
		LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
		LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
		LEFT JOIN sCommon.tOrganizationDepartmentMaster OD on E.OrganizationDepartmentId = OD.Id
		LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=EFD.RelationshipId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId
		LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
		LEFT JOIN sExamination.tStatusMaster SSM on E.StatusId = SSM.Id
		LEFT JOIN sExamination.tVital V on V.SourceId = E.Id	
		WHERE E.Id = @rId 
	END
	ELSE
	BEGIN
		SELECT E.Id AS ExaminationId,
		E.OrgId,
		ST.MainTypeId,
		MT.Title AS MainTypeName,
		E.StoreLocationId,
		SLM.Title AS StoreLocationName,
		SLM.LocationId,
		LM.Title AS LocationName,
		OrganizationDepartmentId,
		OD.Title AS DepartmentName,
		E.SetupId,
		SM.RoundNumber,
		E.StatusId,
		ExaminationDate,
		ParticipantSourceTypeId,
		ParticipantSourceId,
		ISNULL(DoctorEmployeeId,0) AS DoctorEmployeeId,
		ParticipantCode = CASE E.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
		ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN
		(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) 
		WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END,
		RelationName = CASE E.ParticipantSourceTypeId WHEN  95 THEN 'SELF' WHEN 1001 THEN RM.Title WHEN 1009 THEN 'Other' END,
		GenderId = CASE E.ParticipantSourceTypeId WHEN 95 THEN EPD.GenderId
		WHEN 1001 THEN ISNULL([sCommon].[fGenderIdFromRelationIdGet](EFD.RelationshipId),'')
		WHEN 1009 THEN BM.GenderId END,
		Gender = CASE E.ParticipantSourceTypeId	WHEN 95 THEN GM.Title
		WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
		WHEN 1009 THEN GM2.Title END,
		DateOfBirth = CASE E.ParticipantSourceTypeId WHEN 95 THEN ISNULL(EPD.DateOfBirth,'')
		WHEN 1001 THEN ISNULL(EFD.DateOfBirth,'')
		WHEN 1009 THEN ISNULL(BM.DateOfBirth,'') END,
		Age = CASE E.ParticipantSourceTypeId
		WHEN 95 THEN ISNULL(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0)
		WHEN 1001 THEN ISNULL(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0)
		WHEN 1009 THEN ISNULL(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) END,
		isnull(EmployeeDesignationId,0) as EmployeeDesignationId,
		isnull(E.ProcessTypeId,0) as ProcessTypeId,
		SM.Title AS Setup,		
		isnull(Height,0) as Height,
	    CASE 
    WHEN E.ParticipantSourceTypeId = 1009 
        THEN ISNULL(BM.MobileNO, ETO.MobileNumber) when E.ParticipantSourceTypeId = 1001 
        THEN ISNULL(BM.MobileNO, ETO.MobileNumber)
    ELSE 
        ISNULL(EC.MobileNumber, ETO.MobileNumber)
END AS MobileNumber,
		CompanyEmail,
		SSM.Title as StatusName,
		ISNULL(@lPreviousDate,'1900/01/01') AS PreviousDate,
		ISNULL(@lCriteriaGroupId,0) AS CriteriaGroupId,
		isnull(@lTargetGroupId,0) AS TargetGroupId
		FROM sExamination.tExamination E
		INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
		INNER JOIN sExamination.tSubTypeMaster ST on SM.SubTypeId = ST.Id
		INNER JOIN sExamination.tMainTypeMaster MT on ST.MainTypeId = MT.Id
		INNER JOIN sIp.tStoreLocationMaster SLM on E.StoreLocationId = SLM.Id
		INNER JOIN sCommon.tLocationMaster LM on SLM.LocationId = LM.Id
		LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id
		LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
		LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
		LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
		LEFT JOIN sCommon.tOrganizationDepartmentMaster OD on E.OrganizationDepartmentId = OD.Id
		LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=EFD.RelationshipId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId
		LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
		LEFT JOIN sExamination.tStatusMaster SSM on E.StatusId = SSM.Id
		LEFT JOIN sExamination.tVital V on V.SourceId = E.Id	
		WHERE E.Id = @rId
	END
END
GO
PRINT N'Altering Procedure [sMro].[pMROFullViewGet]...';


GO
ALTER proc [sMro].[pMROFullViewGet]
@rSourceId bigint,
@rSourceTypeId int,
@rOrgId int,
@rAreaId int,
@rParticipantSourceId bigint,
@rParticipantSourceTypeId int,
@rGenderId int,
@rAge int
as
begin
	declare @lConfigurationValue varchar(5)
	select @lConfigurationValue = sConfig.fConfigurationValueGet('Examination.IsTempChangetoCelsius', @rOrgId, 0, 0, 0)	
	Declare @rTargetGroupId int, @rSetupId int;
    set @rTargetGroupId = (select TargetGroupId from sExamination.tExamination where id=@rSourceId)  --0049369
    set @rSetupId = (select SetupId from sExamination.tExamination where id=@rSourceId)
	declare @tbltmpArea table
	(
		tid int identity(1,1),t_AreaId int,t_AreaName varchar(200),t_URL varchar(2000),
		t_ImagePath varchar(2000),t_AreaTypeId int
	)
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(1,@rOrgId),'Vital','','../../Images/Icon 16x16/icon_appointmnt.gif',0
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(2,@rOrgId),'Habit Hygiene','','~/Images/Icon 16x16/icon_habits.gif',4  --//Mantis:0031798 By-Shivam on 11/03/2024
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(4,@rOrgId),'Existing Disease','','~/Images/Icon 16x16/icon_ExistingDisease.gif',4
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(5,@rOrgId),'Past History','','~/Images/Icon 16x16/icon_PastHistory.gif',4
		
	insert into @tbltmpArea
	select TM.Id,TM.Title,'','../../Images/Icon 16x16/icon_outpatient.gif',1
	from sOrderEntry.tTestMaster TM
	inner join sExamination.tTestRequest TR on TM.Id = TR.TestId
	where TR.SourceId = @rSourceId and TM.OrgId = @rOrgId and TM.IsObsolete = 0
	

	union all
		select TM.Id,TM.Title,'','../../Images/Icon 16x16/icon_outpatient.gif',1
	from sOrderEntry.tTestMaster TM
	inner join sExamination.tArchieveTestRequest TR on TM.Id = TR.TestId
	where TR.SourceId = @rSourceId and TM.OrgId = @rOrgId and TM.IsObsolete = 0


	insert into @tbltmpArea
	select GM.Id,GM.Title,'','../../Images/Icon 16x16/icon_general.gif',3
	from sExamination.tGeneralTemplateMaster GM
	inner join sExamination.tGeneralTemplateExamination GE on GM.Id = GE.GeneralTemplateId
	where GE.SourceId = @rSourceId and GM.OrgId = @rOrgId and GM.IsObsolete = 0
	union all
		select GM.Id,GM.Title,'','../../Images/Icon 16x16/icon_general.gif',3
	from sExamination.tGeneralTemplateMaster GM
	inner join sExamination.tArchieveGeneralTemplateExamination GE on GM.Id = GE.GeneralTemplateId
	where GE.SourceId = @rSourceId and GM.OrgId = @rOrgId and GM.IsObsolete = 0
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(23,@rOrgId),'Audiometry','','~/Images/Icon 16x16/icon_outpatient.gif',2
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(28,@rOrgId),'Pulmonary','','~/Images/Icon 16x16/icon_outpatient.gif',2
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(10000,@rOrgId),'Diagnosis','','../../Images/Icon 16x16/icon_diagnosis.gif',0
	
	declare @cnt int,@i int
	select @cnt = count(*),@i = 1 from @tbltmpArea
	
	declare @tbltmpview table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),col4 varchar(max),
	col1Name varchar(max),col2Name varchar(max),col3Name varchar(max),col4Name varchar(max),isNormal int,AreaId int)
	
	while @i <= @cnt
	begin
		declare @lAreaId int = 0
		select @lAreaId = t_AreaId from @tbltmpArea where tid = @i
		
		if @lAreaId = [sCommon].[fGetIntIdForOrg](1,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'Height',Convert(Nvarchar(50),Height) + ' Cm','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			union all
			SELECT 'Height',Convert(Nvarchar(50),Height) + ' Cm','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tArchieveVital where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Weight',convert(varchar,BodyWeight)+ ' Kg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			union all
			SELECT 'Weight',convert(varchar,BodyWeight)+ ' Kg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tArchieveVital where SourceId = @rSourceId
			
			insert into @tbltmpview		
			SELECT 'BMI',convert(varchar,BMI) --+ CASE WHEN @lConfigurationValue = 'True' THEN ' °C' ELSE ' °F' END
			,'','',      --0049369
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			union all
						SELECT 'BMI',convert(varchar,BMI) --+ CASE WHEN @lConfigurationValue = 'True' THEN ' °C' ELSE ' °F' END
						,'','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tArchieveVital where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'BMI Result',[sExamination].[fBMIValueGet](isnull(BMI,0)) -- + ' /Min'
			,'','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			Union all

			SELECT 'BMI Result',[sExamination].[fBMIValueGet](isnull(BMI,0))  --+ ' /Min'
			,'','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tArchieveVital where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'BPSystolic',convert(varchar,BloodPressureSystolic) + ' mmHg','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			union all

			SELECT 'BPSystolic',convert(varchar,BloodPressureSystolic) + ' mmHg','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tArchieveVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'BPDiastolic',convert(varchar,BloodPressureDiastolic) + ' mmHg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			union all

						SELECT 'BPDiastolic',convert(varchar,BloodPressureDiastolic) + ' mmHg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tArchieveVital where SourceId = @rSourceId
			
			--insert into @tbltmpview  ---0049369
			--SELECT 'Inhalation',convert(varchar,ChestExpansionInhalation) + ' Cm','','',
			--'Parametr','Value','','',1,@lAreaId
			--From sExamination.tVital where SourceId = @rSourceId
			
			--insert into @tbltmpview  
			--SELECT 'Exhalation',convert(varchar,ChestExpansionExhalation) + ' Cm','','',
			--'Parametr','Value','','',1,@lAreaId
			--From sExamination.tVital where SourceId = @rSourceId

			--union all

			--			SELECT 'Exhalation',convert(varchar,ChestExpansionExhalation) + ' Cm','','',
			--'Parametr','Value','','',1,@lAreaId
			--From sExamination.tArchieveVital where SourceId = @rSourceId
			
			--insert into @tbltmpview
			--SELECT 'ChestExpansion',convert(varchar,ChestExpansion) + ' Cm','','',
			--'Parametr','Value','','',1,@lAreaId
			--From sExamination.tVital where SourceId = @rSourceId

			--union all

			--			SELECT 'ChestExpansion',convert(varchar,ChestExpansion) + ' Cm','','',
			--'Parametr','Value','','',1,@lAreaId
			--From sExamination.tArchieveVital where SourceId = @rSourceId
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](2,@rOrgId)
		begin
			insert into @tbltmpview			
			SELECT H.Title,HHD.Remark,convert(varchar,HHD.Duration) + '-' + DUM.Title,'',
			'Name','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tHabitHygine HH
			INNER JOIN sExamination.tHabitHygineDetail HHD ON HH.Id = HHD.HabitHygineId
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HHD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tHabitTypeMaster H ON H.Id = HHD.HabitId
			  INNER join sExamination.tTargetGroupExaminationTemplate TG    on TG.SourceParameterId = H.Id and TG.TargetGroupId = @rTargetGroupId -- -mantis id:0049369
			WHERE HH.SourceId = @rSourceId AND HH.SourceTypeId = @rSourceTypeId
			AND HH.OrgId = @rOrgId AND HHD.IsObsolete = 0 AND HH.IsObsolete = 0	 and TG.MainTypeId = @rSetupId  and TG.TargetGroupId = @rTargetGroupId and TG.SourceTemplateId = 10160 --and H.OrgId =@rOrgId  ---Habit

			union all

			SELECT H.Title,HHD.Remark,convert(varchar,HHD.Duration) + '-' + DUM.Title,'',
			'Name','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tArchieveHabitHygine HH
			INNER JOIN sExamination.tArchieveHabitHygineDetail HHD ON HH.Id = HHD.HabitHygineId
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HHD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tHabitTypeMaster H ON H.Id = HHD.HabitId
			  INNER join sExamination.tTargetGroupExaminationTemplate TG    on TG.SourceParameterId = H.Id and TG.TargetGroupId = @rTargetGroupId -- -mantis id:0049369
			WHERE HH.SourceId = @rSourceId AND HH.SourceTypeId = @rSourceTypeId
			AND HH.OrgId = @rOrgId AND HHD.IsObsolete = 0 AND HH.IsObsolete = 0	 and TG.MainTypeId = @rSetupId  and TG.TargetGroupId = @rTargetGroupId and TG.SourceTemplateId = 10160 --and H.OrgId =@rOrgId  ---Habit
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](4,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT DM.Title,ED.Remark,convert(varchar,ED.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tExistingDisease E
			INNER JOIN sExamination.tExistingDiseaseDetail ED ON E.Id = ED.ExistingDiseaseId AND E.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON ED.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = ED.DiseaseId
			  INNER join sExamination.tTargetGroupExaminationTemplate TG  on TG.SourceParameterId = DM.Id   --- -- -mantis id:0049369
			WHERE E.SourceId = @rSourceId AND E.OrgId = @rOrgId AND ED.IsObsolete = 0 and TG.TargetGroupId = @rTargetGroupId  and TG.MainTypeId = @rSetupId and TG.SourceTemplateId = 10161 ---Disease

			union all

						SELECT DM.Title,ED.Remark,convert(varchar,ED.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tArchieveExistingDisease E
			INNER JOIN sExamination.tArchieveExistingDiseaseDetail ED ON E.Id = ED.ExistingDiseaseId AND E.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON ED.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = ED.DiseaseId
			  INNER join sExamination.tTargetGroupExaminationTemplate TG  on TG.SourceParameterId = DM.Id   --- -- -mantis id:0049369
			WHERE E.SourceId = @rSourceId AND E.OrgId = @rOrgId AND ED.IsObsolete = 0 and TG.TargetGroupId = @rTargetGroupId  and TG.MainTypeId = @rSetupId and TG.SourceTemplateId = 10161 ---Disease
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](5,@rOrgId)
		begin
			insert into @tbltmpview			
			SELECT DM.Title + '-' + RM.Title,HD.Remark,convert(varchar,HD.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tHistory H
			INNER JOIN sExamination.tHistoryDetail HD ON H.Id = HD.HistoryId AND H.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = HD.DiseaseId
			INNER JOIN sCommon.tRelationshipMaster RM on RM.Id=HD.RelationshipId
			WHERE H.ParticipantSourceId = @rParticipantSourceId
			AND H.ParticipantSourceTypeId = @rParticipantSourceTypeId
			AND H.OrgId = @rOrgId AND HD.IsObsolete = 0
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](23,@rOrgId)
	begin
	  IF EXISTS (
        SELECT 1
        FROM sExamination.tTargetGroupExaminationTemplate TG
        WHERE TG.TargetGroupId = @rTargetGroupId
          AND TG.MainTypeId = @rSetupId
          AND TG.SourceTemplateId = 10162   -- Audiometry-- -mantis id:0049369
    )
	begin

			insert into @tbltmpview
			SELECT 'Left Ac Result',ISNULL(ARM.Title,''),'','','Parameter',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultLeftId
			where SourceId = @rSourceId

			union all

						SELECT 'Left Ac Result',ISNULL(ARM.Title,''),'','','Parameter',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tArchieveAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultLeftId
			where SourceId = @rSourceId

			insert into @tbltmpview
			SELECT 'Left Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultLeftId
			where SourceId = @rSourceId

			union all

						SELECT 'Left Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tArchieveAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultLeftId
			where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'Left Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkLeftId
			where SourceId = @rSourceId

			union all

						SELECT 'Left Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tArchieveAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkLeftId
			where SourceId = @rSourceId
		
			insert into @tbltmpview			
			SELECT 'Right Ac Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultRightId
			where SourceId = @rSourceId

			union all

						SELECT 'Right Ac Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tArchieveAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultRightId
			where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Right Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultRightId
			where SourceId = @rSourceId

			union all

						SELECT 'Right Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tArchieveAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultRightId
			where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Right Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkRightId
			where SourceId = @rSourceId

			union all

			
			SELECT 'Right Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tArchieveAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkRightId
			where SourceId = @rSourceId
		end
		end
		
       ELSE IF @lAreaId = [sCommon].[fGetIntIdForOrg](28, @rOrgId)
       BEGIN                                            -- Pulmonary-- -mantis id:0049369
           IF EXISTS (
               SELECT 1
               FROM sExamination.tTargetGroupExaminationTemplate TG
               WHERE TG.TargetGroupId = @rTargetGroupId
                 AND TG.MainTypeId = @rSetupId
                 AND TG.SourceTemplateId = 10163
           )
           BEGIN
       
               ;WITH Params AS (
                   SELECT 'FVC%' AS Param, 1 AS Seq
                   UNION ALL SELECT 'FEV1%', 2
                   UNION ALL SELECT 'FEV1/FVC%', 3
                   UNION ALL SELECT 'PEFR%', 4
                   UNION ALL SELECT 'RESULT', 5
               ),
               PulmonaryData AS (
                   SELECT *
                   FROM sExamination.tPulmonary
                   WHERE SourceId = @rSourceId
       
                   UNION ALL
       
                   SELECT *
                   FROM sExamination.tArchievePulmonary
                   WHERE SourceId = @rSourceId
               )
               INSERT INTO @tbltmpview
               SELECT
                   P.Param,
                   CASE P.Param
                       WHEN 'FVC%'       THEN CONVERT(nvarchar(100), D.PerOfPredictedFVC)
                       WHEN 'FEV1%'      THEN CONVERT(nvarchar(100), D.PerOfFEV1)
                       WHEN 'FEV1/FVC%'  THEN CONVERT(nvarchar(100), D.PerOfFEV1ByFVC)
                       WHEN 'PEFR%'      THEN CONVERT(nvarchar(100), D.PerPEFR)
                       WHEN 'RESULT'     THEN [sExamination].[fGetPulmonaryResultNew](@rSourceId)
                   END,
                   '', '',
                   'Parameter', 'Value', '', '',
                   1, @lAreaId
               FROM Params P
               LEFT JOIN PulmonaryData D
                   ON 1 = 1        -- ensures rows even if no data
               ORDER BY P.Seq;
       
           END
       END

		if exists (select 1 from sExamination.tGeneralTemplateExamination GE inner join sExamination.tGeneralTemplateMaster GM
		on GE.GeneralTemplateId = GM.Id where GM.Id = @lAreaId and GE.SourceId = @rSourceId)
		begin
			insert into @tbltmpview		
			SELECT GTP.Title as Colum1,
			CONVERT(NVARCHAR(50),ISNULL(GTED.ParameterValue,'')) as Colum2,
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
				@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			THEN
				ISNULL(GTED.Diagnosis,'')
			END AS Colum3,ISNULL(GTED.Remark,'') AS Colum4,'Parameter' AS Colum1Name,
			'Value' AS Colum2Name,'Diagnosis' AS Colum3Name,'Remark' AS Colum4Name, --mantis id-49369
			1,@lAreaId from sExamination.tGeneralTemplateExamination GTE
			INNER JOIN sExamination.tGeneralTemplateExaminationDetail GTED ON GTED.GeneralTemplateExaminationId = GTE.Id
			INNER JOIN sExamination.tGeneralTemplateMaster GTM ON GTM.Id = GTE.GeneralTemplateId
			INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTED.GeneralTemplateParameterId
			INNER join sExamination.tTargetGroupExaminationTemplate TG    on TG.SourceParameterId = GTP.Id  -- -mantis id:0049369
			WHERE GTM.OrgId = @rOrgId
			AND GTE.SourceTypeId = @rSourceTypeId
			AND GTE.SourceId = @rSourceId
			And ((GTM.Id = @lAreaId) OR (@lAreaId = 0))
			AND ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			AND GTED.ParameterValue <> ' -- Select -- '
			 and TG.TargetGroupId = @rTargetGroupId and TG.MainTypeId = @rSetupId     and TG.SourceTemplateId = 119 --and   GTM.GeneralTemplateGroupId = 2   --general,Clinical
		end
		if exists (select 1 from sExamination.tArchieveGeneralTemplateExamination GE inner join sExamination.tGeneralTemplateMaster GM
		on GE.GeneralTemplateId = GM.Id where GM.Id = @lAreaId and GE.SourceId = @rSourceId)
		begin
			insert into @tbltmpview		
			SELECT GTP.Title as Colum1,
			CONVERT(NVARCHAR(50),ISNULL(GTED.ParameterValue,'')) as Colum2,
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
				@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			THEN
				ISNULL(GTED.Diagnosis,'')
			END AS Colum3,ISNULL(GTED.Remark,'') AS Colum4,'Parameter' AS Colum1Name,
			'Value' AS Colum2Name,'Diagnosis' AS Colum3Name,'Remark' AS Colum4Name,   --mantis id-49369
			1,@lAreaId from sExamination.tArchieveGeneralTemplateExamination GTE
			INNER JOIN sExamination.tArchieveGeneralTemplateExaminationDetail GTED ON GTED.GeneralTemplateExaminationId = GTE.Id
			INNER JOIN sExamination.tGeneralTemplateMaster GTM ON GTM.Id = GTE.GeneralTemplateId
			INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTED.GeneralTemplateParameterId
		    INNER join sExamination.tTargetGroupExaminationTemplate TG    on TG.SourceParameterId = GTP.Id  -- -mantis id:0049369
			WHERE GTM.OrgId = @rOrgId
			AND GTE.SourceTypeId = @rSourceTypeId
			AND GTE.SourceId = @rSourceId
			And ((GTM.Id = @lAreaId) OR (@lAreaId = 0))
			AND ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			AND GTED.ParameterValue <> ' -- Select -- '
					 and TG.TargetGroupId = @rTargetGroupId and TG.MainTypeId = @rSetupId     and TG.SourceTemplateId = 119 --and   GTM.GeneralTemplateGroupId = 2   --general,Clinical
		end
		
		if exists(select 1 from sExamination.tTestRequest TR inner join sOrderEntry.tTestMaster TM on TR.TestId = TM.Id
		where TM.Id = @lAreaId and TR.SourceId = @rSourceId)
		begin
			insert into @tbltmpview	
			SELECT TPM.Title,CONVERT(NVARCHAR(50),ISNULL(TRD.ServiceValue,'')),
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,
				TPM.ParameterValueTypeId,@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1) = 0 
			THEN
				ISNULL(TRD.Diagnosis,'')
			END,ISNULL(TRD.Remark,''),
			'Parameter','ServiceValue','Diagnosis','Remark',
			ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,TPM.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1),@lAreaId
			FROM sExamination.tTestRequest TR
			INNER JOIN sOrderEntry.tTestMaster SM ON TR.TestId = SM.Id
			INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId=TR.Id
			AND TR.IsObsolete = 0 INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id
			INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
		    INNER JOIN sExamination.tTargetGroupExaminationTemplate TG on TG.SourceParameterId = TPM.Id      --mantis id:0049369
			WHERE TR.OrgId = @rOrgId AND TR.SourceTypeId = @rSourceTypeId
			AND TR.SourceId = @rSourceId And ((TR.TestId = @lAreaId) OR (@lAreaId = 0))
			AND TRD.ServiceValue <> ' -- Select -- '
				AND TG.MainTypeId = @rSetupId and TG.TargetGroupId = @rTargetGroupId and TG.SourceTemplateId = 118  ---test
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg] (10000,@rOrgId)
		begin
			insert into @tbltmpview	
			SELECT ISNULL(DiagnosisRemark,''),ISNULL(RecommendationEnglish,''),
			'','','Diagnosis Remark','Recommendation Remark','','',1,@lAreaId  --//Mantis:0031954 By-Shivam on 11/03/2024
			FROM sExamination.tDiagnosis WHERE SourceId = @rSourceId
		end

				if exists(select 1 from sExamination.tArchieveTestRequest TR inner join sOrderEntry.tTestMaster TM on TR.TestId = TM.Id
		where TM.Id = @lAreaId and TR.SourceId = @rSourceId)
		begin
			insert into @tbltmpview	
			SELECT TPM.Title,CONVERT(NVARCHAR(50),ISNULL(TRD.ServiceValue,'')),
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,
				TPM.ParameterValueTypeId,@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1) = 0 
			THEN
				ISNULL(TRD.Diagnosis,'')
			END,ISNULL(TRD.Remark,''),
			'Parameter','ServiceValue','Diagnosis','Remark',
			ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,TPM.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1),@lAreaId
			FROM sExamination.tArchieveTestRequest TR
			INNER JOIN sOrderEntry.tTestMaster SM ON TR.TestId = SM.Id
			INNER JOIN sExamination.tArchieveTestRequestDetail TRD ON TRD.TestRequestId=TR.Id
			AND TR.IsObsolete = 0 INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id
			INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
			INNER JOIN sExamination.tTargetGroupExaminationTemplate TG on TG.SourceParameterId = TPM.Id      --mantis id:0049369
			WHERE TR.OrgId = @rOrgId AND TR.SourceTypeId = @rSourceTypeId
			AND TR.SourceId = @rSourceId And ((TR.TestId = @lAreaId) OR (@lAreaId = 0))
			AND TRD.ServiceValue <> ' -- Select -- '
			AND TG.MainTypeId = @rSetupId and TG.TargetGroupId = @rTargetGroupId and TG.SourceTemplateId = 118  ---test
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg] (10000,@rOrgId)
		begin
			insert into @tbltmpview	
			SELECT ISNULL(DiagnosisRemark,''),ISNULL(RecommendationEnglish,''),
			'','','Diagnosis Remark','Recommendation Remark','','',1,@lAreaId  --//Mantis:0031954 By-Shivam on 11/03/2024
			FROM sExamination.tArchieveDiagnosis WHERE SourceId = @rSourceId
		end
		
		select @i = @i + 1
	end
	
	declare @rescnt int,@j int,@res varchar(max)='',@newres varchar(max)='',@resab varchar(max)=''
	
	select @cnt = 0, @i = 0
	select @cnt = count(*),@i = 1 from @tbltmpArea
		
	Declare @ParticipantCode nvarchar(20), @ParticipantName nvarchar(100), @Setup nvarchar(100);
	IF EXISTS (SELECT 1 FROM sExamination.tExamination WHERE Id = @rSourceId)
BEGIN
	select 
	@ParticipantCode = CASE E.ParticipantSourceTypeId 
		WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
		@ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN
		(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) 
		WHEN 95 THEN EM.FirstName + ' ' + EM.LastName 
		WHEN 1001 THEN EFD.Name END, @Setup = SM.Title
	from sExamination.tExamination E
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id
		LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
		LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
		Where E.Id = @rSourceId
		end
	else IF EXISTS (SELECT 1 FROM sExamination.tArchieveExamination WHERE Id = @rSourceId)
BEGIN
	select 
	@ParticipantCode = CASE E.ParticipantSourceTypeId 
		WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
		@ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN
		(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) 
		WHEN 95 THEN EM.FirstName + ' ' + EM.LastName 
		WHEN 1001 THEN EFD.Name END, @Setup = SM.Title
	from sExamination.tArchieveExamination E
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id
		LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
		LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
		Where E.Id = @rSourceId
		end
	select @res = @res + '<div class="content-wrapper">
    <h6 class="p-2"><b>Code: </b>' + @ParticipantCode + ' | <b>Name: </b>' + @ParticipantName + ' | <b>Round: </b>' + @Setup + '</h6>
    <div>'

	while @i <= @cnt
	begin
		declare @areaid int = 0,@areaname varchar(max)='',@imgpath varchar(max)='',@pagepath varchar(max)=''
		declare @testareaid int
		select @areaid = t_AreaId,@areaname = t_AreaName,@imgpath = replace(t_ImagePath,'~/','../../'),
		@pagepath = replace(t_URL,'~/','/') from @tbltmpArea where tid = @i order by tid
		
		declare @lcnt int = 0
		select @lcnt = count(*) from @tbltmpview where AreaId = @areaid
		select @lcnt = isnull(@lcnt,0)
		--<div class="fRight" style="margin-top: -3px;"> 
		--	<img src="' + @imgpath + '" alt="' + @areaname + '" style="border-width:0px;">
		--	</div>

		if @lcnt > 0
		begin
			select @res = @res + '<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header alert alert-light col-md-12 mb-0">
                <h4 class="card-title">' + @areaname + '</h4></div>'
			
			--<a href="' + @pagepath + '" target="_blank">' + @areaname + '</a>
			
			create table #tbltmpnew(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),col4 varchar(max),
			col1Name varchar(max),col2Name varchar(max),col3Name varchar(max),col4Name varchar(max),isNormal int,AreaId int)
			
			insert into #tbltmpnew
			select col1,col2,col3,col4,col1Name,col2Name,col3Name,col4Name,isNormal,AreaId
			from @tbltmpview where AreaId = @areaid
			
			select @rescnt = count(*),@j = 1 from #tbltmpnew
			
			while @j <= @rescnt
			begin
				declare @col1 varchar(max)='',@col2 varchar(max)='',@col3 varchar(max)='',@col4 varchar(max)='',@isnormal int=0,
				@col1Name varchar(max)='',@col2Name varchar(max)='',@col3Name varchar(max)='',@col4Name varchar(max)=''
				
				if @j = 1
				begin
					select top 1 @col1Name=isnull(col1Name,''),@col2Name=isnull(col2Name,''),
					@col3Name=isnull(col3Name,''),@col4Name=isnull(col4Name,'') from #tbltmpnew where AreaId = @areaid
					
					select @newres = @newres + '<div class="card-content">
    <div class="card-body">
        <div class="row">
            <div class="col-12">
                    <div class="table-responsive" id="htmlData" #htmlData>
					<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
					<tbody>
					<tr>
					<th scope="col"> <span>' + @col1Name + '</span> </th>
					<th scope="col"> <span>' + @col2Name + '</span> </th>				
					<th scope="col"> <span>' + @col3Name + '</span> </th>				
					<th scope="col"> <span>' + @col4Name + '</span> </th>				
					</tr>'
				end
				
				select @col1=isnull(col1,''),@col2=isnull(col2,''),@col3=isnull(col3,''),@col4=isnull(col4,''),@isnormal = isnull(isnormal,0) from #tbltmpnew where tid = @j			
				
				select @resab = @resab + '<tr'+ (case when @isnormal=1 then '' else ' style="color:red"' end)+'>'+'
				<td style="width:25%;"><span title="' + @col1 + '" class="boxEllips" style="display:inline-block;">' + @col1 + '</span> </td>
				<td style="width:25%;"><span title="' + @col2 + '" class="boxEllips" style="display:inline-block;">' + @col2 + '</span> </td>			
				<td style="width:25%;"><span title="' + @col3 + '" class="boxEllips" style="display:inline-block;">' + @col3 + '</span> </td>			
				<td style="width:25%;"><span title="' + @col4 + '" class="boxEllips" style="display:inline-block;">' + @col4 + '</span> </td>			
				</tr>'
				
				if @j = @rescnt
				begin
					select @res = @res + @newres + @resab + '</div></div></tbody></table></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>'
					select @newres = '',@resab = ''				
				end
				
				select @j = @j + 1
			end
			drop table #tbltmpnew
		end		
		
		select @i = @i + 1
	end
		
	select @res = isnull(@res,'')	
	select @res as res
end
GO
PRINT N'Altering Procedure [sMro].[pDaignosisViewGet]...';


GO

ALTER proc [sMro].[pDaignosisViewGet]
@rSourceId bigint,
@rSourceTypeId int,
@rOrgId int,
@rAreaId int,
@rParticipantSourceId bigint,
@rParticipantSourceTypeId int,
@rGenderId int,
@rAge int
as
begin
	declare @lConfigurationValue varchar(5)
	select @lConfigurationValue = sConfig.fConfigurationValueGet('Examination.IsTempChangetoCelsius', @rOrgId, 0, 0, 0)	
	declare @tbltmpArea table
	(
		tid int identity(1,1),t_AreaId int,t_AreaName varchar(200),t_URL varchar(2000),
		t_ImagePath varchar(2000),t_AreaTypeId int
	)
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(1,@rOrgId),'Vital','','../../Images/Icon 16x16/icon_appointmnt.gif',0
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(2,@rOrgId),'Habit Hygiene','','~/Images/Icon 16x16/icon_habits.gif',4  --//Mantis:0031798 By-Shivam on 11/03/2024
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(4,@rOrgId),'Existing Disease','','~/Images/Icon 16x16/icon_ExistingDisease.gif',4
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(5,@rOrgId),'Past History','','~/Images/Icon 16x16/icon_PastHistory.gif',4
		
	insert into @tbltmpArea
	select TM.Id,TM.Title,'','../../Images/Icon 16x16/icon_outpatient.gif',1
	from sOrderEntry.tTestMaster TM
	inner join sExamination.tTestRequest TR on TM.Id = TR.TestId
	where TR.SourceId = @rSourceId and TM.OrgId = @rOrgId and TM.IsObsolete = 0
	order by TM.OrderIndex 

	insert into @tbltmpArea
	select GM.Id,GM.Title,'','../../Images/Icon 16x16/icon_general.gif',3
	from sExamination.tGeneralTemplateMaster GM
	inner join sExamination.tGeneralTemplateExamination GE on GM.Id = GE.GeneralTemplateId
	where GE.SourceId = @rSourceId and GM.OrgId = @rOrgId and GM.IsObsolete = 0
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(23,@rOrgId),'Audiometry','','~/Images/Icon 16x16/icon_outpatient.gif',2
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(28,@rOrgId),'Pulmonary','','~/Images/Icon 16x16/icon_outpatient.gif',2
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(10000,@rOrgId),'Diagnosis','','../../Images/Icon 16x16/icon_diagnosis.gif',0
	
	declare @cnt int,@i int
	select @cnt = count(*),@i = 1 from @tbltmpArea
	
	declare @tbltmpview table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),col4 varchar(max),
	col1Name varchar(max),col2Name varchar(max),col3Name varchar(max),col4Name varchar(max),isNormal int,AreaId int)
	
	while @i <= @cnt
	begin
		declare @lAreaId int = 0
		select @lAreaId = t_AreaId from @tbltmpArea where tid = @i
		
		if @lAreaId = [sCommon].[fGetIntIdForOrg](1,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'Height',Convert(Nvarchar(50),Height) + ' Cm','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Weight',convert(varchar,BodyWeight)+ ' Kg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview		
			SELECT 'Temperature',convert(varchar,Temperature) + CASE WHEN @lConfigurationValue = 'True' THEN ' °C' ELSE ' °F' END,'','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'Pulse',convert(varchar,Pulse) + ' /Min','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'BPSystolic',convert(varchar,BloodPressureSystolic) + ' mmHg','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'BPDiastolic',convert(varchar,BloodPressureDiastolic) + ' mmHg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'Inhalation',convert(varchar,ChestExpansionInhalation) + ' Cm','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'Exhalation',convert(varchar,ChestExpansionExhalation) + ' Cm','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'ChestExpansion',convert(varchar,ChestExpansion) + ' Cm','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](2,@rOrgId)
		begin
			insert into @tbltmpview			
			SELECT H.Title,HHD.Remark,convert(varchar,HHD.Duration) + '-' + DUM.Title,'',
			'Name','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tHabitHygine HH
			INNER JOIN sExamination.tHabitHygineDetail HHD ON HH.Id = HHD.HabitHygineId
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HHD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tHabitTypeMaster H ON H.Id = HHD.HabitId
			WHERE HH.SourceId = @rSourceId AND HH.SourceTypeId = @rSourceTypeId
			AND HH.OrgId = @rOrgId AND HHD.IsObsolete = 0 AND HH.IsObsolete = 0	
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](4,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT DM.Title,ED.Remark,convert(varchar,ED.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tExistingDisease E
			INNER JOIN sExamination.tExistingDiseaseDetail ED ON E.Id = ED.ExistingDiseaseId AND E.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON ED.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = ED.DiseaseId
			WHERE E.SourceId = @rSourceId AND E.OrgId = @rOrgId AND ED.IsObsolete = 0
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](5,@rOrgId)
		begin
			insert into @tbltmpview			
			SELECT DM.Title + '-' + RM.Title,HD.Remark,convert(varchar,HD.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tHistory H
			INNER JOIN sExamination.tHistoryDetail HD ON H.Id = HD.HistoryId AND H.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = HD.DiseaseId
			INNER JOIN sCommon.tRelationshipMaster RM on RM.Id=HD.RelationshipId
			WHERE H.ParticipantSourceId = @rParticipantSourceId
			AND H.ParticipantSourceTypeId = @rParticipantSourceTypeId
			AND H.OrgId = @rOrgId AND HD.IsObsolete = 0
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](23,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'Left Ac Result',ISNULL(ARM.Title,''),'','','Parameter',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultLeftId
			where SourceId = @rSourceId

			insert into @tbltmpview
			SELECT 'Left Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultLeftId
			where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'Left Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkLeftId
			where SourceId = @rSourceId
		
			insert into @tbltmpview			
			SELECT 'Right Ac Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultRightId
			where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Right Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultRightId
			where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Right Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkRightId
			where SourceId = @rSourceId
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg] (28,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'FVC%',CONVERT(nvarchar(100),PerOfPredictedFVC),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'FEV1%',CONVERT(nvarchar(100),PerOfFEV1),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'FEV1/FVc%',CONVERT(nvarchar(100),PerOfFEV1ByFVC),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'PEFR%',CONVERT(nvarchar(100),PerPEFR),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'RESULT',(select item1 + ' ' + item2 from [sExamination].[fGetPulmonaryResults_NEW](@rSourceId)),'','',
			'Parameter','Value','','',1,@lAreaId
		end
		
		if exists (select 1 from sExamination.tGeneralTemplateExamination GE inner join sExamination.tGeneralTemplateMaster GM
		on GE.GeneralTemplateId = GM.Id where GM.Id = @lAreaId and GE.SourceId = @rSourceId)
		begin
			insert into @tbltmpview		
			SELECT GTP.Title as Colum1,
			CONVERT(NVARCHAR(50),ISNULL(GTED.ParameterValue,'')) as Colum2,
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
				@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			THEN
				ISNULL(GTED.Diagnosis,'')
			END AS Colum3,ISNULL(GTED.Remark,'') AS Colum4,'Parameter' AS Colum1Name,
			'ServiceValue' AS Colum2Name,'Diagnosis' AS Colum3Name,'Remark' AS Colum4Name,
			1,@lAreaId from sExamination.tGeneralTemplateExamination GTE
			INNER JOIN sExamination.tGeneralTemplateExaminationDetail GTED ON GTED.GeneralTemplateExaminationId = GTE.Id
			INNER JOIN sExamination.tGeneralTemplateMaster GTM ON GTM.Id = GTE.GeneralTemplateId
			INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTED.GeneralTemplateParameterId
			WHERE GTM.OrgId = @rOrgId
			AND GTE.SourceTypeId = @rSourceTypeId
			AND GTE.SourceId = @rSourceId
			And ((GTM.Id = @lAreaId) OR (@lAreaId = 0))
			AND ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			AND GTED.ParameterValue <> ' -- Select -- '
		end
		
		if exists(select 1 from sExamination.tTestRequest TR inner join sOrderEntry.tTestMaster TM on TR.TestId = TM.Id
		where TM.Id = @lAreaId and TR.SourceId = @rSourceId)
		begin
			insert into @tbltmpview	
			SELECT TPM.Title,CONVERT(NVARCHAR(50),ISNULL(TRD.ServiceValue,'')),
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,
				TPM.ParameterValueTypeId,@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1) = 0 
			THEN
				ISNULL(TRD.Diagnosis,'')
			END,ISNULL(TRD.Remark,''),
			'Parameter','ServiceValue','Diagnosis','Remark',
			ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,TPM.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1),@lAreaId
			FROM sExamination.tTestRequest TR
			INNER JOIN sOrderEntry.tTestMaster SM ON TR.TestId = SM.Id
			INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId=TR.Id
			AND TR.IsObsolete = 0 INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id
			INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
			WHERE TR.OrgId = @rOrgId AND TR.SourceTypeId = @rSourceTypeId
			AND TR.SourceId = @rSourceId And ((TR.TestId = @lAreaId) OR (@lAreaId = 0))
			AND TRD.ServiceValue <> ' -- Select -- '
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg] (10000,@rOrgId)
		begin
			insert into @tbltmpview	
			SELECT ISNULL(DiagnosisRemark,''),ISNULL(RecommendationEnglish,''),
			'','','Diagnosis Remark','Recommendation Remark','','',1,@lAreaId  --//Mantis:0031954 By-Shivam on 11/03/2024
			FROM sExamination.tDiagnosis WHERE SourceId = @rSourceId
		end
		
		select @i = @i + 1
	end
	
	declare @rescnt int,@j int,@res varchar(max)='',@newres varchar(max)='',@resab varchar(max)=''
	
	select @cnt = 0, @i = 0
	select @cnt = count(*),@i = 1 from @tbltmpArea
		
	Declare @ParticipantCode nvarchar(20), @ParticipantName nvarchar(100), @Setup nvarchar(100);
	select 
	@ParticipantCode = CASE E.ParticipantSourceTypeId 
		WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
		@ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN
		(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) 
		WHEN 95 THEN EM.FirstName + ' ' + EM.LastName 
		WHEN 1001 THEN EFD.Name END, @Setup = SM.Title
	from sExamination.tExamination E
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id
		LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
		LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
		Where E.Id = @rSourceId

	select @res = @res + '<div class="content-wrapper">
    <h6 class="p-2"><b>Code: </b>' + @ParticipantCode + ' | <b>Name: </b>' + @ParticipantName + ' | <b>Round: </b>' + @Setup + '</h6>
    <div>'

	while @i <= @cnt
	begin
		declare @areaid int = 0,@areaname varchar(max)='',@imgpath varchar(max)='',@pagepath varchar(max)=''
		declare @testareaid int
		select @areaid = t_AreaId,@areaname = t_AreaName,@imgpath = replace(t_ImagePath,'~/','../../'),
		@pagepath = replace(t_URL,'~/','/') from @tbltmpArea where tid = @i order by tid
		
		declare @lcnt int = 0
		select @lcnt = count(*) from @tbltmpview where AreaId = @areaid
		select @lcnt = isnull(@lcnt,0)
		--<div class="fRight" style="margin-top: -3px;"> 
		--	<img src="' + @imgpath + '" alt="' + @areaname + '" style="border-width:0px;">
		--	</div>

		if @lcnt > 0
		begin
			select @res = @res + '<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header alert alert-light col-md-12 mb-0">
                <h4 class="card-title">' + @areaname + '</h4></div>'
			
			--<a href="' + @pagepath + '" target="_blank">' + @areaname + '</a>
			
			create table #tbltmpnew(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),col4 varchar(max),
			col1Name varchar(max),col2Name varchar(max),col3Name varchar(max),col4Name varchar(max),isNormal int,AreaId int)
			
			insert into #tbltmpnew
			select col1,col2,col3,col4,col1Name,col2Name,col3Name,col4Name,isNormal,AreaId
			from @tbltmpview where AreaId = @areaid
			
			select @rescnt = count(*),@j = 1 from #tbltmpnew
			
			while @j <= @rescnt
			begin
				declare @col1 varchar(max)='',@col2 varchar(max)='',@col3 varchar(max)='',@col4 varchar(max)='',@isnormal int=0,
				@col1Name varchar(max)='',@col2Name varchar(max)='',@col3Name varchar(max)='',@col4Name varchar(max)=''
				
				if @j = 1
				begin
					select top 1 @col1Name=isnull(col1Name,''),@col2Name=isnull(col2Name,''),
					@col3Name=isnull(col3Name,''),@col4Name=isnull(col4Name,'') from #tbltmpnew where AreaId = @areaid
					
					select @newres = @newres + '<div class="card-content">
    <div class="card-body">
        <div class="row">
            <div class="col-12">
                    <div class="table-responsive" id="htmlData" #htmlData>
					<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
					<tbody>
					<tr>
					<th scope="col"> <span>' + @col1Name + '</span> </th>
					<th scope="col"> <span>' + @col2Name + '</span> </th>				
					<th scope="col"> <span>' + @col3Name + '</span> </th>				
					<th scope="col"> <span>' + @col4Name + '</span> </th>				
					</tr>'
				end
				
				select @col1=isnull(col1,''),@col2=isnull(col2,''),@col3=isnull(col3,''),@col4=isnull(col4,''),@isnormal = isnull(isnormal,0) from #tbltmpnew where tid = @j			
				
				select @resab = @resab + '<tr'+ (case when @isnormal=1 then '' else ' style="color:red"' end)+'>'+'
				<td style="width:25%;"><span title="' + @col1 + '" class="boxEllips" style="display:inline-block;">' + @col1 + '</span> </td>
				<td style="width:25%;"><span title="' + @col2 + '" class="boxEllips" style="display:inline-block;">' + @col2 + '</span> </td>			
				<td style="width:25%;"><span title="' + @col3 + '" class="boxEllips" style="display:inline-block;">' + @col3 + '</span> </td>			
				<td style="width:25%;"><span title="' + @col4 + '" class="boxEllips" style="display:inline-block;">' + @col4 + '</span> </td>			
				</tr>'
				
				if @j = @rescnt
				begin
					select @res = @res + @newres + @resab + '</div></div></tbody></table></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>'
					select @newres = '',@resab = ''				
				end
				
				select @j = @j + 1
			end
			drop table #tbltmpnew
		end		
		
		select @i = @i + 1
	end
		
	select @res = isnull(@res,'')	
	select @res as res
end
GO
PRINT N'Altering Procedure [sExamination].[pDaignosisFullViewGet]...';


GO

ALTER proc [sExamination].[pDaignosisFullViewGet]
@rSourceId bigint,
@rSourceTypeId int,
@rOrgId int, 
@rAreaId int,
@rParticipantSourceId bigint,
@rParticipantSourceTypeId int,
@rGenderId int,
@rAge int
as
begin
	declare @lConfigurationValue varchar(5)
	select @lConfigurationValue = sConfig.fConfigurationValueGet('Examination.IsTempChangetoCelsius', @rOrgId, 0, 0, 0)	
	declare @tbltmpArea table
	(
		tid int identity(1,1),t_AreaId int,t_AreaName varchar(200),t_URL varchar(2000),
		t_ImagePath varchar(2000),t_AreaTypeId int
	)
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(1,@rOrgId),'Vital','','../../Images/Icon 16x16/icon_appointmnt.gif',0
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(2,@rOrgId),'Habit Hygiene','','~/Images/Icon 16x16/icon_habits.gif',4  --//Mantis:0031798 By-Shivam on 11/03/2024
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(4,@rOrgId),'Existing Disease','','~/Images/Icon 16x16/icon_ExistingDisease.gif',4
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(5,@rOrgId),'Past History','','~/Images/Icon 16x16/icon_PastHistory.gif',4
		
	insert into @tbltmpArea
	select TM.Id,TM.Title,'','../../Images/Icon 16x16/icon_outpatient.gif',1
	from sOrderEntry.tTestMaster TM
	inner join sExamination.tTestRequest TR on TM.Id = TR.TestId
	where TR.SourceId = @rSourceId and TM.OrgId = @rOrgId and TM.IsObsolete = 0
	order by TM.OrderIndex 

	insert into @tbltmpArea
	select GM.Id,GM.Title,'','../../Images/Icon 16x16/icon_general.gif',3
	from sExamination.tGeneralTemplateMaster GM
	inner join sExamination.tGeneralTemplateExamination GE on GM.Id = GE.GeneralTemplateId
	where GE.SourceId = @rSourceId and GM.OrgId = @rOrgId and GM.IsObsolete = 0
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(23,@rOrgId),'Audiometry','','~/Images/Icon 16x16/icon_outpatient.gif',2
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(28,@rOrgId),'Pulmonary','','~/Images/Icon 16x16/icon_outpatient.gif',2
	
	insert into @tbltmpArea
	select sCommon.fGetIntIdForOrg(10000,@rOrgId),'Diagnosis','','../../Images/Icon 16x16/icon_diagnosis.gif',0
	
	declare @cnt int,@i int
	select @cnt = count(*),@i = 1 from @tbltmpArea
	
	declare @tbltmpview table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),col4 varchar(max),
	col1Name varchar(max),col2Name varchar(max),col3Name varchar(max),col4Name varchar(max),isNormal int,AreaId int)
	
	while @i <= @cnt
	begin
		declare @lAreaId int = 0
		select @lAreaId = t_AreaId from @tbltmpArea where tid = @i
		
		if @lAreaId = [sCommon].[fGetIntIdForOrg](1,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'Height',Convert(Nvarchar(50),Height) + ' Cm','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Weight',convert(varchar,BodyWeight)+ ' Kg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview		
			SELECT 'Temperature',convert(varchar,Temperature) + CASE WHEN @lConfigurationValue = 'True' THEN ' °C' ELSE ' °F' END,'','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'Pulse',convert(varchar,Pulse) + ' /Min','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'BPSystolic',convert(varchar,BloodPressureSystolic) + ' mmHg','','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'BPDiastolic',convert(varchar,BloodPressureDiastolic) + ' mmHg','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'Inhalation',convert(varchar,ChestExpansionInhalation) + ' Cm','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'Exhalation',convert(varchar,ChestExpansionExhalation) + ' Cm','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
			
			insert into @tbltmpview
			SELECT 'ChestExpansion',convert(varchar,ChestExpansion) + ' Cm','','',
			'Parametr','Value','','',1,@lAreaId
			From sExamination.tVital where SourceId = @rSourceId
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](2,@rOrgId)
		begin
			insert into @tbltmpview			
			SELECT H.Title,HHD.Remark,convert(varchar,HHD.Duration) + '-' + DUM.Title,'',
			'Name','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tHabitHygine HH
			INNER JOIN sExamination.tHabitHygineDetail HHD ON HH.Id = HHD.HabitHygineId
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HHD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tHabitTypeMaster H ON H.Id = HHD.HabitId
			WHERE HH.SourceId = @rSourceId AND HH.SourceTypeId = @rSourceTypeId
			AND HH.OrgId = @rOrgId AND HHD.IsObsolete = 0 AND HH.IsObsolete = 0	
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](4,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT DM.Title,ED.Remark,convert(varchar,ED.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tExistingDisease E
			INNER JOIN sExamination.tExistingDiseaseDetail ED ON E.Id = ED.ExistingDiseaseId AND E.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON ED.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = ED.DiseaseId
			WHERE E.SourceId = @rSourceId AND E.OrgId = @rOrgId AND ED.IsObsolete = 0
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](5,@rOrgId)
		begin
			insert into @tbltmpview			
			SELECT DM.Title + '-' + RM.Title,HD.Remark,convert(varchar,HD.Duration) + '-' + DUM.Title,'',
			'Disease','Remark','Duration - Unit','',1,@lAreaId
			FROM sExamination.tHistory H
			INNER JOIN sExamination.tHistoryDetail HD ON H.Id = HD.HistoryId AND H.IsObsolete = 0
			LEFT JOIN sCommon.tDurationUnitMaster DUM ON HD.DurationUnitId = DUM.Id
			INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = HD.DiseaseId
			INNER JOIN sCommon.tRelationshipMaster RM on RM.Id=HD.RelationshipId
			WHERE H.ParticipantSourceId = @rParticipantSourceId
			AND H.ParticipantSourceTypeId = @rParticipantSourceTypeId
			AND H.OrgId = @rOrgId AND HD.IsObsolete = 0
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg](23,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'Left Ac Result',ISNULL(ARM.Title,''),'','','Parameter',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultLeftId
			where SourceId = @rSourceId

			insert into @tbltmpview
			SELECT 'Left Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultLeftId
			where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'Left Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkLeftId
			where SourceId = @rSourceId
		
			insert into @tbltmpview			
			SELECT 'Right Ac Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryAcResultRightId
			where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Right Bc Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudiometryResultMaster ARM ON ARM.Id = AM.AudiometryBcResultRightId
			where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'Right Remark Result',ISNULL(ARM.Title,''),'','','Parametr',
			'AudioMetry Result','','',1,@lAreaId
			from sExamination.tAudiometry AM
			Left Join sExamination.tAudioMetryRemarkMaster ARM ON ARM.Id = AM.AudiometryResultRemarkRightId
			where SourceId = @rSourceId
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg] (28,@rOrgId)
		begin
			insert into @tbltmpview
			SELECT 'FVC%',CONVERT(nvarchar(100),PerOfPredictedFVC),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'FEV1%',CONVERT(nvarchar(100),PerOfFEV1),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'FEV1/FVc%',CONVERT(nvarchar(100),PerOfFEV1ByFVC),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId

			insert into @tbltmpview			
			SELECT 'PEFR%',CONVERT(nvarchar(100),PerPEFR),'','',
			'Parameter','Value','','',1,@lAreaId
			From sExamination.tPulmonary where SourceId = @rSourceId
			
			insert into @tbltmpview			
			SELECT 'RESULT',(select item1 + ' ' + item2 from [sExamination].[fGetPulmonaryResults_NEW](@rSourceId)),'','',
			'Parameter','Value','','',1,@lAreaId
		end
		
		if exists (select 1 from sExamination.tGeneralTemplateExamination GE inner join sExamination.tGeneralTemplateMaster GM
		on GE.GeneralTemplateId = GM.Id where GM.Id = @lAreaId and GE.SourceId = @rSourceId)
		begin
			insert into @tbltmpview		
			SELECT GTP.Title as Colum1,
			CONVERT(NVARCHAR(50),ISNULL(GTED.ParameterValue,'')) as Colum2,
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
				@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			THEN
				ISNULL(GTED.Diagnosis,'')
			END AS Colum3,ISNULL(GTED.Remark,'') AS Colum4,'Parameter' AS Colum1Name,
			'ServiceValue' AS Colum2Name,'Diagnosis' AS Colum3Name,'Remark' AS Colum4Name,
			1,@lAreaId from sExamination.tGeneralTemplateExamination GTE
			INNER JOIN sExamination.tGeneralTemplateExaminationDetail GTED ON GTED.GeneralTemplateExaminationId = GTE.Id
			INNER JOIN sExamination.tGeneralTemplateMaster GTM ON GTM.Id = GTE.GeneralTemplateId
			INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTED.GeneralTemplateParameterId
			WHERE GTM.OrgId = @rOrgId
			AND GTE.SourceTypeId = @rSourceTypeId
			AND GTE.SourceId = @rSourceId
			And ((GTM.Id = @lAreaId) OR (@lAreaId = 0))
			AND ISNULL([sExamination].[fGetNormalAbnormalForClinical](GTP.Id,GTP.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(GTED.ParameterValue,'')),@rAge),1) = 0
			AND GTED.ParameterValue <> ' -- Select -- '
		end
		
		if exists(select 1 from sExamination.tTestRequest TR inner join sOrderEntry.tTestMaster TM on TR.TestId = TM.Id
		where TM.Id = @lAreaId and TR.SourceId = @rSourceId)
		begin
			insert into @tbltmpview	
			SELECT TPM.Title,CONVERT(NVARCHAR(50),ISNULL(TRD.ServiceValue,'')),
			CASE WHEN
				ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,
				TPM.ParameterValueTypeId,@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1) = 0 
			THEN
				ISNULL(TRD.Diagnosis,'')
			END,ISNULL(TRD.Remark,''),
			'Parameter','ServiceValue','Diagnosis','Remark',
			ISNULL([sExamination].[fGetNormalAbnormalForTest](TPM.Id,TPM.ListValueTypeId,TPM.ParameterValueTypeId,
			@rGenderId,CONVERT(NVARCHAR(100),ISNULL(TRD.ServiceValue,'')),@rAge),1),@lAreaId
			FROM sExamination.tTestRequest TR
			INNER JOIN sOrderEntry.tTestMaster SM ON TR.TestId = SM.Id
			INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId=TR.Id
			AND TR.IsObsolete = 0 INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId=TD.Id
			INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id=TD.TestParameterId
			WHERE TR.OrgId = @rOrgId AND TR.SourceTypeId = @rSourceTypeId
			AND TR.SourceId = @rSourceId And ((TR.TestId = @lAreaId) OR (@lAreaId = 0))
			AND TRD.ServiceValue <> ' -- Select -- '
		end
		
		else if @lAreaId = [sCommon].[fGetIntIdForOrg] (10000,@rOrgId)
		begin
			insert into @tbltmpview	
			SELECT ISNULL(DiagnosisRemark,''),ISNULL(RecommendationEnglish,''),
			'','','Diagnosis Remark','Recommendation Remark','','',1,@lAreaId  --//Mantis:0031954 By-Shivam on 11/03/2024
			FROM sExamination.tDiagnosis WHERE SourceId = @rSourceId
		end
		
		select @i = @i + 1
	end
	
	declare @rescnt int,@j int,@res varchar(max)='',@newres varchar(max)='',@resab varchar(max)=''
	
	select @cnt = 0, @i = 0
	select @cnt = count(*),@i = 1 from @tbltmpArea
		
	Declare @ParticipantCode nvarchar(20), @ParticipantName nvarchar(100), @Setup nvarchar(100);
	select 
	@ParticipantCode = CASE E.ParticipantSourceTypeId 
		WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
		@ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN
		(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) 
		WHEN 95 THEN EM.FirstName + ' ' + EM.LastName 
		WHEN 1001 THEN EFD.Name END, @Setup = SM.Title
	from sExamination.tExamination E
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id
		LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
		LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
		Where E.Id = @rSourceId

	select @res = @res + '<div class="content-wrapper">
    <h6 class="p-2"><b>Code: </b>' + @ParticipantCode + ' | <b>Name: </b>' + @ParticipantName + ' | <b>Round: </b>' + @Setup + '</h6>
    <div>'

	while @i <= @cnt
	begin
		declare @areaid int = 0,@areaname varchar(max)='',@imgpath varchar(max)='',@pagepath varchar(max)=''
		declare @testareaid int
		select @areaid = t_AreaId,@areaname = t_AreaName,@imgpath = replace(t_ImagePath,'~/','../../'),
		@pagepath = replace(t_URL,'~/','/') from @tbltmpArea where tid = @i order by tid
		
		declare @lcnt int = 0
		select @lcnt = count(*) from @tbltmpview where AreaId = @areaid
		select @lcnt = isnull(@lcnt,0)
		--<div class="fRight" style="margin-top: -3px;"> 
		--	<img src="' + @imgpath + '" alt="' + @areaname + '" style="border-width:0px;">
		--	</div>

		if @lcnt > 0
		begin
			select @res = @res + '<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header alert alert-light col-md-12 mb-0">
                <h4 class="card-title">' + @areaname + '</h4></div>'
			
			--<a href="' + @pagepath + '" target="_blank">' + @areaname + '</a>
			
			create table #tbltmpnew(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),col4 varchar(max),
			col1Name varchar(max),col2Name varchar(max),col3Name varchar(max),col4Name varchar(max),isNormal int,AreaId int)
			
			insert into #tbltmpnew
			select col1,col2,col3,col4,col1Name,col2Name,col3Name,col4Name,isNormal,AreaId
			from @tbltmpview where AreaId = @areaid
			
			select @rescnt = count(*),@j = 1 from #tbltmpnew
			
			while @j <= @rescnt
			begin
				declare @col1 varchar(max)='',@col2 varchar(max)='',@col3 varchar(max)='',@col4 varchar(max)='',@isnormal int=0,
				@col1Name varchar(max)='',@col2Name varchar(max)='',@col3Name varchar(max)='',@col4Name varchar(max)=''
				
				if @j = 1
				begin
					select top 1 @col1Name=isnull(col1Name,''),@col2Name=isnull(col2Name,''),
					@col3Name=isnull(col3Name,''),@col4Name=isnull(col4Name,'') from #tbltmpnew where AreaId = @areaid
					
					select @newres = @newres + '<div class="card-content">
    <div class="card-body">
        <div class="row">
            <div class="col-12">
                    <div class="table-responsive" id="htmlData" #htmlData>
					<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
					<tbody>
					<tr>
					<th scope="col"> <span>' + @col1Name + '</span> </th>
					<th scope="col"> <span>' + @col2Name + '</span> </th>				
					<th scope="col"> <span>' + @col3Name + '</span> </th>				
					<th scope="col"> <span>' + @col4Name + '</span> </th>				
					</tr>'
				end
				
				select @col1=isnull(col1,''),@col2=isnull(col2,''),@col3=isnull(col3,''),@col4=isnull(col4,''),@isnormal = isnull(isnormal,0) from #tbltmpnew where tid = @j			
				
				select @resab = @resab + '<tr'+ (case when @isnormal=1 then '' else ' style="color:red"' end)+'>'+'
				<td style="width:25%;"><span title="' + @col1 + '" class="boxEllips" style="display:inline-block;">' + @col1 + '</span> </td>
				<td style="width:25%;"><span title="' + @col2 + '" class="boxEllips" style="display:inline-block;">' + @col2 + '</span> </td>			
				<td style="width:25%;"><span title="' + @col3 + '" class="boxEllips" style="display:inline-block;">' + @col3 + '</span> </td>			
				<td style="width:25%;"><span title="' + @col4 + '" class="boxEllips" style="display:inline-block;">' + @col4 + '</span> </td>			
				</tr>'
				
				if @j = @rescnt
				begin
					select @res = @res + @newres + @resab + '</div></div></tbody></table></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>'
					select @newres = '',@resab = ''				
				end
				
				select @j = @j + 1
			end
			drop table #tbltmpnew
		end		
		
		select @i = @i + 1
	end
		
	select @res = isnull(@res,'')	
	select @res as res
end
GO
PRINT N'Altering Procedure [sExamination].[pGetEmployeeExaminationViewDatas]...';


GO

ALTER proc [sExamination].[pGetEmployeeExaminationViewDatas]
@rExaminationId bigint
as
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
begin
	declare @lConfigurationValue varchar(5), @lOrgId int
	declare @lVitalRes varchar(max)='',@lDiagnosisRes varchar(max)='',@lTestRes varchar(max)='',@lPrescriptionRes varchar(max)=''
	declare @lVitalHead varchar(max)='',@lDiagnosisHead varchar(max)='',@lTestHead varchar(max)='',@lPrescriptionHead varchar(max)=''
	declare @lComplaintRes varchar(max)='',@lComplaintHead varchar(max)='',@lReferralRes varchar(max)='',@lReferralHead varchar(max)=''
	
	select @lOrgId = OrgId from sExamination.tExamination where Id = @rExaminationId
	select @lConfigurationValue = sConfig.fConfigurationValueGet('Examination.IsTempChangetoCelsius', @lOrgId, 0, 0, 0)	

	declare @tbltmpview table(tid int identity(1,1),col1 varchar(max),col2 varchar(max))	
	insert into @tbltmpview
	select 'Height',Convert(varchar(50),Height) + ' Cm'	
	from sExamination.tVital where SourceId = @rExaminationId
	union
	select 'Height',Convert(varchar(50),Height) + ' Cm'	
	from sExamination.tArchieveVital where SourceId = @rExaminationId
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'Weight',convert(varchar,BodyWeight)+ ' Kg'
	from sExamination.tVital where SourceId = @rExaminationId
	union
	select 'Weight',convert(varchar,BodyWeight)+ ' Kg'
	from sExamination.tArchieveVital where SourceId = @rExaminationId
	OPTION (RECOMPILE)

	insert into @tbltmpview		
	select 'Temperature',convert(varchar,Temperature) + CASE WHEN @lConfigurationValue = 'True' THEN ' °C' ELSE ' °F' END
	from sExamination.tVital where SourceId = @rExaminationId
	union
	select 'Temperature',convert(varchar,Temperature) + CASE WHEN @lConfigurationValue = 'True' THEN ' °C' ELSE ' °F' END
	from sExamination.tArchieveVital where SourceId = @rExaminationId
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'Pulse',convert(varchar,Pulse) + ' /Min'
	from sExamination.tVital where SourceId = @rExaminationId
	union
	select 'Pulse',convert(varchar,Pulse) + ' /Min'
	from sExamination.tArchieveVital where SourceId = @rExaminationId
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'BPSystolic',convert(varchar,BloodPressureSystolic) + ' mmHg'
	from sExamination.tVital where SourceId = @rExaminationId
	union
	select 'BPSystolic',convert(varchar,BloodPressureSystolic) + ' mmHg'
	from sExamination.tArchieveVital where SourceId = @rExaminationId
	OPTION (RECOMPILE)

	insert into @tbltmpview
	select 'BPDiastolic',convert(varchar,BloodPressureDiastolic) + ' mmHg'
	from sExamination.tVital where SourceId = @rExaminationId
	union
	select 'BPDiastolic',convert(varchar,BloodPressureDiastolic) + ' mmHg'
	from sExamination.tArchieveVital where SourceId = @rExaminationId
	OPTION (RECOMPILE)

	Declare @ParticipantCode nvarchar(20), @ParticipantName nvarchar(100), @ExaminationNumber nvarchar(100);
	select 
	@ParticipantCode = CASE E.ParticipantSourceTypeId 
		WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
		@ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN
		(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) 
		WHEN 95 THEN EM.FirstName + ' ' + EM.LastName 
		WHEN 1001 THEN EFD.Name END, @ExaminationNumber = E.ExaminationNumber
	from sExamination.tExamination E
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id
		LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001
		LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009
		LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
		Where E.Id = @rExaminationId

	Declare @res nvarchar(max) = '';
	select @res = @res + '<div class="">
    <h6 class="py-2"><b>Code: </b>' + @ParticipantCode + ' | <b>Name: </b>' + @ParticipantName + ' | <b>OPD Number: </b>' + @ExaminationNumber + '</h6>
    </div>'

	select @lVitalHead = @lVitalHead + '<div class="contentHolder box-body box-solid gridviewfont">
	<div class="himsBoxHeader"><div class="leftdiv"> </div>
	<div class="himsBoxTitle pTop5"><div class="headerText">		
	<div class="fLeft"> <span style="color:Black;font-weight:bold;">Vital</span> </div></div>
	<div class="fRight" style="margin-top: -3px;"> 
	<img src="/Images/Icon 16x16/icon_appointmnt.gif" alt="Vital" style="border-width:0px;">
	</div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
	<tbody><tr><th scope="col"> <span>Parameter</span></th><th scope="col"><span>Value</span></th></tr>'
	OPTION (RECOMPILE)

	select @lVitalRes = @lVitalRes + '<tr>
	<td><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col1,'') + '</span> </td>
	<td><span title="' + isnull(col2,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col2,'') + '</span> </td>			
	</tr>' from @tbltmpview
	OPTION (RECOMPILE)

	select @lVitalRes = @lVitalRes + '</tbody></table></div></div></div>'
	select @lVitalRes = @res + @lVitalHead + @lVitalRes
	OPTION (RECOMPILE)

	declare @tbltmpComplaint table(tid int identity(1,1),col1 varchar(max))	
	insert into @tbltmpComplaint
	SELECT Remark from sExamination.tComplaint where SourceId = @rExaminationId and IsObsolete = 0
	union
	SELECT Remark from sExamination.tArchieveComplaint where SourceId = @rExaminationId and IsObsolete = 0
	OPTION (RECOMPILE)

	select @lComplaintHead = @lComplaintHead + '<div class="contentHolder box-body box-solid gridviewfont">
	<div class="himsBoxHeader"><div class="leftdiv"> </div>
	<div class="himsBoxTitle pTop5"><div class="headerText">		
	<div class="fLeft"> <span style="color:Black;font-weight:bold;">Complaint</span> </div></div>
	<div class="fRight" style="margin-top: -3px;"> 
	<img src="/Images/Icon 16x16/icon_appointmnt.gif" alt="Prescription" style="border-width:0px;">
	</div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
	<tbody><tr><th scope="col"> <span>Complain</span></th></tr>'
	OPTION (RECOMPILE)

	select @lComplaintRes = @lComplaintRes + '<tr>
	<td><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col1,'') + '</span> </td>	
	</tr>' from @tbltmpComplaint
	OPTION (RECOMPILE)

	select @lComplaintRes = @lComplaintRes + '</tbody></table></div></div></div>'
	select @lComplaintRes = @lComplaintHead + @lComplaintRes
	OPTION (RECOMPILE)

	declare @tbltmpReferral table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max))
	insert into @tbltmpReferral
	SELECT C.Title,R.ContactPerson,o.FurtherActionRemark from sExamination.tReferral R inner join sCommon.tClinicMaster C on R.ReferToClinicId = C.Id
	left join sExamination.topd o on o.examinationid = R.SourceId
	where SourceId = @rExaminationId and IsObsolete = 0
	union
	SELECT C.Title,R.ContactPerson,o.FurtherActionRemark from sExamination.tArchieveReferral R inner join sCommon.tClinicMaster C on R.ReferToClinicId = C.Id
	left join sExamination.tArchieveopd o on o.examinationid = R.SourceId
	where SourceId = @rExaminationId and IsObsolete = 0
	OPTION (RECOMPILE)

	select @lReferralHead = @lReferralHead + '<div class="contentHolder box-body box-solid gridviewfont">
	<div class="himsBoxHeader"><div class="leftdiv"> </div>
	<div class="himsBoxTitle pTop5"><div class="headerText">		
	<div class="fLeft"> <span style="color:Black;font-weight:bold;">Referral</span> </div></div>
	<div class="fRight" style="margin-top: -3px;"> 
	<img src="/Images/Icon 16x16/icon_appointmnt.gif" alt="Prescription" style="border-width:0px;">
	</div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
	<tbody><tr><th scope="col"> <span>Hospital</span></th><th scope="col"> <span>Contact Person</span></th><th scope="col"> <span>Remark</span></th></tr>'
	OPTION (RECOMPILE)

	select @lReferralRes = @lReferralRes + '<tr>
	<td><span title="' + isnull(col1,'') + '" class="boxEllips">' + isnull(col1,'') + '</span> </td>	
	<td><span title="' + isnull(col2,'') + '" class="boxEllips">' + isnull(col2,'') + '</span> </td>	
	<td><span title="' + isnull(col3,'') + '" class="boxEllips">' + isnull(col3,'') + '</span> </td>	
	</tr>' from @tbltmpReferral
	OPTION (RECOMPILE)

	select @lReferralRes = @lReferralRes + '</tbody></table></div></div></div>'
	select @lReferralRes = @lReferralHead + @lReferralRes
	OPTION (RECOMPILE)

	declare @tbltmpdisese table(tid int identity(1,1),col1 varchar(max),col2 varchar(max))	
	insert into @tbltmpdisese
	SELECT DM.Title,ED.Remark
	FROM sExamination.tExaminDisease E
	INNER JOIN sExamination.tExaminDiseaseDetail ED
	ON E.Id = ED.ExaminDiseaseId AND E.IsObsolete = 0	
	INNER JOIN sExamination.tDiseaseMaster DM
	ON DM.Id = ED.DiseaseId
	WHERE E.SourceId = @rExaminationId AND ED.IsObsolete = 0
	union
	SELECT DM.Title,ED.Remark
	FROM sExamination.tArchieveExaminDisease E
	INNER JOIN sExamination.tArchieveExaminDiseaseDetail ED
	ON E.Id = ED.ExaminDiseaseId AND E.IsObsolete = 0	
	INNER JOIN sExamination.tDiseaseMaster DM
	ON DM.Id = ED.DiseaseId
	WHERE E.SourceId = @rExaminationId AND ED.IsObsolete = 0
	OPTION (RECOMPILE)

	select @lDiagnosisHead = @lDiagnosisHead + '<div class="contentHolder box-body box-solid gridviewfont">
	<div class="himsBoxHeader"><div class="leftdiv"> </div>
	<div class="himsBoxTitle pTop5"><div class="headerText">		
	<div class="fLeft"> <span style="color:Black;font-weight:bold;">Diagnosis</span> </div></div>
	<div class="fRight" style="margin-top: -3px;"> 
	<img src="/Images/Icon 16x16/icon_appointmnt.gif" alt="Vital" style="border-width:0px;">
	</div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
	<tbody><tr><th scope="col"> <span>Disease</span></th><th scope="col"><span>Remark</span></th></tr>'
	OPTION (RECOMPILE)

	select @lDiagnosisRes = @lDiagnosisRes + '<tr>
	<td><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col1,'') + '</span> </td>
	<td><span title="' + isnull(col2,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col2,'') + '</span> </td>			
	</tr>' from @tbltmpdisese
	OPTION (RECOMPILE)

	select @lDiagnosisRes = @lDiagnosisRes + '</tbody></table></div></div></div>'
	select @lDiagnosisRes = @lDiagnosisHead + @lDiagnosisRes
	OPTION (RECOMPILE)

	declare @tbltmptest table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max))	
	insert into @tbltmptest
	SELECT TP.Title,TRD.ServiceValue,TRD.Remark
	FROM sExamination.tTestRequestDetail TRD
	INNER JOIN sExamination.tTestRequest TR	ON TRD.TestRequestId = TR.Id
	INNER JOIN sOrderEntry.tTestDetail TD on TD.Id = TRD.TestDetailId
	INNER JOIN sOrderEntry.tTestParameterMaster TP	on TD.TestParameterId = TP.Id
	WHERE TR.SourceId = @rExaminationId AND TP.IsObsolete = 0 and TRD.ServiceValue <> '-- Select --'
	union
	SELECT TP.Title,TRD.ServiceValue,TRD.Remark
	FROM sExamination.tArchieveTestRequestDetail TRD
	INNER JOIN sExamination.tArchieveTestRequest TR
	ON TRD.TestRequestId = TR.Id
	INNER JOIN sOrderEntry.tTestDetail TD
	on TD.Id = TRD.TestDetailId
	INNER JOIN sOrderEntry.tTestParameterMaster TP
	on TD.TestParameterId = TP.Id
	WHERE TR.SourceId = @rExaminationId AND TP.IsObsolete = 0 and TRD.ServiceValue <> '-- Select --'
	OPTION (RECOMPILE)

	select @lTestHead = @lTestHead + '<div class="contentHolder box-body box-solid gridviewfont">
	<div class="himsBoxHeader"><div class="leftdiv"> </div>
	<div class="himsBoxTitle pTop5"><div class="headerText">		
	<div class="fLeft"> <span style="color:Black;font-weight:bold;">Test</span> </div></div>
	<div class="fRight" style="margin-top: -3px;"> 
	<img src="/Images/Icon 16x16/icon_appointmnt.gif" alt="Prescription" style="border-width:0px;">
	</div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
	<tbody><tr><th scope="col"> <span>Parameter</span></th><th scope="col"><span>Result</span></th><th scope="col"><span>Remark</span></th></tr>'
	OPTION (RECOMPILE)

	select @lTestRes = @lTestRes + '<tr>
	<td><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;">' + isnull(col1,'') + '</span> </td>
	<td><span title="' + isnull(col2,'') + '" class="boxEllips" style="display:inline-block;">' + isnull(col2,'') + '</span> </td>
	<td><span title="' + isnull(col3,'') + '" class="boxEllips" style="display:inline-block;">' + isnull(col3,'') + '</span> </td>			
	</tr>' from @tbltmptest
	OPTION (RECOMPILE)

	select @lTestRes = @lTestRes + '</tbody></table></div></div></div>'
	select @lTestRes = @lTestHead + @lTestRes
	
	declare @tbltmpPres table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max),
	col4 varchar(max),col5 varchar(max),col6 varchar(max))
	insert into @tbltmpPres
	SELECT SM.Title,PD.Dosage,FM.Title,S.Title,PD.Duration,PD.PrescribedQuantity
	from sExamination.tPrescriptionDetail PD
	inner join sExamination.tPrescription P on PD.PrescriptionId = P.Id
	inner join sIp.tStockItemMaster SM on SM.Id = PD.StockItemId
	LEFT JOin sIp.tDrugDosageFrequencyMaster FM on PD.DrugDosageFrequencyId = FM.Id
	LEFT JOin sIp.tDrugScheduleMaster S on PD.DrugDosageScheduleId = S.Id
	where PD.IsObsolete = 0 and P.IsObsolete = 0
	and P.SourceId = @rExaminationId
	union
	SELECT SM.Title,PD.Dosage,FM.Title,S.Title,PD.Duration,PD.PrescribedQuantity
	from sExamination.tArchievePrescriptionDetail PD
	inner join sExamination.tArchievePrescription P on PD.PrescriptionId = P.Id
	inner join sIp.tStockItemMaster SM on SM.Id = PD.StockItemId
	LEFT JOin sIp.tDrugDosageFrequencyMaster FM on PD.DrugDosageFrequencyId = FM.Id
	LEFT JOin sIp.tDrugScheduleMaster S on PD.DrugDosageScheduleId = S.Id
	where PD.IsObsolete = 0 and P.IsObsolete = 0
	and P.SourceId = @rExaminationId
	OPTION (RECOMPILE)

	select @lPrescriptionHead = @lPrescriptionHead + '<div class="contentHolder box-body box-solid gridviewfont">
	<div class="himsBoxHeader"><div class="leftdiv"> </div>
	<div class="himsBoxTitle pTop5"><div class="headerText">		
	<div class="fLeft"> <span style="color:Black;font-weight:bold;">Prescription</span> </div></div>
	<div class="fRight" style="margin-top: -3px;"> 
	<img src="/Images/Icon 16x16/icon_appointmnt.gif" alt="Vital" style="border-width:0px;">
	</div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse;">
	<tbody><tr><th scope="col"> <span>Name</span></th><th scope="col"><span>Dose</span></th>
	<th scope="col"><span>Frequency</span></th><th scope="col"><span>Schedule</span></th>
	<th scope="col"><span>Days</span></th><th scope="col"><span>Quantity</span></th></tr>'
	OPTION (RECOMPILE)

	select @lPrescriptionRes = @lPrescriptionRes + '<tr>
	<td><span title="' + isnull(col1,'') + '" class="boxEllips">' + isnull(col1,'') + '</span> </td>
	<td><span title="' + isnull(col2,'') + '" class="boxEllips">' + isnull(col2,'') + '</span> </td>			
	<td><span title="' + isnull(col3,'') + '" class="boxEllips">' + isnull(col3,'') + '</span> </td>			
	<td><span title="' + isnull(col4,'') + '" class="boxEllips">' + isnull(col4,'') + '</span> </td>			
	<td><span title="' + isnull(col5,'') + '" class="boxEllips">' + isnull(col5,'') + '</span> </td>			
	<td><span title="' + isnull(col6,'') + '" class="boxEllips">' + isnull(col6,'') + '</span> </td>			
	</tr>' from @tbltmpPres
	OPTION (RECOMPILE)

	select @lPrescriptionRes = @lPrescriptionRes + '</tbody></table></div></div></div>'
	select @lPrescriptionRes = @lPrescriptionHead + @lPrescriptionRes
	OPTION (RECOMPILE)

	select isnull(@lVitalRes,'') as Vital,isnull(@lDiagnosisRes,'') as Diagnos,isnull(@lTestRes,'') as Test,
	isnull(@lPrescriptionRes,'') as Pres,isnull(@lComplaintRes,'') as Comp,isnull(@lReferralRes,'') as Ref
	OPTION (RECOMPILE)
	SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off
end
GO
PRINT N'Altering Procedure [sHospitalization].[pMedicalReviewLogGet]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pMedicalReviewLogGet]      
    @rTicketNumber NVARCHAR(50)     
AS      
BEGIN      
    SET NOCOUNT ON;    
    
    ;WITH CombinedActivities AS    
    (    
        ---------------------------------------------------------    
        -- 1. Remarks    
        ---------------------------------------------------------    
        SELECT      
           -- UR.DisplayTitle AS UserName,    
           --  CASE       
          -- WHEN PAL.TicketStatus <> 'New'       
            --    THEN  
    ISNULL(UR.DisplayTitle, '')    
          -- ELSE ''      
          --END   
    AS UserName,      
            'Remark' AS ActivityType,    
            CONVERT(VARCHAR(10), R.CreatedDateTime, 103) + ' ' +    
           sCommon.fn_ConvertToIST(CONVERT(VARCHAR(8), R.CreatedDateTime, 24)) AS ActivityDateTime,    
            R.Remark AS Remark,    
            ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS AssignedDoctor,    
            sCommon.fn_ConvertToIST(R.CreatedDateTime) AS SortDate,    
            'TKT-' + RIGHT(PAL.TicketNumber, 5) AS TicketNumber,    
            R.Status AS Status    
        FROM sHospitalization.tIntimationRemark R    
        Inner JOIN sHospitalization.tIntimationDetails PAL    
            ON PAL.Id = R.HospitalizationIntimationDetailId    
        Inner JOIN sSecurity.tUser UR      
            ON UR.id = R.CreatedUserId and ur.OrgId=R.OrgId    
        LEFT JOIN sHrm.tEmployeeMaster EM    
            ON EM.Id = R.DoctorEmployeeId      
        WHERE PAL.TicketNumber = @rTicketNumber    
    
    
        UNION ALL    
    
        ---------------------------------------------------------    
        -- 2. Doctor Assignment Logs    
        ---------------------------------------------------------    
        SELECT      
          --  UR.DisplayTitle AS UserName,    
          CASE       
       WHEN SM.Status = 'New'   
         AND SM.PreviousDoctorEmployeeId IS NULL  
        THEN 'System'  
  else   
  UR.DisplayTitle  
          END AS UserName,      
            'Doctor Assignment' AS ActivityType,    
            CONVERT(VARCHAR(10), SM.AssignedDate, 103) + ' ' +    
               
   sCommon.fn_ConvertToIST(CONVERT(VARCHAR(8),  SM.AssignedDate, 24)) AS ActivityDateTime,    
            '' AS Remark,    
            ISNULL(E2.FirstName,'') + ' ' + ISNULL(E2.LastName,'') AS AssignedDoctor,    
            sCommon.fn_ConvertToIST(SM.AssignedDate) AS SortDate,    
            'TKT-' + RIGHT(PAL.TicketNumber, 5) AS TicketNumber,    
            SM.Status AS Status    
        FROM sHospitalization.tIntimationDoctorAssignmentLog SM    
        INNER JOIN sHospitalization.tIntimationDetails PAL    
            ON PAL.Id = SM.HospitalizationIntimationDetailId    
        LEFT JOIN sSecurity.tUser UR      
            ON UR.Id = SM.CreatedUserId and UR.OrgId=SM.OrgId    
        LEFT JOIN sHrm.tEmployeeMaster E2    
            ON E2.Id = SM.NewDoctorEmployeeId    
        WHERE PAL.TicketNumber = @rTicketNumber    
    )    
    
    SELECT     
        UserName,    
        ActivityType,    
        ActivityDateTime,    
        Remark,    
        AssignedDoctor,    
        SortDate,    
        TicketNumber,    
        Status    
    FROM CombinedActivities    
    ORDER BY SortDate ASC;    
END
GO
PRINT N'Altering Procedure [sHospitalization].[pDashboardDetailsGetAll]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pDashboardDetailsGetAll]  
    @rFromDate NVARCHAR(50) = NULL,  
    @rToDate NVARCHAR(50) = NULL,  
    @rDoctorId NVARCHAR(50) = NULL,  
    @rStatus NVARCHAR(50) = NULL,  
 @rState NVARCHAR(50) = NULL,  
    @rOrgId BIGINT = NULL  
AS  
BEGIN    
    SET NOCOUNT ON;  

    IF @rFromDate = '' SET @rFromDate = NULL;  
    IF @rToDate = '' SET @rToDate = NULL;  
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;  
    IF @rStatus = '' OR @rStatus = '0' SET @rStatus = NULL;  
  
    DECLARE @FromDateConverted DATE = NULL;  
    DECLARE @ToDateConverted DATE = NULL;  
  

    IF @rFromDate IS NOT NULL  
        SET @FromDateConverted = CONVERT(DATE, LEFT(@rFromDate, 10), 103);  -- dd/MM/yyyy  
  
    IF @rToDate IS NOT NULL  
        SET @ToDateConverted = CONVERT(DATE, LEFT(@rToDate, 10), 103);  -- dd/MM/yyyy  
  
   
    IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL AND @FromDateConverted > @ToDateConverted)  
    BEGIN  
        DECLARE @tmp DATE;  
        SET @tmp = @FromDateConverted;  
        SET @FromDateConverted = @ToDateConverted;  
        SET @ToDateConverted = @tmp;  
    END  
  
    -- DoctorID conversion  
    DECLARE @DoctorIdConverted BIGINT = NULL;  
    IF ISNUMERIC(@rDoctorId) = 1  
        SET @DoctorIdConverted = CAST(@rDoctorId AS BIGINT);  
  

  
    SELECT    
   ROW_NUMBER() OVER (ORDER BY PAL.TicketNumber) AS [Serial No],  
    PAL.EmpCode AS [Employee Code],  
     PAL.ProposerName AS [Employee Name],    
     --HosB.Title as Business,
	 SCT.Title as Business,
	   LM.Title AS   [Hr Location],   
  PAL.BeneficiaryName as [Beneficiary Name],  
  PAL.Relation,
  PAL.TreatingDoctor,
   PAL.Age,  
           PAL.NatureOfIllness as [Nature Of Illness]  , 
		     CUR.EmployeeName AS [Assigned Doctor],  
			   PAL.TicketStatus AS [Status],    
			   STUFF((  
    SELECT   
        CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103)   
        + ': ' + R.Remark  
    FROM sHospitalization.tIntimationRemark R  
    WHERE R.HospitalizationIntimationDetailId = pal.Id  
    ORDER BY R.CreatedDateTime DESC  
    FOR XML PATH(''), TYPE  
).value('.', 'nvarchar(max)'), 1, 1, '') AS Remarks ,
  Pal.HospitalName as [Hospital Name],  
    PAL.NetworkCity as [Network City],  
	     PAL.State as [State],    
  PAL.ClaimType as [Claim Type],  
      CASE   
          WHEN PAL.DateOfIntimation = DATEADD(DAY, DATEDIFF(DAY, 0, PAL.DateOfIntimation), 0)  
              THEN CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)  
          ELSE   
              CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)  
              + ' ' + CONVERT(VARCHAR(8), PAL.DateOfIntimation, 108)  
      END AS [Date Of Intimation]  
       

    FROM [sHospitalization].[tIntimationDetails] PAL    
    LEFT JOIN [sHospitalization].[tIntimationAssignedDoctor] SM    
        ON SM.Id = PAL.IntimationAssignedDoctorId  
    LEFT JOIN [sSecurity].[tUser] UR    
        ON UR.Id = PAL.CreatedUserId    
        AND UR.IsObsolete = 0   
        AND UR.OrgId = PAL.OrgId  
    LEFT JOIN [shrm].[vEmployeeCommonDetail] CUR    
        ON CUR.EmployeeId = PAL.AssignedDoctorId    
  
    Left JOIN [sHrm].[tSectorMaster] HosB    
        ON HosB.Id = SM.AssignSubTypeId and  HosB.IsObsolete =SM.IsObsolete and HosB.OrgId = SM.OrgId  
  
    Left JOIN [sHrm].[tEmployeeMaster] EMD     
            ON EMD.Id = SM.DoctorEmployeeId    
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP     
            ON EMP.Id = PAL.ParticipantSourceId    
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD     
            ON ECD.EmployeeId = EMP.Id    
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD     
            ON EJD.EmployeeId = EMP.Id    
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM     
            ON ETM.Id = EJD.EmployeeTypeId    
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM     
            ON ECM.Id = EJD.EmployeeCompanyId    
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM     
            ON CGM.Id = ECM.CompanyGroupId    
        LEFT JOIN [sHrm].[tVerticalMaster] VTM     
            ON VTM.Id = CGM.VerticalId    
        LEFT JOIN [sHrm].[tSectorMaster] SCT     
            ON SCT.Id = VTM.SectorId    
        Left JOIN [sCommon].[tLocationMaster] LM     
            ON LM.Id = EJD.EmployeeLocationId    
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM     
            ON DGM.Id = EJD.OrganizationDepartmentId    
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM     
            ON ODM.Id = EJD.OrganizationDepartmentId    
    
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS     
            ON EMDS.Id = EJD.EmployeeDesignationId    
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS     
            ON VEMDS.EmployeeId = PAL.ParticipantSourceId    
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1     
            ON VEMDS1.EmployeeId = PAL.AssignedDoctorId    
     LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS2    
            ON VEMDS2.EmployeeId = PAL.UpdatedUserId    
        LEFT JOIN [sHrm].[tGradeMaster] GRD     
            ON GRD.Id = VEMDS.GradeId    
    
    WHERE   
        PAL.OrgId = @rOrgId  
        AND PAL.IsObsolete = 0  
        AND (@FromDateConverted IS NULL OR PAL.DateOfIntimation >= @FromDateConverted)  
        AND (@ToDateConverted IS NULL OR PAL.DateOfIntimation < DATEADD(DAY, 1, @ToDateConverted))  
        AND (@DoctorIdConverted IS NULL OR PAL.AssignedDoctorId = @DoctorIdConverted)  
        AND (@rStatus IS NULL OR PAL.TicketStatus = @rStatus)  
   AND (  
       @rState IS NULL  
       OR @rState = ''  
       OR @rState = '0'  
       OR @rState = '- All -'  
       OR PAL.State = @rState  
    )  
  
    ORDER BY PAL.CreatedDateTime ASC;  
END
GO
PRINT N'Altering Procedure [sHospitalization].[pGetDoctorHospitalizationDataForDashboard]...';


GO
 CREATE OR ALTER PROCEDURE [sHospitalization].[pGetDoctorHospitalizationDataForDashboard]    
    @rFromDate NVARCHAR(50) = NULL,    
    @rToDate NVARCHAR(50) = NULL,    
    @rDoctorId NVARCHAR(50) = NULL,    
    @rStatus NVARCHAR(50) = NULL,    
 @rState NVARCHAR(50) = NULL,    
    @rOrgId BIGINT = NULL    
AS    
BEGIN    
    SET NOCOUNT ON;    
      
    -------------------------------------------------------------    
    -- 🔄 STEP 0: Convert Empty Strings ('') to NULL    
    -------------------------------------------------------------    
    IF @rFromDate = '' SET @rFromDate = NULL;    
    IF @rToDate = '' SET @rToDate = NULL;    
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;    
    IF @rStatus = '' SET @rStatus = NULL;    
 IF @rState = '' SET @rState = NULL;       
    
   -- IF @rOrgId IS NULL SET @rOrgId = 9999;    
    
    -------------------------------------------------------------    
    -- 🔄 STEP 1: Convert NVARCHAR date inputs to DATE    
    -------------------------------------------------------------    
    --DECLARE @FromDateConverted DATE = TRY_CAST(@rFromDate AS DATE);    
    --DECLARE @ToDateConverted DATE = TRY_CAST(@rToDate AS DATE);    
    --DECLARE @DoctorIdConverted BIGINT = TRY_CAST(@rDoctorId AS BIGINT);    
    
 -------------------------------------------------------------    
-- STEP 1: Convert NVARCHAR date inputs to DATE (dd/MM/yyyy)    
-------------------------------------------------------------    
DECLARE @FromDateConverted DATE = NULL;    
DECLARE @ToDateConverted DATE = NULL;    
DECLARE @DoctorIdConverted BIGINT = TRY_CAST(@rDoctorId AS BIGINT);    
    
-- Convert FromDate    
IF (@rFromDate IS NOT NULL AND @rFromDate <> '')    
BEGIN    
    SET @FromDateConverted = CONVERT(DATE, @rFromDate, 103);    
END    
    
-- Convert ToDate    
IF (@rToDate IS NOT NULL AND @rToDate <> '')    
BEGIN    
    SET @ToDateConverted = CONVERT(DATE, @rToDate, 103);    
END    
    
-- Swap if reversed    
IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL    
    AND @FromDateConverted > @ToDateConverted)    
BEGIN    
    DECLARE @tmp DATE = @FromDateConverted;    
    SET @FromDateConverted = @ToDateConverted;    
    SET @ToDateConverted = @tmp;    
END    
    
    
    -------------------------------------------------------------    
    -- 🧹 STEP 2: Prepare base data    
    -------------------------------------------------------------    
    IF OBJECT_ID('tempdb..#BaseData') IS NOT NULL    
        DROP TABLE #BaseData;    
    
    SELECT     
        TD.Id,    
        TD.OrgId,    
        TD.BeneficiaryName,    
        TD.DateOfIntimation,    
        TD.DateOfAdmission,    
    CASE   
        WHEN TD.ParticipantSourceId IS NULL   
         AND TD.ParticipantSourceTypeId IS NULL   
            THEN 'Non-Oracle'  
        ELSE 'Oracle'  
    END AS OracleNonOracleType,  
  
        TD.DateOfDischarge,    
        TD.ClaimType,    
        TD.IntimationNumber,    
        TD.StatusOfIntimation,    
        TD.NetworkCity,    
        TD.State,    
        SM.StateName,    
        TD.HospitalName,    
        TD.Age,    
        TD.Relation,    
        TD.ProposerName,    
        TD.NatureOfIllness,    
        TD.TicketStatus,    
        TD.AssignedDoctorId,    
        ISNULL(    
            CASE     
                WHEN ISNULL(EM.EmployeePrefix, '') = ''     
                    THEN EM.FirstName + ' ' + ISNULL(EM.LastName, '')    
                ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + ISNULL(EM.LastName, '')    
            END,     
        'Unassigned') AS DoctorName,    
        TD.TicketNumber,    
        TD.TicketOpenDate,    
        TD.ModeOfStatus,    
        TD.Grade,    
        TD.GroupCode,    
        TD.AdmissionType,    
        CASE     
            WHEN TD.EstimatedAmount IS NOT NULL     
                 AND TD.EstimatedAmount != ''    
                 AND ISNUMERIC(REPLACE(REPLACE(TD.EstimatedAmount, ',', ''), '.', '')) = 1    
            THEN TRY_CAST(REPLACE(TD.EstimatedAmount, ',', '') AS DECIMAL(18,2))    
            ELSE NULL     
        END AS EstimatedAmount,    
        TD.NetworkStatus,    
        TD.IsObsolete,    
        TD.Remarks,    
        TD.CreatedDateTime,    
    SCT.Title AS Business,  
        DATEDIFF(DAY, TD.TicketOpenDate, ISNULL(TD.DateOfDischarge, GETDATE())) AS AgeingDays,    
        CASE     
            WHEN TD.TicketStatus = 'Close' THEN 'Close'    
       WHEN TD.TicketStatus = 'New'   THEN 'New'    
            ELSE 'Open'    
        END AS StatusCategory    
    INTO #BaseData    
    FROM sHospitalization.tIntimationDetails TD    
    LEFT JOIN sHospitalization.tStateMaster SM    
        ON SM.StateName = TD.State AND SM.OrgId = TD.OrgId    
    LEFT JOIN sHrm.tEmployeeMaster EM    
        ON EM.Id = TD.AssignedDoctorId    
          LEFT JOIN [sHrm].[tEmployeeCommunications] ECD     
            ON ECD.EmployeeId = EM.Id    
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD     
            ON EJD.EmployeeId = EM.Id    
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM     
            ON ETM.Id = EJD.EmployeeTypeId    
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM     
            ON ECM.Id = EJD.EmployeeCompanyId    
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM     
            ON CGM.Id = ECM.CompanyGroupId    
        LEFT JOIN [sHrm].[tVerticalMaster] VTM     
            ON VTM.Id = CGM.VerticalId    
        LEFT JOIN [sHrm].[tSectorMaster] SCT     
            ON SCT.Id = VTM.SectorId    
        Left JOIN [sCommon].[tLocationMaster] LM     
            ON LM.Id = EJD.EmployeeLocationId    
    WHERE     
        TD.OrgId = @rOrgId    
        AND TD.IsObsolete = 0    
AND (    
        @FromDateConverted IS NULL     
        OR CAST(TD.DateOfIntimation AS DATE) >= @FromDateConverted    
    )    
AND (    
        @ToDateConverted IS NULL     
        OR CAST(TD.DateOfIntimation AS DATE) <= @ToDateConverted    
    )    
    
    
        AND (@DoctorIdConverted IS NULL OR TD.AssignedDoctorId = @DoctorIdConverted)    
        AND (@rStatus IS NULL OR @rStatus = '0' OR TD.TicketStatus = @rStatus)    
   And (@rState IS NULL OR @rState = '0' OR TD.State = @rState)    
    
    
    
-- select @rState    
    
    -------------------------------------------------------------    
    -- 🧾 STEP 3: Summary Data    
    -------------------------------------------------------------    
    IF OBJECT_ID('tempdb..#SummaryData') IS NOT NULL    
        DROP TABLE #SummaryData;    
    
    SELECT     
        COUNT(DISTINCT Id) AS TotalCases,    
        COUNT(DISTINCT AssignedDoctorId) AS TotalDoctors,    
        COUNT(DISTINCT State) AS TotalStates,    
        COUNT(DISTINCT HospitalName) AS TotalHospitals,    
        SUM(CASE WHEN StatusCategory = 'Close' THEN 1 ELSE 0 END) AS ClosedCases,    
        SUM(CASE WHEN StatusCategory = 'Open' THEN 1 ELSE 0 END) AS OpenCases,   
  SUM(CASE WHEN StatusCategory = 'New' THEN 1 ELSE 0 END) AS NewCases,  
        CAST(AVG(EstimatedAmount) AS DECIMAL(18,2)) AS AverageEstimatedAmount,    
        CAST(SUM(EstimatedAmount) AS DECIMAL(18,2)) AS TotalEstimatedAmount,    
        CAST(SUM(CASE WHEN StatusCategory = 'Close' THEN 1 ELSE 0 END) * 100.0 / NULLIF(COUNT(DISTINCT Id), 0) AS DECIMAL(5,2)) AS ClosureRate    
    INTO #SummaryData    
    FROM #BaseData;    
    
    
    -------------------------------------------------------------    
    -- 📊 STEP 4: Result Sets    
    -------------------------------------------------------------    
    
    -- 1️⃣ Monthly Trend Data    
    SELECT     
        FORMAT(DateOfIntimation, 'yyyy-MM') AS MonthYear,    
        FORMAT(DateOfIntimation, 'MMM yyyy') AS MonthYearDisplay,    
        COUNT(Id) AS CaseCount    
    FROM #BaseData    
    WHERE DateOfIntimation IS NOT NULL    
    GROUP BY FORMAT(DateOfIntimation, 'yyyy-MM'), FORMAT(DateOfIntimation, 'MMM yyyy')    
    ORDER BY MonthYear;    
    
    -- 2️⃣ Status Summary (Pie Chart)    
    SELECT     
        TicketStatus,    
        COUNT(Id) AS StatusCount,    
        CASE     
            WHEN TicketStatus = 'New' THEN '#36A2EB'    
            WHEN TicketStatus = 'Open' THEN '#FF6384'    
            WHEN TicketStatus = 'Close' THEN '#4BC0C0'    
            ELSE '#9966FF'    
        END AS ColorCode    
    FROM #BaseData    
    GROUP BY TicketStatus    
    ORDER BY StatusCount DESC;    
    
    -- 3️⃣ Doctor-wise Beneficiary Count    
    SELECT     
        DoctorName,    
        COUNT(Id) AS BeneficiaryCount,
	    SUM(CASE WHEN TicketStatus = 'Open' THEN 1 ELSE 0 END) AS OpenCases,
    SUM(CASE WHEN TicketStatus = 'Close' THEN 1 ELSE 0 END) AS CloseCases,
    SUM(CASE WHEN TicketStatus = 'New' THEN 1 ELSE 0 END) AS NewCases
    FROM #BaseData    
    WHERE DoctorName IS NOT NULL    
    GROUP BY DoctorName    
    ORDER BY BeneficiaryCount DESC;    
    
   -- 4️⃣ Open Cases Ageing Analysis (0-7, 8-15, 16-30 Days)  
SELECT  
    AgeingCategory,  
    TotalCases  
FROM (  
    SELECT  
        CASE  
            WHEN AgeingDays <= 7  THEN '0-7 Days'  
            WHEN AgeingDays <= 15 THEN '8-15 Days'  
            WHEN AgeingDays <= 30 THEN '16-30 Days'  
            ELSE 'Above 30 Days'  
        END AS AgeingCategory,  
        COUNT(*) AS TotalCases,  
        CASE  
            WHEN AgeingDays <= 7  THEN 1  
            WHEN AgeingDays <= 15 THEN 2  
            WHEN AgeingDays <= 30 THEN 3  
            ELSE 4  
        END AS SortOrder  
    FROM #BaseData  
    WHERE StatusCategory = 'Open'  
    GROUP BY  
        CASE  
            WHEN AgeingDays <= 7  THEN '0-7 Days'  
            WHEN AgeingDays <= 15 THEN '8-15 Days'  
            WHEN AgeingDays <= 30 THEN '16-30 Days'  
            ELSE 'Above 30 Days'  
        END,  
        CASE  
            WHEN AgeingDays <= 7  THEN 1  
            WHEN AgeingDays <= 15 THEN 2  
            WHEN AgeingDays <= 30 THEN 3  
            ELSE 4  
        END  
) AS AgedData  
ORDER BY SortOrder;  
  
    
    -- 5️⃣ Summary Statistics    
    SELECT     
        TotalCases,    
        TotalDoctors,    
        TotalStates,    
        TotalHospitals,    
        ClosedCases,    
        OpenCases,   
  NewCases,  
        ClosureRate,    
        AverageEstimatedAmount,    
        TotalEstimatedAmount    
    FROM #SummaryData;    
    
    -- 6️⃣ State-wise Distribution    
    SELECT     
        ISNULL(StateName, 'Unknown') AS StateName,    
        COUNT(Id) AS CaseCount    ,
			    SUM(CASE WHEN TicketStatus = 'Open' THEN 1 ELSE 0 END) AS OpenCases,
    SUM(CASE WHEN TicketStatus = 'Close' THEN 1 ELSE 0 END) AS CloseCases,
    SUM(CASE WHEN TicketStatus = 'New' THEN 1 ELSE 0 END) AS NewCases
    FROM #BaseData    
    GROUP BY ISNULL(StateName, 'Unknown')    
    ORDER BY CaseCount DESC;    
    
    -- 7️⃣ Hospital-wise Distribution    
    SELECT     
        ISNULL(HospitalName, 'Unknown') AS HospitalName,    
        COUNT(Id) AS CaseCount    
    FROM #BaseData    
    GROUP BY ISNULL(HospitalName, 'Unknown')    
    ORDER BY CaseCount DESC;    
    
    -- 8️⃣ Claim Type Distribution    
    SELECT     
        ISNULL(ClaimType, 'Unknown') AS ClaimType,    
        COUNT(Id) AS CaseCount    
    FROM #BaseData    
    GROUP BY ISNULL(ClaimType, 'Unknown')    
    ORDER BY CaseCount DESC;    
  
       
     -- 8️⃣ Oracle vs Non-Oracle Distribution  
     SELECT     
         OracleNonOracleType AS OracleandNonOracleChartType,  
         COUNT(Id) AS CaseCount  
     FROM #BaseData  
     GROUP BY OracleNonOracleType  
     ORDER BY CaseCount DESC;  
  
      -- 9️⃣ Business-wise Distribution  
      SELECT     
          ISNULL(Business, 'Unknown') AS Business,  
          COUNT(Id) AS CaseCount  ,
		  	    SUM(CASE WHEN TicketStatus = 'Open' THEN 1 ELSE 0 END) AS OpenCases,
    SUM(CASE WHEN TicketStatus = 'Close' THEN 1 ELSE 0 END) AS CloseCases,
    SUM(CASE WHEN TicketStatus = 'New' THEN 1 ELSE 0 END) AS NewCases
      FROM #BaseData  
      GROUP BY ISNULL(Business, 'Unknown')  
      ORDER BY CaseCount DESC;  
        
    
    
    -------------------------------------------------------------    
    -- 🧹 Clean up    
    -------------------------------------------------------------    
    DROP TABLE #BaseData;    
    DROP TABLE #SummaryData;    
    
END;
GO
PRINT N'Altering Procedure [sHospitalization].[pHospitalizationDoctorAssignmentMailGet]...';


GO
ALTER   PROCEDURE [sHospitalization].[pHospitalizationDoctorAssignmentMailGet]    
(    
    @rOrgId INT,    
    @rTemplate NVARCHAR(MAX),    
    @rMailSubject NVARCHAR(MAX),    
    @rIntimationDetailId BIGINT,    
    @rEventId INT    
)    
AS    
BEGIN    
    SET NOCOUNT ON;    
  
    SELECT    
        ID.OrgId AS OrgGroupId,    
        95 AS SourceTypeId,    
        EC.MobileNumber AS MobileNo,    
        EC.CompanyEmail AS EmailId,    
        ID.TicketNumber,    
        EM.FirstName,    
        EC.ExtensionNo,    
        ID.Relation,    
        EM1.FirstName,    
  
        -- 🔹 Message text with ALL replacements  
        REPLACE(  
            REPLACE(  
                REPLACE(  
                    REPLACE(  
                        REPLACE(  
                            REPLACE(  
                                REPLACE(  
                                    REPLACE(  
                                        @rTemplate,  
                                        '[DoctorName]',  
                                        LTRIM(RTRIM(  
                                            ISNULL(EM.FirstName, '') +  
                                            CASE WHEN ISNULL(EM.MiddleName, '') <> '' THEN ' ' + EM.MiddleName ELSE '' END +  
                                            CASE WHEN ISNULL(EM.LastName, '') <> '' THEN ' ' + EM.LastName ELSE '' END  
                                        ))  
                                    ),  
                                    '[BeneficiaryName]', ISNULL(ID.BeneficiaryName, '')  
                                ),  
                                '[RecipientName]',  
                                LTRIM(RTRIM(  
                                    ISNULL(EM1.FirstName, '') +  
                                    CASE WHEN ISNULL(EM1.MiddleName, '') <> '' THEN ' ' + EM1.MiddleName ELSE '' END +  
                                    CASE WHEN ISNULL(EM1.LastName, '') <> '' THEN ' ' + EM1.LastName ELSE '' END  
                                ))  
                            ),  
                            '[Relationship]', ISNULL(ID.Relation, '')  
                        ),  
                        '[Extension]', ISNULL(EC.ExtensionNo, '')  
                    ),  
                    '[MobileNumber]', ISNULL(EC.MobileNumber, '')  
                ),  
                '[NewAssignedCount]',  
               -- CAST(  
               --     (  
               --SELECT COUNT(1)  
               -- FROM sHospitalization.tIntimationDetails ID2  
               -- INNER JOIN sHospitalization.tIntimationAssignedDoctor AD  
               --     ON AD.Id = ID2.IntimationAssignedDoctorId  
               -- WHERE AD.DoctorEmployeeId = EM.Id  
  
               --     ) AS NVARCHAR(10)  
               -- )  
			    CAST(
                    (
               SELECT COUNT(1)
                FROM sHospitalization.tIntimationDetails ID2               
                WHERE ID2.AssignedDoctorId = EM.Id and ID2.TicketStatus = 'New'
				AND CONVERT(DATE,ID2.CreatedDateTime,103)=CONVERT(DATE,GETDATE(),103)
                    ) AS NVARCHAR(10)
                )
            ),  
 '[OpenFrom]',  
CAST(  
(  
    --SELECT COUNT(1)  
    --FROM sHospitalization.tIntimationDetails ID2  
    --INNER JOIN sHospitalization.tIntimationAssignedDoctor AD2  
    --    ON AD2.Id = ID2.IntimationAssignedDoctorId  
    --WHERE AD2.DoctorEmployeeId = EM.Id  
    --  AND ISNULL(ID2.IsObsolete, 0) = 0  
    --  AND ID2.TicketStatus = 'New'  
    --  AND ID2.DateOfAdmission >= DATEADD(HOUR, -48, GETDATE())  

	      SELECT COUNT(1)  
    FROM sHospitalization.tIntimationDetails ID2  
    INNER JOIN sHospitalization.tIntimationAssignedDoctor AD2  
        ON AD2.Id = ID2.IntimationAssignedDoctorId  
    WHERE AD2.DoctorEmployeeId = EM.Id  
      AND ISNULL(ID2.IsObsolete, 0) = 0  
     AND TicketStatus IN ('Open', 'New') 
     AND ID2.CreatedDateTime <= DATEADD(HOUR, -48, GETDATE())  
) AS NVARCHAR(10)  
)  
  
        ) AS MsgText,  
  
        @rMailSubject AS Subject    
  
    FROM sHospitalization.tIntimationDetails ID    
    LEFT JOIN sHrm.tEmployeeMaster EM    
        ON ID.AssignedDoctorId = EM.Id    
    LEFT JOIN sHrm.tEmployeeCommunications EC    
        ON EM.Id = EC.EmployeeId    
    LEFT JOIN sHrm.tEmployeeMaster EM1    
        ON ID.ParticipantSourceId = EM1.Id    
   -- LEFT JOIN sHospitalization.tIntimationAssignedDoctor EM2    
     --   ON ID.AssignedDoctorId = EM2.DoctorEmployeeId    
  
    WHERE ID.Id = @rIntimationDetailId    
      AND ISNULL(ID.AssignedDoctorId, 0) <> 0;    
  
END;
GO
PRINT N'Altering Procedure [sHospitalization].[pIntimationDetailsGetList]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pIntimationDetailsGetList]    
(    
    @rFromDate NVARCHAR(50) = NULL,    
    @rToDate   NVARCHAR(50) = NULL,    
    @rOrgId    INT    
)    
AS    
BEGIN    
    SET NOCOUNT ON;    
    
    DECLARE @FromDate DATETIME = NULL,    
            @ToDate   DATETIME = NULL;    
    
    ---------------------------------------------------    
    -- Convert only if valid AND not blank    
    ---------------------------------------------------    
    IF (ISDATE(@rFromDate) = 1 AND LTRIM(RTRIM(@rFromDate)) <> '')    
        SET @FromDate = CONVERT(DATETIME, @rFromDate, 103);    
    
    IF (ISDATE(@rToDate) = 1 AND LTRIM(RTRIM(@rToDate)) <> '')    
        SET @ToDate = CONVERT(DATETIME, @rToDate, 103);    
    
    
    ---------------------------------------------------    
    IF (@FromDate IS NULL)    
    BEGIN    
        SET @FromDate = '1900-01-01';  -- earliest    
        SET @ToDate = '2099-12-31';    -- latest    
    END    
    ELSE    
    BEGIN    
        -- If FromDate is valid but ToDate is blank → use today    
        IF (@ToDate IS NULL)    
            SET @ToDate = GETDATE();    
    END    
    
    ---------------------------------------------------    
    -- MAIN QUERY    
    ---------------------------------------------------    
    SELECT    
        TD.Id,    
        TD.OrgId,    
        TD.EmpCode as EmployeeCode,    
        TD.BeneficiaryName,    
        TD.DateOfIntimation,    
        CONVERT(VARCHAR(10), TD.DateOfIntimation, 103) AS DateOfIntimation1,    
        TD.DateOfAdmission,    
        TD.DateOfDischarge,    
        TD.HospitalName,    
        TD.State,    
   TD.TicketStatus as Status,    
        TD.NetworkCity,    
        TD.TypeOfIntimation,    
        TD.StatusOfIntimation,    
        TD.ClaimType,    
        TD.IntimationNumber,    
        TD.Relation,    
        TD.Age,    
        TD.ProposerName,    
        TD.Mobile1,    
        TD.EstimatedAmount,    
        TD.AdmissionType,    
        TD.NetworkStatus,    
        TD.NatureOfIllness,    
        TD.TAT,    
        TD.TAT_Godi,    
        TD.TAT_Band_Godi,    
        TD.Remarks,    
        TD.CreatedDateTime,    
      --  FORMAT(TD.CreatedDateTime, 'dd/MM/yyyy') AS CreatedDate,    
		  CONVERT(VARCHAR(10), TD.CreatedDateTime, 103) AS CreatedDate,    
        TD.AssignedDoctorId,    
        EM.Code AS DoctorCode,    
        TD.IsObsolete,    
        TD.TicketNumber,    
        AD.AssignTypeId,    
        AD.AssignSubTypeId,    
        AD.DoctorEmployeeId,    
        CASE AD.AssignTypeId    
            WHEN 2012 THEN 'Business'    
            WHEN 1014 THEN 'Sub Location'    
            WHEN 2010 THEN 'Organization'    
            ELSE 'State / Zone'    
        END AS AssignType,    
        CASE AD.DesignationId    
            WHEN 1 THEN 'Business Doctor'    
            WHEN 2 THEN 'Central Doctor'    
            WHEN 3 THEN 'Site Doctor'    
            WHEN 4 THEN 'Zonal Doctor'    
        END AS Designation,    
        ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS AssignDoctor    
    FROM [sHospitalization].[tIntimationDetails] TD    
    INNER JOIN [sHospitalization].[tIntimationAssignedDoctor] AD     
        ON TD.IntimationAssignedDoctorId = AD.Id    
    LEFT JOIN [sHrm].[tEmployeeMaster] EM    
        ON EM.Id = TD.AssignedDoctorId    
    WHERE    
        TD.IsObsolete = 0    
        AND TD.DateOfIntimation BETWEEN @FromDate AND @ToDate    
        AND (@rOrgId = 0 OR TD.OrgId = @rOrgId)    
    ORDER BY TD.DateOfIntimation DESC;    
END
GO
PRINT N'Altering Procedure [sHospitalization].[pIntimationDetailsInsert]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pIntimationDetailsInsert]     
    @rHospitalName NVARCHAR(255) = NULL,      
    @rPatientName NVARCHAR(255) = NULL,      
    @rEmpCode NVARCHAR(100) = NULL,      
    @rMobile1 NVARCHAR(20) = NULL,      
    @rOrgId INT = NULL,      
    -- Raw Excel Columns      
    @rRawEmployeeNo NVARCHAR(100) = NULL,      
    @rRawBeneficiaryName NVARCHAR(255) = NULL,      
    @rRawAge NVARCHAR(10) = NULL,      
    @rRawRelation NVARCHAR(100) = NULL,      
    @rRawNatureOfIllness NVARCHAR(500) = NULL,      
    @rRawProposerName NVARCHAR(255) = NULL,      
    @rRawContact1 NVARCHAR(20) = NULL,      
    @rRawHospitalName NVARCHAR(255) = NULL,      
    @rRawNetworkCity NVARCHAR(100) = NULL,      
    @rRawState NVARCHAR(100) = NULL,      
    @rRawTreatingDoctor NVARCHAR(255) = NULL,      
    @rRawLikelyDateOfAdmission NVARCHAR(200) = NULL,      
    @rRawDateOfDischarge NVARCHAR(200) = NULL,      
    @rRawStatusOfIntimation NVARCHAR(100) = NULL,      
    @rRawTypeOfIntimation NVARCHAR(100) = NULL,      
    @rRawFIRNo NVARCHAR(100) = NULL,      
    @rRawDateOfFileReceived NVARCHAR(200) = NULL,      
    @rRawClaimType NVARCHAR(200) = NULL,      
    @rRawIntimationNo NVARCHAR(100) = NULL,      
    @rRawDateOfIntimation NVARCHAR(200) = NULL,      
    @rRawTPACardNo NVARCHAR(100) = NULL,      
    @rRawGrade NVARCHAR(200) = NULL,      
    @rRawGroupCode NVARCHAR(200) = NULL,      
    @rRawModeOfStatus NVARCHAR(200) = NULL,      
    @rRawTAT NVARCHAR(200) = NULL,      
    @rRawAdmissionType NVARCHAR(200) = NULL,      
    @rRawEstimatedAmount NVARCHAR(200) = NULL,      
    @rRawNetworkStatus NVARCHAR(200) = NULL,      
    @rRawTAT_Godi NVARCHAR(200) = NULL,      
    @rRawTAT_Band_Godi NVARCHAR(200) = NULL,      
    @rCreatedUserId BIGINT = NULL,      
    @rIsObsolete BIT = 0,      
    @AssignedDoctorId BIGINT = NULL,      
 @IntimationAssignedDoctorId INT = NULL ,
 @rflag BIT = 0 
          
AS      
BEGIN      
    SET nocount ON;      
 DECLARE @NewRecordId BIGINT ;      
  DECLARE @ParticipantSourceId BIGINT ;     
    BEGIN try      
        DECLARE @EmployeeId BIGINT = NULL,      
                @PreviousDoctorId BIGINT = NULL,      
                @TicketStatus NVARCHAR(50) = 'New',      
                @CurrentDateTime DATETIME = Getutcdate(),      
                @TicketNumber NVARCHAR(50) = NULL,      
                @AssignTypeId BIGINT = NULL,      
                @AssignSubTypeId BIGINT = NULL,      
                @DesignationId BIGINT = NULL,      
                @ParsedDateOfAdmission DATE,      
                @ParsedDateOfDischarge DATE,      
                @ParsedDateOfIntimation DATE,      
                @ParsedEstimatedAmount DECIMAL(18, 2),      
                @ParsedAge INT,      
                @lNextNumber BIGINT,      
                @FIRNo_num NUMERIC(18, 0) = NULL,      
                @TPACardNo_num NUMERIC(18, 0) = NULL,      
                @EstimatedAmount_num DECIMAL(18, 2) = NULL,      
                @TAT_Godi_int INT = NULL,      
                @ParticipantSourceTypeId BIGINT = NULL;      
          
        ---------------------------------------------------------------------      
        -- Generate new RowId      
        ---------------------------------------------------------------------      
        EXEC scommon.ptablerowidget @rOrgId = @rOrgId,      
                                    @rTableTitle = 'sHospitalization.tIntimationDetails',      
                                    @rIsCurrentNumber = 0,      
                                    @rSeed = 1,      
                                    @rIncrement = 1,      
                                    @outNextNumber = @lNextNumber output;      
        SET @NewRecordId = @lNextNumber;      
        ---------------------------------------------------------------------      
        -- Resolve EmployeeId (if present)      
        ---------------------------------------------------------------------      
        ---------------------------------------------------------------------      
        -- Resolve EmployeeId (if present)      
        ---------------------------------------------------------------------      
        IF ISNULL(LTRIM(RTRIM(@rRawEmployeeNo)), '') <> ''      
        BEGIN      
            SELECT @EmployeeId = Id      
            FROM [sHrm].[tEmployeeMaster]      
            WHERE Code = @rRawEmployeeNo      
     AND IsObsolete = 0;      
      
            IF @EmployeeId IS NOT NULL      
            BEGIN      
      
                SET @ParticipantSourceTypeId = 95;      
            END      
            ELSE      
            BEGIN      
      
                SET @ParticipantSourceTypeId = NULL;      
            END      
        END      
        ELSE      
        BEGIN      
      
            SET @ParticipantSourceTypeId = NULL;      
        END      
      
        ---------------------------------------------------------------------      
        -- Doctor assignment placeholder logic (currently manual or external)      
        ---------------------------------------------------------------------      
        -- ASSIGNDOCTORDONE:      
        ---------------------------------------------------------------------      
        -- Generate Ticket Number      
        ---------------------------------------------------------------------      
        -- SET @TicketNumber = 'TKT-' + Format(Getutcdate(), 'yyyyMMdd') + '-' + RIGHT('00000' + Cast(Abs(Checksum(Newid())) % 100000 AS NVARCHAR(5)), 5);      
        -- Generate sequential TicketNumber (e.g. TKT-20251105-00001)      
        ---------------------------------------------------------------------      
        -- Generate sequential TicketNumber like TKT-20251105-00001      
        ---------------------------------------------------------------------      
        DECLARE @NextNumber INT;      
      
        SELECT @NextNumber = ISNULL(MAX(CAST(RIGHT(TicketNumber, 5) AS INT)), 0) + 1      
        FROM [sHospitalization].[tIntimationDetails]      
        WHERE TicketNumber LIKE 'TKT-' + FORMAT(GETUTCDATE(), 'yyyyMMdd') + '%';      
      
        SET @TicketNumber      
            = 'TKT-' + FORMAT(GETUTCDATE(), 'yyyyMMdd') + '-' + RIGHT('00000' + CAST(@NextNumber AS NVARCHAR(5)), 5);      
      
      
        ---------------------------------------------------------------------      
        -- Parse / normalize fields      
        ---------------------------------------------------------------------      
        SET @ParsedDateOfAdmission = dbo.Fn_parsedatestring(@rRawLikelyDateOfAdmission);      
        SET @ParsedDateOfDischarge = dbo.Fn_parsedatestring(@rRawDateOfDischarge);      
        SET @ParsedDateOfIntimation = dbo.Fn_parsedatestring(@rRawDateOfIntimation);      
        -- Normalize estimated amount      
        IF Isnull(Ltrim(Rtrim(@rRawEstimatedAmount)), '') <> ''      
        BEGIN      
            SET @rRawEstimatedAmount = Replace(Replace(Ltrim(Rtrim(@rRawEstimatedAmount)), ',', ''), ' ', '');      
            SET @ParsedEstimatedAmount = try_cast(@rRawEstimatedAmount as decimal(18, 2));      
        END      
        ELSE      
            SET @ParsedEstimatedAmount = NULL;      
        SET @ParsedAge = try_cast(@rRawAge as int);      
        ---------------------------------------------------------------------      
        -- Validate numeric fields BEFORE INSERT      
        ---------------------------------------------------------------------      
        -- FIRNo      
        IF Isnull(Ltrim(Rtrim(@rRawFIRNo)), '') <> ''      
        BEGIN      
            SET @FIRNo_num = try_cast(Replace(Ltrim(Rtrim(@rRawFIRNo)), ' ', '') as numeric(18, 0));      
            IF @FIRNo_num IS NULL      
                RAISERROR('Invalid FIRNo: cannot convert [%s] to numeric', 16, 1, @rRawFIRNo);      
        END      
        ELSE      
            SET @FIRNo_num = NULL;      
        -- TPACardNo      
        IF Isnull(Ltrim(Rtrim(@rRawTPACardNo)), '') <> ''      
        BEGIN      
            SET @TPACardNo_num = try_cast(Replace(Ltrim(Rtrim(@rRawTPACardNo)), ' ', '') as numeric(18, 0));      
            IF @TPACardNo_num IS NULL      
                RAISERROR('Invalid TPACardNo: cannot convert [%s] to numeric', 16, 1, @rRawTPACardNo);      
        END      
        ELSE      
            SET @TPACardNo_num = NULL;      
        -- EstimatedAmount      
        IF Isnull(Ltrim(Rtrim(@rRawEstimatedAmount)), '') <> ''      
        BEGIN      
            IF @ParsedEstimatedAmount IS NULL      
                RAISERROR('Invalid EstimatedAmount: cannot convert [%s] to decimal', 16, 1, @rRawEstimatedAmount);      
            ELSE      
                SET @EstimatedAmount_num = @ParsedEstimatedAmount;      
        END      
        ELSE      
           SET @EstimatedAmount_num = NULL;      
        -- TAT_Godi      
        IF Isnull(Ltrim(Rtrim(@rRawTAT_Godi)), '') <> ''      
        BEGIN      
            SET @TAT_Godi_int = try_cast(Ltrim(Rtrim(@rRawTAT_Godi)) as int);      
            IF @TAT_Godi_int IS NULL      
                RAISERROR('Invalid TAT_Godi: cannot convert [%s] to int', 16, 1, @rRawTAT_Godi);      
        END      
        ELSE      
            SET @TAT_Godi_int = NULL;      
      
      
           ---------------------------------------------------------------------      
        -- Insert / Update State Master      
        ---------------------------------------------------------------------      
        IF ISNULL(LTRIM(RTRIM(@rRawState)), '') <> ''      
        BEGIN      
            DECLARE @lStateId BIGINT;      
      
            -- Check if state already exists      
            SELECT @lStateId = Id      
            FROM [sHospitalization].[tStateMaster]      
            WHERE StateName = @rRawState      
                  AND OrgId = @rOrgId      
                  AND IsObsolete = 0;      
      
            -- If not found, insert new      
            IF @lStateId IS NULL      
            BEGIN      
                EXEC scommon.ptablerowidget       
                    @rOrgId = @rOrgId,      
                    @rTableTitle = 'sHospitalization.tStateMaster',      
                    @rIsCurrentNumber = 0,      
                    @rSeed = 1,      
                    @rIncrement = 1,      
                    @outNextNumber = @lStateId OUTPUT;      
      
                INSERT INTO [sHospitalization].[tStateMaster]      
                (      
                    Id,      
                    OrgId,      
                    StateName,      
                    CreatedUserId,      
                    CreatedDateTime,      
                    UpdatedUserId,      
                    UpdatedDateTime,      
                    IsObsolete      
                )      
                VALUES      
                (      
                    @lStateId,      
                    @rOrgId,      
                    @rRawState,      
                    @rCreatedUserId,      
                    @CurrentDateTime,      
                    @rCreatedUserId,      
                    @CurrentDateTime,      
                    0      
                );      
            END      
        END      
      
        ---------------------------------------------------------------------      
        -- All validations passed — perform insert inside a transaction      
        ---------------------------------------------------------------------      
IF @ParsedDateOfIntimation IS NOT NULL AND NOT EXISTS  
(  
    SELECT 1  
    FROM [sHospitalization].[tIntimationDetails]  
    WHERE EmpCode = @rRawEmployeeNo  
      AND BeneficiaryName = @rRawBeneficiaryName  
      AND DateOfIntimation = @ParsedDateOfIntimation  
)   
  BEGIN      
        BEGIN TRANSACTION;      
      
        
    INSERT INTO [sHospitalization].[tIntimationDetails]      
        (      
            id,      
            orgid,      
            participantsourceid,      
            participantsourcetypeid,      
            empcode,      
            beneficiaryname,      
            dateofintimation,      
           dateofadmission,      
            dateofdischarge,      
            claimtype,      
            intimationnumber,      
            natureofillness,      
            status,      
            hospitalname,      
            networkcity,      
            state,      
            age,      
            mobile1,      
            assigneddoctorid,      
   IntimationAssignedDoctorId,      
            ticketnumber,      
            ticketstatus,      
            ticketopendate,      
            relation,      
            proposername,      
            statusofintimation,      
            typeofintimation,      
  firno,      
            tpacardno,      
            grade,      
            groupcode,      
            modeofstatus,      
            tat,      
            admissiontype,      
            estimatedamount,      
            networkstatus,      
            tat_godi,      
            tat_band_godi,      
            isobsolete,      
            createddatetime,      
            createduserid,      
            updateddatetime,      
            updateduserid,
			TreatingDoctor,
			Flag
        )      
        VALUES      
        (@NewRecordId,      
         Isnull(@rOrgId, 0),      
         @EmployeeId,      
         @ParticipantSourceTypeId,      
         @rRawEmployeeNo,      
@rRawBeneficiaryName,      
         @ParsedDateOfIntimation,      
         @ParsedDateOfAdmission,      
         @ParsedDateOfDischarge,      
         @rRawClaimType,      
         @rRawIntimationNo,      
         @rRawNatureOfIllness,      
         @rRawStatusOfIntimation,      
         @rRawHospitalName,      
         @rRawNetworkCity,      
         @rRawState,      
         @ParsedAge,      
         @rRawContact1,      
         @AssignedDoctorId,      
   @IntimationAssignedDoctorId,      
         @TicketNumber,      
         @TicketStatus,      
         @CurrentDateTime,      
         @rRawRelation,      
         @rRawProposerName,      
         @rRawStatusOfIntimation,      
         @rRawTypeOfIntimation,      
         @FIRNo_num,      
         @TPACardNo_num,      
         @rRawGrade,      
         @rRawGroupCode,      
         @rRawModeOfStatus,      
         @rRawTAT,      
         @rRawAdmissionType,      
         @EstimatedAmount_num,      
         @rRawNetworkStatus,      
         @TAT_Godi_int,      
         @rRawTAT_Band_Godi,      
         @rIsObsolete,      
         @CurrentDateTime,      
         @rCreatedUserId,      
         @CurrentDateTime,      
         @rCreatedUserId ,
		 @rRawTreatingDoctor,
		 @rflag     
        );      
        
        ---------------------------------------------------------------------      
        -- Insert doctor assignment log      
        ---------------------------------------------------------------------      
              
  IF @AssignedDoctorId IS NOT NULL      
        BEGIN      
            DECLARE @lAssignLogId BIGINT;      
            EXEC scommon.ptablerowidget @rOrgId = @rOrgId,      
                                        @rTableTitle = 'sHospitalization.tIntimationDoctorAssignmentLog',      
                                        @rIsCurrentNumber = 0,      
                                        @rSeed = 1,      
                                        @rIncrement = 1,      
                                        @outNextNumber = @lAssignLogId output;      
            INSERT INTO [sHospitalization].[tIntimationDoctorAssignmentLog]      
            (      
                id,      
                orgid,      
                hospitalizationintimationdetailid,      
                previousdoctoremployeeid,      
                newdoctoremployeeid,      
                assigneddate,      
                ticketnumber,      
                createduserid,      
                createddatetime,      
                updateduserid,      
                updateddatetime,      
    Status      
            )      
            VALUES      
            (@lAssignLogId,      
             Isnull(@rOrgId, 0),      
             @NewRecordId,      
             @PreviousDoctorId,      
             @AssignedDoctorId,      
             @CurrentDateTime,      
             @TicketNumber,      
             @rCreatedUserId,      
             @CurrentDateTime,      
             @rCreatedUserId,      
             @CurrentDateTime,      
    'New'      
            );      
      
        END      
        COMMIT TRANSACTION;      
  END      
  ---------------------------------------------------------------------      
-- Insert default remark entry with Status = 'New'      
---------------------------------------------------------------------      
--IF @AssignedDoctorId IS NOT NULL      
--BEGIN      
--    DECLARE @lRemarkId BIGINT;      
      
--    EXEC scommon.ptablerowidget       
--        @rOrgId = @rOrgId,      
--        @rTableTitle = 'sHospitalization.tIntimationRemark',      
--        @rIsCurrentNumber = 0,      
--        @rSeed = 1,      
--        @rIncrement = 1,      
--        @outNextNumber = @lRemarkId OUTPUT;      
      
--    INSERT INTO [sHospitalization].[tIntimationRemark]      
--    (      
--        Id,      
--        OrgId,      
--        HospitalizationIntimationDetailId,      
--        DoctorEmployeeId,      
--        Remark,      
--        CreatedUserId,      
--        CreatedDateTime,      
--        UpdatedUserId,      
--        UpdatedDateTime,      
--        Status      
--    )      
--    VALUES      
--    (      
--        @lRemarkId,      
--        @rOrgId,      
--        @NewRecordId,      
--        @AssignedDoctorId,      
--        NULL,                     -- Remark initially empty      
--        @rCreatedUserId,      
--        @CurrentDateTime,      
--        @rCreatedUserId,      
--        @CurrentDateTime,      
--        'New'                     -- Default Status      
--    );      
--END      
      
        ---------------------------------------------------------------------      
        -- Return newly created record id      
        ---------------------------------------------------------------------      
        SELECT @NewRecordId AS newrecordid ,@EmployeeId as ParticipantSourceId ,@IntimationAssignedDoctorId as IntimationAssignedDoctorId ;      
      
        RETURN;      
    END try      
    BEGIN catch      
        -- Ensure rollback      
        IF @@TRANCOUNT > 0      
            ROLLBACK TRANSACTION;      
        DECLARE @ErrorMessage NVARCHAR(4000) = Error_message();      
        DECLARE @lErrorId BIGINT;      
        EXEC scommon.ptablerowidget @rOrgId = @rOrgId,      
                                    @rTableTitle = 'sHospitalization.tErrorLog',      
                                    @rIsCurrentNumber = 0,      
                                    @rSeed = 1,      
                                    @rIncrement = 1,      
                                    @outNextNumber = @lErrorId output;      
        INSERT INTO [sHospitalization].[tErrorLog]      
        (      
            id,      
            errormessage,      
            storedprocedure,      
            errordatetime,      
            userid,      
            orgid      
        )      
        VALUES      
        (@lErrorId, @ErrorMessage, 'sHospitalization.pIntimationDetailsInsert', Getutcdate(), @rCreatedUserId, @rOrgId);      
      
        SET @NewRecordId = -1;      
        RAISERROR(@ErrorMessage, 16, 1);      
        RETURN;      
    END catch      
END;
GO
PRINT N'Altering Procedure [sHospitalization].[pIntimationDetailsListReviewGet]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pIntimationDetailsListReviewGet]
(            
    @rOrgId SMALLINT,            
    @rFromDate NVARCHAR(50) = NULL,            
    @rToDate NVARCHAR(50) = NULL,            
    @rDoctorId BIGINT = 0,            
    @rStatusId VARCHAR(50) = 0,            
    @rCodeLike NVARCHAR(MAX) = ''            
)            
AS            
BEGIN            
    SET NOCOUNT ON;            
    SET DATEFORMAT dmy;            
            
    DECLARE             
        @FromDate DATETIME = NULL,            
        @ToDate DATETIME = NULL;            
            
DECLARE @StatusIds TABLE (Id INT);      

            
INSERT INTO @StatusIds (Id)            
SELECT T.X.value('.', 'INT')            
FROM (            
    SELECT CAST(            
        '<x>' + REPLACE(@rStatusId, ',', '</x><x>') + '</x>'            
        AS XML            
    ) AS XmlData            
) A            
CROSS APPLY XmlData.nodes('/x') AS T(X);            
            
            
     
    -- Map rStatusId to text            
    --DECLARE @StatusText NVARCHAR(20) = NULL;            
    --IF @rStatusId = 1 SET @StatusText = 'New';            
    --IF @rStatusId = 2 SET @StatusText = 'Open';            
    --IF @rStatusId = 3 SET @StatusText = 'Close';            
 --IF @rStatusId = 4 SET @StatusText = 'New & Open';            
            
    -----------------------------------------            
    -- ✅ SQL 2008/2012 SAFE DATE CONVERSION            
    -----------------------------------------            
    IF (@rFromDate IS NOT NULL AND @rFromDate <> '')            
        SET @FromDate = CONVERT(DATETIME, @rFromDate, 103);  -- FORCES DD/MM/YYYY            
            
    IF (@rToDate IS NOT NULL AND @rToDate <> '')            
        SET @ToDate = DATEADD(DAY, 1, CONVERT(DATETIME, @rToDate, 103));  -- include full day            
            
    -----------------------------------------            
    -- If no code, make it empty            
    -----------------------------------------            
    IF (ISNULL(@rCodeLike, '') = '') SET @rCodeLike = '';            
            
    BEGIN TRY            
        SELECT             
            TD.Id AS IntimationId,            
            TD.EmpCode AS EmployeeCode,            
            TD.BeneficiaryName,            
            TD.Relation,            
            --TD.Age,            
       CASE             
        WHEN UPPER(ISNULL(TD.Relation, '')) = 'SELF'            
             AND VEMDS.EmployeeId = TD.ParticipantSourceId            
            THEN ISNULL(VEMDS.Age, TD.Age)            
        ELSE TD.Age            
    END AS Age,            
            TD.HospitalName,            
            TD.NetworkCity,            
            TD.State,            
            TD.StatusOfIntimation,            
            TD.TypeOfIntimation,            
            TD.FIRNo,            
            TD.CreatedDateTime,            
            TD.TicketStatus AS StatusName,            
            TD.Grade AS Grade,            
            TD.NatureOfIllness,            
            TD.IntimationNumber,            
            TD.ClaimType,            
            TD.DateOfIntimation,            
            TD.DateOfAdmission,            
            TD.DateOfDischarge,            
            TD.TicketNumber,            
            TD.Remarks,            
            
            ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS AssignedDoctor,            
            --AD.DesignationId,            
   EMDS.id as DesignationId,            
          -- ISNULL(VEMDS.FirstName, '') + ' ' + ISNULL(VEMDS.LastName, '') AS EmployeeName,            
    CASE             
    WHEN (ISNULL(VEMDS.FirstName, '') = '' AND ISNULL(VEMDS.LastName, '') = '')            
         THEN TD.ProposerName            
    ELSE ISNULL(VEMDS.FirstName, '') + ' ' + ISNULL(VEMDS.LastName, '')            
END AS EmployeeName,            
            
            ISNULL(ECD.CompanyEmail, '') AS CompanyEmail,      
       --    ISNULL(VEMDS1.MobileNumber, '') AS OracleMobile,            
    ISNULL(VEMDS.MobileNumber, '') AS OracleMobile,            
   ISNULL(TD.Mobile1, '') AS ApiMobile,            
        
            SCT.Title AS Business,            
            VTM.Title AS Vertical,            
            CGM.Title AS CompanyGroup,            
            ECM.Title AS Company,            
            LM.Title AS Location,            
            DGM.Title AS DepartmentGroup,            
            ODM.Title AS Department,            
            ETM.Title AS EmployeeType,            
            GRD.Title AS GradeTitle,            
   VEMDS.Designation as DesignationName,            
            
            AD.UpdatedDateTime AS LastActionDate,            
            TD.AssignedDoctorId AS DoctorEmployeeId,            
   TD.ParticipantSourceId as EmployeeId,            
            
ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS AssignDoctor,            
ISNULL(VEMDS1.ExtensionNo,'') DoctorExtensionNo,            
ISNULL(VEMDS1.MobileNumber,'') DoctorMobileNumber,            
CASE  
  
    WHEN TDLog.PreviousDoctorEmployeeId IS NOT NULL  
        THEN ISNULL(VEMDS2.FirstName, '') + ' ' + ISNULL(VEMDS2.LastName, '')  
    ELSE 'System'  
END AS AssignBYDoctor  
,            AL.CreatedDate,
        
            
            
            STUFF((SELECT ', ' + R.Remark            
                FROM sHospitalization.tIntimationRemark R            
                WHERE R.HospitalizationIntimationDetailId = TD.Id            
                ORDER BY R.CreatedDateTime DESC            
                FOR XML PATH(''), TYPE            
            ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS AllRemarks,            
            
            (            
                SELECT             
                    R.Id,            
                    R.Remark,            
                    R.CreatedDateTime,            
                    R.CreatedUserId            
                FROM sHospitalization.tIntimationRemark R            
                WHERE R.HospitalizationIntimationDetailId = TD.Id            
                ORDER BY R.CreatedDateTime DESC            
                FOR JSON PATH            
            ) AS RemarkHistoryJSON,
			Isnull(TD.TreatingDoctor,'NA') as TreatingDoctor,
			  CASE 
        WHEN TD.Flag = 1
             AND YEAR(TD.CreatedDateTime) = YEAR(GETDATE())
        THEN 'Repeat Case'
        ELSE ''
    END AS RepeatCaseTitle,
	ECD1.CompanyEmail as Reportingmanagermail,
	(
    SELECT TOP 1 MailSubject
    FROM sAlert.tEventTemplate
    WHERE OrgId = @rOrgId 
      AND EventId = 108 
      AND IsAutoSend = 1
) AS MailSubject,

(
    SELECT TOP 1 Template
    FROM sAlert.tEventTemplate
    WHERE OrgId = @rOrgId 
      AND EventId = 108 
      AND IsAutoSend = 1
) AS MailTemplate
            
        FROM [sHospitalization].[tIntimationDetails] TD            
        INNER JOIN [sHospitalization].[tIntimationAssignedDoctor] AD             
            ON  TD.IntimationAssignedDoctorId = AD.Id            
        Left JOIN [sHrm].[tEmployeeMaster] EMD             
            ON EMD.Id = AD.DoctorEmployeeId            
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP             
            ON EMP.Id = TD.ParticipantSourceId            
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD             
            ON ECD.EmployeeId = EMP.Id            
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD             
            ON EJD.EmployeeId = EMP.Id            
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM             
            ON ETM.Id = EJD.EmployeeTypeId            
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM             
            ON ECM.Id = EJD.EmployeeCompanyId            
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM             
            ON CGM.Id = ECM.CompanyGroupId            
        LEFT JOIN [sHrm].[tVerticalMaster] VTM             
            ON VTM.Id = CGM.VerticalId            
        LEFT JOIN [sHrm].[tSectorMaster] SCT             
            ON SCT.Id = VTM.SectorId            
        Left JOIN [sCommon].[tLocationMaster] LM             
            ON LM.Id = EJD.EmployeeLocationId            
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM             
            ON DGM.Id = EJD.OrganizationDepartmentId            
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM             
            ON ODM.Id = EJD.OrganizationDepartmentId            
            
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS             
            ON EMDS.Id = EJD.EmployeeDesignationId            
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS             
            ON VEMDS.EmployeeId = TD.ParticipantSourceId            
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1             
            ON VEMDS1.EmployeeId = TD.AssignedDoctorId            
     LEFT JOIN [sHrm].[vExtEmployeeMaster]    VEMDS2            
            ON VEMDS2.UserId = TD.UpdatedUserId            
     LEFT JOIN [sHrm].[tGradeMaster] GRD             
            ON GRD.Id = VEMDS.GradeId       
	LEFT JOIN [sHrm].[tEmployeeCommunications] ECD1             
            ON ECD1.EmployeeId = EJD.ReportingMangerEmployeeId
OUTER APPLY  
(  
    SELECT TOP 1 *  
    FROM sHospitalization.tIntimationDoctorAssignmentLog L  
    WHERE L.HospitalizationIntimationDetailId = TD.Id  
    ORDER BY L.AssignedDate DESC  
) TDLog  
OUTER APPLY (
    SELECT TOP 1
        CreatedDateTime AS CreatedDate
    FROM sAlert.tAlertLog
    WHERE ClaimIntimationDetailId = TD.Id
    ORDER BY CreatedDateTime DESC
) AL

            
        WHERE             
            TD.OrgId = @rOrgId            
            AND (TD.AssignedDoctorId = @rDoctorId OR @rDoctorId = 0)            
            -----------------------------------------            
            -- ✅ CORRECT DATE FILTER (NO 2025 LEAK)            
            -----------------------------------------            
            AND (            
                    (@FromDate IS NULL OR TD.CreatedDateTime >= @FromDate)            
                AND (@ToDate   IS NULL OR TD.CreatedDateTime <  @ToDate)            
            )            
            
            AND (                      EXISTS (            
                    SELECT 1            
                    FROM sCommon.fnsplit(@rCodeLike, ',') AS SplitValues            
                    WHERE             
                        (CHARINDEX(',', @rCodeLike) = 0 AND TD.EmpCode LIKE SplitValues.item + '%')            
                        OR            
                        (CHARINDEX(',', @rCodeLike) > 0 AND TD.EmpCode = SplitValues.item)            
                )            
                OR @rCodeLike = ''            
            )            
            AND (            
             
               --    (@rStatusId <> 4 AND TD.TicketStatus = @StatusText)            
               -- OR (@rStatusId = 4 AND TD.TicketStatus IN ('New', 'Open'))            
            
                --TD.TicketStatus = @StatusText            
            
                   @rStatusId = '0'            
                   OR TD.TicketStatus IN (            
             SELECT            
                           CASE Id            
                               WHEN 1 THEN 'New'            
                               WHEN 2 THEN 'Open'            
                               WHEN 3 THEN 'Close'            
                           END            
                       FROM @StatusIds            
                   )            
            )            
            
        ORDER BY TD.CreatedDateTime DESC;            
    END TRY            
            
    BEGIN CATCH            
        DECLARE @ErrMsg NVARCHAR(MAX) = ERROR_MESSage();            
        INSERT INTO [sHospitalization].[tErrorLog]            
        (            
            ErrorMessage,             
            StoredProcedure,             
            ErrorDateTime,             
            UserId,             
            OrgId            
        )            
        VALUES            
        (            
            @ErrMsg,             
            'pIntimationDetailsListReviewGet',             
            GETUTCDATE(),             
            NULL,             
            @rOrgId            
        );            
    END CATCH            
END;
GO
PRINT N'Altering Procedure [sHospitalization].[pIntimationDetailsListReviewGetExport]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pIntimationDetailsListReviewGetExport]  
(  
    @rOrgId SMALLINT,  
    @rFromDate NVARCHAR(50) = NULL,  
    @rToDate NVARCHAR(50) = NULL,  
    @rDoctorId BIGINT = 0,  
    @rStatusId VARCHAR(50) = 0,  
    @rCodeLike NVARCHAR(MAX) = ''  
)  
AS  
BEGIN  
    SET NOCOUNT ON;  
    SET DATEFORMAT dmy;        -- ✅ FORCE DD/MM/YYYY parsing  
  
    DECLARE   
        @FromDate DATETIME = NULL,  
        @ToDate DATETIME = NULL;  
  
  
DECLARE @StatusIds TABLE (Id INT);  
  
INSERT INTO @StatusIds (Id)  
SELECT T.X.value('.', 'INT')  
FROM (  
    SELECT CAST(  
        '<x>' + REPLACE(@rStatusId, ',', '</x><x>') + '</x>'  
        AS XML  
    ) AS XmlData  
) A  
CROSS APPLY XmlData.nodes('/x') AS T(X);  
  
    -- Map rStatusId to text  
    --DECLARE @StatusText NVARCHAR(20) = NULL;  
    --IF @rStatusId = 1 SET @StatusText = 'New';  
    --IF @rStatusId = 2 SET @StatusText = 'Open';  
    --IF @rStatusId = 3 SET @StatusText = 'Close';  
 --IF @rStatusId = 4 SET @StatusText = 'New & Open';  
  
    -----------------------------------------  
    -- ✅ SQL 2008/2012 SAFE DATE CONVERSION  
    -----------------------------------------  
    IF (@rFromDate IS NOT NULL AND @rFromDate <> '')  
        SET @FromDate = CONVERT(DATETIME, @rFromDate, 103);  -- FORCES DD/MM/YYYY  
  
    IF (@rToDate IS NOT NULL AND @rToDate <> '')  
        SET @ToDate = DATEADD(DAY, 1, CONVERT(DATETIME, @rToDate, 103));  -- include full day  
  
    -----------------------------------------  
    -- If no code, make it empty  
    -----------------------------------------  
    IF (ISNULL(@rCodeLike, '') = '') SET @rCodeLike = '';  
  
    BEGIN TRY  
        SELECT   
         --   TD.Id AS IntimationId,  
              TD.EmpCode AS [Employee Code],  
         CASE   
              WHEN (ISNULL(VEMDS.FirstName, '') = '' AND ISNULL(VEMDS.LastName, '') = '')  
              THEN TD.ProposerName  
              ELSE ISNULL(VEMDS.FirstName, '') + ' ' + ISNULL(VEMDS.LastName, '')  
              END AS EmployeeName,  
   -- TD.Relation,  
   --TD.ProposerName as [Proposer Name],  
   --         ISNULL(EMD.FirstName, '') + ' ' + ISNULL(EMD.LastName, '') AS [Assigned Doctor],  
   --         --TD.DateOfAdmission AS [Date Of Admission],  
   --        -- TD.DateOfDischarge AS [Date Of Discharge],  
   --CONVERT(VARCHAR(10), TD.DateOfAdmission, 103) AS [Date Of Admission],  
   --         CONVERT(VARCHAR(10), TD.DateOfDischarge, 103) AS [Date Of Discharge],  
   --         TD.StatusOfIntimation AS [Status Of Intimation],  
   --         TD.TypeOfIntimation AS [Type Of Intimation],  
   --         TD.FIRNo AS [FIR No],  
   ----delete  
   --         --TD.CreatedDateTime,  
   --   TD.ClaimType AS [Claim Type],  
   --       TD.IntimationNumber AS [Intimation Numberr],  
   --         TD.TicketStatus AS [Status Name],  
   --        -- TD.Grade AS Grade,  
   -- GRD.Title AS Grade,  
   --         TD.IntimationNumber as [Intimation Number],  
   --         TD.ClaimType,  
   -- --   TD.DateOfIntimation,  
   -- CONVERT(VARCHAR(10), TD.DateOfIntimation, 103) AS [Date Of Intimation],  
   -- TD.TPACardNo,  
     --TD.Grade,  
      -- GRD.Title AS Grade,  
      --TD.GroupCode,  
      --TD.ModeOfStatus,  
      --TD.ModeOfStatus,   
      --TD.TAT,  
      --TD.AdmissionType,   
      VEMDS.Designation as Designation,  
      SCT.Title AS Business,  
      LM.Title AS [Hr Location],  
               CASE   
                            WHEN TD.TicketStatus != 'New'   
                                THEN ISNULL(VEMDS2.FirstName, '') + ' ' + ISNULL(VEMDS2.LastName, '')  
                            ELSE 'System'  
                        END AS [Assigned By],  
      ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS [Assigned To],  
        TD.BeneficiaryName,  
      TD.Relation,  
      TD.Age,  
      TD.HospitalName as [Hospital Name],  
         TD.State,  
      TD.NetworkCity as [Network City],  
      ISNULL(ECD.MobileNumber, '') AS [Mobile (Oracle)],  
      TD.Mobile1 as [Mobile (PHS)],  
      TD.NatureOfIllness as [Nature Of Illness],  
                        STUFF((  
                           SELECT   
                               CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103)   
                               + ': ' + R.Remark  
                           FROM sHospitalization.tIntimationRemark R  
                           WHERE R.HospitalizationIntimationDetailId = Td.Id  
                           ORDER BY R.CreatedDateTime DESC  
                           FOR XML PATH(''), TYPE  
                        ).value('.', 'nvarchar(max)'), 1, 1, '') AS [Remarks],  
      TD.TicketStatus as [Status]  
     -- TD.EstimatedAmount,  
     -- TD.NetworkStatus,  
     -- TD.TAT_Godi,  
     -- TD.TAT_Band_Godi  
   --         TD.TicketNumber,  
   --         TD.Remarks,  
  
   --         --AD.DesignationId,  
   --EMDS.id as DesignationId,  
   --        ISNULL(EMD.FirstName, '') + ' ' + ISNULL(EMD.LastName, '') AS EmployeeName,  
   --         ISNULL(ECD.CompanyEmail, '') AS CompanyEmail,  
   --         ISNULL(ECD.MobileNumber, '') AS EmployeeMobile,  
  
   --         SCT.Title AS Business,  
   --         VTM.Title AS Vertical,  
   --         CGM.Title AS CompanyGroup,  
   --         ECM.Title AS Company,  
   --         LM.Title AS Location,  
   --         DGM.Title AS DepartmentGroup,  
   --         ODM.Title AS Department,  
   --         ETM.Title AS EmployeeType,  
   --         GRD.Title AS GradeTitle,  
   --EMDS.Code as DesignationName,  
  
   --         AD.UpdatedDateTime AS LastActionDate,  
   --         TD.AssignedDoctorId AS DoctorEmployeeId,  
  
   --         STUFF((SELECT ', ' + R.Remark  
   --             FROM sHospitalization.tIntimationRemark R  
   --             WHERE R.HospitalizationIntimationDetailId = TD.Id  
   --             ORDER BY R.CreatedDateTime DESC  
   --             FOR XML PATH(''), TYPE  
   --         ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS AllRemarks,  
  
   --         (  
   --             SELECT   
   --                 R.Id,  
   --                 R.Remark,  
   --                 R.CreatedDateTime,  
   --                 R.CreatedUserId  
   --             FROM sHospitalization.tIntimationRemark R  
   --             WHERE R.HospitalizationIntimationDetailId = TD.Id  
   --             ORDER BY R.CreatedDateTime DESC  
   --             FOR JSON PATH  
   --         ) AS RemarkHistoryJSON  
  
        FROM [sHospitalization].[tIntimationDetails] TD  
        INNER JOIN [sHospitalization].[tIntimationAssignedDoctor] AD   
            ON  TD.IntimationAssignedDoctorId = AD.Id  
        LEFT JOIN [sHrm].[tEmployeeMaster] EMD   
            ON EMD.Id = AD.DoctorEmployeeId  
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP   
            ON EMP.Id = TD.ParticipantSourceId  
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD   
            ON ECD.EmployeeId = EMP.Id  
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD   
            ON EJD.EmployeeId = EMP.Id  
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM   
            ON ETM.Id = EJD.EmployeeTypeId  
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM   
            ON ECM.Id = EJD.EmployeeCompanyId  
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM   
            ON CGM.Id = ECM.CompanyGroupId  
        LEFT JOIN [sHrm].[tVerticalMaster] VTM   
            ON VTM.Id = CGM.VerticalId  
        LEFT JOIN [sHrm].[tSectorMaster] SCT   
            ON SCT.Id = VTM.SectorId  
        LEFT JOIN [sCommon].[tLocationMaster] LM   
            ON LM.Id = EJD.EmployeeLocationId  
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM   
            ON DGM.Id = EJD.OrganizationDepartmentId  
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM   
            ON ODM.Id = EJD.OrganizationDepartmentId  
        LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS   
            ON VEMDS.EmployeeId = TD.ParticipantSourceId  
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1   
            ON VEMDS1.EmployeeId = TD.AssignedDoctorId  
     LEFT JOIN [sHrm].[vExtEmployeeMaster]   VEMDS2  
            ON VEMDS2.UserId = TD.UpdatedUserId  
   LEFT JOIN [sHrm].[tGradeMaster] GRD   
            ON GRD.Id = VEMDS.GradeId  
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS   
            ON EMDS.Id = EJD.EmployeeDesignationId  
  
        WHERE   
            TD.OrgId = @rOrgId  
            AND (AD.DoctorEmployeeId = @rDoctorId OR @rDoctorId = 0)  
  
            -----------------------------------------  
            -- ✅ CORRECT DATE FILTER (NO 2025 LEAK)  
            -----------------------------------------  
            AND (  
                    (@FromDate IS NULL OR TD.CreatedDateTime >= @FromDate)  
                AND (@ToDate   IS NULL OR TD.CreatedDateTime <  @ToDate)  
            )  
  
            AND (  
                EXISTS (  
                    SELECT 1  
                    FROM sCommon.fnsplit(@rCodeLike, ',') AS SplitValues  
                    WHERE   
                        (CHARINDEX(',', @rCodeLike) = 0 AND TD.EmpCode LIKE SplitValues.item + '%')  
                        OR  
                        (CHARINDEX(',', @rCodeLike) > 0 AND TD.EmpCode = SplitValues.item)  
                )  
                OR @rCodeLike = ''  
            )  
            AND (  
                --TD.TicketStatus = @StatusText  
               @rStatusId = '0'  
                   OR TD.TicketStatus IN (  
                       SELECT  
                           CASE Id  
                               WHEN 1 THEN 'New'  
                               WHEN 2 THEN 'Open'  
                               WHEN 3 THEN 'Close'  
                           END  
                       FROM @StatusIds  
                   )  
  
            )  
  
        ORDER BY TD.CreatedDateTime DESC;  
    END TRY  
  
    BEGIN CATCH  
        DECLARE @ErrMsg NVARCHAR(MAX) = ERROR_MESSAGE();  
        INSERT INTO [sHospitalization].[tErrorLog]  
        (  
            ErrorMessage,   
            StoredProcedure,   
            ErrorDateTime,   
            UserId,   
            OrgId  
        )  
        VALUES  
        (  
            @ErrMsg,   
            'pIntimationDetailsListReviewGet',   
            GETUTCDATE(),   
            NULL,   
            @rOrgId  
        );  
    END CATCH  
END;
GO
PRINT N'Altering Procedure [sAppointment].[tTimeSlotMasterAdd]...';


GO
CREATE OR ALTER PROCEDURE [sAppointment].[tTimeSlotMasterAdd]
    @rId int,
    @rOrgId smallint,
    @rStoreLocationId int,
    @rCreatedUserId bigint,
    @rUpdatedUserId bigint,
    @rFromTime time = null,
    @rToTime time = null,
    @rInterval int = 10,
    @rFromDate datetime,
    @rToDate datetime,
    @rMainTypeId int = 1,
    @rIsBooked bit = 0,
	@rShiftRoasterId bigint = 0,
	@rIsNotAvailable bit = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
    BEGIN TRY
 
        declare @doctorId BigInt,
                @isonline bit,
                @isoffline bit
        select @doctorId = DoctorEmployeeId,
               @isonline = IsOnline,
               @isoffline = IsOffline
        from sAppointment.tTimeSlotSetup
        where Id = @rMainTypeId
        select @rFromTime = convert(time, convert(varchar(5), @rFromTime)),
               @rToTime = convert(time, convert(varchar(5), @rToTime))
        --select @rFromTime,@rToTime
        IF (@rId = 0)
        BEGIN
            If Exists
            (
				SELECT Id
				FROM [sAppointment].[tTimeSlotMaster] TSM
				WHERE 
					--StoreLocationId = @rStoreLocationId
					--AND
					OrgId = @rOrgId
					AND TimeSlotSetupId = @rMainTypeId
					AND TimeSlotDate >= @rFromDate and TimeSlotDate <= @rToDate 
					AND (
						  ((@rFromTime >= FromTime AND @rFromTime < ToTime) OR (@rToTime > FromTime AND @rToTime <= ToTime)) 
						  OR ((FromTime >= @rFromTime AND FromTime < @rToTime) OR (ToTime > @rFromTime AND ToTime <= @rToTime))
						)
            )
            BEGIN
                select -102 as Result
                RETURN
            END
        END
        ELSE
		  If Exists
            (
				SELECT Id
				FROM [sAppointment].[tTimeSlotMaster] TSM
				WHERE 
					--StoreLocationId = @rStoreLocationId
					--AND 
					OrgId = @rOrgId
					AND TimeSlotSetupId = @rMainTypeId
					AND Id <> @rId
					AND TimeSlotDate >= @rFromDate and TimeSlotDate <= @rToDate 
					AND (
						  ((@rFromTime >= FromTime AND @rFromTime < ToTime) OR (@rToTime > FromTime AND @rToTime <= ToTime)) 
						  OR ((FromTime >= @rFromTime AND FromTime < @rToTime) OR (ToTime > @rFromTime AND ToTime <= @rToTime))
						)
            )
            BEGIN
			  select -102 as Result
                RETURN
        END
        --BEGIN		
        --	If  Exists(select Id from  sSupport.tVaccineDoseMaster where VaccineId=@rVaccineId AND OrgId=@rOrgId AND Id<>@rId AND Upper(Title)=Upper(@rTitle))
        --	Begin
        --		select -103 as Result
        --		RETURN
        --	End
 
        --END
 
        BEGIN TRANSACTION
        DECLARE @lNextNumber BIGINT
 
        IF (@rId = 0)
        BEGIN
            declare @table table
            (
                tid int identity(1, 1),
                starttime time,
                endtime time
            )
            while (@rFromTime < @rToTime)
            begin
                insert into @table
                Select convert(varchar, @rFromTime, 108) as Starttime,
                       convert(varchar, DATEADD(minute, @rInterval, @rFromTime), 108) as Endtime
 
                set @rFromTime = DATEADD(minute, @rInterval, @rFromTime)
 
            end
 
            declare @tabledt table
            (
                tid int identity(1, 1),
                FromDate Datetime,
                starttime time,
                endtime time
            )
            while (@rFromDate <= @rToDate)
            begin
                --insert into @tabledt
                Insert into [sAppointment].[tTimeSlotMaster]
                --SELECT @rFromDate as FromDate,convert(time,convert(varchar(5),t.starttime)) as starttime,convert(time,convert(varchar(5),t.endtime)) as endtime,0,@rMainTypeId,@rOrgId,@rStoreLocationId,@rCreatedUserId,getdate(),@rUpdatedUserId,getdate() 			
                SELECT @rFromDate as FromDate,
                       t.starttime as starttime,
                       t.endtime as endtime,
                       0,
                       @rMainTypeId,
                       @rOrgId,
                       @rStoreLocationId,
                       @rCreatedUserId,
                       getdate(),
                       @rUpdatedUserId,
                       getdate(),
                       @rIsBooked,
					   @rShiftRoasterId,
					   @rIsNotAvailable
                From @table as t
 
                SET @rFromDate = DATEADD(d, 1, @rFromDate)
            end
 
            --select * from @tabledt
            SELECT 1 AS Result
        END
        ELSE
        BEGIN
          UPDATE  [sAppointment].[tTimeSlotMaster]
              SET
            FromTime=@rFromTime,	        	
            ToTime=@rToTime,	
            TimeSlotDate=@rFromDate,
			TimeSlotSetupId = @rMainTypeId
 
                WHERE Id = @rId
            SELECT 11 AS Result
        END
 
        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION
		SELECT -1 AS Result
        SELECT ERROR_MESSAGE() AS Result
    END CATCH
 
END
GO
PRINT N'Altering Procedure [sAudit].[pActivityLogGet]...';


GO
  
ALTER  PROCEDURE [sAudit].[pActivityLogGet]  
   
 @rUserName nvarchar(100),  
 @rScreenName nvarchar(100),  
 @rActivity nvarchar(100),  
 @rFromDate date,  
 @rToDate date,  
 @rStoreLocationId int=0,  
 @ViewLog Bit,  
 @SortColumnName NVARCHAR(MAX)= '',  
 @IsAscendingOrder bit= 0,  
 @PageNumber int = 1,  
 @PageSize int = 20,  
 @GlobalSearch NVARCHAR(MAX)= '',  
 @rOSType int  ,
 @rUserId bigint,
 @rScreenDetails NVARCHAR(100)= ''
  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
  
SET @rScreenName = sCommon.fSearchStringGet(@rScreenName)  
SET @rActivity = sCommon.fSearchStringGet(@rActivity)  
SET @rToDate = DATEADD(day,1,@rToDate)  
 
 ;WITH PageNumbers AS(  
 SELECT   
  ROW_NUMBER() OVER(  
   ORDER BY CASE WHEN @SortColumnName = 'SubLocationTitle' AND @IsAscendingOrder = 0 THEN SLM.Title END DESC,  
      CASE WHEN @SortColumnName = 'SubLocationTitle' AND @IsAscendingOrder = 1 THEN SLM.Title END,  
      CASE WHEN @SortColumnName = 'UserName' AND @IsAscendingOrder = 0 THEN ISNULL(U.DisplayTitle, '') END DESC,  
      CASE WHEN @SortColumnName = 'UserName' AND @IsAscendingOrder = 1 THEN ISNULL(U.DisplayTitle, '') END,  
      CASE WHEN @SortColumnName = 'OSType' AND @IsAscendingOrder = 0 THEN ISNULL(AL.OSType,'') END DESC,  
      CASE WHEN @SortColumnName = 'OSType' AND @IsAscendingOrder = 1 THEN ISNULL(AL.OSType,'') END,  
	  CASE WHEN @SortColumnName = 'ScreenDetails' AND @IsAscendingOrder = 0 THEN ISNULL(AL.ScreenDetail,'') END DESC,  
      CASE WHEN @SortColumnName = 'ScreenDetails' AND @IsAscendingOrder = 1 THEN ISNULL(AL.ScreenDetail,'') END, 
      CASE WHEN @SortColumnName = 'ScreenName' AND @IsAscendingOrder = 0 THEN (case when ISNULL(AL.SourceTypeId,2023)=2024 then R.Title else S.Title end) END DESC,  
      CASE WHEN @SortColumnName = 'ScreenName' AND @IsAscendingOrder = 1 THEN (case when ISNULL(AL.SourceTypeId,2023)=2024 then R.Title else S.Title end) END,  
      CASE WHEN @SortColumnName = 'AuditDate' AND @IsAscendingOrder = 0 THEN ISNULL(AL.AuditDate,'') END DESC,  
      CASE WHEN @SortColumnName = 'AuditDate' AND @IsAscendingOrder = 1 THEN ISNULL(AL.AuditDate,'') END,  
      CASE WHEN @SortColumnName = 'Activity' AND @IsAscendingOrder = 0 THEN AL.Activity END DESC,  
      CASE WHEN @SortColumnName = 'Activity' AND @IsAscendingOrder = 1 THEN AL.Activity END,  
      CASE WHEN @SortColumnName = 'RecordDetail' AND @IsAscendingOrder = 0 THEN ISNULL(AL.RecordDetail,'') END DESC,  
      CASE WHEN @SortColumnName = 'RecordDetail' AND @IsAscendingOrder = 1 THEN ISNULL(AL.RecordDetail,'') END,  
      CASE WHEN ISNULL(@SortColumnName,'') = '' THEN AL.AuditDate END DESC  
  ) ID,  
  COUNT(*) OVER() 'RecordCount',  
  
            AL.OrgId,  
            OM.Title AS OrganizationName,  
            AL.UserId,  
   U.DisplayTitle AS UserName,  
   U.LoginTitle,  
   U.SessionId,  
   CASE   
    WHEN AL.OSType = 1 THEN 'Android'  
    WHEN AL.OSType = 2 THEN 'IOS'  
    ELSE 'Web'  
   END as OSType,  
   case when ISNULL(AL.SourceTypeId,2023)=2024 then R.Title else S.Title end AS ScreenName,     
   AL.AuditDate,  
   AL.Activity,  
   AL.ScreenDetail, 
   ISNULL(AL.RecordSourceId,0) AS RecordSourceId,  
   ISNULL(AL.RecordDetail,'') AS RecordDetail,  
    SLM.Title as SubLocationTitle
       FROM          
       sAudit.tActivityLog AL  
       INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId  
    INNER JOin sSecurity.tUserLocation UL on UL.Userid=U.id 
    INNER JOIN sCommon.tCompanyInformation OM ON OM.Id = AL.OrgId  
    left JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId  
       left JOIN sCommon.tReport R ON R.Id = AL.ScreenId
	   inner join sIp.tStoreLocationMaster SLM on SLM.Id = UL.StoreLocationId
      WHERE   
    ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))  
    AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))  
AND (
       (@ViewLog = 0 AND AL.Activity NOT IN ('View', 'Search'))
    OR (@ViewLog = 1 AND AL.Activity IN ('View', 'Search'))
    ) 
    AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))  
    AND (AL.AuditDate >= @rFromDate)  
    AND (AL.AuditDate <= @rToDate)  
    AND ((AL.OSType LIKE @rOSType) OR (@rOSType = '')) 
    AND ((AL.ScreenDetail LIKE @rScreenDetails) OR (@rScreenDetails = '')) 

    AND
    (
        (@rStoreLocationId <> 0 AND UL.StoreLocationId = @rStoreLocationId)
        OR
        (
            @rStoreLocationId = 0
            AND EXISTS (
                SELECT 1
                FROM sSecurity.tUserLocation UL2
                WHERE UL2.UserId = @rUserId
                  AND UL2.StoreLocationId = UL.StoreLocationId
            )
        )
    )

    AND
    (
        ISNULL(@GlobalSearch,'') = ''
        OR U.DisplayTitle LIKE '%'+@GlobalSearch+'%'  
        OR ISNULL(S.Title, '') LIKE '%'+@GlobalSearch+'%'  
        OR ISNULL(AL.Activity,'') LIKE '%'+@GlobalSearch+'%'  
        OR CONVERT(VARCHAR, AL.AuditDate, 120) LIKE '%'+@GlobalSearch+'%'  
        OR OM.Title LIKE '%'+@GlobalSearch+'%'  
        OR AL.RecordDetail LIKE '%'+@GlobalSearch+'%'  
    )
    )  
 SELECT  *  
 FROM    PageNumbers  
 WHERE  (@PageSize = -1 OR ID  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize))   
END
GO
PRINT N'Altering Procedure [sAudit].[pActivityLogGetArchive]...';


GO
 CREATE OR ALTER PROCEDURE [sAudit].[pActivityLogGetArchive]   
 @rUserName nvarchar(100),  
 @rScreenName nvarchar(100),  
 @rActivity nvarchar(100),  
 @rFromDate date,  
 @rToDate date,  
 @rStoreLocationId int=0,  
 @ViewLog Bit,  
 @SortColumnName NVARCHAR(MAX)= '',  
 @IsAscendingOrder bit= 0,  
 @PageNumber int = 1,  
 @PageSize int = 20,  
 @GlobalSearch NVARCHAR(MAX)= '',  
 @rOSType int  ,
 @rScreenDetails NVARCHAR(100)= '',
 @rUserId bigint 
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
  
SET @rScreenName = sCommon.fSearchStringGet(@rScreenName)  
SET @rActivity = sCommon.fSearchStringGet(@rActivity)  
SET @rScreenDetails = sCommon.fSearchStringGet(@rScreenDetails)  
SET @rToDate = DATEADD(day,1,@rToDate)  
  
 ;WITH PageNumbers AS(  
 SELECT   
  ROW_NUMBER() OVER(  
   ORDER BY CASE WHEN @SortColumnName = 'SubLocationTitle' AND @IsAscendingOrder = 0 THEN SLM.Title END DESC,  
      CASE WHEN @SortColumnName = 'SubLocationTitle' AND @IsAscendingOrder = 1 THEN SLM.Title END,  
      CASE WHEN @SortColumnName = 'UserName' AND @IsAscendingOrder = 0 THEN ISNULL(U.DisplayTitle, '') END DESC,  
      CASE WHEN @SortColumnName = 'UserName' AND @IsAscendingOrder = 1 THEN ISNULL(U.DisplayTitle, '') END,  
      CASE WHEN @SortColumnName = 'OSType' AND @IsAscendingOrder = 0 THEN ISNULL(AL.OSType,'') END DESC,  
      CASE WHEN @SortColumnName = 'OSType' AND @IsAscendingOrder = 1 THEN ISNULL(AL.OSType,'') END,  
      CASE WHEN @SortColumnName = 'ScreenName' AND @IsAscendingOrder = 0 THEN (case when ISNULL(AL.SourceTypeId,2023)=2024 then R.Title else S.Title end) END DESC,  
      CASE WHEN @SortColumnName = 'ScreenName' AND @IsAscendingOrder = 1 THEN (case when ISNULL(AL.SourceTypeId,2023)=2024 then R.Title else S.Title end) END,  
      CASE WHEN @SortColumnName = 'AuditDate' AND @IsAscendingOrder = 0 THEN ISNULL(AL.AuditDate,'') END DESC,  
      CASE WHEN @SortColumnName = 'AuditDate' AND @IsAscendingOrder = 1 THEN ISNULL(AL.AuditDate,'') END,  
      CASE WHEN @SortColumnName = 'Activity' AND @IsAscendingOrder = 0 THEN AL.Activity END DESC,  
      CASE WHEN @SortColumnName = 'Activity' AND @IsAscendingOrder = 1 THEN AL.Activity END,  
      CASE WHEN @SortColumnName = 'RecordDetail' AND @IsAscendingOrder = 0 THEN ISNULL(AL.RecordDetail,'') END DESC,  
      CASE WHEN @SortColumnName = 'RecordDetail' AND @IsAscendingOrder = 1 THEN ISNULL(AL.RecordDetail,'') END,  
      CASE WHEN ISNULL(@SortColumnName,'') = '' THEN AL.AuditDate END DESC  
  ) ID,  
  COUNT(*) OVER() 'RecordCount',  
  
            AL.OrgId,  
            OM.Title AS OrganizationName,  
            AL.UserId,  
   U.DisplayTitle AS UserName,  
   U.LoginTitle,  
   U.SessionId,  
   CASE   
    WHEN AL.OSType = 1 THEN 'Android'  
    WHEN AL.OSType = 2 THEN 'IOS'  
    ELSE 'Web'  
   END as OSType,  
   case when ISNULL(AL.SourceTypeId,2023)=2024 then R.Title else S.Title end AS ScreenName,     
   AL.AuditDate,  
   AL.Activity,  
   ISNULL(AL.RecordSourceId,0) AS RecordSourceId,  
   ISNULL(AL.RecordDetail,'') AS RecordDetail,  
    SLM.Title as SubLocationTitle  
     
       FROM   
         
       sAudit.tActivityLogArchive AL  
       INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId  
    INNER JOin sSecurity.tUserLocation UL on UL.Userid=U.id and (@rStoreLocationId = 0 OR UL.StoreLocationId = @rStoreLocationId)  
    INNER JOIN sCommon.tCompanyInformation OM ON OM.Id = AL.OrgId  
    left JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId  
       left JOIN sCommon.tReport R ON R.Id = AL.ScreenId  
	   inner join sIp.tStoreLocationMaster SLM on SLM.Id = UL.StoreLocationId
       WHERE   
    ((U.DisplayTitle = @rUserName) OR (@rUserName = ''))  
    AND ((S.Title LIKE @rScreenName) OR (@rScreenName = ''))  
    AND (
       (@ViewLog = 0 AND AL.Activity NOT IN ('View', 'Search'))
    OR (@ViewLog = 1 AND AL.Activity IN ('View', 'Search'))
    ) 
    AND ((AL.Activity LIKE @rActivity) OR (@rActivity = ''))  
    AND (AL.AuditDate >= @rFromDate)  
    AND (AL.AuditDate <= @rToDate)  
    AND ((AL.OSType LIKE @rOSType) OR (@rOSType = '')) 
    AND ((AL.ScreenDetail LIKE @rScreenDetails) OR (@rScreenDetails = '')) 

    AND
    (
        (@rStoreLocationId <> 0 AND UL.StoreLocationId = @rStoreLocationId)
        OR
        (
            @rStoreLocationId = 0
            AND EXISTS (
                SELECT 1
                FROM sSecurity.tUserLocation UL2
                WHERE UL2.UserId = @rUserId
                  AND UL2.StoreLocationId = UL.StoreLocationId
            )
        )
    )

    AND
    (
        ISNULL(@GlobalSearch,'') = ''
        OR U.DisplayTitle LIKE '%'+@GlobalSearch+'%'  
        OR ISNULL(S.Title, '') LIKE '%'+@GlobalSearch+'%'  
        OR ISNULL(AL.Activity,'') LIKE '%'+@GlobalSearch+'%'  
        OR CONVERT(VARCHAR, AL.AuditDate, 120) LIKE '%'+@GlobalSearch+'%'  
        OR OM.Title LIKE '%'+@GlobalSearch+'%'  
        OR AL.RecordDetail LIKE '%'+@GlobalSearch+'%'  
    )
    )  
 SELECT  *  
 FROM    PageNumbers  
 WHERE  (@PageSize = -1 OR ID  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize))   
END
GO
PRINT N'Altering Procedure [sCommon].[pBlobStorageSizeGet]...';


GO
ALTER   PROC [sCommon].[pBlobStorageSizeGet] 
@rOrgId INT
WITH EXECUTE AS CALLER
AS
BEGIN
    SET NOCOUNT ON;

     SELECT 
         -- SUM(ISNULL(DocumentSize, 0)) / (1024.0 * 1024) AS TotalSizeGB,
      	  --SUM(ISNULL(DocumentSize, 0)) / 1024.0 AS TotalSizeMB,
      	  --SUM(ISNULL(DocumentSize, 0)) AS TotalSizeKB  
		  SUM(CAST(ISNULL(DocumentSize, 0) AS BIGINT) * 1024) AS TotalSizeBytes
      FROM 
          sCommon.tCloudUploadDocumentDetail 
      WHERE 
          OrgId = @rOrgId;

END
GO
PRINT N'Altering Procedure [sCommon].[pEmployeeSearchDetailGet]...';


GO
CREATE OR ALTER PROCEDURE [sCommon].[pEmployeeSearchDetailGet]
    @rSearchString [nvarchar](MAX),
    @rUserId       [nvarchar](MAX),
    @rOrgId        smallint
AS
BEGIN
    SET NOCOUNT ON;
 
    -- Local variables to avoid parameter sniffing (very helpful in SQL 2008)
    DECLARE @Search  nvarchar(MAX) = LTRIM(RTRIM(@rSearchString));
    DECLARE @UserId  nvarchar(MAX) = @rUserId;
    DECLARE @OrgId   smallint      = @rOrgId;
 
    SELECT DISTINCT TOP 10
        EM.Id AS EmployeeId,
        EM.Code AS EmployeeCode,
        (EM.FirstName + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '')) AS EmployeeName,
        GenderId,
        DateOfBirth,
        DateOfJoining,
        GM.Title AS Gender,
        StatusId,
        EM.IsObsolete,
        PhoneNoCompany,
        CompanyEmail,
        ExtensionNo,
        DepartmentId,
        DepartmentCode,
        DepartmentName,
        ISNULL(MobileNumber, 0) AS MobileNumber,
        EmployeeJobTitleId,
        EmployeeTypeId,
        EmployeeJobTitle,
        EmployeeLocationId,
        DATEDIFF(yy, DateOfBirth, sCommon.fGetDate()) AS Age,
        DesignationId,
        ProcessTypeId,
        ParticipantSourceTypeId,
        EI.EmployeePhoto
    FROM sHrm.vEmployeeDetail EM WITH (NOLOCK)
    INNER JOIN sIp.tStoreLocationMaster SLM WITH (NOLOCK) 
        ON SLM.LocationId = EM.EmployeeLocationId
    INNER JOIN sSecurity.tUserLocation UL WITH (NOLOCK) 
        ON UL.StoreLocationId = SLM.Id
    LEFT JOIN [sHrm].[tEmployeeImages] EI WITH (NOLOCK) 
        ON EM.EmployeeId = EI.EmployeeId
    LEFT JOIN sCommon.tGenderMaster GM WITH (NOLOCK) 
        ON GM.Id = EM.GenderId
    WHERE ((EM.Code        LIKE @Search + N'%')
        OR (EM.FirstName   LIKE @Search + N'%')
        OR (EM.LastName    LIKE @Search + N'%')
        OR (EM.MiddleName  LIKE @Search + N'%'))
      AND EM.OrgId = @OrgId
      AND UL.UserId = @UserId
    OPTION (RECOMPILE);
END
GO
PRINT N'Altering Procedure [sCommon].[pEmployeeSearchGet]...';


GO

CREATE OR ALTER PROCEDURE [sCommon].[pEmployeeSearchGet]
@rOrgId [int],
@rEmployeeCode [nvarchar](20) = '',
@rFirstName [nvarchar](30) = '',
@rMobileNumber [nvarchar](20) = '',
@rDOB [datetime] = '1/1/1900',
@rEmployeeLocationId int,
@rLastName [nvarchar](30) = '',
@rParticipantSourceTypeId int = 0,
@rDepartmentId int = 0,
@rEmployeeId bigint = 0,
@rEmployeeStoreLocationId int=0,
@rMiddleName varchar(200) = null,
@rIsIndividualWithOpd bit = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	declare @lLocationId int
	select @lLocationId = LocationId from sIp.tStoreLocationMaster where Id = @rEmployeeStoreLocationId
	select @lLocationId = isnull(@lLocationId,0)
	IF(@rParticipantSourceTypeId = 95 OR @rParticipantSourceTypeId = 0)
	BEGIN
		 
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rMobileNumber = sCommon.fSearchStringGet(@rMobileNumber)
		 
		Select * from
		(
			SELECT distinct OrgID,EM.Id,EmployeeId,EM.Code,
			FirstName,MiddleName,LastName,
			EmployeeName,GenderId,DateOfBirth,
			DateOfJoining,G.Title AS Gender,StatusId,
			EM.IsObsolete,PhoneNoCompany,CompanyEmail,
			ExtensionNo,DepartmentId,DepartmentCode,
			DepartmentName,ISNULL (MobileNumber,0) AS MobileNumber,
			EmployeeJobTitleId,EmployeeTypeId,EmployeeJobTitle,
			EmployeeLocationId, EmployeeStoreLocationId,isnull(DATEDIFF(yy,DateOfBirth,sCommon.fGetDate()),0) AS Age,
			DesignationId,ProcessTypeId,EM.ParticipantSourceTypeId,'Employee' as 'TypeName',
			EM.EmployeeCompanyId,
			EM.TargetGroupId,
			ISNULL(LDT.IsonSugarMedication, 0) IsonSugarMedication,
			ISNULL(LDT.IsonBPMedication, 0) IsonBPMedication,
			(Case When ISNULL(LDT.RiskCategoryId, 0) = 1 Then 1 Else 0 END) RiskCategoryChecked,
			em.CompanyEmail as Email
			FROM sHrm.vEmployeeDetail EM   -- changed view, DT- 11/01/2024; Mantis id =28791; Nidhi Pandey 
			LEFT JOIN sExamination.tLSDTrackerEmployee LDT ON LDT.ParticipantSourceId = EM.EmployeeId and LDT.ParticipantSourceTypeId = 95
			LEFT JOIN [sCommon].[tGenderMaster] G ON EM.GenderId = G.Id
			WHERE ((EM.Code = @rEmployeeCode) OR (@rEmployeeCode = ''))
			AND ((EM.FirstName Like  @rFirstName)  OR (ISNULL(@rFirstName,'') = ''))
			AND ((EM.LastName Like  @rLastName)  OR (ISNULL(@rLastName,'') = ''))
			AND ((EM.MiddleName Like  @rMiddleName)  OR (ISNULL(@rMiddleName,'') = ''))
			AND ((EM.MobileNumber Like @rMobileNumber) OR(ISNULL(@rMobileNumber,'') = ''))
			AND EM.IsObsolete = 0 AND EM.OrgId = @rOrgId
			AND ((EM.EmployeeLocationId = @rEmployeeLocationId) OR (ISNULL(@rEmployeeLocationId,0) = 0))
			AND ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
		) as a
	END
	ELSE IF(@rParticipantSourceTypeId = 1001)
	BEGIN
		SELECT distinct EFD.OrgId,EFD.DependentId,EFD.EmployeeCode AS Code,
		EFD.EmployeeId AS Id,EFD.Name AS EmployeeName,EFD.DateOfBirth,EFD.AGE,
		0 AS GenderId,EFD.DepartmentId,EFD.DepartmentName,0 AS MobileNumber,
		EFD.DesignationId,'' AS FirstName,'' AS LastName,
		1001 AS ParticipantSourceTypeId,'' as 'TypeName',0 as EmployeeCompanyId,EJD.EmployeeStoreLocationId
		FROM sHrm.vExtEmployeeFamilyDetail EFD
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EFD.EmployeeId
		Where (EFD.EmployeeCode Like @rEmployeeCode) AND EFD.DependentId = @rEmployeeId
		AND EFD.OrgId = @rOrgId AND (EFD.EmployeeLocationId = @rEmployeeLocationId or @rEmployeeLocationId = 0)
	END
	ELSE IF(@rParticipantSourceTypeId = 1009)
	BEGIN
		IF(@rIsIndividualWithOpd = 0)
		BEGIN
			SELECT distinct ECB.OrgId,EmployeeId AS Id,EmployeeId,ECB.Code,ECB.FirstName,
			ECB.LastName,ECB.EmployeeName,G.Title AS Gender,ECB.GenderId,ISNULL(ECB.DateOfBirth,'') AS DateOfBirth,
			'' AS DepartmentName,1009 AS ParticipantSourceTypeId,0 AS  DepartmentId,0 AS DesignationId,
			ISNULL(DATEDIFF(yy,ECB.DateOfBirth,sCommon.fGetDate()),0) AS Age,DATEDIFF(mm, ECB.DateOfBirth, sCommon.fGetDate()) % 12 as [Month],
			0 AS ProcessTypeId,ECB.OrgId,ECB.LocationId, ISNULL(CB.MobileNo,'') AS MobileNumber,'Other' as 'TypeName',0 as EmployeeCompanyId, 
			CB.MobileNo, CB.UIDNumber, ECB.CSRBenefiterTypeId, ECB.LocationId as EmployeeLocationId
			FROM sHrm.vExtCsrBenefiterMaster as ECB
			Inner Join sHrm.tCsrBenefiterMaster CB ON CB.Id = ECB.EmployeeId
			LEFT JOIN [sCommon].[tGenderMaster] G ON ECB.GenderId = G.Id
			WHERE (ECB.Code Like @rEmployeeCode) AND ECB.OrgId = @rOrgId
			AND (ECB.LocationId = @rEmployeeLocationId or @rEmployeeLocationId = 0)
			AND (ECB.LocationId = @lLocationId or @lLocationId = 0)
		END
		Else
		BEGIN
			SELECT distinct ECB.OrgId,EmployeeId AS Id,EmployeeId,ECB.Code,ECB.FirstName,
			ECB.LastName,ECB.EmployeeName,G.Title AS Gender,ECB.GenderId,ISNULL(ECB.DateOfBirth,'') AS DateOfBirth,
			'' AS DepartmentName,1009 AS ParticipantSourceTypeId,0 AS  DepartmentId,0 AS DesignationId,
			ISNULL(DATEDIFF(yy,ECB.DateOfBirth,sCommon.fGetDate()),0) AS Age,DATEDIFF(mm, ECB.DateOfBirth, sCommon.fGetDate()) % 12 as [Month],
			0 AS ProcessTypeId,ECB.OrgId,ECB.LocationId, ISNULL(CB.MobileNo,'') AS MobileNumber,'Other' as 'TypeName',0 as EmployeeCompanyId, 
			CB.MobileNo, CB.UIDNumber, ECB.CSRBenefiterTypeId, ECB.LocationId as EmployeeLocationId
			FROM sHrm.vExtCsrBenefiterMaster as ECB
			Inner Join sHrm.tCsrBenefiterMaster CB ON CB.Id = ECB.EmployeeId
			LEFT Join sHrm.tCsrBenefiterTypeMaster CBTM ON CBTM.Id = ECB.CSRBenefiterTypeId
			LEFT JOIN [sCommon].[tGenderMaster] G ON ECB.GenderId = G.Id
			WHERE (ECB.Code Like @rEmployeeCode) AND ECB.OrgId = @rOrgId
			AND (ECB.LocationId = @rEmployeeLocationId or @rEmployeeLocationId = 0)
			AND (ECB.LocationId = @lLocationId or @lLocationId = 0) and CBTM.IsOtherId = 1
		END
	END	
END
GO
PRINT N'Altering Procedure [sCommon].[pRangeDetailsGet]...';


GO


ALTER PROC [sCommon].[pRangeDetailsGet] @rRangeTableId int,@rOrgId int=1
AS
BEGIN

	Declare @lBPRangeCalculationVal nvarchar(10);

	select @lBPRangeCalculationVal = sConfig.fConfigurationValueGet('Examination.BPRangeCalculation',@rOrgId,0,0,0)

    DECLARE @TableOne TABLE (
        tId int IDENTITY (1, 1),
		Id int,
        FromRange nvarchar(100),
        ToRange nvarchar(100),
        Code nvarchar(100),
        Title nvarchar(100),
        IsObsolete nvarchar(100),
		Recommendation nvarchar(max)
    )

	 DECLARE @TableTwo TABLE (
        tId int IDENTITY (1, 1),
		Id int,
        SystolicmmHg nvarchar(100),
        DiastolicmmHg nvarchar(100),
        BloodPressureCategory nvarchar(100),
        Recommendation nvarchar(max),
        IsObsolete nvarchar(100)
    )

    IF (@rRangeTableId IN (1, 2, 3))
    BEGIN
        IF (@rRangeTableId = 1 AND @lBPRangeCalculationVal = 'Diastolic')
        BEGIN
            INSERT INTO @TableOne
                SELECT Id, FromRange, ToRange, Code, Title, CASE
                    WHEN IsObsolete = 0 THEN 'False'
                    ELSE 'True'
                END, Recommendation
                FROM sExamination.tBloodPressureRangeMaster
                ORDER BY id
        END
		ELSE IF (@rRangeTableId = 1 AND @lBPRangeCalculationVal = 'AHA')
        BEGIN
            INSERT INTO @TableTwo
                SELECT Id, SystolicmmHg, DiastolicmmHg, BloodPressureCategory, Recommendation, CASE
                    WHEN IsObsolete = 0 THEN 'False'
                    ELSE 'True'
                END
                FROM sExamination.tBloodPressureAHARangeMaster
                ORDER BY id
        END
		ELSE IF (@rRangeTableId = 1 AND @lBPRangeCalculationVal = 'IND')
        BEGIN
            INSERT INTO @TableTwo
                SELECT Id, SystolicmmHg, DiastolicmmHg, BloodPressureCategory, Recommendation, CASE
                    WHEN IsObsolete = 0 THEN 'False'
                    ELSE 'True'
                END
                FROM sExamination.tBloodPressureINDRangeMaster
                ORDER BY id
        END
        ELSE
        IF (@rRangeTableId = 2)
        BEGIN
            INSERT INTO @TableOne
                SELECT Id, FromRange, ToRange, Code, Title, CASE
                    WHEN IsObsolete = 0 THEN 'False'
                    ELSE 'True'
                END, Recommendation
                FROM sExamination.tBMIRangeMaster
                ORDER BY id
        END
        ELSE
        IF (@rRangeTableId = 3)
        BEGIN
            INSERT INTO @TableOne
                SELECT Id, FromRange, ToRange, Code, Title, CASE
                    WHEN IsObsolete = 0 THEN 'False'
                    ELSE 'True'
                END, Recommendation
                FROM sExamination.tAudiometryRangeMaster
                ORDER BY id
        END

		IF (@rRangeTableId = 1 AND (@lBPRangeCalculationVal = 'AHA' OR @lBPRangeCalculationVal = 'IND'))
		BEGIN
			--SELECT RangeDetails = '
			--					<td>    ' + CONVERT(varchar, tId) + '			</td>
			--					<td>    ' + ISNULL(FromRange, '') + '			</td>
			--					<td>    ' + ISNULL(ToRange, '') + '			</td>
			--					<td>    ' + ISNULL(Title, '') + '			</td>
			--					<td><input type="text" class="form-control" value="' + ISNULL(Recommendation, '') + '" id="Recommendation_' + CONVERT(NVARCHAR(10), Id) + '" />
			--					</td>
			--					' FROM @TableTwo
			SELECT RangeDetails = '<thead class="thead-light">
									<tr style="background-color: #f9f9f9;">
										<th align="left" scope="col" style="width: 10%;">Sr No</th>
										<th align="left" scope="col" style="width: 20%;">SYSTOLIC&nbsp;mm&nbsp;Hg&nbsp;(upper&nbsp;number)</th>
										<th align="left" scope="col" style="width: 20%;">DIASTOLIC&nbsp;mm&nbsp;Hg&nbsp;(lower&nbsp;number)</th>
										<th align="left" scope="col" style="width: 20%;">BLOOD&nbsp;PRESSURE&nbsp;CATEGORY</th>
										<th align="left" scope="col" style="width: 30%;">Recommendation</th>
									</tr>
								</thead>
								<tbody id="tblBloodPressureReadings">' 
								+ STUFF((
									SELECT 
										'</tr><tr>
											<td hidden>' + CONVERT(VARCHAR, Id) + '</td>
											<td>' + CONVERT(VARCHAR, tId) + '</td>
											<td>' + Systolic + '</td>
											<td>' + Diastolic + '</td>
											<td>' + Category + '</td>
											<td><input type="text" class="form-control" value="' + ISNULL(Recommendation, '') + '" id="Recommendation_' + CONVERT(NVARCHAR(10), Id) + '" /></td>
										</tr>'
									FROM (
										SELECT tId, Id, SystolicmmHg as Systolic, DiastolicmmHg as Diastolic, BloodPressureCategory as Category, Recommendation from @TableTwo
									) AS BPReadings
									ORDER BY Tid
									FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 5, '') 
								+ '</tbody>'
		END
		ELSE
		BEGIN
			SELECT RangeDetails = '
								<td hidden>' + CONVERT(VARCHAR, Id) + '</td>
								<td>    ' + CONVERT(varchar, tId) + '			</td>
								<td>    ' + ISNULL(FromRange, '') + '			</td>
								<td>    ' + ISNULL(ToRange, '') + '			</td>
								<td>    ' + ISNULL(Title, '') + '			</td>
								<td><input type="text" class="form-control" value="' + ISNULL(Recommendation, '') + '" id="Recommendation_' + CONVERT(NVARCHAR(10), Id) + '" />
								</td>
								' FROM @TableOne
			ORDER BY Tid
		END
        SELECT *
        FROM @TableOne
    END
    ELSE
    IF (@rRangeTableId IN (4))
    BEGIN
		Declare @lIsPulmonaryCalculationVal nvarchar(10);

		select @lIsPulmonaryCalculationVal = sConfig.fConfigurationValueGet('Examination.IsPulmonaryCalculation',@rOrgId,0,0,0)

        DECLARE @tPulmonaryObserved nvarchar(max) = ''
        DECLARE @tPulmonaryPredicting nvarchar(max) = ''
        DECLARE @tPulmonaryRangeMaster nvarchar(max) = ''

        SELECT @tPulmonaryObserved = @tPulmonaryObserved + '
		<tr><td>' + CONVERT(varchar, id) + '</td>
		<td>' + ISNULL(Title, '') + '</td>
		<td>' + ISNULL(Formula, '') + '</td></tr>'

        FROM sExamination.tPulmonaryObserved
        ORDER BY id

        SELECT @tPulmonaryPredicting = @tPulmonaryPredicting + '<tr>
			<td>' + CONVERT(varchar, ROW_NUMBER() OVER (Order by Id ASC)) + '</td>
			<td>' + CONVERT(varchar, ISNULL(Title, '')) + '</td>
			<td>' + CONVERT(varchar, ISNULL(AgeFrom, '')) + '</td>
			<td>' + CONVERT(varchar, ISNULL(AgeTo, '')) + '</td>
			<td>' + CONVERT(varchar, ISNULL(HightFrom, '')) + '</td>
			<td>' + CONVERT(varchar, ISNULL(HightTo, '')) + '</td>
			<td>' + CASE
            WHEN CONVERT(varchar, ISNULL(GenderId, '1')) = '1' THEN 'Male'
            ELSE 'Female'
        END + '</td>
			<td>' + CONVERT(nvarchar(max), ISNULL(Formula, '')) + '</td>
			</tr>'
        FROM sExamination.tPulmonaryPredicting
		Where (Config = @lIsPulmonaryCalculationVal or @lIsPulmonaryCalculationVal = '')
        ORDER BY id
        SELECT @tPulmonaryRangeMaster = @tPulmonaryRangeMaster + '<tr>
				<td>' + CONVERT(varchar, ROW_NUMBER() OVER (Order by Id) ) + '</td>
				<td>' + ISNULL(Condition, '') + '</td>
				<td>' + ISNULL(ConditionDetail, '') + '</td>
				<td>' + ISNULL(IntensityCondition, '') + '</td>
				<td>' + ISNULL(Intensity, '') + '</td>
				<td>' + ISNULL(Status, '') + '</td>
				</tr>'
        FROM sExamination.tPulmonaryRangeMaster
		Where (OrgId=case when @rOrgId=3001 then @rOrgId else 1 end)
        ORDER BY id

        DECLARE @TableExport nvarchar(max) = '<tr><td colspan="8">Pulmonary Observed Details:</td></tr>
                                              <tr>
												<td colspan="2">Sr No</td>
                                                <td colspan="3">Title</td>
                                                <td colspan="3">Formula</td>
                                              </tr>'



        SELECT @TableExport = @TableExport + '<tr><td colspan="2">' + CONVERT(varchar, id) + '</td>
		<td colspan="3">' + ISNULL(Title, '') + '</td><td colspan="3">' + ISNULL(Formula, '') + '</td></tr>'
        FROM sExamination.tPulmonaryObserved
        ORDER BY id


        SELECT @TableExport = @TableExport + '<tr><td colspan="8"></td></tr>
                                            <tr><td colspan="8"></td></tr>
                                            <tr><td colspan="8">Pulmonary Predicting Details:</td></tr>
											<tr><td>Sr No</td><td>Title</td><td>Age From</td><td>Age To</td>
                                            <td>Hight From</td><td>Hight To</td><td>Gender</td><td>Formula</td></tr>'

        SELECT @TableExport = @TableExport + '<tr>
					<td>' + CONVERT(varchar, ISNULL(Id, '')) + '</td>
					<td>' + CONVERT(varchar, ISNULL(Title, '')) + '</td>
					<td>' + CONVERT(varchar, ISNULL(AgeFrom, '')) + '</td>
					<td>' + CONVERT(varchar, ISNULL(AgeTo, '')) + '</td>
					<td>' + CONVERT(varchar, ISNULL(HightFrom, '')) + '</td>
					<td>' + CONVERT(varchar, ISNULL(HightTo, '')) + '</td>
					<td>' + CASE
            WHEN CONVERT(varchar, ISNULL(GenderId, '1')) = '1' THEN 'Male'
            ELSE 'Female'
        END + '</td>
					<td>' + CONVERT(varchar, ISNULL(Formula, '')) + '</td>
					</tr>'
        FROM sExamination.tPulmonaryPredicting
        ORDER BY id

        SELECT @TableExport = @TableExport + '<tr><td colspan="8"></td></tr><tr><td colspan="8">
		</td></tr><tr><td colspan="8">Pulmonary Range Details:</td></tr><tr><td>Sr No</td><td colspan="2">Condition</td>
		<td>Condition Detail</td><td colspan="2">Intensity Condition</td><td>Intensity</td><td>Status</td></tr>'

        SELECT @TableExport = @TableExport + ' <tr> <td>' + CONVERT(varchar, ROW_NUMBER() OVER (Order by Id)) + '</td>
				<td colspan="2">' + ISNULL(Condition, '') + '</td>
				<td>' + ISNULL(ConditionDetail, '') + '</td>
				<td colspan="2">' + ISNULL(IntensityCondition, '') + '</td>
				<td>' + ISNULL(Intensity, '') + '</td>
				<td>' + ISNULL(Status, '') + '</td> </tr>'
        FROM sExamination.tPulmonaryRangeMaster
		Where (OrgId=case when @rOrgId=3001 then @rOrgId else 1 end)
        ORDER BY id
        SELECT PulmonaryObserved = @tPulmonaryObserved, PulmonaryPredicting = @tPulmonaryPredicting, PulmonaryRangeMaster = @tPulmonaryRangeMaster, TableExport = @TableExport, LEN(@TableExport)
    END
    ELSE
    IF (@rRangeTableId IN (0))
    BEGIN
        SELECT RangeDetails = ''
    END
END
GO
PRINT N'Altering Procedure [sExamination].[pBulkOperationDiagnosisGenerateAll]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pBulkOperationDiagnosisGenerateAll]         
(        
 @rOrgId [int] = 0,           
 @rSetupGroupId [int] = 0,              
 @rSetupId [int] = 0       
)        
AS        
BEGIN        
           
  DECLARE @rExaminationId nvarchar(max) = ''  
  DECLARE @NewLineChar AS char(2) = CHAR(13) + CHAR(10)  
            
 DECLARE @lConfValue varchar(20)        
 SELECT TOP 1 @lConfValue = ISNULL(CS.ItemValue,CM.ItemValue)        
 FROM sConfig.tConfigurationMaster as CM        
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id        
 WHERE CM.ItemKey = 'Examination.IsStatusCompleteRestrict'   

  DECLARE @lConfValueDiagnosis varchar(20)        
	 --SELECT TOP 1 @lConfValueDiagnosis = ISNULL(CS.ItemValue,CM.ItemValue)        
	 --FROM sConfig.tConfigurationMaster as CM        
	 --LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id        
	 --WHERE CM.ItemKey = 'Examiation.AllowAutoUpdateDiagnosis'   
	      
 select @lConfValueDiagnosis = sConfig.fConfigurationValueGet('Examiation.AllowAutoUpdateDiagnosis',@rOrgId,0,0,0)      
 --select @lConfValueDiagnosis

 DECLARE @DiagnosisTable TABLE        
 (        
  tId int IDENTITY(1,1),rowid int,ExaminationId bigint,ParticipantCode nvarchar(50),        
  ParticipantName nvarchar(100),SetupId int,StatusId int,OrganizationDepartmentId int,        
  DiagnosisId bigint,DiagnosisRemark nvarchar(max),RecommendationEnglish nvarchar(max),        
  FitUnfitId int,StatusName nvarchar(100),IsPublish int,IsNewDiabetic bit,IsNewHyperTension bit,        
  IsDoneAudio bit,IsDonePulmo bit,Age varchar(10)        
 )        
 INSERT INTO @DiagnosisTable        
 SELECT * FROM        
 (        
  SELECT ROW_NUMBER() OVER (ORDER BY Exm.Id asc) AS rowid,        
  ExaminationId = Exm.Id,ParticipantCode = EM.Code,        
  ParticipantName = EM.FirstName + ' ' + EM.LastName,        
  SetupId = Exm.SetupId,Exm.StatusId,Exm.OrganizationDepartmentId,        
  ISNULL(D.Id, 0) AS DiagnosisId,D.DiagnosisRemark,D.RecommendationEnglish,        
  ISNULL(D.FitUnfitId, 0) AS FitUnfitId,        
  ST.Title + '<br/>' + case when @lConfValue='True' then case when Isnull(TGET.AutoId,0)>0 then case when (Isnull(A.IsDoneLeft,0) =1 or Isnull(A.IsDoneRight,0) =1) then 'A-Done' Else 'A-NotDone' End Else 'A-Done' End         
  + '<br/>' + case when Isnull(TGET1.AutoId,0)>0 then case when Isnull(P.IsDone,0) =1 then 'P-Done' Else 'P-NotDone' End Else 'P-Done' End Else '' END AS StatusName,        
  isnull(Exm.IsPublish,0) as IsPublish,isnull(IsNewDiabatic,0) as IsNewDiabatic,        
  isnull(IsNewHyperTension,0) as IsNewHyperTension,        
  case when Isnull(TGET.AutoId,0)>0 then case when (Isnull(A.IsDoneLeft,0) =1 or Isnull(A.IsDoneRight,0) =1) then 'True' Else 'False' End Else 'True' End as IsDoneAudio,        
  case when Isnull(TGET1.AutoId,0)>0 then case when Isnull(P.IsDone,0) =1 then 'True' Else 'False' End Else 'True' End as IsDonePulmo,        
  CONVERT(varchar,ISNULL(datediff(yy,DateOfBirth,getdate()), '')) Age        
  FROM sExamination.tExamination Exm        
  INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = Exm.ParticipantSourceId        
  LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId        
  LEFT JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.Id        
  INNER JOIN sExamination.tSetupMaster SM ON SM.Id = Exm.SetupId        
  LEFT JOIN sExamination.tDiagnosis D ON D.SourceId = Exm.Id        
  INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = Exm.StoreLocationId        
  LEFT JOIN sExamination.tStatusMaster ST ON Exm.StatusId = ST.Id        
  left join sExamination.tAudiometry A on A.SourceId=Exm.id and A.SourceTypeId=1002        
  left join sExamination.tPulmonary P on P.SourceId=Exm.Id and P.SourceTypeId=1002        
  left join sExamination.tTargetGroupExaminationTemplate TGET on TGET.TargetGroupId=Exm.TargetGroupId and TGET.MainTypeId=Exm.SetupId and TGET.SourceTemplateId=10162        
  left join sExamination.tTargetGroupExaminationTemplate TGET1 on TGET1.TargetGroupId=Exm.TargetGroupId and TGET1.MainTypeId=Exm.SetupId and TGET1.SourceTemplateId=10163         
  WHERE Exm.OrgId = @rOrgId             
  AND Exm.ParticipantSourceTypeId = 95          
  AND ((Exm.SetupId = @rSetupId) OR (@rSetupId = 0)) 
  AND ((SM.SetupGroupId = @rSetupGroupId) OR (@rSetupGroupId = 0))
 ) AS t ORDER BY t.ExaminationId DESC        
         
 SELECT @rExaminationId = COALESCE(@rExaminationId + ',', '') + CONVERT(varchar, ExaminationId) FROM @DiagnosisTable        
         
 DECLARE @tbltmpTestDetail TABLE        
 (        
  tid int IDENTITY(1,1),t_TestParameterId int,t_ServiceValue nvarchar(500),        
  t_DateOfBirth date,t_GenderId int,t_ParameterValueTypeId int,t_ListValueTypeId int,        
  t_TestType int,t_Age int,t_DetailId bigint,t_ExaminationId bigint,t_StaticTestParameterId int        
 )        
 INSERT INTO @tbltmpTestDetail        
 SELECT TPM.Id,TRD.ServiceValue,EP.DateOfBirth,EP.GenderId,TPM.ParameterValueTypeId,        
 TPM.ListValueTypeId,1,DATEDIFF(yy,EP.DateOfBirth,GETDATE()),TRD.Id,ED.Id,TPM.StaticTestParameterId        
 FROM sExamination.tExamination ED        
 INNER JOIN sHrm.tEmployeePersonalDetail EP ON ED.ParticipantSourceId = EP.EmployeeId        
 INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId        
 INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId        
 INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id        
 INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id        
 WHERE ED.Id IN (SELECT word FROM dbo.fnc_SplitWord(@rExaminationId, ',') WHERE word <> '')        
 AND TPM.ParameterValueTypeId IN (1, 2) AND TPM.IsObsolete = 0        
 AND ISNULL(TRD.ServiceValue, '') <> '' ORDER BY TPM.ParameterValueTypeId        
         
 INSERT INTO @tbltmpTestDetail        
 SELECT GP.Id,GED.ParameterValue,EP.DateOfBirth,EP.GenderId,GP.ParameterValueTypeId,0,2,        
 DATEDIFF(yy,EP.DateOfBirth,GETDATE()),GED.Id,ED.Id,0        
 FROM sExamination.tExamination ED        
 INNER JOIN sHrm.tEmployeePersonalDetail EP ON ED.ParticipantSourceId = EP.EmployeeId        
 INNER JOIN sExamination.tGeneralTemplateExamination GE ON ED.Id = GE.SourceId        
 INNER JOIN sExamination.tGeneralTemplateExaminationDetail GED ON GE.Id = GED.GeneralTemplateExaminationId        
 INNER JOIN sExamination.tGeneralTemplateParameter GP ON GED.GeneralTemplateParameterId = GP.Id        
 WHERE ED.Id IN (SELECT word FROM dbo.fnc_SplitWord(@rExaminationId, ',') WHERE word <> '')        
 AND GP.ParameterValueTypeId IN (1, 2) AND GP.IsObsolete = 0        
 AND ISNULL(GED.ParameterValue, '') <> '' ORDER BY GP.ParameterValueTypeId        
         
 DECLARE @tbltmpDiagnosis TABLE        
 (        
  tid int IDENTITY(1,1),d_DiagnosisRemark varchar(max),d_Recommendation varchar(max),        
  d_DetailId bigint,d_Type int,d_MainId bigint,d_ExaminationId bigint,d_StaticTestParameterId int        
 )        
 INSERT INTO @tbltmpDiagnosis        
 SELECT a.BMI,case when a.BMI='Overweight' OR a.BMI='Obese' then 'Reduce weight' else '' end,        
 0,0,0,a.ExaminationId,0        
 FROM        
 (        
  SELECT VTL.SourceId [ExaminationId],[sExamination].[fBMIValueGet](ISNULL(BMI, 0)) [BMI]        
  FROM sExamination.tVital AS VTL WHERE VTL.SourceId IN        
  (        
   SELECT word FROM dbo.fnc_SplitWord(@rExaminationId, ',') WHERE word <> ''        
  )        
 ) AS a WHERE ISNULL(a.BMI, '') <> 'Normal' AND a.BMI IS NOT NULL AND ISNULL(a.BMI, '') <> ''        
         
 UNION ALL        
         
 SELECT a.BloodPressure,RecommendationRemark,0,0,0,a.ExaminationId,0        
 FROM        
 (        
  SELECT VTL.SourceId [ExaminationId],        
  [sExamination].[fBMIBloodPressureResultGet](ISNULL(BloodPressureSystolic,0),ISNULL(BloodPressureDiastolic, 0),OrgId) [BloodPressure],        
  isnull((select RecommendationRemark from sExamination.tDiseaseHabitSetup where SourceId = sCommon.fGetIntIdForOrg(13,@rOrgId) and SourceTypeId = 3004        
  and [sExamination].[fBMIBloodPressureResultGet](ISNULL(BloodPressureSystolic,0),ISNULL(BloodPressureDiastolic, 0),OrgId) = 'Hypertension'),'')        
  as RecommendationRemark        
  FROM sExamination.tVital AS VTL WHERE VTL.SourceId IN        
  (        
   SELECT word FROM dbo.fnc_SplitWord(@rExaminationId, ',') WHERE word <> ''        
  )        
 ) AS a WHERE (ISNULL(a.BloodPressure, '') <> 'Normal' and ISNULL(a.BloodPressure, '') <> 'Optimal')AND a.BloodPressure IS NOT NULL      
 AND ISNULL(a.BloodPressure, '') <> ''        
         
 INSERT INTO @tbltmpDiagnosis        
 SELECT ISNULL(TPD.Diagnosis, ''),ISNULL(TPD.Recommendation, ''),TPD.Id,t_TestType,        
 t_DetailId,t_ExaminationId,t_StaticTestParameterId        
 FROM sOrderEntry.tTestParameterDetail TPD        
 INNER JOIN @tbltmpTestDetail TD ON TPD.TestParameterId = TD.t_TestParameterId        
 WHERE TPD.GenderId = TD.t_GenderId AND t_Age BETWEEN TPD.AgeFrom AND TPD.AgeTo        
 AND ISNULL(TPD.IsNormal, 0) = 0 AND TD.t_ParameterValueTypeId = 1 AND t_TestType = 1        
 AND CONVERT(decimal(18, 9), t_ServiceValue) BETWEEN CAST(TPD.Minimum AS decimal(12, 4)) AND CAST(TPD.Maximum AS decimal(12, 4))
 AND LTRIM(RTRIM(t_ServiceValue)) <> '+' AND t_ServiceValue NOT LIKE '%e%' AND t_ServiceValue NOT LIKE '%E%'
 AND ISNUMERIC(t_ServiceValue) = 1 AND ISNULL(TPD.Diagnosis, '') <> ''      
         
 INSERT INTO @tbltmpDiagnosis        
 SELECT ISNULL(DiagnosisRemark, ''),ISNULL(RecommendationRemark, ''),TLS.Id,t_TestType,        
 t_DetailId,t_ExaminationId,0        
 FROM sExamination.tTestListTypeSetup TLS        
 INNER JOIN @tbltmpTestDetail TD ON TLS.TestParameterId = TD.t_TestParameterId        
 INNER JOIN sOrderEntry.tListValueTypeMaster LVTM ON LVTM.Id = TD.t_ListValueTypeId        
 INNER JOIN sOrderEntry.tListValueMaster LV ON LV.ListValueTypeId = LVTM.Id AND LV.Id = TLS.ListValueId        
 WHERE TLS.IsNormal = 0 AND LV.Title LIKE TD.t_ServiceValue AND TD.t_ParameterValueTypeId = 2        
 AND t_TestType = 1 AND ISNULL(DiagnosisRemark, '') <> ''        
         
 INSERT INTO @tbltmpDiagnosis        
 SELECT ISNULL(Diagnosis, ''),ISNULL(Recommendation, ''),GETS.Id,t_TestType,t_DetailId,        
 t_ExaminationId,0        
 FROM sExamination.tGeneralTemplateParameterRange GETS        
 INNER JOIN @tbltmpTestDetail TD ON GETS.GeneralTemplateParameterId = TD.t_TestParameterId        
 WHERE GETS.GenderId = TD.t_GenderId AND TD.t_Age BETWEEN GETS.AgeFrom AND GETS.AgeTo        
 AND TD.t_ParameterValueTypeId = 1 AND t_TestType = 2        
 AND CONVERT(decimal(18, 9), t_ServiceValue) BETWEEN CAST(GETS.Minimum AS decimal(12, 4)) AND CAST(GETS.Maximum AS decimal(12, 4))        
 AND ISNUMERIC(t_ServiceValue) = 1 AND ISNULL(Diagnosis, '') <> ''        
         
 INSERT INTO @tbltmpDiagnosis        
 SELECT ISNULL(Diagnosis, ''),ISNULL(Recommendation, ''),GPL.Id,t_TestType,t_DetailId,        
 t_ExaminationId,0        
 FROM sExamination.tGeneralTemplateParameterList GPL        
 INNER JOIN @tbltmpTestDetail TD ON TD.t_TestParameterId = GPL.GeneralTemplateParameterId        
 WHERE GPL.IsNormal = 0 AND GPL.Title LIKE t_ServiceValue AND TD.t_ParameterValueTypeId = 2        
 AND t_TestType = 2 AND ISNULL(Diagnosis, '') <> ''        
         
 DECLARE @tbltmpHabitDiseaseDetail TABLE        
 (        
  tid int IDENTITY(1,1),hd_DetailId bigint,hd_SourceId int,hd_SourceTypeId int,hd_ExaminationId bigint        
 )        
 INSERT INTO @tbltmpHabitDiseaseDetail        
 SELECT HHD.Id,HHD.HabitId,239,E.Id        
 FROM sExamination.tExamination E        
 INNER JOIN sExamination.tHabitHygine HH ON E.Id = HH.SourceId        
 INNER JOIN sExamination.tHabitHygineDetail HHD ON HH.Id = HHD.HabitHygineId        
 WHERE E.Id IN        
 (        
  SELECT word FROM dbo.fnc_SplitWord(@rExaminationId, ',') WHERE word <> ''        
 )        
         
 UNION ALL        
         
 SELECT EDD.Id,EDD.DiseaseId,3004,E.Id        
 FROM sExamination.tExamination E        
 INNER JOIN sExamination.tExistingDisease ED ON E.Id = ED.SourceId        
 INNER JOIN sExamination.tExistingDiseaseDetail EDD ON ED.Id = EDD.ExistingDiseaseId        
 WHERE E.Id IN        
 (        
  SELECT word FROM dbo.fnc_SplitWord(@rExaminationId, ',') WHERE word <> ''        
 )        
         
 INSERT INTO @tbltmpDiagnosis        
 SELECT ISNULL(DiagnosisRemark, ''),ISNULL(RecommendationRemark, ''),t.hd_DetailId,3,        
 t.hd_DetailId,hd_ExaminationId,0        
 FROM sExamination.tDiseaseHabitSetup DHS        
 INNER JOIN @tbltmpHabitDiseaseDetail t ON DHS.SourceId = t.hd_SourceId        
 AND DHS.SourceTypeId = t.hd_SourceTypeId WHERE ISNULL(DiagnosisRemark, '') <> ''        
         
 INSERT INTO @tbltmpDiagnosis        
 SELECT AM.Title,'',0,5,0,A.SourceId,0        
 FROM sExamination.tAudiometry A        
 INNER JOIN sExamination.tAudiometryResultMaster AM ON A.AudiometryAcResultLeftId = AM.Id        
 WHERE A.SourceId IN        
 (        
  SELECT word FROM dbo.fnc_SplitWord(@rExaminationId, ',') WHERE word <> ''        
 ) AND AM.Id <> 1 AND AM.Title <> ''        
         
 UNION        
         
 SELECT AM.Title,'',0,5,0,A.SourceId,0        
 FROM sExamination.tAudiometry A        
 INNER JOIN sExamination.tAudiometryResultMaster AM ON A.AudiometryAcResultRightId = AM.Id        
 WHERE A.SourceId IN        
 (        
  SELECT word FROM dbo.fnc_SplitWord(@rExaminationId, ',') WHERE word <> ''        
 ) AND AM.Id <> 1 AND AM.Title <> ''        
         
 INSERT INTO @tbltmpDiagnosis        
 SELECT ISNULL(PulmonaryResulIntensity, '') + ' ' + ISNULL(PulmonaryResult, ''),'',0,6,0,        
 SourceId,0        
 FROM sExamination.tPulmonary WHERE SourceId IN        
 (        
  SELECT word FROM dbo.fnc_SplitWord(@rExaminationId, ',') WHERE word <> ''        
 ) AND PerOfPredictedFVC IS NOT NULL         
 --AND ISNULL(PulmonaryResulIntensity, '') <> ''        
 AND UPPER(ISNULL(PulmonaryResult, '')) <> 'NORMAL'        
         
 UPDATE TRD SET TRD.Diagnosis = t.d_DiagnosisRemark,TRD.Recommendation = t.d_Recommendation,        
 TRD.IsAbnormal = 1 FROM sExamination.tTestRequestDetail AS TRD        
 INNER JOIN @tbltmpDiagnosis AS t ON TRD.Id = d_MainId WHERE t.d_Type = 1        
         
 UPDATE GED SET GED.Diagnosis = t.d_DiagnosisRemark,GED.Recommendation = t.d_Recommendation,        
 GED.IsAbnormal = 1 FROM sExamination.tGeneralTemplateExaminationDetail GED        
 INNER JOIN @tbltmpDiagnosis AS t ON GED.Id = d_MainId WHERE t.d_Type = 2        
         
 DECLARE @tblMain TABLE        
 (        
  tid int IDENTITY(1,1),m_ExaminationId bigint,m_Diagnosis varchar(max),m_Recommendation varchar(max)        
 )        
         
 INSERT INTO @tblMain        
 SELECT DISTINCT d_ExaminationId,'','' FROM @tbltmpDiagnosis        
        
 declare @configval varchar(50)='Independent'        
 select @configval=ISNULL(CS.ItemValue,CM.ItemValue)         
 FROM sConfig.tConfigurationMaster CM        
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id         
 where CM.id=190        
 print @configval        
 DECLARE @cnt int, @i int        
         
 SELECT @i=1,@cnt=COUNT(*) FROM @tblMain        
         
 WHILE @i <= @cnt        
 BEGIN        
  DECLARE @lExaminationId bigint,@lDiagnosis varchar(max)='',@lRecommendation varchar(max)=''        
          
  SELECT @lExaminationId = m_ExaminationId FROM @tblMain WHERE tid = @i        
          
  if(@configval='Priority')        
   begin        
    -- For adani We have changes the priority MS 2019-04-09 (Abhi)        
    if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=25 and Isnull(d_DiagnosisRemark,'')<>'' and d_ExaminationId = @lExaminationId)        
     begin        
      Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,21) and d_ExaminationId = @lExaminationId        
     end        
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=19 and Isnull(d_DiagnosisRemark,'')<>'' and d_ExaminationId = @lExaminationId)        
     begin        
      Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (20,21) and d_ExaminationId = @lExaminationId        
     end        
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=20 and Isnull(d_DiagnosisRemark,'')<>'' and d_ExaminationId = @lExaminationId)        
     begin        
      Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (21) and d_ExaminationId = @lExaminationId        
     end        
        
    if exists        
     (select 1 FROM sExamination.tExamination ED                
     INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId        
     INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId        
     INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id        
     INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id and StaticTestParameterId=25        
     WHERE ED.Id IN (@lExaminationId)        
     and TRD.IsAbnormal = 0 and (Isnull(TRD.ServiceValue,'')<>'')        
     )        
      begin        
      Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,21) and d_ExaminationId = @lExaminationId        
      end        
    else if exists        
     (        
     select 1 FROM sExamination.tExamination ED                
     INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId        
     INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId        
     INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id        
     INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id and StaticTestParameterId=19        
     WHERE ED.Id IN (@lExaminationId)        
     and TRD.IsAbnormal = 0 and (Isnull(TRD.ServiceValue,'')<>'')        
     )        
      begin        
       Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (20,21) and d_ExaminationId = @lExaminationId        
      end        
    else if exists        
     (        
     select 1 FROM sExamination.tExamination ED                
     INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId        
     INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId        
     INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id        
     INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id and StaticTestParameterId=20        
     WHERE ED.Id IN (@lExaminationId)        
     and TRD.IsAbnormal = 0 and (Isnull(TRD.ServiceValue,'')<>'')        
     )        
      begin        
       Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (21) and d_ExaminationId = @lExaminationId        
      end        
        
   end        
  else if(@configval='Priority Abnormal')        
   begin        
    if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=25 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic' and d_ExaminationId = @lExaminationId)        
    begin        
     print 5        
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,21) and d_ExaminationId = @lExaminationId        
    end        
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=19 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic' and d_ExaminationId = @lExaminationId)        
    begin        
     print 6        
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (20,21,25) and d_ExaminationId = @lExaminationId        
    end        
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=20 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic' and d_ExaminationId = @lExaminationId)        
    begin        
     print 7        
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,21,25) and d_ExaminationId = @lExaminationId        
    end 
	else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=21 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic' and d_ExaminationId = @lExaminationId)        
    begin        
     print 8        
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,25) and d_ExaminationId = @lExaminationId        
    end        
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=25 and Isnull(d_DiagnosisRemark,'')<>'Diabetic' and d_ExaminationId = @lExaminationId)        
    begin        
     print 1        
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,21,20) and d_ExaminationId = @lExaminationId        
    end        
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=19 and Isnull(d_DiagnosisRemark,'')<>'Diabetic' and d_ExaminationId = @lExaminationId)        
    begin        
     print 2        
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (20,21,25) and d_ExaminationId = @lExaminationId        
    end        
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=20 and Isnull(d_DiagnosisRemark,'')<>'Diabetic' and d_ExaminationId = @lExaminationId)        
    begin        
     print 3        
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,21,25) and d_ExaminationId = @lExaminationId        
    end 
	else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=21 and Isnull(d_DiagnosisRemark,'')<>'Diabetic' and d_ExaminationId = @lExaminationId)        
    begin        
     print 4        
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,25) and d_ExaminationId = @lExaminationId        
    end         
   end        

   DECLARE @rIsDiabetic bit = 0, @rIsDiabeticExisting bit = 0, @rIsHypertension bit = 0 , @rIsHypertensionExisting bit = 0;
	 set @rIsDiabetic = (select top 1 1 from @tbltmpDiagnosis where d_DiagnosisRemark = 'Diabetic' and d_ExaminationId = @lExaminationId)
	 --set @rIsDiabeticExisting = (select top 1 1 from @tbltmpDiagnosis where d_DiagnosisRemark = 'Diabetic ( Existing )' and d_ExaminationId = @lExaminationId)
	 set @rIsDiabeticExisting = (select top 1 1 from sExamination.tExistingDisease ED
										INNER JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId = ED.Id
										INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = EDD.DiseaseId
										Where DM.StaticDiseaseId = 7 AND ED.SourceId = @lExaminationId)
	 set @rIsHypertension = (select top 1 1 from @tbltmpDiagnosis where (d_DiagnosisRemark = 'Hypertension' or d_DiagnosisRemark = 'Stage I HTN' or d_DiagnosisRemark = 'Stage II HTN' 
																		or d_DiagnosisRemark = 'Stage III HTN' or d_DiagnosisRemark = 'Hypertension Crisis') and d_ExaminationId = @lExaminationId)
	 --set @rIsHypertensionExisting = (select top 1 1 from @tbltmpDiagnosis where d_DiagnosisRemark = 'Hypertension ( Existing )' and d_ExaminationId = @lExaminationId)
	 set @rIsHypertensionExisting = (select top 1 1 from sExamination.tExistingDisease ED
										INNER JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId = ED.Id
										INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = EDD.DiseaseId
										Where DM.StaticDiseaseId = 13 AND ED.SourceId = @lExaminationId)

	 IF(@rIsDiabetic = 1 and ISNULL(@rIsDiabeticExisting, 0) <> 1)
	 BEGIN
			update sExamination.tDiagnosis set IsNewDiabatic = 1 where SourceId = @lExaminationId
			--set @rIsNewDiabatic = 1;
  	 END
	 ELSE
	 BEGIN
			update sExamination.tDiagnosis set IsNewDiabatic = 0 where SourceId = @lExaminationId
  	 END

	 IF(@rIsHypertension = 1 and ISNULL(@rIsHypertensionExisting, 0) <> 1)
	 BEGIN
			update sExamination.tDiagnosis set IsNewHyperTension = 1 where SourceId = @lExaminationId
			--set @rIsNewHyperTension = 1;
  	 END
	 ELSE
	 BEGIN
			update sExamination.tDiagnosis set IsNewHyperTension = 0 where SourceId = @lExaminationId
  	 END

	-- -- Dummy table to capture and discard result set
	--CREATE TABLE #dummy (reulst int, ResultStrin nvarchar(50));  -- Adjust column type to match actual output

	---- Discard the result
	--INSERT INTO #dummy
	--EXEC [sExamination].[pUpdateDiagnosis] @lExaminationId, @rIsNewDiabatic, @rIsNewHyperTension;

	--DROP TABLE #dummy;
        
  SELECT @lDiagnosis = @lDiagnosis + d_DiagnosisRemark + @NewLineChar        
  FROM @tbltmpDiagnosis WHERE d_ExaminationId = @lExaminationId        
          
  SELECT @lRecommendation = @lRecommendation + d_Recommendation + @NewLineChar        
  FROM (SELECT DISTINCT d_Recommendation FROM @tbltmpDiagnosis WHERE d_ExaminationId = @lExaminationId AND d_Recommendation <> ''  ) AS a        
          
  UPDATE @tblMain SET m_Diagnosis = @lDiagnosis, m_Recommendation = @lRecommendation        
  WHERE m_ExaminationId = @lExaminationId        
          
  SELECT @lDiagnosis = '', @lRecommendation = ''        
  SELECT @i = @i + 1        
 END        
         
 --select * from @tbltmpDiagnosis order by d_ExaminationId     
 IF (@lConfValueDiagnosis = 'true')
BEGIN
    UPDATE D
	 SET DiagnosisRemarkNew = m_Diagnosis,
        RecommendationEnglishNew = m_Recommendation
    FROM sExamination.tDiagnosis D
    INNER JOIN @tblMain t ON t.m_ExaminationId = D.SourceId
	INNER JOIN sExamination.tExamination E ON E.Id = D.SourceId
	where E.StatusId = 1
END
ELSE
BEGIN
    UPDATE D
       SET DiagnosisRemark = m_Diagnosis,
        RecommendationEnglish = m_Recommendation
    FROM sExamination.tDiagnosis D
    INNER JOIN @tblMain t ON t.m_ExaminationId = D.SourceId
	INNER JOIN sExamination.tExamination E ON E.Id = D.SourceId
	where E.StatusId = 1
END
Select 1 as tId 
 --SELECT dt.tId,dt.rowid,CauseId=dt.rowid,ParentExaminationId=dt.ExaminationId,        
 --dt.ParticipantCode,dt.ParticipantName,dt.SetupId,dt.StatusId,dt.OrganizationDepartmentId,        
 --Id=dt.DiagnosisId,Diagnosis=tm.m_Diagnosis,Recommendation=tm.m_Recommendation,        
 --dt.FitUnfitId,Status=dt.StatusName,DepartmentId=0,dt.IsPublish,dt.IsNewDiabetic as NewDiabatic,        
 --dt.IsNewHyperTension as NewHyperTension,dt.IsDoneAudio,dt.IsDonePulmo,dt.Age        
 --FROM @DiagnosisTable AS dt LEFT JOIN @tblMain tm ON dt.ExaminationId = tm.m_ExaminationId        
 --order by ParentExaminationId asc        
        
 END
GO
PRINT N'Altering Procedure [sExamination].[pDiagnosisAllResultGet]...';


GO

ALTER proc [sExamination].[pDiagnosisAllResultGet]
@rExaminationId bigint    
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
BEGIN
    Declare @rOrgId int;
    select @rOrgId = (select OrgId from sExamination.tExamination where Id = @rExaminationId);

    Declare @lBPRangeCalculationVal nvarchar(10);
	select @lBPRangeCalculationVal = sConfig.fConfigurationValueGet('Examination.BPRangeCalculation',@rOrgId,0,0,0)
     
    
    DECLARE @tbltmpTestDetail TABLE (tid int IDENTITY (1, 1),t_TestParameterId int,t_ServiceValue nvarchar(500),t_DateOfBirth date,t_GenderId int,t_ParameterValueTypeId int,t_ListValueTypeId int,t_TestType int,t_Age int,t_DetailId bigint,    
 t_ExaminationId bigint,t_StaticTestParameterId int)    
 DECLARE @tbltmpDiagnosis TABLE (tid int IDENTITY (1, 1),d_DiagnosisRemark varchar(max),d_Recommendation varchar(max),d_DetailId bigint,d_Type int,d_MainId bigint,d_ExaminationId bigint,d_StaticTestParameterId int)    
 DECLARE @tbltmpHabitDiseaseDetail TABLE (tid int IDENTITY (1, 1),hd_DetailId bigint,hd_SourceId int,hd_SourceTypeId int,hd_ExaminationId bigint)    
     
 INSERT INTO @tbltmpTestDetail    
        SELECT TPM.Id, TRD.ServiceValue, EP.DateOfBirth, EP.GenderId, TPM.ParameterValueTypeId, TPM.ListValueTypeId, 1,    
        DATEDIFF(yy, EP.DateOfBirth, GETDATE()), TRD.Id, ED.Id,TPM.StaticTestParameterId    
        FROM sExamination.tExamination ED    
        INNER JOIN sHrm.tEmployeePersonalDetail EP ON ED.ParticipantSourceId = EP.EmployeeId    
        INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId    
        INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId    
        INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id    
        INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id    
        WHERE ED.Id IN (SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> '')    
        AND TPM.ParameterValueTypeId IN (1, 2)    
        AND TPM.IsObsolete = 0    
        AND ISNULL(TRD.ServiceValue, '') <> ''    
        ORDER BY TPM.ParameterValueTypeId    
 INSERT INTO @tbltmpTestDetail    
        SELECT GP.Id, GED.ParameterValue, EP.DateOfBirth, EP.GenderId, GP.ParameterValueTypeId, 0, 2,    
        DATEDIFF(yy, EP.DateOfBirth, GETDATE()), GED.Id, ED.Id,null    
        FROM sExamination.tExamination ED    
        INNER JOIN sHrm.tEmployeePersonalDetail EP ON ED.ParticipantSourceId = EP.EmployeeId    
        INNER JOIN sExamination.tGeneralTemplateExamination GE ON ED.Id = GE.SourceId    
        INNER JOIN sExamination.tGeneralTemplateExaminationDetail GED ON GE.Id = GED.GeneralTemplateExaminationId    
        INNER JOIN sExamination.tGeneralTemplateParameter GP ON GED.GeneralTemplateParameterId = GP.Id    
        WHERE ED.Id IN (SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> '')    
        AND GP.ParameterValueTypeId IN (1, 2)    
        AND GP.IsObsolete = 0    
        AND ISNULL(GED.ParameterValue, '') <> ''    
        ORDER BY GP.ParameterValueTypeId   
		
    INSERT INTO @tbltmpDiagnosis

    SELECT a.BMI, case when (select isnull(bm.Recommendation,'') from sExamination.tBMIRangeMaster bm
				       where bm.Title = a.BMI) <> '' THEN (select isnull(bm.Recommendation,'') from sExamination.tBMIRangeMaster bm
				       where bm.Title = a.BMI) ELSE (case when a.BMI='Overweight' OR a.BMI='Obese' then 'Reduce weight' else '' end) end,
	0, 0, 0, a.ExaminationId,0
    FROM (SELECT    
        VTL.SourceId [ExaminationId],
        [sExamination].[fBMIValueGet](ISNULL(BMI, 0)) [BMI]    
    FROM sExamination.tVital AS VTL    
    WHERE VTL.SourceId IN (SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> '')) AS a    
    WHERE ISNULL(a.BMI, '') <> 'Normal' AND a.BMI IS NOT NULL    
    
    UNION ALL
    
    SELECT a.BloodPressure, case when
		@lBPRangeCalculationVal = 'AHA' then (case when (select isnull(aha.Recommendation,'') from sExamination.tBloodPressureAHARangeMaster aha
		where aha.BloodPressureCategory = a.BloodPressure) <> '' THEN (select isnull(aha.Recommendation,'') from sExamination.tBloodPressureAHARangeMaster aha
		where aha.BloodPressureCategory = a.BloodPressure) ELSE '' END) 
		when
		@lBPRangeCalculationVal = 'IND' then (case when (select isnull(ind.Recommendation,'') from sExamination.tBloodPressureINDRangeMaster ind
		where ind.BloodPressureCategory = a.BloodPressure) <> '' THEN (select isnull(ind.Recommendation,'') from sExamination.tBloodPressureINDRangeMaster ind
		where ind.BloodPressureCategory = a.BloodPressure) ELSE '' END)
		when
		@lBPRangeCalculationVal = 'Diastolic' then (case when (select isnull(dia.Recommendation,'') from sExamination.tBloodPressureRangeMaster dia
		where dia.Title = a.BloodPressure) <> '' THEN (select isnull(dia.Recommendation,'') from sExamination.tBloodPressureRangeMaster dia
		where dia.Title = a.BloodPressure) ELSE '' END)
		end,
	0, 0, 0, a.ExaminationId,0    
    FROM (SELECT VTL.SourceId [ExaminationId],    
        [sExamination].[fBMIBloodPressureResultGet](ISNULL(BloodPressureSystolic, 0), ISNULL(BloodPressureDiastolic, 0),OrgId) [BloodPressure]    
    FROM sExamination.tVital AS VTL    
    WHERE VTL.SourceId IN (SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> '')) AS a    
    WHERE (ISNULL(a.BloodPressure, '') <> 'Normal' AND ISNULL(a.BloodPressure, '') <> 'Optimal') AND a.BloodPressure IS NOT NULL    
    
    
    INSERT INTO @tbltmpDiagnosis    
        SELECT ISNULL(TPD.Diagnosis, ''), ISNULL(TPD.Recommendation, ''), TPD.Id, t_TestType, t_DetailId, t_ExaminationId,t_StaticTestParameterId    
        FROM sOrderEntry.tTestParameterDetail TPD    
        INNER JOIN @tbltmpTestDetail TD ON TPD.TestParameterId = TD.t_TestParameterId    
        WHERE TPD.GenderId = TD.t_GenderId    
        AND t_Age BETWEEN TPD.AgeFrom AND TPD.AgeTo    
        AND ISNULL(TPD.IsNormal, 0) = 0    
        AND TD.t_ParameterValueTypeId = 1    
        AND t_TestType = 1    
        AND CONVERT(decimal(18, 9), t_ServiceValue) BETWEEN CAST(TPD.Minimum AS decimal(12, 4)) AND CAST(TPD.Maximum AS decimal(12, 4))    
  and ISNUMERIC(t_ServiceValue)=1    
  AND t_ServiceValue <>'+'    
  AND ISNULL(TPD.Diagnosis, '')<>''     
    INSERT INTO @tbltmpDiagnosis    
        SELECT ISNULL(DiagnosisRemark, ''), ISNULL(RecommendationRemark, ''), TLS.Id, t_TestType, t_DetailId, t_ExaminationId,0    
        FROM sExamination.tTestListTypeSetup TLS    
        INNER JOIN @tbltmpTestDetail TD ON TLS.TestParameterId = TD.t_TestParameterId    
        INNER JOIN sOrderEntry.tListValueTypeMaster LVTM ON LVTM.Id = TD.t_ListValueTypeId    
        INNER JOIN sOrderEntry.tListValueMaster LV ON LV.ListValueTypeId = LVTM.Id AND LV.Id = TLS.ListValueId    
        WHERE TLS.IsNormal = 0    
        AND LV.Title LIKE TD.t_ServiceValue    
        AND TD.t_ParameterValueTypeId = 2    
        AND t_TestType = 1    
  AND ISNULL(DiagnosisRemark, '')<>''    
    INSERT INTO @tbltmpDiagnosis    
        SELECT ISNULL(Diagnosis, ''), ISNULL(Recommendation, ''), GETS.Id, t_TestType, t_DetailId, t_ExaminationId,0    
        FROM sExamination.tGeneralTemplateParameterRange GETS    
        INNER JOIN @tbltmpTestDetail TD ON GETS.GeneralTemplateParameterId = TD.t_TestParameterId    
        WHERE GETS.GenderId = TD.t_GenderId    
        AND TD.t_Age BETWEEN GETS.AgeFrom AND GETS.AgeTo    
        AND TD.t_ParameterValueTypeId = 1    
        AND t_TestType = 2    
        AND CONVERT(decimal(18, 9), t_ServiceValue) BETWEEN CAST(GETS.Minimum AS decimal(12, 4)) AND CAST(GETS.Maximum AS decimal(12, 4))    
  AND ISNUMERIC(t_ServiceValue)=1    
  AND ISNULL(Diagnosis, '')<>''    
    INSERT INTO @tbltmpDiagnosis    
    SELECT ISNULL(Diagnosis, ''), ISNULL(Recommendation, ''), GPL.Id, t_TestType, t_DetailId, t_ExaminationId,0    
    FROM sExamination.tGeneralTemplateParameterList GPL    
    INNER JOIN @tbltmpTestDetail TD ON TD.t_TestParameterId = GPL.GeneralTemplateParameterId    
    WHERE GPL.IsNormal = 0    
    AND GPL.Title LIKE t_ServiceValue    
    AND TD.t_ParameterValueTypeId = 2    
    AND t_TestType = 2    
 AND ISNULL(Diagnosis, '')<>''    
    INSERT INTO @tbltmpHabitDiseaseDetail    
        SELECT HHD.Id, HHD.HabitId, 239, E.Id    
        FROM sExamination.tExamination E     
  INNER JOIN sExamination.tHabitHygine HH ON E.Id = HH.SourceId    
        INNER JOIN sExamination.tHabitHygineDetail HHD ON HH.Id = HHD.HabitHygineId    
        WHERE E.Id IN (SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> '')    
        UNION ALL    
        SELECT EDD.Id, EDD.DiseaseId, 3004, E.Id    
        FROM sExamination.tExamination E    
        INNER JOIN sExamination.tExistingDisease ED ON E.Id = ED.SourceId    
        INNER JOIN sExamination.tExistingDiseaseDetail EDD ON ED.Id = EDD.ExistingDiseaseId    
        WHERE E.Id IN (SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> '')    
    INSERT INTO @tbltmpDiagnosis    
        SELECT ISNULL(DiagnosisRemark, ''), ISNULL(RecommendationRemark, ''), t.hd_DetailId, 3, t.hd_DetailId, hd_ExaminationId,0    
        FROM sExamination.tDiseaseHabitSetup DHS    
        INNER JOIN @tbltmpHabitDiseaseDetail t ON DHS.SourceId = t.hd_SourceId    
        AND DHS.SourceTypeId = t.hd_SourceTypeId    
  WHERE ISNULL(DiagnosisRemark, '')<>''    
     
     
 INSERT INTO @tbltmpDiagnosis    
  SELECT case when A.AudiometryAcResultLeftId=A.AudiometryAcResultRightId then AM.Title else 'Left Audiometry - '+AM.Title end, 
  case when (select isnull(arm.Recommendation,'') from sExamination.tAudiometryRangeMaster arm
		where arm.Title = AM.Title or (arm.title = 'Moderate-severe hearing loss' and AM.Title = 'Moderate to severe hearing loss')) <> '' THEN (select isnull(arm.Recommendation,'') from sExamination.tAudiometryRangeMaster arm
		where arm.Title = AM.Title or (arm.title = 'Moderate-severe hearing loss' and AM.Title = 'Moderate to severe hearing loss')) ELSE '' end,
  0, 5, 0, A.SourceId,0
        FROM sExamination.tAudiometry A    
        INNER JOIN sExamination.tAudiometryResultMaster AM ON A.AudiometryAcResultLeftId = AM.Id    
        WHERE A.SourceId IN (SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> '')          AND AM.Id <> 1    
  AND AM.Title<>''    
  UNION    
  SELECT case when A.AudiometryAcResultLeftId=A.AudiometryAcResultRightId then AM.Title else 'Right Audiometry - '+AM.Title end, 
  case when (select isnull(arm.Recommendation,'') from sExamination.tAudiometryRangeMaster arm
		where arm.Title = AM.Title or (arm.title = 'Moderate-severe hearing loss' and AM.Title = 'Moderate to severe hearing loss')) <> '' THEN (select isnull(arm.Recommendation,'') from sExamination.tAudiometryRangeMaster arm
		where arm.Title = AM.Title or (arm.title = 'Moderate-severe hearing loss' and AM.Title = 'Moderate to severe hearing loss')) ELSE '' end,
  0, 5, 0, A.SourceId,0    
FROM sExamination.tAudiometry A    
        INNER JOIN sExamination.tAudiometryResultMaster AM ON A.AudiometryAcResultRightId = AM.Id    
        WHERE A.SourceId IN (SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> '')    
        AND AM.Id <> 1    
  AND AM.Title<>''    
    
 INSERT INTO @tbltmpDiagnosis    
        SELECT  isnull(PulmonaryResulIntensity,'')+' '+isnull(PulmonaryResult,''), '', 0, 6, 0, SourceId,0    
        FROM sExamination.tPulmonary    
        WHERE SourceId IN (SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> '')    
  AND PerOfPredictedFVC IS NOt NULL     
  --AND isnull(PulmonaryResulIntensity,'')<>''     
  AND Upper(isnull(PulmonaryResult,''))<>'NORMAL'    
  
  -- Added BY MS For Testing Purpose For Mentis issue:23971
  --Select * from @tbltmpDiagnosis  
  --return  
	--UPDATE TRD SET TRD.Diagnosis = '',TRD.Recommendation = ''    
 --   FROM sExamination.tTestRequest TR 
 --   INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId 
	--Where TR.SourceId=@rExaminationId
-- Ended Change For Mentis issue:23971

    UPDATE TRD SET TRD.Diagnosis = t.d_DiagnosisRemark,TRD.Recommendation = t.d_Recommendation,TRD.IsAbnormal = 1    
    FROM sExamination.tTestRequestDetail AS TRD    
    INNER JOIN @tbltmpDiagnosis AS t ON TRD.Id = d_MainId    
    WHERE t.d_Type = 1    
 UPDATE GED SET GED.Diagnosis = t.d_DiagnosisRemark, GED.Recommendation = t.d_Recommendation,GED.IsAbnormal = 1    
    FROM sExamination.tGeneralTemplateExaminationDetail GED    
    INNER JOIN @tbltmpDiagnosis AS t ON GED.Id = d_MainId    
    WHERE t.d_Type = 2    
    
 declare @configval varchar(50)='Independent'    
 select @configval=ISNULL(CS.ItemValue,CM.ItemValue)     
 FROM sConfig.tConfigurationMaster CM    
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id     
 where CM.id=190    
     
 --select * from @tbltmpDiagnosis    
 print @configval    
 if(@configval='Priority')    
  begin    
     
   -- For adani We have changes the priority MS 2019-04-09 (Abhi)    
   if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=25 and Isnull(d_DiagnosisRemark,'')<>'')    
    begin    
     print 1    
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,21)    
    end    
   else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=19 and Isnull(d_DiagnosisRemark,'')<>'')    
    begin    
     print 2    
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (20,21)    
    end    
   else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=20 and Isnull(d_DiagnosisRemark,'')<>'')    
    begin    
     print 2    
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (21)    
    end    
    
   if exists    
    (select 1 FROM sExamination.tExamination ED            
    INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId    
    INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId    
    INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id    
    INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id and StaticTestParameterId=25    
    WHERE ED.Id IN (SELECT Distinct d_ExaminationId FROM @tbltmpDiagnosis)    
    and TRD.IsAbnormal = 0 and (Isnull(TRD.ServiceValue,'')<>'')    
    )    
     begin    
      print 3    
      Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,21)    
     end    
   else if exists    
     (    
     select 1 FROM sExamination.tExamination ED            
     INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId    
     INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId    
     INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id    
     INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id and StaticTestParameterId=19    
     WHERE ED.Id IN (SELECT Distinct d_ExaminationId FROM @tbltmpDiagnosis)    
     and TRD.IsAbnormal = 0 and (Isnull(TRD.ServiceValue,'')<>'')    
     )    
     begin    
      print 4    
      Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (20,21)    
     end    
   else if exists    
     (    
     select 1 FROM sExamination.tExamination ED            
     INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId    
     INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId    
     INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id    
     INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id and StaticTestParameterId=20    
     WHERE ED.Id IN (SELECT Distinct d_ExaminationId FROM @tbltmpDiagnosis)    
     and TRD.IsAbnormal = 0 and (Isnull(TRD.ServiceValue,'')<>'')    
     )    
     begin    
      print 4    
      Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (21)    
     end
  END    
 else if(@configval='Priority Abnormal')    
  begin    
    
   -- For adani We have changes the priority MS 2019-04-09 (dasSir,Rahul)12021    
   if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=25 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic')    
    begin    
     print 5    
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (21,19,20)    
    end    
   else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=19 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic')    
    begin    
     print 6   
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (20,21,25)    
    end    
   else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=20 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic')    
    begin    
     print 7    
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,21,25)    
    end  
	 else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=21 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic')    
    begin    
     print 8    
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,25)    
    end    
   else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=25 and Isnull(d_DiagnosisRemark,'')<>'Diabetic')    
    begin    
     print 1    
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (21,19,20)    
    end    
   else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=19 and Isnull(d_DiagnosisRemark,'')<>'Diabetic')    
    begin    
     print 2    
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (20,21,25)    
    end    
   else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=20 and Isnull(d_DiagnosisRemark,'')<>'Diabetic')    
    begin    
     print 3    
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,21,25)    
    end 
	else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=21 and Isnull(d_DiagnosisRemark,'')<>'Diabetic')    
    begin    
     print 4    
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,25)    
    end       
  end
  
  DECLARE @rIsDiabetic bit = 0, @rIsDiabeticExisting bit = 0, @rIsHypertension bit = 0 , @rIsHypertensionExisting bit = 0;
	 set @rIsDiabetic = (select top 1 1 from @tbltmpDiagnosis where d_DiagnosisRemark = 'Diabetic' and d_ExaminationId = @rExaminationId)
	 --set @rIsDiabeticExisting = (select top 1 1 from @tbltmpDiagnosis where d_DiagnosisRemark = 'Diabetic ( Existing )' and d_ExaminationId = @rExaminationId)
	 set @rIsDiabeticExisting = (select top 1 1 from sExamination.tExistingDisease ED
										INNER JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId = ED.Id
										INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = EDD.DiseaseId
										Where DM.StaticDiseaseId = 7 AND ED.SourceId = @rExaminationId)
	 set @rIsHypertension = (select top 1 1 from @tbltmpDiagnosis where (d_DiagnosisRemark = 'Hypertension' or d_DiagnosisRemark = 'Stage I HTN' or d_DiagnosisRemark = 'Stage II HTN' 
																		or d_DiagnosisRemark = 'Stage III HTN' or d_DiagnosisRemark = 'Hypertension Crisis')
																  and d_ExaminationId = @rExaminationId)
	 --set @rIsHypertensionExisting = (select top 1 1 from @tbltmpDiagnosis where d_DiagnosisRemark = 'Hypertension ( Existing )' and d_ExaminationId = @rExaminationId)
	 set @rIsHypertensionExisting = (select top 1 1 from sExamination.tExistingDisease ED
										INNER JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId = ED.Id
										INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = EDD.DiseaseId
										Where DM.StaticDiseaseId = 13 AND ED.SourceId = @rExaminationId)

	 IF(@rIsDiabetic = 1 and ISNULL(@rIsDiabeticExisting, 0) <> 1)
 	 BEGIN
			update sExamination.tDiagnosis set IsNewDiabatic = 1 where SourceId = @rExaminationId
			--set @rIsNewDiabatic = 1;
  	 END
	 ELSE
	 BEGIN
			update sExamination.tDiagnosis set IsNewDiabatic = 0 where SourceId = @rExaminationId
  	 END

	 IF(@rIsHypertension = 1 and ISNULL(@rIsHypertensionExisting, 0) <> 1)
	 BEGIN
			update sExamination.tDiagnosis set IsNewHyperTension = 1 where SourceId = @rExaminationId
			--set @rIsNewHyperTension = 1;
  	 END
	 ELSE
	 BEGIN
			update sExamination.tDiagnosis set IsNewHyperTension = 0 where SourceId = @rExaminationId
  	 END

	select DiagnosisRemark=d_DiagnosisRemark,RecommendationEnglish=d_Recommendation,DetailId=d_DetailId,TestParameterId=d_StaticTestParameterId  from @tbltmpDiagnosis    
    
	 --EXEC [sExamination].[pUpdateDiagnosis] @rExaminationId, @rIsNewDiabatic, @rIsNewHyperTension;
    
 --DECLARE @lCount int,@TestParameterId int,@TemplateParameterId int,@ParametertypeId int,@ParameterValue nvarchar(100)    
 --DECLARE @ServiceValue nvarchar(100),@DiagnosisRemark nvarchar(200),@RecommandationEnglish nvarchar(200),@ParameterValueTypeId int    
 --DECLARE @DateOfBirth date,@GenderId int,@ListValueTypeId int,@TestParameterDetailId bigint,@TestListSetupId int    
 --DECLARE @GeneralExamintionDetailId bigint,@ListValueId int,@1ListValueTypeId int,@1GeneralTemplateRangeId bigint    
 --DECLARE @1SourceId bigint --for DiseaseHabitSetup    
 --DECLARE @1SourceTypeId bigint --for DiseaseHabitSetup    
 --DECLARE @1SourceTypeDetailId bigint ----for DiseaseHabitSetup    
 --DECLARE @1QueryText nvarchar(max)    
 --DECLARE @1DiagnosisSetupId int    
 --DECLARE @1TestRequestDetailId bigint    
     
 ----TestSetup    
 --CREATE TABLE #tmpTestDetail    
 --(    
 -- Id int IDENTITY(1,1),TestParameterId int,ServiceValue nvarchar(100),DateOfBirth date,    
 -- GenderId int,ParameterValueTypeId int,ListValueTypeId int,TestRequestDetailId bigint    
 --)    
     
 --CREATE TABLE #tmpDiagnosis    
 --(    
 -- DiagnosisRemark nvarchar(max),RecommendationEnglish nvarchar(max),DetailId bigint,TestTypeId int    
 --)    
 --INSERT INTO #tmpTestDetail    
 --SELECT TPM.Id,case when isnumeric(ServiceValue)=1 then convert(varchar,ServiceValue) else '0' end,    
 --EPD.DateOfBirth,EPD.GenderId,TPM.ParameterValueTypeId,TPM.ListValueTypeId,TRD.Id    
 --FROM sExamination.tExamination E    
 --INNER JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95    
 --LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId    
 --INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.Id    
 --INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id AND (ISNULL(TRD.ServiceValue, '') != '')    
 --INNER JOIN sOrderEntry.tTestMaster TM ON TM.Id = TR.TestId    
 --INNER JOIN sOrderEntry.tTestDetail TD ON TD.TestId = TM.Id AND TD.Id = TRD.TestDetailId    
 --INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId    
 --WHERE E.Id = @rExaminationId AND TPM.ParameterValueTypeId IN (1, 2)    
     
 --UPDATE sExamination.tTestRequestDetail SET Diagnosis = '',    
 --Recommendation = '' WHERE Id IN (SELECT TestRequestDetailId FROM #tmpTestDetail)    
     
 --SELECT @lCount = COUNT(Id) FROM #tmpTestDetail    
     
 --INSERT INTO #tmpDiagnosis (DiagnosisRemark, RecommendationEnglish, DetailId)    
 --SELECT a.BMI,'',1    
 --FROM    
 --(    
 -- SELECT VTL.SourceId [ExaminationId],    
 -- [sExamination].[fBMIValueGet](ISNULL(BMI, 0)) [BMI]    
 -- FROM sExamination.tVital AS VTL    
 -- WHERE VTL.SourceId = @rExaminationId    
 --) AS a    
 --WHERE ISNULL(a.BMI, '') <> 'Normal' AND a.BMI IS NOT NULL    
      
 --UNION ALL    
     
 --SELECT a.BloodPressure,'',1    
 --FROM    
 --(    
 -- SELECT VTL.SourceId [ExaminationId],    
 -- [sExamination].[fBMIBloodPressureResultGet](ISNULL(BloodPressureSystolic, 0),    
 -- ISNULL(BloodPressureDiastolic, 0)) [BloodPressure]    
 -- FROM sExamination.tVital AS VTL    
 -- WHERE VTL.SourceId = @rExaminationId    
 --) AS a    
 --WHERE ISNULL(a.BloodPressure, '') <> 'Normal' AND a.BloodPressure IS NOT NULL    
      
 --WHILE @lCount > 0    
 --BEGIN    
 -- SET @DiagnosisRemark = ''    
 -- SET @RecommandationEnglish = ''    
      
 -- SELECT @TestParameterId = TestParameterId,    
 -- @ServiceValue = ServiceValue,    
 -- @DateOfBirth = DateOfBirth,    
 -- @GenderId = GenderId,    
 -- @1TestRequestDetailId = TestREquestDetailId,    
 -- @ParameterValueTypeId = ParameterValueTypeId,    
 -- @ListValueTypeId = ListValueTypeId    
 -- FROM #tmpTestDetail WHERE Id = @lCount    
      
 -- IF (@ParameterValueTypeId = 1)    
 -- BEGIN    
 --  SELECT @DiagnosisRemark = ISNULL(TPD.Diagnosis, ''),    
 --  @RecommandationEnglish = ISNULL(TPD.Recommendation, ''),    
 --  @TestParameterDetailId = TPD.Id    
 --  FROM sOrderEntry.tTestParameterDetail TPD    
 --  WHERE TPD.TestParameterId = @TestParameterId AND TPD.GenderId = @GenderId    
 --  AND DATEDIFF(YY, @DateOfBirth, GETDATE()) BETWEEN TPD.AgeFrom AND TPD.AgeTo    
 --  AND (ISNULL(TPD.IsNormal, 0) = 0    
 --  AND CAST(@ServiceValue AS decimal(12, 4)) BETWEEN CAST(TPD.Minimum AS decimal(12, 4))    
 --  AND CAST(TPD.Maximum AS decimal(12, 4)))    
       
 --  IF NOT EXISTS (SELECT 1 FROM #tmpDiagnosis WHERE DetailId = @TestParameterDetailId)    
 --  BEGIN    
 --   INSERT INTO #tmpDiagnosis (DiagnosisRemark, RecommendationEnglish, DetailId)    
 --   VALUES (@DiagnosisRemark, @RecommandationEnglish, @TestParameterDetailId)    
 --  END    
 -- END    
 -- IF (@ParameterValueTypeId = 2)    
 -- BEGIN    
 --  SELECT @DiagnosisRemark = DiagnosisRemark,    
 --  @RecommandationEnglish = RecommendationRemark,    
 --  @TestListSetupId = TLS.Id    
 --  FROM sExamination.tTestListTypeSetup TLS    
 --  INNER JOIN sOrderEntry.tListValueTypeMaster LVTM ON LVTM.Id = @ListValueTypeId    
 --  INNER JOIN sOrderEntry.tListValueMaster LV ON LV.ListValueTypeId = LVTM.Id AND LV.Id = TLS.ListValueId    
 --  WHERE TLS.TestParameterId = @TestParameterId AND TLS.IsNormal = 0 AND LV.Title LIKE @ServiceValue    
       
 --  IF NOT EXISTS (SELECT 1 FROM #tmpDiagnosis WHERE DetailId = @TestListSetupId AND TestTypeId = 1)    
 --  BEGIN    
 --   INSERT INTO #tmpDiagnosis (DiagnosisRemark, RecommendationEnglish, DetailId, TestTypeId)    
 --   VALUES (@DiagnosisRemark, @RecommandationEnglish, @TestListSetupId, 1)    
 --  END    
 -- END    
 -- IF (@DiagnosisRemark != '' OR @RecommandationEnglish != '')    
 -- BEGIN    
 --  UPDATE sExamination.tTestRequestDetail SET Diagnosis = @DiagnosisRemark,    
 --  Recommendation = @RecommandationEnglish, IsAbnormal = 1    
 --  WHERE Id = @1TestRequestDetailId    
 -- END    
 -- SET @lCount = @lCount - 1    
 --END    
     
 ----GeneralExaminationSetup    
 --CREATE TABLE #tmpGeneralExaminationDetail    
 --(    
 -- Id int IDENTITY(1,1),ParameterId int,ParameterValue nvarchar(100),    
 -- ParameterValueTypeId int,GeneralExamintionDetailId bigint,DateOfBirth date,GenderId int    
 --)    
 --INSERT INTO #tmpGeneralExaminationDetail    
 --SELECT GETD.GeneralTemplateParameterId,    
 --GETD.ParameterValue,    
 --GTP.ParameterValueTypeId,    
 --GETD.Id,    
 --EPD.DateOfBirth,EPD.GenderId    
 --FROM sExamination.tExamination E    
 --INNER JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95    
 --LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId    
 --INNER JOIN sExamination.tGeneralTemplateExamination GTE ON GTE.SourceId = E.Id    
 --INNER JOIN sExamination.tGeneralTemplateExaminationDetail GETD ON GETD.GeneralTemplateExaminationId = GTE.Id    
 --INNER JOIN sExamination.tGeneralTemplateMaster GETM ON GETM.Id = GTE.GeneralTemplateId    
 --INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GETD.GeneralTemplateParameterId    
 --WHERE GTE.SourceId = @rExaminationId AND ISNULL(Parametervalue, '') != ''    
     
 --SELECT @lCount = COUNT(Id) FROM #tmpGeneralExaminationDetail    
     
 --WHILE @lCount > 0    
 --BEGIN    
 -- SET @DiagnosisRemark = ''    
 -- SET @RecommandationEnglish = ''    
      
 -- SELECT @GeneralExamintionDetailId = GeneralExamintionDetailId,    
 -- @TemplateParameterId = ParameterId,@ParametertypeId = ParameterValueTypeId,    
 -- @ParameterValue = ParameterValue, @DateOfBirth = DateOfBirth, @GenderId = GenderId    
 -- FROM #tmpGeneralExaminationDetail WHERE Id = @lCount    
      
 -- IF (@ParametertypeId = 1)    
 -- BEGIN    
 --  SELECT @DiagnosisRemark = Diagnosis,@RecommandationEnglish = Recommendation,    
 --  @1GeneralTemplateRangeId = GETS.Id    
 --  FROM sExamination.tGeneralTemplateParameterRange GETS    
 --  WHERE GETS.GeneralTemplateParameterId = @TemplateParameterId    
 --  AND GETS.GenderId = @GenderId    
 --  AND DATEDIFF(YY, @DateOfBirth, GETDATE()) BETWEEN GETS.AgeFrom AND GETS.AgeTo    
 --  AND (ISNULL(GETS.IsNormal, 0) = 0    
 --  AND CAST(@ParameterValue AS decimal(12, 4)) BETWEEN CAST(GETS.Minimum AS decimal(12, 4))    
 --  AND CAST(GETS.Maximum AS decimal(12, 4)))    
       
 --  IF NOT EXISTS (SELECT 1 FROM #tmpDiagnosis WHERE DetailId = @1GeneralTemplateRangeId)    
 --  BEGIN    
 --   INSERT INTO #tmpDiagnosis (DiagnosisRemark, RecommendationEnglish, DetailId, TestTypeId)    
 --   VALUES (@DiagnosisRemark, @RecommandationEnglish, @1GeneralTemplateRangeId, 2)    
 --  END    
 -- END    
 -- IF (@ParametertypeId = 2)    
 -- BEGIN    
 --  SELECT @DiagnosisRemark = Diagnosis,@RecommandationEnglish = Recommendation,    
 --  @TestListSetupId = GPL.Id    
 --  FROM sExamination.tGeneralTemplateParameterList GPL    
 --  WHERE GPL.GeneralTemplateParameterId = @TemplateParameterId    
 --  AND GPL.IsNormal = 0 AND GPL.Title LIKE @ParameterValue    
       
 --  IF NOT EXISTS (SELECT 1 FROM #tmpDiagnosis WHERE DetailId = @TestListSetupId AND TestTypeId = 2)    
 --  BEGIN    
 --   INSERT INTO #tmpDiagnosis (DiagnosisRemark, RecommendationEnglish, DetailId, TestTypeId)    
 --   VALUES (@DiagnosisRemark, @RecommandationEnglish, @TestListSetupId, 1)    
 --  END    
 -- END    
 -- IF (@DiagnosisRemark != '' OR @RecommandationEnglish != '')    
 -- BEGIN    
 --  UPDATE sExamination.tGeneralTemplateExaminationDetail    
 --  SET Diagnosis = @DiagnosisRemark,Recommendation = @RecommandationEnglish,IsAbnormal = 1    
 --  WHERE Id = @GeneralExamintionDetailId    
 -- END    
 -- SET @lCount = @lCount - 1    
 --END    
     
 ----DiseaseHabitSetup    
     
 --CREATE TABLE #tmpDiseaseHabitDetail    
 --(    
 -- Id int IDENTITY(1,1),DetailId bigint,SourceId bigint,SourceTypeId int    
 --)    
 --INSERT INTO #tmpDiseaseHabitDetail    
 --SELECT HHD.Id AS DetailId,HHD.HabitId AS SourceId,239 AS SourceTypeId    
 --FROM sExamination.tExamination E    
 --INNER JOIN sExamination.tHabitHygine HH ON HH.SourceId = E.Id    
 --INNER JOIN sExamination.tHabitHygineDetail HHD ON HHD.HabitHygineId = HH.Id    
 --WHERE HH.SourceId = @rExaminationId    
     
 --UNION ALL    
     
 --SELECT EDD.Id AS DetailId,EDD.DiseaseId AS SourceId,3004 AS SourceTypeId    
 --FROM sExamination.tExamination E    
 --INNER JOIN sExamination.tExistingDisease ED ON ED.SourceId = E.Id    
 --INNER JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId = ED.Id    
 --WHERE ED.SourceId = @rExaminationId    
     
 --SELECT @lCount = COUNT(Id) FROM #tmpDiseaseHabitDetail    
     
 --WHILE @lCount > 0    
 --BEGIN    
 -- SELECT @1SourceTypeDetailId = DetailId,@1SourceId = SourceId,@1SourceTypeId = SourceTypeId    
 -- FROM #tmpDiseaseHabitDetail WHERE Id = @lCount    
      
 -- SELECT @DiagnosisRemark = DiagnosisRemark,@RecommandationEnglish = RecommendationRemark    
 -- FROM sExamination.tDiseaseHabitSetup DHS WHERE DHS.SourceId = @1SourceId    
 -- AND DHS.SourceTypeId = @1SourceTypeId    
      
 -- INSERT INTO #tmpDiagnosis (DiagnosisRemark, RecommendationEnglish, DetailId, TestTypeId)    
 -- VALUES (@DiagnosisRemark, @RecommandationEnglish, @1SourceTypeDetailId, 3)    
      
 -- SET @lCount = @lCount - 1    
 --END    
     
 ----AudiometryResult    
     
 --BEGIN    
 -- SELECT @1SourceTypeDetailId = DetailId,@1SourceId = SourceId,@1SourceTypeId = SourceTypeId    
 -- FROM #tmpDiseaseHabitDetail WHERE Id = @lCount    
      
 -- SELECT @DiagnosisRemark = ISNULL(ARM.Title, '')    
 -- FROM sExamination.tAudiometry A    
 -- INNER JOIN sExamination.tAudiometryResultMaster ARM ON ARM.Id = A.AudiometryAcResultLeftId    
 -- WHERE A.SourceId = @rExaminationId AND ARM.Id != 1    
      
 -- INSERT INTO #tmpDiagnosis (DiagnosisRemark, RecommendationEnglish, DetailId, TestTypeId)    
 -- VALUES (@DiagnosisRemark, '', 1, 5)    
      
 -- SELECT @DiagnosisRemark = ISNULL(ARM2.Title, '')    
 -- FROM sExamination.tAudiometry A    
 -- INNER JOIN sExamination.tAudiometryResultMaster ARM2 ON ARM2.Id = A.AudiometryAcResultRightId    
 -- WHERE A.SourceId = @rExaminationId AND ARM2.Id != 1    
      
 -- INSERT INTO #tmpDiagnosis (DiagnosisRemark, RecommendationEnglish, DetailId, TestTypeId)    
 -- VALUES (@DiagnosisRemark, '', 1, 5)    
      
 -- SET @DiagnosisRemark = ''    
 --END    
     
 ----Pulmonary    
     
 --BEGIN    
 -- SELECT @DiagnosisRemark = P.PulmonaryResulIntensity + ' ' + P.PulmonaryResult    
 -- FROM sExamination.tPulmonary P WHERE P.SourceId = @rExaminationId    
      
 -- INSERT INTO #tmpDiagnosis (DiagnosisRemark, RecommendationEnglish, DetailId, TestTypeId)    
 -- VALUES (@DiagnosisRemark, '', 1, 6)    
 --END    
     
 ----DiagnosisSetupMaster    
     
 --CREATE TABLE #tmpDiagnosisSetup    
 --(    
 -- Id int IDENTITY(1,1),DiagnosisSetupId int,QueryText nvarchar(max),    
 -- DiagnosisRemark nvarchar(max),RecommandationEnglish nvarchar(max)    
 --)    
 --INSERT INTO #tmpDiagnosisSetup    
 --SELECT Id, QueryText + CONVERT(nvarchar(50), @rExaminationId),    
 --DiagnosisRemark,RecommendationEnglish    
 --FROM sExamination.tDiagnosisSetup WHERE IsObsolete = 0    
     
 --SELECT @lCount = COUNT(Id) FROM #tmpDiagnosisSetup    
     
 --WHILE @lCount > 0    
 --BEGIN    
 -- SELECT @1DiagnosisSetupId = DiagnosisSetupId, @1QueryText = QueryText,    
 -- @DiagnosisRemark = DiagnosisRemark,@RecommandationEnglish = RecommandationEnglish    
 -- FROM #tmpDiagnosisSetup WHERE Id = @lCount    
      
 -- IF (@1QueryText != NULL)    
 -- BEGIN    
 --  DECLARE @TEMPDIAG TABLE (ID int)    
 --  INSERT INTO @TEMPDIAG    
 --  EXEC (@1QueryText)    
       
 --  IF EXISTS (SELECT 1 FROM @TEMPDIAG)    
 --  BEGIN    
 --   INSERT INTO #tmpDiagnosis (DiagnosisRemark, RecommendationEnglish, DetailId, TestTypeId)    
 --   VALUES (@DiagnosisRemark, @RecommandationEnglish, @1DiagnosisSetupId, 4)    
 --  END    
 -- END    
 -- SET @lCount = @lCount - 1    
 --END    
 --SELECT DiagnosisRemark, RecommendationEnglish,DetailId    
 --FROM #tmpDiagnosis WHERE (ISNULL(DiagnosisRemark, '') != '')    
 --AND ISNULL(DetailId, 0) != 0    
    
 --DECLARE @rExaminationId nvarchar(max) = '9999000003875'    
    
    
    
    
END
GO
PRINT N'Altering Procedure [sExamination].[pDiagnosisAnalysisSearch]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pDiagnosisAnalysisSearch]
 @rMaINTypeId INT,  
 @rOrgId INT,
 @rSetupGroupId INT,  
 @rSetupId INT,  
 @rSectorId INT,  
 @rVerticalId INT,  
 @rCompanyGroupId INT,  
 @rEmployeeCompanyId INT,  
 @rLocationMainGroupId INT,  
 @rLocationSubGroupId INT,  
 @rLocationId INT,  
 @rStoreLocationId INT,  
 @rFunctionId INT,  
 @rDepartmentGroupId INT,  
 @rDepartmentId INT,  
 @rEmployeeCode VARCHAR(100),  
 @rEmployeeFname VARCHAR(100),  
 @rEmployeeLname VARCHAR(100),  
 @rFromDate varchar(100),  
 @rToDate varchar(100),  
 @rTargetGroupId NVarchar(MAX)='',  
 @rmtype INT,  
 @rUserId bigint,  
 @rIsActiveHealth int,  
 @rIsOPDSetup int,  
 @rDojfromDate varchar(20)='',  
 @rDOJtoDate varchar(20)='',
 @rIsBusinessWise bit = 0
WITH EXECUTE AS CALLER
AS  
SET NOCOUNT ON     
BEGIN

DECLARE @lExcludeExistingOrNewRecordsFromTracker varchar(5);
      
select @lExcludeExistingOrNewRecordsFromTracker = sConfig.fConfigurationValueGet('Diagnosis.ExcludeExistingOrNewRecordsFromTracker',@rOrgId,0,0,0);

 DECLARE @rFlag int =1  
 SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)  
 SET @rEmployeeFname = sCommon.fSearchStringGet(@rEmployeeFname)  
 SET @rEmployeeLname = sCommon.fSearchStringGet(@rEmployeeLname)  
   
 IF(@rToDate='')  
 BEGIN  
  SET @rToDate='01/06/2050'  
 END  
 IF(@rDOJtoDate='')  
 BEGIN  
  SET @rDOJtoDate=sCommon.fGetDate()  
 END  
 select @rFromDate = CONVERT(VARCHAR(10), CONVERT(date, @rFromDate, 105), 23)  
 select @rToDate = CONVERT(VARCHAR(10), CONVERT(date, @rToDate, 105), 23)  
 select @rDojfromDate = CONVERT(VARCHAR(10), CONVERT(date, @rDojfromDate, 105), 23)  
 select @rDOJtoDate = CONVERT(VARCHAR(10), CONVERT(date, @rDOJtoDate, 105), 23)  
   
 DECLARE @TableOne TABLE  
 (  
  tId int IDENTITY(1,1),GroupId int,GroupName varchar(max)  
 )  
 DECLARE @TableHeader TABLE  
 (  
  tId int IDENTITY(1,1),HeaderId int,HeaderName varchar(50)  
 )  
 DECLARE @tExamination TABLE  
 (  
  tId int IDENTITY(1,1),Id bigint,StoreLocationId int,OrganizationDepartmentId int,EmployeeCompanyId int  
 )  
   
 IF (@rmtype = 1)  
 BEGIN  
  INSERT INTO @TableOne (GroupId, GroupName)  
  SELECT distinct SLM.Id,SLM.Title  
  FROM sExamination.tExamination AS EXM   
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId=EXM.Id  
  INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId  
  INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId  
  INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId   
  INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId  
  INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID  
  INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD ON EPD.EmployeeId=EMP.ID  
  INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id= (case when @rIsBusinessWise=0 then EXM.EmployeeCompanyId else EJD.EmployeeCompanyId end)
  INNER JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId  
  INNER JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId  
  INNER JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId  
  INNER JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId  
  INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId  
  INNER JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId    
  INNER JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId  
  INNER JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId  
  INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId  
  INNER JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId  
  LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId  AND ((LMN.LocationSubGroupId=@rLocationSubGroupId) OR (@rLocationSubGroupId=0))   
  LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId AND ((LSG.LocationMainGroupId=@rLocationMainGroupId) OR (@rLocationMainGroupId=0))  
  
  WHERE  EXM.ParticipantSourceTypeId=95  
  AND EXM.OrgId=@rOrgId  
  AND UL.UserId = @rUserId  
  AND SSM.MaINTypeId=@rMaINTypeId   
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))  
  AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))  
  AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))  
  AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))  
  AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))  
  AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))  
  AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))  
  AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))  
  AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))  
  AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))  
  AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((EMP.Code LIKE @rEmployeeCode)OR (@rEmployeeCode = ''))  
  AND ((EMP.FirstName LIKE @rEmployeeFname )OR (@rEmployeeFname = ''))  
  AND ((EMP.LastName LIKE @rEmployeeLname) OR (@rEmployeeLname = ''))  
  --AND ((EXM.TargetGroupId =@rTargetGroupId) OR (@rTargetGroupId=0))  
  AND ((EXM.TargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupId,',') )) or @rTargetGroupId='') --Nidhi DT-17/01/23; id - 0022915
  AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')  
  AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='')  
  AND (SLM.IsActiveHealth = @rIsActiveHealth or @rIsActiveHealth = 0)  
  AND (SLM.IsOpdSetup = @rIsOPDSetup or @rIsOPDSetup = 0)  
  AND (datediff(day,@rDojfromDate,EJD.DateOfJoining)>=0 or @rDojfromDate = '')  
  AND (datediff(day,EJD.DateOfJoining,@rDOJtoDate)>=0 or @rDOJtoDate ='') 
  AND IsNULL(EXM.IsCancel,0) = 0 --mantis - 27996, Nidhi Pandey, DT - 11/10/2023 
 END  
 ELSE IF (@rmtype = 2)  
 BEGIN  
  INSERT INTO @TableOne (GroupId, GroupName)  
  SELECT distinct DPT.Id,DPT.Title FROM  sExamination.tExamination AS EXM   
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId=EXM.Id  
  INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId  
  INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId  
  INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId   
  INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId  
  INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID  
  INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD ON EPD.EmployeeId=EMP.ID  
  INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id = (case when @rIsBusinessWise=0 then EXM.EmployeeCompanyId else EJD.EmployeeCompanyId end)
  INNER JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId  
  INNER JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId  
  INNER JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId  
  INNER JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId  
  INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId  
  INNER JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId    
  INNER JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId  
  INNER JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId  
  INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId  
  INNER JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId  
  LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId  AND ((LMN.LocationSubGroupId=@rLocationSubGroupId) OR (@rLocationSubGroupId=0))   
  LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId AND ((LSG.LocationMainGroupId=@rLocationMainGroupId) OR (@rLocationMainGroupId=0))  
  
  WHERE  EXM.ParticipantSourceTypeId=95  
  AND EXM.OrgId=@rOrgId  
  AND UL.UserId = @rUserId  
  AND SSM.MaINTypeId=@rMaINTypeId   
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))  
  AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))  
  AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))  
  AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))  
  AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))  
  AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))  
  AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))  
  AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))  
  AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))  
  AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))  
  AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((EMP.Code LIKE @rEmployeeCode)OR (@rEmployeeCode = ''))  
  AND ((EMP.FirstName LIKE @rEmployeeFname )OR (@rEmployeeFname = ''))  
  AND ((EMP.LastName LIKE @rEmployeeLname) OR (@rEmployeeLname = ''))  
  --AND ((EXM.TargetGroupId =@rTargetGroupId) OR (@rTargetGroupId=0))  
  AND ((EXM.TargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupId,',') )) or @rTargetGroupId='') --Nidhi DT-17/01/23; id - 0022915
  AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')  
  AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='')    
  AND (datediff(day,@rDojfromDate,EJD.DateOfJoining)>=0 or @rDojfromDate = '')  
  AND (datediff(day,EJD.DateOfJoining,@rDOJtoDate)>=0 or @rDOJtoDate ='') 
  AND IsNULL(EXM.IsCancel,0) = 0 --mantis - 27996, Nidhi Pandey, DT - 11/10/2023 
 END  
 ELSE IF (@rmtype = 3)  
 BEGIN  
  INSERT INTO @TableOne (GroupId, GroupName)  
  SELECT distinct ECM.Id,ECM.Title FROM  sExamination.tExamination AS EXM   
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId=EXM.Id  
  INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId  
  INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId  
  INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId   
  INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId  
  INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID  
  INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD ON EPD.EmployeeId=EMP.ID  
  INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id = (case when @rIsBusinessWise=0 then EXM.EmployeeCompanyId else EJD.EmployeeCompanyId end)
  INNER JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId  
  INNER JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId  
  INNER JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId  
  INNER JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId  
  INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId  
  INNER JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId    
  INNER JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId  
  INNER JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId  
  INNER JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId  
  INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId  
  LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId  AND ((LMN.LocationSubGroupId=@rLocationSubGroupId) OR (@rLocationSubGroupId=0))   
  LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId AND ((LSG.LocationMainGroupId=@rLocationMainGroupId) OR (@rLocationMainGroupId=0))  
  
  WHERE  EXM.ParticipantSourceTypeId=95  
  AND EXM.OrgId=@rOrgId  
  AND UL.UserId = @rUserId  
  AND SSM.MaINTypeId=@rMaINTypeId   
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))  
  AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))  
  AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))  
  AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))  
  AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))  
  AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))  
  AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))  
  AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))  
  AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))  
  AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))  
  AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((EMP.Code LIKE @rEmployeeCode)OR (@rEmployeeCode = ''))  
  AND ((EMP.FirstName LIKE @rEmployeeFname )OR (@rEmployeeFname = ''))  
  AND ((EMP.LastName LIKE @rEmployeeLname) OR (@rEmployeeLname = ''))  
  --AND ((EXM.TargetGroupId =@rTargetGroupId) OR (@rTargetGroupId=0))  
  AND ((EXM.TargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupId,',') )) or @rTargetGroupId='') --Nidhi DT-17/01/23; id - 0022915
  AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')  
  AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='')  
  AND (datediff(day,@rDojfromDate,EJD.DateOfJoining)>=0 or @rDojfromDate = '')  
  AND (datediff(day,EJD.DateOfJoining,@rDOJtoDate)>=0 or @rDOJtoDate ='') 
  AND IsNULL(EXM.IsCancel,0) = 0 --mantis - 27996, Nidhi Pandey, DT - 11/10/2023 
 END   
   
 select @rIsActiveHealth = case @rmtype when 1 then @rIsActiveHealth else 0 end  
 select @rIsOPDSetup = case @rmtype when 1 then @rIsOPDSetup else 0 end  
   
 INSERT INTO @tExamination(Id,StoreLocationId,OrganizationDepartmentId,EmployeeCompanyId)  
 SELECT EXM.Id,EXM.StoreLocationId,EXM.OrganizationDepartmentId,EXM.EmployeeCompanyId  
 FROM sExamination.tExamination AS EXM   
 INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId=EXM.Id  
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId  
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId  
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId   
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId  
 INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID  
 INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD ON EPD.EmployeeId=EMP.ID  
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id = (case when @rIsBusinessWise=0 then EXM.EmployeeCompanyId else EJD.EmployeeCompanyId end)
 INNER JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId  
 INNER JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId  
 INNER JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId  
 INNER JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId  
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId  
 INNER JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId    
 INNER JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId  
 INNER JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId  
 INNER JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId  
 INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId  
 LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId  AND ((LMN.LocationSubGroupId=@rLocationSubGroupId) OR (@rLocationSubGroupId=0))   
 LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId AND ((LSG.LocationMainGroupId=@rLocationMainGroupId) OR (@rLocationMainGroupId=0))  
  
 WHERE EXM.ParticipantSourceTypeId=95  
 AND EXM.OrgId=@rOrgId  
 AND UL.UserId = @rUserId  
 AND SSM.MaINTypeId=@rMaINTypeId   
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))  
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))  
 AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))  
 AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))  
 AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))  
 AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))  
 AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))  
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))  
 AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))  
 AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))  
 AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 AND ((EMP.Code LIKE @rEmployeeCode)OR (@rEmployeeCode = ''))  
 AND ((EMP.FirstName LIKE @rEmployeeFname )OR (@rEmployeeFname = ''))  
 AND ((EMP.LastName LIKE @rEmployeeLname) OR (@rEmployeeLname = ''))  
 --AND ((EXM.TargetGroupId =@rTargetGroupId) OR (@rTargetGroupId=0))  
 AND ((EXM.TargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupId,',') )) or @rTargetGroupId='') --Nidhi DT-17/01/23; id - 0022915
 AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')  
 AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='')  
 AND (SLM.IsActiveHealth = @rIsActiveHealth or @rIsActiveHealth = 0)  
 AND (SLM.IsOpdSetup = @rIsOPDSetup or @rIsOPDSetup = 0)  
 AND (datediff(day,@rDojfromDate,EJD.DateOfJoining)>=0 or @rDojfromDate = '')  
 AND (datediff(day,EJD.DateOfJoining,@rDOJtoDate)>=0 or @rDOJtoDate ='')  
 AND IsNULL(EXM.IsCancel,0) = 0 --mantis - 27996, Nidhi Pandey, DT - 11/10/2023
  
 IF OBJECT_ID('tempdb..##tempTable') IS NOT NULL  
 BEGIN  
  DROP TABLE ##tempTable  
 END  
  
 CREATE TABLE ##tempTable  
 (  
  tId int IDENTITY(1,1),GroupId int,GroupName varchar(max),[Tobacco] smallint,[Smoker] smallint,  
  [Alcohol] smallint,[UnderWeight] smallint,[OverWeight] smallint,[Obese] smallint,  
  [TB] smallint,[COPD] smallint,[NewPreHypertension] smallint, [PreHypertension] smallint,[NewHypertension] smallint, [Hypertension] smallint,  
  [NewPreDiabetic] smallint, [Pre Diabetic] smallint, [NewDiabetic] smallint, [Diabetic] smallint,[IHD] smallint,[NIHLMild] smallint,  
  [NIHLModerate] smallint,[NIHLSevere] smallint,[XrayILO] smallint,[Low Hb] smallint,  
  [Hypercholesterolemia] smallint,[Borderline Cholesterol] smallint,[Hypertriglyceridemia] smallint,  
  [Borderline Triglyceride] smallint,[Elevated  LDL] smallint,[Borderline LDL] smallint,  
  [Low HDL] smallint,[Elevated  SGPT] smallint,[High Serum Creatinine] smallint,  
  [Abnormal ECG] smallint,[Abnormal TMT] smallint,[Abnormal ECHO] smallint,  
  [Abnormal Sonography] smallint,[ObstructivePFT] smallint,[RestructivePFT] smallint,[MixPFT] smallint,  
  [Mentzer Index] smallint,[Abnormal XRay] smallint,[Diabetic Existing] smallint,[Hypertension Existing] smallint,
  [Metabolic Syndrome] smallint,[CVD Major RISK] smallint,[CVD Minor RISK] smallint,[NCD`s RISK] smallint,[Elevated T3] smallint,[Elevated T4] smallint,[Elevated TSH] smallint,
  [High PSA] smallint,[High Serum Billirubin] smallint,[Hyperuricemia] smallint,
  [Iron Deficiency Anaemia] smallint,[Low T3] smallint,[Low T4] smallint,[Low TSH] smallint,[Thrombocytopenia] smallint,[Vitamin B12 deficiency] smallint,[Vitamin D3 deficiency] smallint
 )
 INSERT INTO ##tempTable
 SELECT t.GroupId,t.GroupName,  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.Tobacco = 1  
 )  
 Tobacco,  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.Smoker = 1  
 )  
 Smoker,  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.Alcohol = 1  
 )  
 Alcohol,  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.BMI = 'Underweight'  
 )  
 UnderWeight,  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.BMI = 'Overweight'  
 )  
 OverWeight,  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.BMI = 'Obese'  
 )  
 Obese,  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.TB = 1  
 )  
 TB,  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.COPD = 1  
 )  
 COPD, 
 (
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
  	ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
	   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	  END = t.GroupId  
  AND DTE.IsNewHypertensionStatus = 1
  )
  NewPreHypertension,
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.BloodPressure = 'PreHypertension'
  AND ((@lExcludeExistingOrNewRecordsFromTracker = 'False') 
		OR (@lExcludeExistingOrNewRecordsFromTracker = 'True' 
		AND (DTE.HypertensionExisting <> 'Hypertension Existing' OR DTE.HypertensionExisting IS NULL) AND ISNULL(DTE.IsNewHypertensionStatus,0) <> 1))
 )  
 PreHypertension,  
 (
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	  END = t.GroupId 
	AND DTE.IsNewHypertensionStatus = 2
 )
 NewHypertension,
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.BloodPressure = 'Hypertension'
  AND ((@lExcludeExistingOrNewRecordsFromTracker = 'False') 
		OR (@lExcludeExistingOrNewRecordsFromTracker = 'True' 
		AND (DTE.HypertensionExisting <> 'Hypertension Existing' OR DTE.HypertensionExisting IS NULL) AND ISNULL(DTE.IsNewHypertensionStatus,0) <> 2))
 )  
 Hypertension,
 (
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
		ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	  END = t.GroupId
	AND DTE.IsNewDiabeticStatus = 1
 )
 NewPreDiabetic,
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.FBS = 'Pre Diabetic'
  AND ((@lExcludeExistingOrNewRecordsFromTracker = 'False') 
		OR (@lExcludeExistingOrNewRecordsFromTracker = 'True' 
		AND (DTE.DiabeticExisting <> 'Diabetic Existing' OR DTE.DiabeticExisting IS NULL) AND ISNULL(DTE.IsNewDiabeticStatus,0) <> 1))
 )  
 PreDiabatic,
 (
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
		ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	  END = t.GroupId
	AND DTE.IsNewDiabeticStatus = 2
 )
 NewDiabetic,
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId
  AND DTE.FBS = 'Diabetic'
  AND ((@lExcludeExistingOrNewRecordsFromTracker = 'False') 
		OR (@lExcludeExistingOrNewRecordsFromTracker = 'True' 
		AND (DTE.DiabeticExisting <> 'Diabetic Existing' OR DTE.DiabeticExisting IS NULL) AND ISNULL(DTE.IsNewDiabeticStatus,0) <> 2))
 )
 Diabatic,  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.IHD = 1  
 )  
 IHD,  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.AudiometryACRight = 'Mild hearing loss'  
 )  
 NIHLMild,  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.AudiometryACRight = 'Moderate hearing loss'  
 )  
 NIHLModerate,  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.AudiometryACRight = 'Severe hearing loss'  
 )  
 NIHLSevere,  
 (0) XrayILO,  
 (SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.Hb = 'Low Hb'  
  )   
  [Low Hb],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.Cholesterol = 'Hypercholesterolemia'  
 )  
 [Cholesterol High],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.Cholesterol = 'Borderline Cholesterol'  
 )  
 [Cholesterol Borderline],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.Triglyceride = 'Hypertriglyceridemia'  
 )  
 [Triglyceride High],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.Triglyceride = 'Borderline Triglyceride'  
 )  
 [Triglyceride Borderline],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.LDL = 'Elevated  LDL'  
 )  
 [LDL High],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.LDL = 'Borderline LDL'  
 )  
 [LDL Borderline],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.HDL = 'Low HDL'  
 )  
 [HDL Low],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.SGPT = 'Elevated  SGPT'  
 )  
 [SGPT High],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.SerumCreatinine = 'High Serum Creatinine'  
 )  
 [High Serum Creatinine],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.ECG = 'ECG Abnormal'  
 )  
 [Abnormal ECG],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.TMT = 'TMT Abnormal'  
 )  
 [Abnormal TMT],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.ECHO = 'ECHO Abnormal'  
 )  
 [Abnormal ECHO],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.Sonography = 'Sonography Abnormal'  
 )  
 [Abnormal Sonography],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  --AND DTE.PFT = 'Obstructive Lung Disease' Mentis issue no:8825  
  AND DTE.PFT like '%Obstructive Pattern%'  
 )  
 [ObstructivePFT],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  --AND DTE.PFT = 'Restrictive Lung Disease' Mentis issue no:8825  
  AND DTE.PFT like '%Restrictive Pattern%'  
 )  
 [RestructivePFT],  
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  --AND DTE.PFT = 'Mix Lung Disease' Mentis issue no:8825  
  AND DTE.PFT like '%Mix Pattern%'  
 )  
 [MixPFT],   
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.MenzerIndex = 'Mentzer < 13'  
 )[Mentzer Index],   
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.AbnormalXRay = '1'  
 )[Abnormal XRay],   
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.DiabeticExisting = 'Diabetic Existing'  
 )[Diabetic Existing],   
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.HypertensionExisting = 'Hypertension Existing'  
 )[Hypertension Existing],
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId 
  AND DTE.MetabolicSyndrome = 1
 )[Metabolic Syndrome],
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId 
  AND DTE.CVDMajorRisk = 1
 )[CVD Major RISK],
 (  
  SELECT COUNT(0)
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId 
  AND DTE.CVDMinorRisk = 1
 )[CVD Minor RISK],
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId 
  AND DTE.NCDsRisk = 1
 )[NCD`s RISK] ,
 (  
  SELECT COUNT(0)  
  FROM @tExamination AS EXM  
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
  WHERE CASE  
   WHEN @rmtype = 1 THEN EXM.StoreLocationId  
   WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
   WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
  END = t.GroupId  
  AND DTE.T3 = 'Elevated T3'  
 )[Elevated T3],
 (  
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	END = t.GroupId  
	AND DTE.T4 = 'Elevated T4'  
 )[Elevated T4],
 (  
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	END = t.GroupId  
	AND DTE.TSH = 'Elevated TSH'  
 )[Elevated TSH],
 (  
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	END = t.GroupId  
	AND DTE.PSA = 'High PSA'  
 )[High PSA],
 (  
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	END = t.GroupId  
	AND DTE.TotalBillirubin = 'High Serum Billirubin'  
 )[High Serum Billirubin],
 (  
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	END = t.GroupId  
	AND DTE.UricAcid= 'Hyperuricemia'  
 )Hyperuricemia,
 (  
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id     
	WHERE CASE  
	WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	END = t.GroupId  
	AND DTE.Iron = 'Iron Deficiency Anaemia'  
 )[Iron Deficiency Anaemia],
 (  
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	END = t.GroupId  
	AND DTE.t3 = 'Low T3'  
 )[Low T3],
 (  
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	END = t.GroupId  
	AND DTE.t4 = 'Low T4'  
) [Low T4],
(  
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	END = t.GroupId  
	AND DTE.TSH = 'Low TSH'  
) [Low TSH],
(  
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	END = t.GroupId  
	AND DTE.PLATELETS = 'Thrombocytopenia'  
) Thrombocytopenia,
(  
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	END = t.GroupId  
	AND DTE.VitaminB12 = 'Vitamin B12 deficiency'  
) [Vitamin B12 deficiency],
(  
	SELECT COUNT(0)  
	FROM @tExamination AS EXM  
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId = EXM.Id  
	WHERE CASE  
	WHEN @rmtype = 1 THEN EXM.StoreLocationId  
	WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
	WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId  
	END = t.GroupId  
	AND DTE.VitaminD3 = 'Vitamin D3 deficiency'  
) [Vitamin D3 deficiency]

 FROM @TableOne t
 ORDER BY 1
   
 DECLARE @columns nvarchar(max) = ''  
 DECLARE @Header nvarchar(max) = ''   
 DECLARE @sqlStatement nvarchar(max) = ''  
  
 IF OBJECT_ID('tempdb..#tblTmp') IS NOT NULL  
 BEGIN  
  DROP TABLE #tblTmp  
 END  
 CREATE TABLE #tblTmp  
 (  
  tid int IDENTITY(1,1),id int,title varchar(200),cnt int  
 )  
  
 IF (@rFlag = 1)  
 BEGIN  
  INSERT INTO #tblTmp  
  SELECT M.Id,'[' + M.Title + ']',0  
  FROM sExamination.tDiagnosisTrackerMaster M  
  INNER JOIN sExamination.tDiagnosisTrackerOrg O ON M.Id = O.DiagnosisTrackerId  
  where m.IsObsolete=0   
  and M.Id not in (49,50,51) and O.OrgId = @rOrgId
  ORDER BY O.OrderIndex ASC
    
  INSERT INTO @TableHeader  
  SELECT M.Id,M.Title  
  FROM sExamination.tDiagnosisTrackerMaster M  
  INNER JOIN sExamination.tDiagnosisTrackerOrg O ON M.Id = O.DiagnosisTrackerId  
  where m.IsObsolete=0   
  and M.Id not in (49,50,51) and O.OrgId = @rOrgId
  ORDER BY O.OrderIndex ASC
    
  SELECT @columns = COALESCE(@columns + ',' + QUOTENAME(Title), QUOTENAME(Title)) + ' smallint',  
  @Header = COALESCE(@Header + ',' + QUOTENAME(Title), QUOTENAME(Title))  
  FROM sExamination.tDiagnosisTrackerMaster M  
  INNER JOIN sExamination.tDiagnosisTrackerOrg O ON M.Id = O.DiagnosisTrackerId  
  WHERE m.IsObsolete=0   
  and M.Id not in (49,50,51) and  O.OrgId = @rOrgId
  ORDER BY O.OrderIndex ASC
 END   
   print @columns
 IF OBJECT_ID('tempdb..##temp007') IS NOT NULL  
  DROP TABLE ##temp007   
  
 if(ISNULL(@columns,'') <> '')  
 begin  
  SET @columns = 'CREATE TABLE ##temp007(tId int identity (1,1), GroupId int, GroupName varchar(max), ' + SUBSTRING(@columns, 2, LEN(@columns)) + ' )'  
 END  
 else  
 BEGIN  
  SET @columns = 'CREATE TABLE ##temp007(tId int identity (1,1), GroupId int, GroupName varchar(max))'  
 END  
   
 print @columns  
 EXECUTE (@columns)  
   
 if(ISNULL(@Header,'') <> '')  
 begin  
  SELECT @Header = SUBSTRING(@Header, 2, LEN(@Header))  
   
  SELECT @sqlStatement = @sqlStatement + 'INSERT INTO  ##temp007 (GroupId,GroupName,' + @Header + ') SELECT GroupId,GroupName,' + @Header + ' FROM ##tempTable'  
 end  
 else  
 BEGIN  
  SELECT @sqlStatement = @sqlStatement + 'INSERT INTO  ##temp007 (GroupId,GroupName) SELECT GroupId,GroupName  FROM ##tempTable'  
 END  
 print @sqlStatement  
 EXECUTE (@sqlStatement)  
   
 DECLARE @DiagnosHeader varchar(max) = '',@ColCnt int,@ColIncr int,@result varchar(max) = '',@RowCnt int,@RowIncr int  
   
 IF @rmtype = 1  
 BEGIN  
  SELECT @DiagnosHeader = '<thead><tr><th>Location</th>'  
 END  
 IF @rmtype = 2  
 BEGIN  
  SELECT @DiagnosHeader = '<thead><tr><th>Department</th>'  
 END  
 IF @rmtype = 3  
 BEGIN  
  SELECT @DiagnosHeader = '<thead><tr><th>Company</th>'  
 END  
 SELECT @ColCnt = COUNT(0), @ColIncr = 1 FROM @TableHeader  
   
 WHILE @ColIncr <= @ColCnt  
 BEGIN  
  DECLARE @ColName varchar(200) = ''  
  SELECT @ColName = HeaderName FROM @TableHeader WHERE tid = @ColIncr  
  SELECT @DiagnosHeader = @DiagnosHeader + '<th>' + @ColName + '</th>'  
  SELECT @ColIncr = @ColIncr + 1  
 END  
  
 SELECT @DiagnosHeader = @DiagnosHeader + '</tr></thead><tbody>'  
   
 SELECT @ColCnt = COUNT(0), @ColIncr = 1 FROM ##temp007  
   
 WHILE @ColIncr <= @ColCnt  
 BEGIN  
  DECLARE @GroupName nvarchar(50) = ''  
  DECLARE @SetupId1 nvarchar(50) = ''  
  SELECT @GroupName = GroupName, @SetupId1 = GroupId FROM ##temp007 WHERE tId = @ColIncr  
  SELECT @result = @result + '<tr><td><a onclick="BindDatasByRound(' + CONVERT(varchar, @SetupId1) + ',' + CONVERT(varchar, @rmtype) + ');">' + ISNULL(@GroupName, '') + '</a></td>'  
  SELECT @RowCnt = COUNT(0), @RowIncr = 1 FROM @TableHeader  
  
  while @RowIncr<=@RowCnt  
  begin  
   declare @ColumnName varchar(50)='',@SqlStatement1 nvarchar(500)=''  
   SELECT @ColumnName=HeaderName FROm @TableHeader Where tid=@RowIncr  
      
   IF OBJECT_ID('tempdb..##temp001') IS NOT NULL  
   DROP TABLE ##temp001  
   CREATE TABLE ##temp001(Value int)  
  
   select @SqlStatement1=@SqlStatement1+'INSERT INTO ##temp001 SELECT ['+@ColumnName+'] FROm  ##temp007 WHERE tId = '+ convert(varchar,@ColIncr)  
  
   EXECUTE (@SqlStatement1)  
  
   declare @Val int = 0  
  
   SELECT @Val=Value FROM ##temp001  
  
   SELECT @result = @result+'<td><a '+ case when  @Val> 0 then 'onclick="myfunction1('''+@ColumnName+''',this,' + CONVERT(varchar,@SetupId1) + ','   
   + convert(varchar,@rmtype) + ','''+replace(convert(varchar(50),newid()),'-','')+''');"  ' else '' end  +'>' + convert(varchar,@Val) + '</a></td>'  
  
   SELECT @RowIncr = @RowIncr + 1  
  END  
  
  SELECT @result = @result + '</tr>'   
  SELECT @ColIncr = @ColIncr + 1    
 END  
   
 SELECT @result = @result + '</tbody>'   
 SELECT @ColCnt = COUNT(0), @ColIncr = 1 FROM #tblTmp  
   
 declare @colscnt int  
 select @colscnt = count(0) from ##tempTable  
   
 IF (@colscnt>0)  
 BEGIN  
  SELECT @result = @result + '<tfoot><tr><th>Total</th>'  
    
  WHILE @ColIncr <= @ColCnt  
  BEGIN  
   DECLARE @ColName2 varchar(200) = '', @quer1 varchar(max)  
    
   SELECT @ColName2 = title FROM #tblTmp WHERE tid = @ColIncr  
    
   SELECT @quer1 = 'update #tblTmp set cnt = (select isnull(sum(' + @ColName2 + '),0) from ##temp007) where title = ''' + @ColName2 + ''''  
   EXEC (@quer1)  
  
   DECLARE @sum1 int  
   SELECT @sum1 = cnt FROM #tblTmp WHERE tid = @ColIncr  
  
   SELECT @result = @result + +'<th><a ' + CASE WHEN @sum1 > 0 THEN 'onclick="myfunction1('''+@ColName2+''',this,0,0,''' + REPLACE(CONVERT(varchar(50), NEWID()), '-', '') + ''');"  ' ELSE '' END + '>' + CONVERT(varchar, @sum1) + '</a></th>'  
  
   SELECT @ColIncr = @ColIncr + 1  
  END  
  SELECT @result = @result + '</tr></tfoot>'  
  END  
  
 declare @h int   
 SELECT @h=count(0) FROM @TableHeader  
   
 select @result = case when isnull(@colscnt,0) = 0  then '<tr><td colspan="' + convert(varchar,@h+1) + '">No Records found in this selected criteria !</td></tr>'  
 else @result end  
   
 select @DiagnosHeader + @result as result   
END
GO
PRINT N'Altering Procedure [sExamination].[pDiagnosisGenerateAll]...';


GO

ALTER PROC [sExamination].[pDiagnosisGenerateAll]
(      
 @rOrgId [int] = 0,      
 @rDepartmentId [int] = 0,      
 @rSetupId [int] = 0,      
 @rCode [nvarchar](20) = '',      
 @rName [nvarchar](50) = '',      
 @rDesignationId [int] = 0,      
 @rStatusId int = 0,      
 @rLocationId int,      
 @rFromDate varchar(20) = NULL,      
 @rToDate varchar(20) = NULL,      
 @rEmployeeStoreLocationId int = 0,      
 @rFromValue int = NULL,      
 @rToValue int = NULL,      
 @rIsExport bit = NULL,      
 @rTargetGroupId int = NULL,       
 @rCompanyId int = NULL      
)      
AS      
BEGIN      
 DECLARE @rExaminationId nvarchar(max) = ''      
 IF ISNULL(@rFromValue, 0) = 0      
  SET @rFromValue = 1      
 IF ISNULL(@rToValue, 0) = 0      
  SET @rToValue = 1000      
      
 SET @rCode = sCommon.fSearchStringGet(@rCode)      
 SET @rName = sCommon.fSearchStringGet(@rName)      
       
 DECLARE @NewLineChar AS char(2) = CHAR(13) + CHAR(10)      
       
 IF (CONVERT(int, @rIsExport) = 1)      
 BEGIN      
  SET @NewLineChar = '-/'      
 END      
 IF (@rToDate = '')      
 BEGIN      
  SET @rToDate = '01/06/2050'      
 END      
    -- change By MS 2022-11-17 Issue No :0021877
 --SELECT @rFromDate = CONVERT(varchar(20), CONVERT(date, @rFromDate, 105), 23)      
 --SELECT @rToDate = CONVERT(varchar(20), CONVERT(date, @rToDate, 105), 23)      

 SELECT @rFromDate = CONVERT(varchar(20),@rFromDate, 23)      
 SELECT @rToDate = CONVERT(varchar(20),@rToDate, 23)      
       
 declare @lConfValue varchar(20), @lConfDiseaseEvaluation varchar(20);     
 select Top 1 @lConfValue = ISNULL(CS.ItemValue,CM.ItemValue)      
 from sConfig.tConfigurationMaster as CM      
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id      
 where CM.ItemKey = 'Examination.IsStatusCompleteRestrict' and SourceId=@rLocationId      

 select Top 1 @lConfDiseaseEvaluation = ISNULL(CS.ItemValue,CM.ItemValue)
	from sConfig.tConfigurationMaster as CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id
	where CM.ItemKey = 'Examination.DiagnosisEvaluation'
      
 DECLARE @DiagnosisTable TABLE      
 (      
  tId int IDENTITY(1,1),rowid int,ExaminationId bigint,ParticipantCode nvarchar(50),      
  ParticipantName nvarchar(100),SetupId int,StatusId int,OrganizationDepartmentId int,      
  DiagnosisId bigint,DiagnosisRemark nvarchar(max),RecommendationEnglish nvarchar(max),      
  FitUnfitId int,StatusName nvarchar(100),IsPublish int,IsNewDiabetic bit,IsNewHyperTension bit,      
  IsDoneAudio bit,IsDonePulmo bit,Age varchar(10),EmployeeId bigint,TargetGroupId int
 )      
 INSERT INTO @DiagnosisTable      
 SELECT * FROM      
 (      
  SELECT ROW_NUMBER() OVER (ORDER BY Exm.Id asc) AS rowid,      
  ExaminationId = Exm.Id,ParticipantCode = EM.Code,      
  ParticipantName = EM.FirstName + ' ' + EM.LastName,      
  SetupId = Exm.SetupId,Exm.StatusId,Exm.OrganizationDepartmentId,      
  ISNULL(D.Id, 0) AS DiagnosisId,D.DiagnosisRemark,D.RecommendationEnglish,      
  ISNULL(D.FitUnfitId, 0) AS FitUnfitId,      
  ST.Title + '<br/>' + case when @lConfValue='True' then case when Isnull(TGET.AutoId,0)>0 then case when (Isnull(A.IsDoneLeft,0) =1 or Isnull(A.IsDoneRight,0) =1) then 'A-Done' Else 'A-NotDone' End Else 'A-Done' End       
  + '<br/>' + case when Isnull(TGET1.AutoId,0)>0 then case when Isnull(P.IsDone,0) =1 then 'P-Done' Else 'P-NotDone' End Else 'P-Done' End Else '' END AS StatusName,      
  isnull(Exm.IsPublish,0) as IsPublish,isnull(IsNewDiabatic,0) as IsNewDiabatic,      
  isnull(IsNewHyperTension,0) as IsNewHyperTension,      
  case when Isnull(TGET.AutoId,0)>0 then case when (Isnull(A.IsDoneLeft,0) =1 or Isnull(A.IsDoneRight,0) =1) then 'True' Else 'False' End Else 'True' End as IsDoneAudio,      
  case when Isnull(TGET1.AutoId,0)>0 then case when Isnull(P.IsDone,0) =1 then 'True' Else 'False' End Else 'True' End as IsDonePulmo,      
  CONVERT(varchar,ISNULL(datediff(yy,DateOfBirth,getdate()), '')) Age,EM.Id as EmployeeId, isnull(Exm.TargetGroupId, 0) as TargetGroupId
  FROM sExamination.tExamination Exm      
  INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = Exm.ParticipantSourceId      
  LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId      
  LEFT JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.Id      
  INNER JOIN sExamination.tSetupMaster SM ON SM.Id = Exm.SetupId      
  LEFT JOIN sExamination.tDiagnosis D ON D.SourceId = Exm.Id      
  INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = Exm.StoreLocationId      
  LEFT JOIN sExamination.tStatusMaster ST ON Exm.StatusId = ST.Id      
  left join sExamination.tAudiometry A on A.SourceId=Exm.id and A.SourceTypeId=1002      
  left join sExamination.tPulmonary P on P.SourceId=Exm.Id and P.SourceTypeId=1002      
  left join sExamination.tTargetGroupExaminationTemplate TGET on TGET.TargetGroupId=Exm.TargetGroupId and TGET.MainTypeId=Exm.SetupId and TGET.SourceTemplateId=10162      
  left join sExamination.tTargetGroupExaminationTemplate TGET1 on TGET1.TargetGroupId=Exm.TargetGroupId and TGET1.MainTypeId=Exm.SetupId and TGET1.SourceTemplateId=10163       
  WHERE Exm.OrgId = @rOrgId      
  AND Exm.StoreLocationId = @rLocationId      
  AND Exm.ParticipantSourceTypeId = 95      
  AND Exm.ExaminationDate BETWEEN @rFromDate AND @rToDate      
  AND ((EM.Code LIKE @rCode) OR (@rCode = ''))      
  AND ((EM.FirstName + ' ' + EM.LastName LIKE @rName + '%') OR (@rName = ''))      
  AND ((Exm.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))      
  AND ((Exm.EmployeeDesignationId = @rDesignationId) OR (@rDesignationId = 0))      
  AND ((Exm.StatusId = @rStatusId) OR (@rStatusId = 0))      
  AND ((Exm.SetupId = @rSetupId) OR (@rSetupId = 0))      
  --AND ((EJD.EmployeeStoreLocationId = @rEmployeeStoreLocationId) OR (ISNULL(@rEmployeeStoreLocationId, 0) = 0))      
  AND ((ISNULL(Exm.TargetGroupId, 0) = @rTargetGroupId) OR (@rTargetGroupId = 0) OR (@rTargetGroupId = -1))         
  AND ((ISNULL(Exm.EmployeeCompanyId, 0) = @rCompanyId) OR (@rCompanyId = 0) OR (@rCompanyId = -1))      
 ) AS t WHERE t.rowid BETWEEN @rFromValue AND @rToValue ORDER BY t.ExaminationId DESC      
       
 SELECT @rExaminationId = COALESCE(@rExaminationId + ',', '') + CONVERT(varchar, ExaminationId) FROM @DiagnosisTable      
       
 DECLARE @tbltmpTestDetail TABLE      
 (      
  tid int IDENTITY(1,1),t_TestParameterId int,t_ServiceValue nvarchar(500),      
  t_DateOfBirth date,t_GenderId int,t_ParameterValueTypeId int,t_ListValueTypeId int,      
  t_TestType int,t_Age int,t_DetailId bigint,t_ExaminationId bigint,t_StaticTestParameterId int      
 )      
 INSERT INTO @tbltmpTestDetail      
 SELECT TPM.Id,TRD.ServiceValue,EP.DateOfBirth,EP.GenderId,TPM.ParameterValueTypeId,      
 TPM.ListValueTypeId,1,DATEDIFF(yy,EP.DateOfBirth,GETDATE()),TRD.Id,ED.Id,TPM.StaticTestParameterId      
 FROM sExamination.tExamination ED      
 INNER JOIN sHrm.tEmployeePersonalDetail EP ON ED.ParticipantSourceId = EP.EmployeeId      
 INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId      
 INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId      
 INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id      
 INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id      
 WHERE ED.Id IN (SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> '')      
 AND TPM.ParameterValueTypeId IN (1, 2) AND TPM.IsObsolete = 0      
 AND ISNULL(TRD.ServiceValue, '') <> '' ORDER BY TPM.ParameterValueTypeId      
       
 INSERT INTO @tbltmpTestDetail      
 SELECT GP.Id,GED.ParameterValue,EP.DateOfBirth,EP.GenderId,GP.ParameterValueTypeId,0,2,      
 DATEDIFF(yy,EP.DateOfBirth,GETDATE()),GED.Id,ED.Id,0      
 FROM sExamination.tExamination ED      
 INNER JOIN sHrm.tEmployeePersonalDetail EP ON ED.ParticipantSourceId = EP.EmployeeId      
 INNER JOIN sExamination.tGeneralTemplateExamination GE ON ED.Id = GE.SourceId      
 INNER JOIN sExamination.tGeneralTemplateExaminationDetail GED ON GE.Id = GED.GeneralTemplateExaminationId      
 INNER JOIN sExamination.tGeneralTemplateParameter GP ON GED.GeneralTemplateParameterId = GP.Id      
 WHERE ED.Id IN (SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> '')      
 AND GP.ParameterValueTypeId IN (1, 2) AND GP.IsObsolete = 0      
 AND ISNULL(GED.ParameterValue, '') <> '' ORDER BY GP.ParameterValueTypeId      
       
 DECLARE @tbltmpDiagnosis TABLE      
 (      
  tid int IDENTITY(1,1),d_DiagnosisRemark varchar(max),d_Recommendation varchar(max),      
  d_DetailId bigint,d_Type int,d_MainId bigint,d_ExaminationId bigint,d_StaticTestParameterId int      
 )      
 INSERT INTO @tbltmpDiagnosis      
 SELECT a.BMI,case when a.BMI='Overweight' OR a.BMI='Obese' then 'Reduce weight' else '' end,      
 0,0,0,a.ExaminationId,0      
 FROM      
 (      
  SELECT VTL.SourceId [ExaminationId],[sExamination].[fBMIValueGet](ISNULL(BMI, 0)) [BMI]      
  FROM sExamination.tVital AS VTL WHERE VTL.SourceId IN      
  (      
   SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> ''      
  )      
 ) AS a WHERE ISNULL(a.BMI, '') <> 'Normal' AND a.BMI IS NOT NULL AND ISNULL(a.BMI, '') <> ''      
       
 UNION ALL      
       
 SELECT a.BloodPressure,RecommendationRemark,0,0,0,a.ExaminationId,0      
 FROM      
 (      
  SELECT VTL.SourceId [ExaminationId],      
  [sExamination].[fBMIBloodPressureResultGet](ISNULL(BloodPressureSystolic,0),ISNULL(BloodPressureDiastolic, 0),OrgId) [BloodPressure],      
  isnull((select RecommendationRemark from sExamination.tDiseaseHabitSetup where SourceId = sCommon.fGetIntIdForOrg(13,@rOrgId) and SourceTypeId = 3004      
  and [sExamination].[fBMIBloodPressureResultGet](ISNULL(BloodPressureSystolic,0),ISNULL(BloodPressureDiastolic, 0),OrgId) = 'Hypertension'),'')      
  as RecommendationRemark      
  FROM sExamination.tVital AS VTL WHERE VTL.SourceId IN      
  (      
   SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> ''      
  )      
 ) AS a WHERE (ISNULL(a.BloodPressure, '') <> 'Normal' and ISNULL(a.BloodPressure, '') <> 'Optimal')AND a.BloodPressure IS NOT NULL      
 AND ISNULL(a.BloodPressure, '') <> ''      
       
 INSERT INTO @tbltmpDiagnosis      
 SELECT ISNULL(TPD.Diagnosis, ''),ISNULL(TPD.Recommendation, ''),TPD.Id,t_TestType,      
 t_DetailId,t_ExaminationId,t_StaticTestParameterId      
 FROM sOrderEntry.tTestParameterDetail TPD      
 INNER JOIN @tbltmpTestDetail TD ON TPD.TestParameterId = TD.t_TestParameterId      
 WHERE TPD.GenderId = TD.t_GenderId AND t_Age BETWEEN TPD.AgeFrom AND TPD.AgeTo      
 AND ISNULL(TPD.IsNormal, 0) = 0 AND TD.t_ParameterValueTypeId = 1 AND t_TestType = 1      
 AND CONVERT(decimal(18, 9), t_ServiceValue) BETWEEN CAST(TPD.Minimum AS decimal(12, 4)) AND CAST(TPD.Maximum AS decimal(12, 4))      
 AND ISNUMERIC(t_ServiceValue) = 1 AND t_ServiceValue <> '+' AND ISNULL(TPD.Diagnosis, '') <> ''      
       
 INSERT INTO @tbltmpDiagnosis      
 SELECT ISNULL(DiagnosisRemark, ''),ISNULL(RecommendationRemark, ''),TLS.Id,t_TestType,      
 t_DetailId,t_ExaminationId,0      
 FROM sExamination.tTestListTypeSetup TLS      
 INNER JOIN @tbltmpTestDetail TD ON TLS.TestParameterId = TD.t_TestParameterId      
 INNER JOIN sOrderEntry.tListValueTypeMaster LVTM ON LVTM.Id = TD.t_ListValueTypeId      
 INNER JOIN sOrderEntry.tListValueMaster LV ON LV.ListValueTypeId = LVTM.Id AND LV.Id = TLS.ListValueId      
 WHERE TLS.IsNormal = 0 AND LV.Title LIKE TD.t_ServiceValue AND TD.t_ParameterValueTypeId = 2      
 AND t_TestType = 1 AND ISNULL(DiagnosisRemark, '') <> ''      
       
 INSERT INTO @tbltmpDiagnosis      
 SELECT ISNULL(Diagnosis, ''),ISNULL(Recommendation, ''),GETS.Id,t_TestType,t_DetailId,      
 t_ExaminationId,0      
 FROM sExamination.tGeneralTemplateParameterRange GETS      
 INNER JOIN @tbltmpTestDetail TD ON GETS.GeneralTemplateParameterId = TD.t_TestParameterId      
 WHERE GETS.GenderId = TD.t_GenderId AND TD.t_Age BETWEEN GETS.AgeFrom AND GETS.AgeTo      
 AND TD.t_ParameterValueTypeId = 1 AND t_TestType = 2      
 AND CONVERT(decimal(18, 9), t_ServiceValue) BETWEEN CAST(GETS.Minimum AS decimal(12, 4)) AND CAST(GETS.Maximum AS decimal(12, 4))      
 AND ISNUMERIC(t_ServiceValue) = 1 AND ISNULL(Diagnosis, '') <> ''      
       
 INSERT INTO @tbltmpDiagnosis      
 SELECT ISNULL(Diagnosis, ''),ISNULL(Recommendation, ''),GPL.Id,t_TestType,t_DetailId,      
 t_ExaminationId,0      
 FROM sExamination.tGeneralTemplateParameterList GPL      
 INNER JOIN @tbltmpTestDetail TD ON TD.t_TestParameterId = GPL.GeneralTemplateParameterId      
 WHERE GPL.IsNormal = 0 AND GPL.Title LIKE t_ServiceValue AND TD.t_ParameterValueTypeId = 2      
 AND t_TestType = 2 AND ISNULL(Diagnosis, '') <> ''      
       
 DECLARE @tbltmpHabitDiseaseDetail TABLE      
 (      
  tid int IDENTITY(1,1),hd_DetailId bigint,hd_SourceId int,hd_SourceTypeId int,hd_ExaminationId bigint      
 )      
 INSERT INTO @tbltmpHabitDiseaseDetail      
 SELECT HHD.Id,HHD.HabitId,239,E.Id      
 FROM sExamination.tExamination E      
 INNER JOIN sExamination.tHabitHygine HH ON E.Id = HH.SourceId      
 INNER JOIN sExamination.tHabitHygineDetail HHD ON HH.Id = HHD.HabitHygineId      
 WHERE E.Id IN      
 (      
  SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> ''      
 )      
       
 UNION ALL      
       
 SELECT EDD.Id,EDD.DiseaseId,3004,E.Id      
 FROM sExamination.tExamination E      
 INNER JOIN sExamination.tExistingDisease ED ON E.Id = ED.SourceId      
 INNER JOIN sExamination.tExistingDiseaseDetail EDD ON ED.Id = EDD.ExistingDiseaseId      
 WHERE E.Id IN      
 (      
  SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> ''      
 )      
       
 INSERT INTO @tbltmpDiagnosis      
 SELECT ISNULL(DiagnosisRemark, ''),ISNULL(RecommendationRemark, ''),t.hd_DetailId,3,      
 t.hd_DetailId,hd_ExaminationId,0      
 FROM sExamination.tDiseaseHabitSetup DHS      
 INNER JOIN @tbltmpHabitDiseaseDetail t ON DHS.SourceId = t.hd_SourceId      
 AND DHS.SourceTypeId = t.hd_SourceTypeId WHERE ISNULL(DiagnosisRemark, '') <> ''      
       
 INSERT INTO @tbltmpDiagnosis      
 SELECT AM.Title,'',0,5,0,A.SourceId,0      
 FROM sExamination.tAudiometry A      
 INNER JOIN sExamination.tAudiometryResultMaster AM ON A.AudiometryAcResultLeftId = AM.Id      
 WHERE A.SourceId IN      
 (      
  SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> ''      
 ) AND AM.Id <> 1 AND AM.Title <> ''      
       
 UNION      
       
 SELECT AM.Title,'',0,5,0,A.SourceId,0      
 FROM sExamination.tAudiometry A      
 INNER JOIN sExamination.tAudiometryResultMaster AM ON A.AudiometryAcResultRightId = AM.Id      
 WHERE A.SourceId IN      
 (      
  SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> ''      
 ) AND AM.Id <> 1 AND AM.Title <> ''      
       
 INSERT INTO @tbltmpDiagnosis      
 SELECT ISNULL(PulmonaryResulIntensity, '') + ' ' + ISNULL(PulmonaryResult, ''),'',0,6,0,      
 SourceId,0      
 FROM sExamination.tPulmonary WHERE SourceId IN      
 (      
  SELECT Item FROM dbo.fSplitStr(@rExaminationId, ',') WHERE Item <> ''      
 ) AND PerOfPredictedFVC IS NOT NULL       
 --AND ISNULL(PulmonaryResulIntensity, '') <> ''      
 AND UPPER(ISNULL(PulmonaryResult, '')) <> 'NORMAL'      
       
 UPDATE TRD SET TRD.Diagnosis = t.d_DiagnosisRemark,TRD.Recommendation = t.d_Recommendation,      
 TRD.IsAbnormal = 1 FROM sExamination.tTestRequestDetail AS TRD      
 INNER JOIN @tbltmpDiagnosis AS t ON TRD.Id = d_MainId WHERE t.d_Type = 1      
       
 UPDATE GED SET GED.Diagnosis = t.d_DiagnosisRemark,GED.Recommendation = t.d_Recommendation,      
 GED.IsAbnormal = 1 FROM sExamination.tGeneralTemplateExaminationDetail GED      
 INNER JOIN @tbltmpDiagnosis AS t ON GED.Id = d_MainId WHERE t.d_Type = 2      
       
 DECLARE @tblMain TABLE      
 (      
  tid int IDENTITY(1,1),m_ExaminationId bigint,m_Diagnosis varchar(max),m_Recommendation varchar(max)      
 )      
       
 INSERT INTO @tblMain      
 SELECT DISTINCT d_ExaminationId,'','' FROM @tbltmpDiagnosis      
      
 declare @configval varchar(50)='Independent'      
 select @configval=ISNULL(CS.ItemValue,CM.ItemValue)       
 FROM sConfig.tConfigurationMaster CM      
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id       
 where CM.id=190      
 print @configval      
 DECLARE @cnt int, @i int      
       
 SELECT @i=1,@cnt=COUNT(*) FROM @tblMain      
       
 WHILE @i <= @cnt      
 BEGIN      
  DECLARE @lExaminationId bigint,@lDiagnosis varchar(max)='',@lRecommendation varchar(max)=''      
        
  SELECT @lExaminationId = m_ExaminationId FROM @tblMain WHERE tid = @i      
        
  if(@configval='Priority')      
   begin      
    -- For adani We have changes the priority MS 2019-04-09 (Abhi)      
    if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=25 and Isnull(d_DiagnosisRemark,'')<>'' and d_ExaminationId = @lExaminationId)      
     begin      
      Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,21) and d_ExaminationId = @lExaminationId      
     end      
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=19 and Isnull(d_DiagnosisRemark,'')<>'' and d_ExaminationId = @lExaminationId)      
     begin      
      Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (20,21) and d_ExaminationId = @lExaminationId      
     end      
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=20 and Isnull(d_DiagnosisRemark,'')<>'' and d_ExaminationId = @lExaminationId)      
     begin      
      Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (21) and d_ExaminationId = @lExaminationId      
     end      
      
    if exists      
     (select 1 FROM sExamination.tExamination ED              
     INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId      
     INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId      
     INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id      
     INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id and StaticTestParameterId=25      
     WHERE ED.Id IN (@lExaminationId)      
     and TRD.IsAbnormal = 0 and (Isnull(TRD.ServiceValue,'')<>'')      
     )      
      begin      
      Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,21) and d_ExaminationId = @lExaminationId      
      end      
    else if exists      
     (      
     select 1 FROM sExamination.tExamination ED              
     INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId      
     INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId      
     INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id      
     INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id and StaticTestParameterId=19      
     WHERE ED.Id IN (@lExaminationId)      
     and TRD.IsAbnormal = 0 and (Isnull(TRD.ServiceValue,'')<>'')      
     )      
      begin      
       Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (20,21) and d_ExaminationId = @lExaminationId      
      end      
    else if exists      
     (      
     select 1 FROM sExamination.tExamination ED              
     INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId      
     INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId      
     INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id      
     INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id and StaticTestParameterId=20      
     WHERE ED.Id IN (@lExaminationId)      
     and TRD.IsAbnormal = 0 and (Isnull(TRD.ServiceValue,'')<>'')      
     )      
      begin      
       Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (21) and d_ExaminationId = @lExaminationId      
      end      
      
   end      
  else if(@configval='Priority Abnormal')      
   begin      
    if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=25 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic' and d_ExaminationId = @lExaminationId)      
    begin      
     print 5      
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,21) and d_ExaminationId = @lExaminationId      
    end      
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=19 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic' and d_ExaminationId = @lExaminationId)      
    begin      
     print 6      
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (20,21,25) and d_ExaminationId = @lExaminationId      
    end      
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=20 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic' and d_ExaminationId = @lExaminationId)      
    begin      
     print 7      
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,21,25) and d_ExaminationId = @lExaminationId      
    end 
	else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=21 and Isnull(d_DiagnosisRemark,'')<>'Pre Diabetic' and d_ExaminationId = @lExaminationId)      
    begin      
     print 8      
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,25) and d_ExaminationId = @lExaminationId      
    end      
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=25 and Isnull(d_DiagnosisRemark,'')<>'Diabetic' and d_ExaminationId = @lExaminationId)      
    begin      
     print 1      
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,21) and d_ExaminationId = @lExaminationId      
    end      
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=19 and Isnull(d_DiagnosisRemark,'')<>'Diabetic' and d_ExaminationId = @lExaminationId)      
    begin      
     print 2      
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (20,21,25) and d_ExaminationId = @lExaminationId      
    end      
    else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=20 and Isnull(d_DiagnosisRemark,'')<>'Diabetic' and d_ExaminationId = @lExaminationId)      
    begin      
     print 3      
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,21,25) and d_ExaminationId = @lExaminationId      
    end 
	 else if exists(select 1 From @tbltmpDiagnosis where d_StaticTestParameterId=21 and Isnull(d_DiagnosisRemark,'')<>'Diabetic' and d_ExaminationId = @lExaminationId)      
    begin      
     print 4      
     Delete from @tbltmpDiagnosis where d_StaticTestParameterId in (19,20,25) and d_ExaminationId = @lExaminationId      
    end       
   end      
    
	DECLARE @rIsDiabetic bit = 0, @rIsDiabeticExisting bit = 0, @rIsHypertension bit = 0 , @rIsHypertensionExisting bit = 0;
	 set @rIsDiabetic = (select top 1 1 from @tbltmpDiagnosis where d_DiagnosisRemark = 'Diabetic' and d_ExaminationId = @lExaminationId)
	 --set @rIsDiabeticExisting = (select top 1 1 from @tbltmpDiagnosis where d_DiagnosisRemark = 'Diabetic ( Existing )' and d_ExaminationId = @lExaminationId)
	 set @rIsDiabeticExisting = (select top 1 1 from sExamination.tExistingDisease ED
										INNER JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId = ED.Id
										INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = EDD.DiseaseId
										Where DM.StaticDiseaseId = 7 AND ED.SourceId = @lExaminationId)
	 set @rIsHypertension = (select top 1 1 from @tbltmpDiagnosis where (d_DiagnosisRemark = 'Hypertension' or d_DiagnosisRemark = 'Stage I HTN' or d_DiagnosisRemark = 'Stage II HTN' 
																		or d_DiagnosisRemark = 'Stage III HTN' or d_DiagnosisRemark = 'Hypertension Crisis')
																		and d_ExaminationId = @lExaminationId)
	 --set @rIsHypertensionExisting = (select top 1 1 from @tbltmpDiagnosis where d_DiagnosisRemark = 'Hypertension ( Existing )' and d_ExaminationId = @lExaminationId)
	 set @rIsHypertensionExisting = (select top 1 1 from sExamination.tExistingDisease ED
										INNER JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId = ED.Id
										INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = EDD.DiseaseId
										Where DM.StaticDiseaseId = 13 AND ED.SourceId = @lExaminationId)

	 IF(@rIsDiabetic = 1 and ISNULL(@rIsDiabeticExisting, 0) <> 1)
	 BEGIN
			update sExamination.tDiagnosis set IsNewDiabatic = 1 where SourceId = @lExaminationId
			--set @rIsNewDiabatic = 1;
  	 END
	 ELSE
	 BEGIN
			update sExamination.tDiagnosis set IsNewDiabatic = 0 where SourceId = @lExaminationId
  	 END

	 IF(@rIsHypertension = 1 and ISNULL(@rIsHypertensionExisting, 0) <> 1)
	 BEGIN
			update sExamination.tDiagnosis set IsNewHyperTension = 1 where SourceId = @lExaminationId
			--set @rIsNewHyperTension = 1;
  	 END
	 ELSE
	 BEGIN
			update sExamination.tDiagnosis set IsNewHyperTension = 0 where SourceId = @lExaminationId
  	 END

	--	-- Dummy table to capture and discard result set
	--CREATE TABLE #dummy (reulst int, ResultStrin nvarchar(50));  -- Adjust column type to match actual output

	---- Discard the result
	--INSERT INTO #dummy
	--EXEC [sExamination].[pUpdateDiagnosis] @lExaminationId, @rIsNewDiabatic, @rIsNewHyperTension;

	--DROP TABLE #dummy;

  SELECT @lDiagnosis = @lDiagnosis + d_DiagnosisRemark + @NewLineChar      
  FROM @tbltmpDiagnosis WHERE d_ExaminationId = @lExaminationId      
        
  SELECT @lRecommendation = @lRecommendation + d_Recommendation + @NewLineChar      
  FROM (SELECT DISTINCT d_Recommendation FROM @tbltmpDiagnosis WHERE d_ExaminationId = @lExaminationId AND d_Recommendation <> ''  ) AS a      
        
  UPDATE @tblMain SET m_Diagnosis = @lDiagnosis, m_Recommendation = @lRecommendation      
  WHERE m_ExaminationId = @lExaminationId      
        
  SELECT @lDiagnosis = '', @lRecommendation = ''      
  SELECT @i = @i + 1      
 END      
       
 --select * from @tbltmpDiagnosis order by d_ExaminationId      
      
 SELECT dt.tId,dt.rowid,CauseId=dt.rowid,ParentExaminationId=dt.ExaminationId,      
 dt.ParticipantCode,dt.ParticipantName,dt.SetupId,dt.StatusId,dt.OrganizationDepartmentId,      
 Id=dt.DiagnosisId,
 Diagnosis=Case When @lConfDiseaseEvaluation ='True' Then [sExamination].[fReplaceDiagnosisRemark](tm.m_Diagnosis) ELSE tm.m_Diagnosis END,
 Recommendation=tm.m_Recommendation,      
 dt.FitUnfitId,Status=dt.StatusName,DepartmentId=0,dt.IsPublish,dt.IsNewDiabetic as NewDiabatic,      
 dt.IsNewHyperTension as NewHyperTension,dt.IsDoneAudio,dt.IsDonePulmo,dt.Age,dt.EmployeeId,dt.TargetGroupId    
 FROM @DiagnosisTable AS dt LEFT JOIN @tblMain tm ON dt.ExaminationId = tm.m_ExaminationId      
 order by ParentExaminationId asc      
      
 IF (CONVERT(int,@rIsExport) = 1)      
 BEGIN      
  SELECT [EmployeeCode] = dt.ParticipantCode,[EmployeeName] = dt.ParticipantName,      
  [Status] = dt.StatusName,Diagnosis = REPLACE(tm.m_Diagnosis, '-/', ','),      
  Recommendation = REPLACE(tm.m_Recommendation, '-/', '')      
  FROM @DiagnosisTable AS dt LEFT JOIN @tblMain tm      
  ON dt.ExaminationId = tm.m_ExaminationId      
 END      
END
GO
PRINT N'Altering Procedure [sExamination].[pDiagnosisSearchListGetWithValue]...';


GO
ALTER PROC [sExamination].[pDiagnosisSearchListGetWithValue]    
@rMainTypeId int,        
@rOrgId int,        
@rSetupGroupId int,        
@rSetupId int,        
@rSectorId int,        
@rVerticalId int,        
@rCompanyGroupId int,        
@rEmployeeCompanyId int,        
@rLocationMainGroupId int,        
@rLocationSubGroupId int,        
@rLocationId int,        
@rStoreLocationId int,        
@rFunctionId int,        
@rDepartmentGroupId int,        
@rDepartmentId int,        
@rEmployeeCode varchar(100),        
@rEmployeeFname varchar(100),        
@rEmployeeLname varchar(100),        
@rSqlColdition nvarchar(max),        
@rTargetGroupId INT=0,        
@rUserId bigint,        
@rManualCondition varchar(100)='0'        
WITH EXECUTE AS CALLER        
AS        
BEGIN        
    SET NOCOUNT ON;
    
    -- Initialize search parameters
    SET @rEmployeeCode  = CASE WHEN @rEmployeeCode = '' THEN '%' ELSE sCommon.fSearchStringGet(@rEmployeeCode) END;
    SET @rEmployeeFname = CASE WHEN @rEmployeeFname = '' THEN '%' ELSE sCommon.fSearchStringGet(@rEmployeeFname) END;
    SET @rEmployeeLname = CASE WHEN @rEmployeeLname = '' THEN '%' ELSE sCommon.fSearchStringGet(@rEmployeeLname) END;
    
    -- Replace conditions in SQL
    SET @rSqlColdition = REPLACE(@rSqlColdition, 'Abnormal XRay=''Abnormal XRay''', 'AbnormalXRay=''1''');
    SET @rSqlColdition = REPLACE(@rSqlColdition, 'Menzer index=''Menzer index''', 'Menzerindex<>''''');
    SET @rSqlColdition = REPLACE(@rSqlColdition, 'Diabetic Existing=''Diabetic Existing''', 'DiabeticExisting=''Diabetic Existing''');
    SET @rSqlColdition = REPLACE(@rSqlColdition, 'Hypertension Existing=''Hypertension Existing''', 'HypertensionExisting=''Hypertension Existing''');
    SET @rSqlColdition = REPLACE(@rSqlColdition, 'PFT=''ObstructivePFT''', 'PFT like''%Obstructive Pattern%''');
    SET @rSqlColdition = REPLACE(@rSqlColdition, 'PFT=''RestructivePFT''', 'PFT like''%Restrictive Pattern%''');
    SET @rSqlColdition = REPLACE(@rSqlColdition, 'PFT=''MixPFT''', 'PFT like''%Mix Pattern%''');
    SET @rSqlColdition = REPLACE(@rSqlColdition, 'AudiometryACRight=''NIHLModerate''', 'AudiometryACRight=''Moderate hearing loss''');
    SET @rSqlColdition = REPLACE(@rSqlColdition, 'AudiometryACRight=''NIHLMild''', 'AudiometryACRight=''Mild hearing loss''');
    SET @rSqlColdition = REPLACE(@rSqlColdition, 'AudiometryACRight=''NIHLSevere''', 'AudiometryACRight=''Severe hearing loss''');
    
    -- Handle manual conditions
    IF (ISNULL(@rManualCondition, '') <> '0')
    BEGIN
        IF (@rManualCondition = 'All Diabetic')
            SET @rSqlColdition = 'And (DiabeticExisting=''Diabetic Existing'' or FBS=''Diabetic'')';
        ELSE IF (@rManualCondition = 'Pre Diabetic')
            SET @rSqlColdition = 'And (Isnull(DiabeticExisting,'''')='''' and FBS=''Pre Diabetic'')';
        ELSE IF (@rManualCondition = 'Diabetic')
            SET @rSqlColdition = 'And (Isnull(DiabeticExisting,'''')='''' and FBS=''Diabetic'')';
        ELSE IF (@rManualCondition = 'Diabetic Controlled')
            SET @rSqlColdition = 'And (DiabeticExisting=''Diabetic Existing'' and (FBS=''Pre Diabetic'' or Isnull(FBS,'''')='''' ))';
        ELSE IF (@rManualCondition = 'Diabetic Uncontrolled')
            SET @rSqlColdition = 'And (DiabeticExisting=''Diabetic Existing'' and FBS=''Diabetic'')';
        ELSE IF (@rManualCondition = 'All Hypertension')
            SET @rSqlColdition = 'And (HypertensionExisting=''Hypertension Existing'' or BloodPressure=''Hypertension'')';
        ELSE IF (@rManualCondition = 'Pre Hypertension')
            SET @rSqlColdition = 'And (Isnull(HypertensionExisting,'''')='''' and BloodPressure=''PreHypertension'')';
        ELSE IF (@rManualCondition = 'Hypertension')
            SET @rSqlColdition = 'And (Isnull(HypertensionExisting,'''')='''' and BloodPressure=''Hypertension'')';
        ELSE IF (@rManualCondition = 'Hypertension Controlled')
            SET @rSqlColdition = 'And (HypertensionExisting=''Hypertension Existing'' and (BloodPressure=''PreHypertension'' or Isnull(BloodPressure,'''')='''' ))';
        ELSE IF (@rManualCondition = 'Hypertension Uncontrolled')
            SET @rSqlColdition = 'And (HypertensionExisting=''Hypertension Existing'' and BloodPressure=''Hypertension'')';
    END
        
    -- Clean up temp tables if they exist
    IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL DROP TABLE #tempTable;
    IF OBJECT_ID('tempdb..#tempFuntionTable') IS NOT NULL DROP TABLE #tempFuntionTable;
    IF OBJECT_ID('tempdb..#tmpMenzerIndex') IS NOT NULL DROP TABLE #tmpMenzerIndex;
    IF OBJECT_ID('tempdb..#tempDiabeticProfileServiceValues') IS NOT NULL DROP TABLE #tempDiabeticProfileServiceValues;
    IF OBJECT_ID('tempdb..#tempFBSTable') IS NOT NULL DROP TABLE #tempFBSTable;
    
    -- Create optimized temp tables with proper indexes
    CREATE TABLE #tempFuntionTable (
        ExaminationId BIGINT,
        StaticTestParameterId INT,
        ServiceValue VARCHAR(100)        
    );
	CREATE CLUSTERED INDEX IX_tempFuntionTable ON #tempFuntionTable (ExaminationId, StaticTestParameterId);
    
    CREATE TABLE #tempFBSTable (
        ExaminationId BIGINT,
        StaticTestParameterId INT,
        ServiceValue VARCHAR(100)        
    );
    CREATE CLUSTERED INDEX IX_tempFBSTable ON #tempFBSTable (ExaminationId);

    -- Populate #tempFuntionTable with optimized query
    INSERT INTO #tempFuntionTable (ExaminationId, StaticTestParameterId, ServiceValue)
    SELECT  
        EXM.Id AS ExaminationId,
        TPM.StaticTestParameterId,
        RTRIM(LTRIM(ISNULL(TRD.ServiceValue, ''))) AS ServiceValue
    FROM sOrderEntry.tTestParameterMaster AS TPM WITH (NOLOCK)
    INNER JOIN sOrderEntry.tTestDetail AS TTD WITH (NOLOCK) ON TTD.TestParameterId = TPM.Id    
    INNER JOIN sExamination.tTestRequestDetail AS TRD WITH (NOLOCK) ON TRD.TestDetailId = TTD.Id    
    INNER JOIN sExamination.tTestRequest AS TR WITH (NOLOCK) ON TR.Id = TRD.TestRequestId
    INNER JOIN sExamination.tExamination AS EXM WITH (NOLOCK) ON EXM.Id = TR.SourceId
    WHERE TR.SourceTypeId = 1002
      AND TPM.StaticTestParameterId IN (2,31,27,32,33,34,38,15,52,53,54,58,158,126,127,40,49);
    
    -- Populate #tempFBSTable with optimized query using CTE
    ;WITH RankedData AS (
        SELECT  
            EXM.Id AS ExaminationId,
            TPM.StaticTestParameterId,
            RTRIM(LTRIM(ISNULL(TRD.ServiceValue, ''))) AS ServiceValue,
            ROW_NUMBER() OVER (
                PARTITION BY EXM.Id 
                ORDER BY 
                    CASE 
                        WHEN TPM.StaticTestParameterId = 25 THEN 1
                        WHEN TPM.StaticTestParameterId = 19 THEN 2
                        WHEN TPM.StaticTestParameterId = 20 THEN 3
                        WHEN TPM.StaticTestParameterId = 21 THEN 4
                        ELSE 5
                    END
            ) AS RowRank
        FROM sOrderEntry.tTestParameterMaster AS TPM WITH (NOLOCK)
        INNER JOIN sOrderEntry.tTestDetail AS TTD WITH (NOLOCK) ON TTD.TestParameterId = TPM.Id    
        INNER JOIN sExamination.tTestRequestDetail AS TRD WITH (NOLOCK) ON TRD.TestDetailId = TTD.Id    
        INNER JOIN sExamination.tTestRequest AS TR WITH (NOLOCK) ON TR.Id = TRD.TestRequestId
        INNER JOIN sExamination.tExamination AS EXM WITH (NOLOCK) ON EXM.Id = TR.SourceId
        WHERE TR.SourceTypeId = 1002
          AND TPM.StaticTestParameterId IN (25, 19, 20, 21)
          AND ISNULL(RTRIM(LTRIM(TRD.ServiceValue)), '') <> ''
    )
    INSERT INTO #tempFBSTable (ExaminationId, StaticTestParameterId, ServiceValue)
    SELECT ExaminationId, StaticTestParameterId, ServiceValue
    FROM RankedData
    WHERE RowRank = 1;
    
    -- Create and populate #tmpMenzerIndex with optimized query
    CREATE TABLE #tmpMenzerIndex (
        ExaminationId BIGINT PRIMARY KEY,
        MenzerIndex VARCHAR(100)
    );
    
    ;WITH MenzerSource AS (
        SELECT *
        FROM (
            SELECT 
                SPM.Title,
                TR.SourceId AS ExaminationId,
                TRD.ServiceValue
            FROM sOrderEntry.tStaticTestParameterMaster AS SPM WITH (NOLOCK)
            INNER JOIN sOrderEntry.tTestParameterMaster AS TPM WITH (NOLOCK) ON TPM.StaticTestParameterId = SPM.Id
            INNER JOIN sOrderEntry.tTestDetail AS TTD WITH (NOLOCK) ON TTD.TestParameterId = TPM.Id
            INNER JOIN sExamination.tTestRequestDetail AS TRD WITH (NOLOCK) ON TRD.TestDetailId = TTD.Id
            INNER JOIN sExamination.tTestRequest AS TR WITH (NOLOCK) ON TR.Id = TRD.TestRequestId
            WHERE SPM.id IN (3, 5)  -- 3 = R.B.C. COUNT, 5 = MCV
        ) AS SourceData
        PIVOT (
            MIN(ServiceValue)
            FOR Title IN ([R.B.C. COUNT], [MCV])
        ) AS piv
    )
    INSERT INTO #tmpMenzerIndex (ExaminationId, MenzerIndex)
    SELECT 
        EXM.ID AS ExaminationId,
        CASE 
			 WHEN piv.[R.B.C. COUNT] <> '' AND piv.[MCV] <> '' AND ISNUMERIC(piv.[MCV]) = 1 
			 AND ISNUMERIC(piv.[R.B.C. COUNT]) = 1 AND CAST(piv.[R.B.C. COUNT] AS FLOAT) <> 0
			 THEN 
				CAST(CAST(piv.[MCV] AS FLOAT) / CAST(piv.[R.B.C. COUNT] AS FLOAT) AS VARCHAR(100))
			 ELSE ''
		END AS MenzerIndex
    FROM sExamination.tExamination AS EXM WITH (NOLOCK)
    INNER JOIN MenzerSource piv ON piv.ExaminationId = EXM.Id
    WHERE EXM.ParticipantSourceTypeId = 95
      AND EXM.OrgId = @rOrgId;
    
    -- Create and populate #tempDiabeticProfileServiceValues with optimized query
    CREATE TABLE #tempDiabeticProfileServiceValues (
        ExaminationId BIGINT PRIMARY KEY,
        ServiceValue VARCHAR(100)
    );
    
    DECLARE @DiabeticProfileTestConfig VARCHAR(10) = 'FBS';
    DECLARE @d_configval VARCHAR(50) = 'Independent';
    
    -- Get configuration values with optimized queries
    SELECT TOP 1 @DiabeticProfileTestConfig = 
        CASE WHEN ISNULL(CS.ItemValue, CM.ItemValue) = 'HBA1C' THEN 'HBA1C' ELSE 'FBS' END
    FROM sConfig.tConfigurationMaster CM WITH (NOLOCK)
    LEFT JOIN sConfig.tConfigurationSetup CS WITH (NOLOCK) ON CS.ConfigurationId = CM.Id
    WHERE CM.Id = 232;
    
    SELECT TOP 1 @d_configval = ISNULL(CS.ItemValue, CM.ItemValue)
    FROM sConfig.tConfigurationMaster CM WITH (NOLOCK)
    LEFT JOIN sConfig.tConfigurationSetup CS WITH (NOLOCK) ON CS.ConfigurationId = CM.Id
    WHERE CM.Id = 190;
    
    ;WITH PIVOTED_VALUES AS (
        SELECT ExaminationId, [F B S], [HBA1C], [R B S], [P P B S]
        FROM (
            SELECT 
                TR.SourceId AS ExaminationId,
                SPM.Title,
                RTRIM(LTRIM(ISNULL(TRD.ServiceValue, ''))) AS ServiceValue
            FROM sOrderEntry.tStaticTestParameterMaster SPM WITH (NOLOCK)
            INNER JOIN sOrderEntry.tTestParameterMaster TPM WITH (NOLOCK) ON TPM.StaticTestParameterId = SPM.Id
            INNER JOIN sOrderEntry.tTestDetail TTD WITH (NOLOCK) ON TTD.TestParameterId = TPM.Id
            INNER JOIN sExamination.tTestRequestDetail TRD WITH (NOLOCK) ON TRD.TestDetailId = TTD.Id
            INNER JOIN sExamination.tTestRequest TR WITH (NOLOCK) ON TR.Id = TRD.TestRequestId
            WHERE SPM.Id IN (2,3,5,15,19,20,21,25,31,32,33,34,38,107,105,109,108,2,27,40,49,126,127)
        ) AS src
        PIVOT (
            MAX(ServiceValue) FOR Title IN ([F B S], [HBA1C], [R B S], [P P B S])
        ) AS piv
    )
    INSERT INTO #tempDiabeticProfileServiceValues (ExaminationId, ServiceValue)
    SELECT 
        EXM.Id,
        CASE
            WHEN @DiabeticProfileTestConfig = 'HBA1C' THEN PIV.[HBA1C]
            ELSE
                CASE 
                    WHEN @d_configval = 'Independent' THEN PIV.[F B S]
                    WHEN @d_configval = 'Priority Abnormal' THEN 
                        CASE 
                            WHEN PIV.[HBA1C] <> 'Normal' THEN PIV.[HBA1C]
                            WHEN PIV.[F B S] <> 'Normal' THEN PIV.[F B S]
                            WHEN PIV.[P P B S] <> 'Normal' THEN PIV.[P P B S]
                            ELSE PIV.[R B S]
                        END
                    WHEN @d_configval = 'Priority' THEN 
                        CASE 
                            WHEN ISNULL(PIV.[HBA1C], '') <> '' THEN PIV.[HBA1C]
                            WHEN ISNULL(PIV.[F B S], '') <> '' THEN PIV.[F B S]
                            WHEN ISNULL(PIV.[P P B S], '') <> '' THEN PIV.[P P B S]
                            ELSE PIV.[R B S]
                        END
                END
        END AS ServiceValue
    FROM sExamination.tExamination EXM WITH (NOLOCK)
    INNER JOIN sExamination.tDiagnosisTrackerEmployee DTE WITH (NOLOCK) ON DTE.ExaminationId = EXM.Id
    INNER JOIN PIVOTED_VALUES PIV WITH (NOLOCK) ON PIV.ExaminationId = EXM.Id
    WHERE EXM.ParticipantSourceTypeId = 95 AND EXM.OrgId = @rOrgId;
    
    -- Create main result table with proper indexing
    CREATE TABLE #tempTable (
        tId int IDENTITY(1,1) PRIMARY KEY,
        EmployeeId bigint,
        ParticipantCode nvarchar(500),
        ParticipantName nvarchar(500),
        DepartmentName nvarchar(500),
        MobileNumber nvarchar(500),
        CompanyEmail nvarchar(500),
        age nvarchar(500),
        Gender nvarchar(50),
        Business nvarchar(500),
        ExaminationId nvarchar(500),
        ParticipantSourceId nvarchar(500),
        GenderId nvarchar(500),
        Diagnosis nvarchar(max),
        FullView nvarchar(50),
        Tobacco nvarchar(10),
        Smoker nvarchar(10),
        Alcohol nvarchar(10),
        AlcoholSocial nvarchar(10),
        Drug nvarchar(10),
        BMI nvarchar(50),
        TB nvarchar(10),
        COPD nvarchar(10),
        IHD nvarchar(10),
        BloodPressure nvarchar(50),
        FBS nvarchar(50),
        Cholesterol nvarchar(50),
        Triglyceride nvarchar(50),
        LDL nvarchar(50),
        HDL nvarchar(50),
        SGPT nvarchar(50),
        ECG nvarchar(50),
        Sonography nvarchar(50),
        TMT nvarchar(50),
        ECHO nvarchar(50),
        PFT nvarchar(50),
        AudiometryACRight nvarchar(50),
        AudiometryACLeft nvarchar(50),
        SerumCreatinine nvarchar(50),
        Hb nvarchar(50),
        MenzerIndex nvarchar(50),
        AbnormalXRay nvarchar(50),
        DiabeticExisting nvarchar(50),
        HypertensionExisting nvarchar(50),
        UricAcid nvarchar(50),
        NewDiabeticStatus nvarchar(50),
        NewHypertensionStatus nvarchar(50),
        ExAlcohol nvarchar(10),
        ExSmoker nvarchar(10),
        ExTobacco nvarchar(10),
        MetabolicSyndrome nvarchar(10),
        CVDMajorRisk nvarchar(10),
        CVDMinorRisk nvarchar(10),
        NCDsRisk nvarchar(10),
        T3 nvarchar(50),
        T4 nvarchar(50),
        TSH nvarchar(50),
        PSA nvarchar(50),
        TotalBillirubin nvarchar(50),
        Iron nvarchar(50),
        Platelets nvarchar(50),
        VitaminB12 nvarchar(50),
        VitaminD3 nvarchar(50),
        INDEX IX_tempTable_ExaminationId NONCLUSTERED (ExaminationId)
    );
    
    -- Build the main query with optimized joins and conditions
    DECLARE @MainQuery NVARCHAR(MAX);
    
    SET @MainQuery = N'
    INSERT INTO #tempTable
    SELECT 
        EXM.ParticipantSourceId,
        ISNULL(EMP.Code, ''''),
        ISNULL(EMP.FirstName, '''') + '' '' + ISNULL(EMP.LastName, ''''),
        ISNULL(SLM.Title, '''') + CASE WHEN ' + CONVERT(VARCHAR, @rMainTypeId) + ' = 8 THEN ''- '' + EXM.ExaminationNumber ELSE '''' END,
        ISNULL(EC.MobileNumber, ''''),
        ISNULL(EC.CompanyEmail, ''''),
        CONVERT(VARCHAR, ISNULL(DATEDIFF(YEAR, EP.DateOfBirth, GETDATE()), '''')),
        ISNULL(VEXL.Gender, ''''),
        ISNULL(VEXL.Business, ''''),
        ISNULL(EXM.Id, ''''),
        ISNULL(EXM.ParticipantSourceId, ''''),
        ISNULL(EP.GenderId, ''''),
        CASE 
            WHEN ISNULL(dte.Tobacco, 0) = 0 THEN '''' ELSE ''Tobacco,'' END + '''' +        
            CASE WHEN ISNULL(dte.Smoker, 0) = 0 THEN '''' ELSE ''Smoker,'' END + '''' +        
            CASE WHEN ISNULL(dte.Alcohol, 0) = 0 THEN '''' ELSE ''Alcohol,'' END + '''' +        
            CASE WHEN ISNULL(dte.AlcoholSocial, 0) = 0 THEN '''' ELSE ''AlcoholSocial,'' END + '''' +        
            CASE WHEN ISNULL(dte.Drug, 0) = 0 THEN '''' ELSE ''Drug,'' END + '''' +        
            CASE WHEN ISNULL(dte.BMI, ''Normal'') = ''Normal'' OR ISNULL(dte.BMI, ''Normal'') = '''' THEN '''' ELSE dte.BMI + '' ('' + CAST(ISNULL(EXL.BMI, 0) AS VARCHAR) + ''),'' END +          
            CASE WHEN ISNULL(dte.TB, 0) = 0 THEN '''' ELSE ''TB,'' END + '''' +        
            CASE WHEN ISNULL(dte.COPD, 0) = 0 THEN '''' ELSE ''COPD,'' END + '''' +        
            CASE WHEN ISNULL(dte.IHD, 0) = 0 THEN '''' ELSE ''IHD,'' END + '''' +        
            CASE WHEN ISNULL(dte.BloodPressure, ''Normal'') = ''Normal'' OR ISNULL(dte.BloodPressure, ''Normal'') = '''' THEN '''' ELSE dte.BloodPressure + '' ('' + CAST(ISNULL(EXL.BloodPressureSystolic, 0) AS VARCHAR) + ''/'' + CAST(ISNULL(EXL.BloodPressureDiastolic, 0) AS VARCHAR) + ''),'' END + '''' +        
            CASE WHEN ISNULL(dte.FBS, ''Normal'') = ''Normal'' THEN '''' ELSE dte.FBS + '' ('' + ISNULL((SELECT tf.ServiceValue FROM #tempFBSTable tf WHERE tf.ExaminationId = EXM.Id), '''') + '')'' + '','' END +   
            CASE WHEN ISNULL(dte.Cholesterol, ''Normal'') = ''Normal'' THEN '''' ELSE dte.Cholesterol + '' ('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 31), '''') + '')'' + '','' END +        
            CASE WHEN ISNULL(dte.Triglyceride, '''') = '''' THEN '''' ELSE dte.Triglyceride + '' ('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 32), '''') + '')'' + '','' END +    
            CASE WHEN ISNULL(dte.LDL, ''Normal'') = ''Normal'' THEN '''' ELSE dte.LDL + '' ('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 34), '''') + '')'' + '','' END +     
            CASE WHEN ISNULL(dte.HDL, ''Normal'') = ''Normal'' THEN '''' ELSE dte.HDL + '' ('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 33), '''') + '')'' + '','' END + 
            CASE WHEN ISNULL(dte.SGPT, '''') = '''' THEN '''' ELSE dte.SGPT + '' ('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 38), '''') + '')'' + '','' END +     
            CASE WHEN ISNULL(dte.ECG, ''Normal'') = ''Normal'' OR ISNULL(dte.ECG, ''Normal'') = '''' THEN '''' ELSE dte.ECG + '','' END + '''' +        
            CASE WHEN ISNULL(dte.Sonography, ''Normal'') = ''Normal'' OR ISNULL(dte.Sonography, ''Normal'') = '''' THEN '''' ELSE dte.Sonography + '','' END + '''' +        
            CASE WHEN ISNULL(dte.TMT, '''') = '''' THEN '''' ELSE dte.TMT + '','' END + '''' +        
            CASE WHEN ISNULL(dte.ECHO, ''Normal'') = ''Normal'' OR ISNULL(dte.ECHO, ''Normal'') = '''' THEN '''' ELSE dte.ECHO + '','' END + '''' +        
            CASE WHEN LTRIM(RTRIM(ISNULL(dte.PFT, ''Normal''))) = ''Normal'' OR LTRIM(RTRIM(ISNULL(dte.PFT, ''Normal''))) = '''' THEN '''' ELSE dte.PFT + '','' END + '''' +        
            CASE WHEN ISNULL(dte.AudiometryACRight, '''') = '''' THEN '''' ELSE dte.AudiometryACRight + '','' END + '''' +        
            CASE WHEN ISNULL(dte.AudiometryACLeft, '''') = '''' THEN '''' ELSE dte.AudiometryACLeft + '','' END + '''' +        
            CASE WHEN ISNULL(dte.SerumCreatinine, '''') = '''' THEN '''' ELSE dte.SerumCreatinine + '' ('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 27), '''') + '')'' + '','' END +          
            CASE WHEN ISNULL(dte.Hb, '''') = '''' THEN '''' ELSE dte.Hb + '' ('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 2), '''') + '')'' + '','' END +          
            CASE 
                WHEN ISNULL(dte.MenzerIndex, '''') = '''' THEN '''' 
                ELSE dte.MenzerIndex + '' ('' + ISNULL((SELECT mi.MenzerIndex FROM #tmpMenzerIndex mi WHERE mi.ExaminationId = EXM.Id), '''') + '')'' + '','' 
            END +
            CASE WHEN ISNULL(dte.AbnormalXRay, ''0'') = ''0'' THEN '''' ELSE ''AbnormalXRay'' + '','' END + '''' +        
            CASE WHEN ISNULL(dte.DiabeticExisting, '''') = '''' THEN '''' ELSE dte.DiabeticExisting + '','' END + '''' +        
            CASE WHEN ISNULL(dte.HypertensionExisting, '''') = '''' THEN '''' ELSE dte.HypertensionExisting + '','' END + '''' +          
            CASE WHEN ISNULL(dte.UricAcid, '''') = '''' THEN '''' ELSE dte.UricAcid + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 49), '''') + '')'' END +  
            CASE WHEN ISNULL(dte.IsNewDiabeticStatus, 0) = 1 THEN ''NewPreDiabetic,'' WHEN ISNULL(dte.IsNewDiabeticStatus, 0) = 2 THEN ''NewDiabetic,'' ELSE '''' END + '''' +         
            CASE WHEN ISNULL(dte.IsNewHypertensionStatus, 0) = 1 THEN ''NewPreHypertension,'' WHEN ISNULL(dte.IsNewHypertensionStatus, 0) = 2 THEN ''NewHypertension,'' ELSE '''' END + '''' +         
            CASE WHEN ISNULL(dte.ExAlcohol, 0) = 0 THEN '''' ELSE ''ExAlcohol,'' END + '''' +         
            CASE WHEN ISNULL(dte.ExSmoker, 0) = 0 THEN '''' ELSE ''ExSmoker,'' END + '''' +         
            CASE WHEN ISNULL(dte.ExTobacco, 0) = 0 THEN '''' ELSE ''ExTobacco,'' END + '''' +         
            CASE WHEN ISNULL(dte.MetabolicSyndrome, 0) = 0 THEN '''' ELSE ''MetabolicSyndrome,'' END + '''' +        
            CASE WHEN ISNULL(dte.CVDMajorRisk, 0) = 0 THEN '''' ELSE ''CVDMajorRisk,'' END + '''' +        
            CASE WHEN ISNULL(dte.CVDMinorRisk, 0) = 0 THEN '''' ELSE ''CVDMinorRisk,'' END + '''' +        
            CASE WHEN ISNULL(dte.NCDsRisk, 0) = 0 THEN '''' ELSE ''NCD`sRisk,'' END +   
            CASE WHEN ISNULL(dte.T3, '''') = '''' THEN '''' ELSE dte.T3 + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 52), '''') + '')'' + '','' END +  
            CASE WHEN ISNULL(dte.T4, '''') = '''' THEN '''' ELSE dte.T4 + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 53), '''') + '')'' + '','' END +
            CASE WHEN ISNULL(dte.TSH, '''') = '''' THEN '''' ELSE dte.TSH + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 54), '''') + '')'' + '','' END +  
            CASE WHEN ISNULL(dte.PSA, '''') = '''' THEN '''' ELSE dte.PSA + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 58), '''') + '')'' + '','' END +
            CASE WHEN ISNULL(dte.TotalBillirubin, '''') = '''' THEN '''' ELSE dte.TotalBillirubin + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 40), '''') + '')'' + '','' END +
            CASE WHEN ISNULL(dte.Iron, '''') = '''' THEN '''' ELSE dte.Iron + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 158), '''') + '')'' + '','' END +  
            CASE WHEN ISNULL(dte.Platelets, '''') = '''' THEN '''' ELSE dte.Platelets + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 15), '''') + '')'' + '','' END +  
            CASE WHEN ISNULL(dte.VitaminB12, '''') = '''' THEN '''' ELSE dte.VitaminB12 + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 126), '''') + '')'' + '','' END +  
            CASE WHEN ISNULL(dte.VitaminD3, '''') = '''' THEN '''' ELSE dte.VitaminD3 + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 127), '''') + '')'' END,
        '''',
        CASE WHEN dte.Tobacco = 1 THEN ''Yes'' WHEN dte.Tobacco = 0 THEN '''' ELSE '''' END,
        CASE WHEN dte.Smoker = 1 THEN ''Yes'' WHEN dte.Smoker = 0 THEN '''' ELSE '''' END,
        CASE WHEN dte.Alcohol = 1 THEN ''Yes'' WHEN dte.Alcohol = 0 THEN '''' ELSE '''' END,
        CASE WHEN dte.AlcoholSocial = 1 THEN ''Yes'' WHEN dte.AlcoholSocial = 0 THEN '''' ELSE '''' END,
        CASE WHEN dte.Drug = 1 THEN ''Yes'' WHEN dte.Drug = 0 THEN '''' ELSE '''' END,
        CASE WHEN ISNULL(dte.BMI, ''Normal'') = ''Normal'' OR ISNULL(dte.BMI, ''Normal'') = '''' THEN '''' ELSE dte.BMI + '' ('' + CAST(CAST(ISNULL(EXL.BMI, 0) AS DECIMAL(10,2)) AS VARCHAR) + '')'' END,
        CASE WHEN dte.TB = 1 THEN ''Yes'' WHEN dte.TB = 0 THEN '''' ELSE '''' END,
        CASE WHEN dte.COPD = 1 THEN ''Yes'' WHEN dte.COPD = 0 THEN '''' ELSE '''' END,
        CASE WHEN dte.IHD = 1 THEN ''Yes'' WHEN dte.IHD = 0 THEN '''' ELSE '''' END,
        CASE WHEN ISNULL(dte.BloodPressure, ''Normal'') = ''Normal'' OR ISNULL(dte.BloodPressure, ''Normal'') = '''' THEN '''' ELSE dte.BloodPressure + '' ('' + CAST(ISNULL(EXL.BloodPressureSystolic, 0) AS VARCHAR) + ''/'' + CAST(ISNULL(EXL.BloodPressureDiastolic, 0) AS VARCHAR) + '')'' END,
        CASE WHEN ISNULL(dte.FBS, ''Normal'') = ''Normal'' THEN '''' ELSE dte.FBS + '' ('' + ISNULL((SELECT tf.ServiceValue FROM #tempFBSTable tf WHERE tf.ExaminationId = EXM.Id), '''') + '')'' END,
        CASE WHEN ISNULL(dte.Cholesterol, ''Normal'') = ''Normal'' THEN ''''  ELSE dte.Cholesterol + '' ('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 31), '''') + '')'' END,
        CASE WHEN ISNULL(dte.Triglyceride, '''') = '''' THEN '''' ELSE dte.Triglyceride + '' ('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 32), '''') + '')'' END,
        CASE WHEN ISNULL(dte.LDL, ''Normal'') = ''Normal'' THEN '''' ELSE dte.LDL + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 34), '''') + '')'' END,
        CASE WHEN ISNULL(dte.HDL, ''Normal'') = ''Normal'' THEN '''' ELSE dte.HDL + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 33), '''') + '')'' END,
        CASE WHEN ISNULL(dte.SGPT, '''') = '''' THEN '''' ELSE dte.SGPT + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 38), '''') + '')'' END,
        CASE WHEN ISNULL(dte.ECG, ''Normal'') = ''Normal'' OR ISNULL(dte.ECG, ''Normal'') = '''' THEN '''' ELSE dte.ECG END,
        CASE WHEN ISNULL(dte.Sonography, ''Normal'') = ''Normal'' OR ISNULL(dte.Sonography, ''Normal'') = '''' THEN '''' ELSE dte.Sonography END,
        CASE WHEN ISNULL(dte.TMT, '''') = '''' THEN '''' ELSE dte.TMT END,
        CASE WHEN ISNULL(dte.ECHO, ''Normal'') = ''Normal'' OR ISNULL(dte.ECHO, ''Normal'') = '''' THEN '''' ELSE dte.ECHO END,
        CASE WHEN ISNULL(dte.PFT, ''Normal'') = ''Normal'' OR ISNULL(dte.PFT, ''Normal'') = '''' THEN '''' ELSE dte.PFT END,
        ISNULL(dte.AudiometryACRight, ''''),
        ISNULL(dte.AudiometryACLeft, ''''),
        CASE WHEN ISNULL(dte.SerumCreatinine, '''') = '''' THEN '''' ELSE dte.SerumCreatinine + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 27), '''') + '')'' END,
        CASE WHEN ISNULL(dte.Hb, '''') = '''' THEN '''' ELSE dte.Hb + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 2), '''') + '')'' END,
        CASE WHEN ISNULL(dte.MenzerIndex, '''') = '''' THEN '''' ELSE dte.MenzerIndex + '' ('' + ISNULL((SELECT mi.MenzerIndex FROM #tmpMenzerIndex mi WHERE mi.ExaminationId = EXM.Id), '''') + '')'' END,
        CASE WHEN dte.AbnormalXRay = 1 THEN ''Abnormal XRay'' WHEN dte.AbnormalXRay = 0 THEN '''' ELSE '''' END,
        ISNULL(dte.DiabeticExisting, ''''),
        ISNULL(dte.HypertensionExisting, ''''),
        CASE WHEN ISNULL(dte.UricAcid, '''') = '''' THEN '''' ELSE dte.UricAcid + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 49), '''') + '')'' END,
        CASE WHEN ISNULL(dte.IsNewDiabeticStatus, 0) = 1 THEN ''NewPreDiabetic'' WHEN ISNULL(dte.IsNewDiabeticStatus, 0) = 2 THEN ''NewDiabetic'' ELSE '''' END,
        CASE WHEN ISNULL(dte.IsNewHypertensionStatus, 0) = 1 THEN ''NewPreHypertension'' WHEN ISNULL(dte.IsNewHypertensionStatus, 0) = 2 THEN ''NewHypertension'' ELSE '''' END,
        CASE WHEN dte.ExAlcohol = 1 THEN ''Yes'' WHEN dte.ExAlcohol = 0 THEN '''' ELSE '''' END,
        CASE WHEN dte.ExSmoker = 1 THEN ''Yes'' WHEN dte.ExSmoker = 0 THEN '''' ELSE '''' END,
        CASE WHEN dte.ExTobacco = 1 THEN ''Yes'' WHEN dte.ExTobacco = 0 THEN '''' ELSE '''' END,
        CASE WHEN dte.MetabolicSyndrome = 1 THEN ''Yes'' WHEN dte.MetabolicSyndrome = 0 THEN '''' ELSE '''' END,
        CASE WHEN dte.CVDMajorRisk = 1 THEN ''Yes'' WHEN dte.CVDMajorRisk = 0 THEN '''' ELSE '''' END,
        CASE WHEN dte.CVDMinorRisk = 1 THEN ''Yes'' WHEN dte.CVDMinorRisk = 0 THEN '''' ELSE '''' END,
        CASE WHEN dte.NCDsRisk = 1 THEN ''Yes'' WHEN dte.NCDsRisk = 0 THEN '''' ELSE '''' END,
        CASE WHEN ISNULL(dte.T3, '''') = '''' THEN '''' ELSE dte.T3 + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 52), '''') + '')'' END,
        CASE WHEN ISNULL(dte.T4, '''') = '''' THEN '''' ELSE dte.T4 + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 53), '''') + '')'' END,
        CASE WHEN ISNULL(dte.TSH, '''') = '''' THEN '''' ELSE dte.TSH + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 54), '''') + '')'' END,
        CASE WHEN ISNULL(dte.PSA, '''') = '''' THEN '''' ELSE dte.PSA + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 58), '''') + '')'' END,
        CASE WHEN ISNULL(dte.TotalBillirubin, '''') = '''' THEN '''' ELSE dte.TotalBillirubin + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 40), '''') + '')'' END,
        CASE WHEN ISNULL(dte.Iron, '''') = '''' THEN '''' ELSE dte.Iron + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 158), '''') + '')'' END,
        CASE WHEN ISNULL(dte.Platelets, '''') = '''' THEN '''' ELSE dte.Platelets + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 15), '''') + '')'' END,
        CASE WHEN ISNULL(dte.VitaminB12, '''') = '''' THEN '''' ELSE dte.VitaminB12 + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 126), '''') + '')'' END,
        CASE WHEN ISNULL(dte.VitaminD3, '''') = '''' THEN '''' ELSE dte.VitaminD3 + ''('' + ISNULL((SELECT tf.ServiceValue FROM #tempFuntionTable tf WHERE tf.ExaminationId = EXM.Id AND tf.StaticTestParameterId = 127), '''') + '')'' END
    FROM sExamination.tExamination AS EXM WITH (NOLOCK)
    INNER JOIN [sExamination].[tSetupMaster] STM WITH (NOLOCK) ON STM.ID = EXM.SetupId
    INNER JOIN [sExamination].[tSubTypeMaster] SSM WITH (NOLOCK) ON SSM.Id = STM.SubTypeId
    INNER JOIN [sHrm].[tEmployeeMaster] EMP WITH (NOLOCK) ON EMP.ID = EXM.ParticipantSourceId AND ISNULL(EMP.Isobsolete, 0) = 0
    INNER JOIN [sHrm].[tEmployeeJobDetail] EJD WITH (NOLOCK) ON EJD.EmployeeId = EMP.ID
    INNER JOIN [sHrm].[tEmployeeCompanyMaster] ECM WITH (NOLOCK) ON ECM.Id = EXM.EmployeeCompanyId
    INNER JOIN [sHrm].[tCompanyGroupMaster] CGM WITH (NOLOCK) ON CGM.Id = ECM.CompanyGroupId
    INNER JOIN [sHrm].[tVerticalMaster] VTM WITH (NOLOCK) ON VTM.ID = CGM.VerticalId
    INNER JOIN [sHrm].[tSectorMaster] SCT WITH (NOLOCK) ON SCT.Id = VTM.SectorId
    INNER JOIN [sCommon].[tCompanyInformation] CMP WITH (NOLOCK) ON CMP.ID = SCT.OrgId
    INNER JOIN [sIp].[tStoreLocationMaster] AS SLM WITH (NOLOCK) ON SLM.Id = EXM.StoreLocationId
    INNER JOIN [sCommon].[tLocationMaster] AS LMN WITH (NOLOCK) ON LMN.Id = SLM.LocationId
    INNER JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT WITH (NOLOCK) ON DPT.Id = EXM.OrganizationDepartmentId
    INNER JOIN [sCommon].[tDepartmentGroupMaster] AS DPG WITH (NOLOCK) ON DPG.id = DPT.DepartmentGroupId
    INNER JOIN [sCommon].[tFunctionMaster] AS FCN WITH (NOLOCK) ON FCN.Id = DPG.FunctionId
    LEFT JOIN [sCommon].[tLocationSubGroupMaster] LSG WITH (NOLOCK) ON LSG.Id = LMN.LocationSubGroupId AND ((LMN.LocationSubGroupId = ' + CONVERT(VARCHAR, @rLocationSubGroupId) + ') OR (' + CONVERT(VARCHAR, @rLocationSubGroupId) + ' = 0))
    LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG WITH (NOLOCK) ON LMG.Id = LSG.LocationMainGroupId AND ((LSG.LocationMainGroupId = ' + CONVERT(VARCHAR, @rLocationMainGroupId) + ') OR (' + CONVERT(VARCHAR, @rLocationMainGroupId) + ' = 0))
    INNER JOIN sHrm.tEmployeeCommunications EC WITH (NOLOCK) ON EMP.Id = EC.EmployeeId
    INNER JOIN sHrm.tEmployeePersonalDetail EP WITH (NOLOCK) ON EP.EmployeeId = EMP.Id
    INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte WITH (NOLOCK) ON dte.ExaminationId = EXM.Id
    INNER JOIN ssecurity.tUserLocation UL WITH (NOLOCK) ON EXM.StoreLocationId = UL.StoreLocationId
    LEFT JOIN sHrm.vEmployeeColumnName VEXL WITH (NOLOCK) ON EMP.id = VEXL.EmployeeNewId
    INNER JOIN sExamination.tVital EXL WITH (NOLOCK) ON EXL.id = dte.ExaminationId
    WHERE EXM.ParticipantSourceTypeId = 95
      AND EXM.OrgId = ' + CONVERT(VARCHAR, @rOrgId) + '
      AND UL.UserId = ' + CONVERT(VARCHAR, @rUserId) + '
      AND SSM.MainTypeId = ' + CONVERT(VARCHAR, @rMainTypeId) + '
      AND ((STM.SetupGroupId = ' + CONVERT(VARCHAR, @rSetupGroupId) + ') OR (' + CONVERT(VARCHAR, @rSetupGroupId) + ' = 0))
      AND ((EXM.SetupId = ' + CONVERT(VARCHAR, @rSetupId) + ') OR (' + CONVERT(VARCHAR, @rSetupId) + ' = 0))
      AND ((VTM.SectorId = ' + CONVERT(VARCHAR, @rSectorId) + ') OR (' + CONVERT(VARCHAR, @rSectorId) + ' = 0))
      AND ((CGM.VerticalId = ' + CONVERT(VARCHAR, @rVerticalId) + ') OR (' + CONVERT(VARCHAR, @rVerticalId) + ' = 0))
      AND ((ECM.CompanyGroupId = ' + CONVERT(VARCHAR, @rCompanyGroupId) + ') OR (' + CONVERT(VARCHAR, @rCompanyGroupId) + ' = 0))
      AND ((STM.SetupGroupId = ' + CONVERT(VARCHAR, @rEmployeeCompanyId) + ') OR (' + CONVERT(VARCHAR, @rEmployeeCompanyId) + ' = 0))
      AND ((SLM.LocationId = ' + CONVERT(VARCHAR, @rLocationId) + ') OR (' + CONVERT(VARCHAR, @rLocationId) + ' = 0))
      AND ((EXM.StoreLocationId = ' + CONVERT(VARCHAR, @rStoreLocationId) + ') OR (' + CONVERT(VARCHAR, @rStoreLocationId) + ' = 0))
      AND ((DPG.FunctionId = ' + CONVERT(VARCHAR, @rFunctionId) + ') OR (' + CONVERT(VARCHAR, @rFunctionId) + ' = 0))
      AND ((DPT.DepartmentGroupId = ' + CONVERT(VARCHAR, @rDepartmentGroupId) + ') OR (' + CONVERT(VARCHAR, @rDepartmentGroupId) + ' = 0))
      AND ((EXM.OrganizationDepartmentId = ' + CONVERT(VARCHAR, @rDepartmentId) + ') OR (' + CONVERT(VARCHAR, @rDepartmentId) + ' = 0))
      AND ((EXM.TargetGroupId = ' + CONVERT(VARCHAR, @rTargetGroupId) + ') OR (' + CONVERT(VARCHAR, @rTargetGroupId) + ' = 0))
      AND ((EMP.Code LIKE ''' + @rEmployeeCode + ''') OR (''' + @rEmployeeCode + '''= ''''))
      AND ((EMP.FirstName LIKE ''' + @rEmployeeFname + ''') OR (''' + @rEmployeeFname + '''= ''''))
      AND ((EMP.LastName LIKE ''' + @rEmployeeLname + ''') OR (''' + @rEmployeeLname + '''= ''''))
      AND ISNULL(EXM.IsCancel, 0) = 0'
      + CASE WHEN LEN(@rSqlColdition) > 6 THEN @rSqlColdition ELSE '' END + '
    ORDER BY ISNULL(EMP.FirstName, '''') + '' '' + ISNULL(EMP.LastName, '''')';
    
    -- Execute the main query
    EXEC sp_executesql @MainQuery;
    ----mantis id 0045551-----
	
 DECLARE @RowCount INT;
 DECLARE @lConfValue INT; 
           
           SELECT @RowCount = COUNT(*)
           FROM #tempTable;
          
           SELECT @lConfValue=CAST (ISNULL(cm.ItemValue,pm.ItemValue)AS INT) FROM sConfig.tConfigurationMaster  AS PM                  
            LEFt JOIN sConfig.tConfigurationSetup AS CM ON cm.ConfigurationId=Pm.Id AND SourceId=@rOrgId AND SourceTypeId=1016                   
            WHERE PM.Id=334        


           IF @RowCount > @lConfValue and @rStoreLocationId = 0
           BEGIN
		       SELECT '-102' AS ConfigurationSetupCount,@lConfValue ConfigurationValue; 
               RETURN -102;
 END

	-----

    ---- Return results
    --SELECT ResultString = 
    --    '<td><input type="checkbox" attrEmpId="' + CONVERT(VARCHAR, EmployeeId) + '" /></td><td>' + ISNULL(ParticipantCode, '') + '</td>' +
    --    '<td>' + ISNULL(ParticipantName, '') + '</td><td>' + ISNULL(DepartmentName, '') + '</td><td>' + ISNULL(MobileNumber, '') + '</td>' +
    --    '<td>' + ISNULL(CompanyEmail, '') + '</td><td>' + CONVERT(VARCHAR, ISNULL(age, '')) + '</td><td>' + ISNULL(Gender, '') + '</td><td>' + ISNULL(Business, '') +
    --    '</td><td>' + ISNULL(ExaminationId, '') +
    --    '</td><td>' + ISNULL(ParticipantSourceId, '') +
    --    '</td><td>' + ISNULL(GenderId, '') +
    --    '</td><td>' + ISNULL(Diagnosis, '') + '</td><td><a data-toggle="modal" data-target="#MROModalPopup" onclick="openExaminationPopup(' +
    --    CAST(ExaminationId AS VARCHAR) + ',' +
    --    CAST(ParticipantSourceId AS VARCHAR) + ',' +
    --    '95,' +
    --    CAST(GenderId AS VARCHAR) + ',' +
    --    CAST(age AS VARCHAR) + ',' +
    --    CAST(@rMainTypeId AS VARCHAR) + ',' +
    --    '1002,' +
    --    CAST(@rSetupId AS VARCHAR) + ')">View</a>' +
    --    '</td><td>' + ISNULL(Tobacco, '') + '</td><td>' + ISNULL(Smoker, '') + '</td><td>' + ISNULL(Alcohol, '') +
    --    '</td><td>' + ISNULL(AlcoholSocial, '') + '</td><td>' + ISNULL(Drug, '') + '</td><td>' + ISNULL(BMI, '') + '</td><td>' + ISNULL(TB, '') +
    --    '</td><td>' + ISNULL(COPD, '') + '</td><td>' + ISNULL(IHD, '') + '</td><td>' + ISNULL(BloodPressure, '') + '</td><td>' + ISNULL(FBS, '') +
    --    '</td><td>' + ISNULL(Cholesterol, '') + '</td><td>' + ISNULL(Triglyceride, '') + '</td><td>' + ISNULL(LDL, '') + '</td><td>' + ISNULL(HDL, '') +
    --    '</td><td>' + ISNULL(SGPT, '') + '</td><td>' + ISNULL(ECG, '') + '</td><td>' + ISNULL(Sonography, '') + '</td><td>' + ISNULL(TMT, '') +
    --    '</td><td>' + ISNULL(ECHO, '') + '</td><td>' + ISNULL(PFT, '') + '</td><td>' + ISNULL(AudiometryACRight, '') +
    --    '</td><td>' + ISNULL(AudiometryACLeft, '') + '</td><td>' + ISNULL(SerumCreatinine, '') + '</td><td>' + ISNULL(Hb, '') +
    --    '</td><td>' + ISNULL(MenzerIndex, '') + '</td><td>' + ISNULL(AbnormalXRay, '') +
    --    '</td><td>' + ISNULL(DiabeticExisting, '') + '</td><td>' + ISNULL(HypertensionExisting, '') + '</td><td>' + ISNULL(UricAcid, '') +
    --    '</td><td>' + ISNULL(IsNewDiabeticStatus, '') +
    --    '</td><td>' + ISNULL(IsNewHypertensionStatus, '') + '</td><td>' + ISNULL(ExAlcohol, '') + '</td><td>' + ISNULL(ExSmoker, '') +
    --    '</td><td>' + ISNULL(ExTobacco, '') +
    --    '</td><td>' + ISNULL(MetabolicSyndrome, '') + '</td><td>' + ISNULL(CVDMajorRisk, '') +
    --    '</td><td>' + ISNULL(CVDMinorRisk, '') + '</td><td>' + ISNULL(NCDsRisk, '') + '</td></td>' + '</td><td>' +
    --    ISNULL(T3, '') + '</td><td>' + ISNULL(T4, '') +
    --    '</td><td>' + ISNULL(TSH, '') + '</td><td>' + ISNULL(PSA, '') + '</td><td>' + ISNULL(TotalBillirubin, '') + '</td><td>' + ISNULL(Iron, '') + '</td><td>' + ISNULL(Platelets, '') +
    --    '</td><td>' + ISNULL(VitaminB12, '') + '</td><td>' + ISNULL(VitaminD3, '')
    --FROM #tempTable;
    
    -- Also return the raw data,
    SELECT ParticipantCode as [Code]	,ParticipantName as [Employee]	
	,MobileNumber as [Mobile]	,CompanyEmail as [Email]
	,age	as [Age],Gender	,Business		,Tobacco	,Smoker	,Alcohol,	AlcoholSocial	,Drug	,BMI	,TB	,COPD	,IHD	,BloodPressure,	FBS,	Cholesterol,	Triglyceride	,LDL	,HDL	,SGPT	,ECG	,Sonography	,TMT,	ECHO,	PFT,	AudiometryACRight,	AudiometryACLeft	,SerumCreatinine	,Hb	,MenzerIndex,	AbnormalXRay	,DiabeticExisting	,HypertensionExisting	,UricAcid	,NewDiabeticStatus	,NewHypertensionStatus,	ExAlcohol,ExSmoker,	ExTobacco	,MetabolicSyndrome	,CVDMajorRisk	,CVDMinorRisk	,NCDsRisk,	T3	,T4	,TSH	,PSA	,TotalBillirubin	,Iron	,Platelets	,VitaminB12	,VitaminD3 FROM #tempTable ORDER BY tId;
	

    
    -- Clean up
    DROP TABLE #tempTable;
    DROP TABLE #tempFuntionTable;
    DROP TABLE #tmpMenzerIndex;
    DROP TABLE #tempDiabeticProfileServiceValues;
    DROP TABLE #tempFBSTable;
END
GO
PRINT N'Altering Procedure [sExamination].[pDiagnosisTrackerEmployeeUpdate]...';


GO
														   
ALTER PROC [sExamination].[pDiagnosisTrackerEmployeeUpdate]     
@rMainTypeId INT,
@rOrgId INT,
@rSetupGroupId INT,
@rSetupId INT,
@rStoreLocationId INT,
@rSourceId bigint = null
WITH EXECUTE AS CALLER    
AS    
BEGIN    
 declare @tbltmp table    
 (    
  tid int identity(1,1),t_ExaminationId bigint    
 )    
     
     
 INSERT INTO @tbltmp    
 select EXM.Id    
 from sExamination.tExamination AS EXM    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND (EXM.OrgId=@rOrgId)    
 AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
 AND (SSM.MaINTypeId=@rMaINTypeId)    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
 AND EXM.Id NOT in    
 (    
  SELECT ExaminationId    
  FROM sExamination.tDiagnosisTrackerEmployee ET    
  INNER JOIN sExamination.tExamination E ON ET.ExaminationId = E.Id    
  AND ((E.SetupId=@rSetupId) OR (@rSetupId=0))    
  AND ((E.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
 )    
    
 INSERT INTO sExamination.tDiagnosisTrackerEmployee    
 (    
  ExaminationId    
 )    
 select EXM.Id    
 from sExamination.tExamination AS EXM    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND (EXM.OrgId=@rOrgId)    
 AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
 AND (SSM.MaINTypeId=@rMaINTypeId)    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
 AND EXM.Id NOT in    
 (    
  SELECT ExaminationId    
  FROM sExamination.tDiagnosisTrackerEmployee ET    
  INNER JOIN sExamination.tExamination E ON ET.ExaminationId = E.Id    
  AND ((E.SetupId=@rSetupId) OR (@rSetupId=0))    
  AND ((E.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
 )    
    
 UPDATE DTE SET DTE.TB = Details.[TB],DTE.IHD = Details.[IHD],    
 DTE.COPD = Details.[COPD]    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId    
 INNER JOIN    
 (    
  SELECT EXM.Id [ExaminationId],Details.[TB],Details.[IHD],Details.[COPD]    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT MDH.ExaminationId,    
   CASE WHEN MDH.[TB] IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [TB],    
   CASE WHEN MDH.[IHD] IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [IHD],    
   CASE WHEN MDH.[COPD] IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [COPD]    
   FROM    
   (    
    SELECT ExaminationId,[TB],[IHD],[COPD]    
    FROM    
    (    
     SELECT SDM.Title,ed.SourceId [ExaminationId]    
     FROM sExamination.tStaticDiseaseMaster AS SDM    
     INNER JOIN sExamination.tDiseaseMaster AS TDM ON TDM.StaticDiseaseId = SDM.ID AND TDM.OrgId = @rOrgId    
     INNER JOIN sExamination.tExistingDiseaseDetail AS EDD ON EDD.DiseaseId = TDM.Id    
     INNER JOIN sExamination.tExistingDisease AS ed ON ed.Id = EDD.ExistingDiseaseId    
     WHERE SDM.id IN (10, 11, 12)    
    )    
    d PIVOT    
    (    
      MAX(Title) FOR Title IN ([TB], [IHD], [COPD])    
    ) piv    
   ) AS MDH    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))     
    
 UPDATE DTE SET DTE.Tobacco = Details.Chewer,    
 DTE.Smoker = Details.Smoker,    
 DTE.Alcohol = Details.Alcohol,    
 DTE.AlcoholSocial = Details.[Alcohol-Social],    
 DTE.Drug = Details.Drugs    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId    
 LEFT JOIN    
 (    
  SELECT EXM.Id [ExaminationId],ISNULL(Details.Alcohol,0) as Alcohol,ISNULL(Details.[Alcohol-Social],0) as [Alcohol-Social],
  ISNULL(Details.Chewer,0) as Chewer, ISNULL(Details.Smoker, 0) as Smoker, ISNULL(Details.Drugs,0) as Drugs
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT MDH.ExaminationId,    
   CASE WHEN MDH.Alcohol IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [Alcohol],    
   CASE WHEN MDH.[Alcohol-Social] IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [Alcohol-Social],    
   CASE WHEN MDH.Chewer IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit)END AS Chewer,    
   CASE WHEN MDH.Smoker IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS Smoker,    
   CASE WHEN MDH.Drugs IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS Drugs    
   FROM    
   (    
    SELECT ExaminationId,[Alcohol],[Alcohol-Social],[Chewer],[Smoker],[Drugs]    
    FROM    
    (    
     SELECT SHM.Title,HHM.SourceId [ExaminationId]    
     FROM sExamination.tStaticHabitHygineMaster AS SHM    
     INNER JOIN sExamination.tHabitTypeMaster AS HTM ON HTM.StaticHabitHygineId = SHM.Id    
     INNER JOIN sExamination.tHabitHygineDetail AS HHD ON HHD.HabitId = HTM.Id    
     INNER JOIN sExamination.tHabitHygine AS HHM ON HHM.Id = HHD.HabitHygineId    
     WHERE SHM.Id IN (3, 5, 1, 2, 7)    
    )    
    d PIVOT    
    (    
     MAX(Title) FOR Title IN ([Alcohol],[Alcohol-Social],[Chewer],[Smoker],[Drugs])    
    ) piv    
   ) AS MDH    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
    
      
  declare @DiabeticProfileTestConfig varchar(10)='FBS'    
  select @DiabeticProfileTestConfig = case when Isnull(CS.ItemValue,CM.ItemValue)='HBA1C' then 'HBA1C' Else 'FBS' End    
  from sConfig.tConfigurationMaster CM    
  LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id     
  where CM.id=232    
    
  -- changes done my MS : 2023-03-17 Mensti issue :23971  
  declare @d_configval varchar(50)='Independent'    
  select @d_configval=ISNULL(CS.ItemValue,CM.ItemValue)     
  FROM sConfig.tConfigurationMaster CM    
  LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id     
  where CM.id=190  
  
 -- change Mentis Issue No:0032667 , Nidhi Pandey, DT - 10/04/2024   
 If(@DiabeticProfileTestConfig = 'HBA1C')  
 BEGIN  
   UPDATE DTE SET     
  --DTE.MenzerIndex =    
  --case when isnull(Details.[MCV],'') <> '' then    
  --case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
  DTE.FBS = Details.[HBA1C],    
  DTE.Cholesterol = Details.[CHOLESTEROL],    
  DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
  DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
  DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
  DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
  DTE.SerumCreatinine = Details.[SERUM CREATININE],    
  DTE.UricAcid = Details.[SERUM URIC ACID],    
  DTE.T3 = Details.[T3],   
  DTE.T4 = Details.[T4],
  DTE.TSH =  Details.[TSH],
  DTE.PSA =  Details.[PSA],
  DTE.TotalBillirubin =  Details.[TotalBillirubin],
  DTE.Iron  =  Details.[Iron],
  DTE.Platelets =  Details.[Platelets],
  DTE.VitaminB12 =  Details.[VitaminB12],
  DTE.VitaminD3  =  Details.[VitaminD3]
  FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
  INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
  INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
  INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
  INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
  INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
  INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId    
  INNER JOIN    
  (    
   SELECT [ExaminationId],Details.[R.B.C. COUNT],Details.[MCV],Details.[F B S],Details.[CHOLESTEROL],    
   Details.[TRIGLYCERIDE],Details.[LDL],Details.[HDL],Details.[SGPT],    
   Details.[ECG],Details.[SONOGRAPHY],Details.[TMT],Details.[ECHO],    
   Details.[HB],Details.[SERUM CREATININE],Details.[SERUM URIC ACID],[HBA1C],[R B S],[P P B S],[T3] ,[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]    
   FROM sExamination.tExamination AS EXM    
   INNER JOIN    
   (    
    SELECT ExaminationId,[R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],    
    [SGPT],[ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],    
    [SERUM URIC ACID],[HBA1C],[R B S],[P P B S] ,[T3],[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]    
    FROM    
    (    
     SELECT SPM.Title,TR.SourceId [ExaminationId],    
     TRD.Diagnosis    
     FROM sOrderEntry.tStaticTestParameterMaster AS SPM    
     INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id    
     INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id    
     INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id    
     INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId    
     WHERE SPM.id IN (3, 5, 19, 20, 21, 25, 31, 32, 33, 34, 38, 107, 105, 109, 108, 2, 27, 49,15,52,53,54,58,158,40,126,127)    
    )    
    d PIVOT    
    (    
     MIN(Diagnosis) FOR Title IN    
     (    
      [R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],[SGPT],    
      [ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],[SERUM URIC ACID],[HBA1C],[R B S],[P P B S],[T3],[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]
     )    
    ) piv    
   ) AS Details ON Details.ExaminationId = EXM.ID    
  ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
  WHERE EXM.ParticipantSourceTypeId=95    
  AND EXM.OrgId=@rOrgId    
  AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
  AND SSM.MaINTypeId=@rMaINTypeId    
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
  AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
  AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))  
 END  
 ELSE  
 BEGIN  
 if (@d_configval ='Independent')  
 BEGIN  
   UPDATE DTE SET     
   --DTE.MenzerIndex =    
   --case when isnull(Details.[MCV],'') <> '' then    
   --case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
   DTE.FBS = Details.[F B S] ,    
   DTE.Cholesterol = Details.[CHOLESTEROL],    
   DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
   DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
   DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
   DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
   DTE.SerumCreatinine = Details.[SERUM CREATININE],    
   DTE.UricAcid = Details.[SERUM URIC ACID],  
   DTE.T3 = Details.[T3],   
   DTE.T4 = Details.[T4],
   DTE.TSH =  Details.[TSH],
   DTE.PSA =  Details.[PSA],
   DTE.TotalBillirubin =  Details.[TotalBillirubin],
   DTE.Iron  =  Details.[Iron],
   DTE.Platelets =  Details.[Platelets],
   DTE.VitaminB12 =  Details.[VitaminB12],
   DTE.VitaminD3  =  Details.[VitaminD3]
   FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
   INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
   INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
   INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
   INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
   INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
   INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId    
   INNER JOIN    
   (    
    SELECT [ExaminationId],Details.[R.B.C. COUNT],Details.[MCV],Details.[F B S],Details.[CHOLESTEROL],    
    Details.[TRIGLYCERIDE],Details.[LDL],Details.[HDL],Details.[SGPT],    
    Details.[ECG],Details.[SONOGRAPHY],Details.[TMT],Details.[ECHO],    
    Details.[HB],Details.[SERUM CREATININE],Details.[SERUM URIC ACID],[HBA1C],[R B S],[P P B S],[T3],[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]   
    FROM sExamination.tExamination AS EXM    
    INNER JOIN    
    (    
     SELECT ExaminationId,[R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],    
     [SGPT],[ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],    
     [SERUM URIC ACID],[HBA1C],[R B S],[P P B S],[T3],[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]
     FROM    
     (    
      SELECT SPM.Title,TR.SourceId [ExaminationId],    
      TRD.Diagnosis    
      FROM sOrderEntry.tStaticTestParameterMaster AS SPM    
      INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id    
      INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id    
      INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id    
      INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId    
      WHERE SPM.id IN (3, 5, 19, 20, 21, 25, 31, 32, 33, 34, 38, 107, 105, 109, 108, 2, 27, 49,15,52,53,54,58,158,40,126,127)    
     )    
     d PIVOT    
     (    
      MIN(Diagnosis) FOR Title IN    
      (    
       [R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],[SGPT],    
       [ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],[SERUM URIC ACID],[HBA1C],[R B S],[P P B S],[T3],[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]
      )    
     ) piv    
    ) AS Details ON Details.ExaminationId = EXM.ID    
   ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
   WHERE EXM.ParticipantSourceTypeId=95    
   AND EXM.OrgId=@rOrgId    
   AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
   AND SSM.MaINTypeId=@rMaINTypeId    
   AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
   AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
   AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))   
  END  
  else if (@d_configval ='Priority Abnormal')  
  BEGIN  
   UPDATE DTE SET     
   --DTE.MenzerIndex =    
   --case when isnull(Details.[MCV],'') <> '' then    
   --case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
   DTE.FBS = case when Details.[HBA1C]<>'Normal' then Details.[HBA1C] else    
    case when Details.[F B S]<>'Normal' then Details.[F B S] else   
    case when Details.[P P B S]<>'Normal' then Details.[P P B S] else Details.[R B S] end end end,    
   DTE.Cholesterol = Details.[CHOLESTEROL],    
   DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
   DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
   DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
   DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
   DTE.SerumCreatinine = Details.[SERUM CREATININE],    
   DTE.UricAcid = Details.[SERUM URIC ACID],
   DTE.T3 = Details.[T3],   
   DTE.T4 = Details.[T4],
   DTE.TSH =  Details.[TSH],
   DTE.PSA =  Details.[PSA],
   DTE.TotalBillirubin =  Details.[TotalBillirubin],
   DTE.Iron  =  Details.[Iron],
   DTE.Platelets =  Details.[Platelets],
   DTE.VitaminB12 =  Details.[VitaminB12],
   DTE.VitaminD3  =  Details.[VitaminD3]
   FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
   INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
   INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
   INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
   INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
   INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
   INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId    
   INNER JOIN    
   (    
    SELECT [ExaminationId],Details.[R.B.C. COUNT],Details.[MCV],Details.[F B S],Details.[CHOLESTEROL],    
    Details.[TRIGLYCERIDE],Details.[LDL],Details.[HDL],Details.[SGPT],    
    Details.[ECG],Details.[SONOGRAPHY],Details.[TMT],Details.[ECHO],    
    Details.[HB],Details.[SERUM CREATININE],Details.[SERUM URIC ACID],[HBA1C],[R B S],[P P B S],[T3],[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]    
    FROM sExamination.tExamination AS EXM    
    INNER JOIN    
    (    
     SELECT ExaminationId,[R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],    
     [SGPT],[ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],    
     [SERUM URIC ACID],[HBA1C],[R B S],[P P B S],[T3],[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]  
     FROM    
     (    
      SELECT SPM.Title,TR.SourceId [ExaminationId],    
      TRD.Diagnosis    
      FROM sOrderEntry.tStaticTestParameterMaster AS SPM    
      INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id    
      INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id    
      INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id    
      INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId    
      WHERE SPM.id IN (3, 5, 19, 20, 21, 25, 31, 32, 33, 34, 38, 107, 105, 109, 108, 2, 27, 49,15,52,53,54,58,158,40,126,127)    
     )    
     d PIVOT    
     (    
      MIN(Diagnosis) FOR Title IN    
      (    
       [R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],[SGPT],    
       [ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],[SERUM URIC ACID],[HBA1C],[R B S],[P P B S],[T3],[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]    
      )    
     ) piv    
    ) AS Details ON Details.ExaminationId = EXM.ID    
   ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
   WHERE EXM.ParticipantSourceTypeId=95    
   AND EXM.OrgId=@rOrgId    
   AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
   AND SSM.MaINTypeId=@rMaINTypeId    
   AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
   AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
   AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))   
  END  
  else if (@d_configval ='Priority')  
  BEGIN  
   UPDATE DTE SET     
   --DTE.MenzerIndex =    
   --case when isnull(Details.[MCV],'') <> '' then    
   --case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
  DTE.FBS = case when ISNULL(Details.[HBA1C],'')<>'' then Details.[HBA1C] else    
    case when ISNULL(Details.[F B S],'')<>'' then Details.[F B S] else   
    case when ISNULL(Details.[P P B S],'')<>'' then Details.[P P B S] else Details.[R B S] end end end,   
   DTE.Cholesterol = Details.[CHOLESTEROL],    
   DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
   DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
   DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
   DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
   DTE.SerumCreatinine = Details.[SERUM CREATININE],    
   DTE.UricAcid = Details.[SERUM URIC ACID],
   DTE.T3 = Details.[T3],   
  DTE.T4 = Details.[T4],
  DTE.TSH =  Details.[TSH],
  DTE.PSA =  Details.[PSA],
  DTE.TotalBillirubin =  Details.[TotalBillirubin],
  DTE.Iron  =  Details.[Iron],
  DTE.Platelets =  Details.[Platelets],
  DTE.VitaminB12 =  Details.[VitaminB12],
  DTE.VitaminD3  =  Details.[VitaminD3]
   FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
   INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
   INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
   INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
   INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
   INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
   INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId    
   INNER JOIN    
   (    
    SELECT [ExaminationId],Details.[R.B.C. COUNT],Details.[MCV],Details.[F B S],Details.[CHOLESTEROL],    
    Details.[TRIGLYCERIDE],Details.[LDL],Details.[HDL],Details.[SGPT],    
    Details.[ECG],Details.[SONOGRAPHY],Details.[TMT],Details.[ECHO],    
    Details.[HB],Details.[SERUM CREATININE],Details.[SERUM URIC ACID],[HBA1C],[R B S],[P P B S],[T3] ,[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]  
    FROM sExamination.tExamination AS EXM    
    INNER JOIN    
    (    
     SELECT ExaminationId,[R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],    
     [SGPT],[ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],    
     [SERUM URIC ACID],[HBA1C],[R B S],[P P B S],[T3] ,[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]      
     FROM    
     (    
      SELECT SPM.Title,TR.SourceId [ExaminationId],    
      TRD.Diagnosis    
      FROM sOrderEntry.tStaticTestParameterMaster AS SPM    
      INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id    
      INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id    
      INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id    
      INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId    
      WHERE SPM.id IN (3, 5, 19, 20, 21, 25, 31, 32, 33, 34, 38, 107, 105, 109, 108, 2, 27, 49,15,52,53,54,58,158,40,126,127)    
     )    
     d PIVOT    
     (    
      MIN(Diagnosis) FOR Title IN    
      (    
       [R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],[SGPT],    
       [ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],[SERUM URIC ACID],[HBA1C],[R B S],[P P B S],[T3],[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]     
      )    
     ) piv    
    ) AS Details ON Details.ExaminationId = EXM.ID    
   ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
   WHERE EXM.ParticipantSourceTypeId=95    
   AND EXM.OrgId=@rOrgId    
   AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
   AND SSM.MaINTypeId=@rMaINTypeId    
   AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
   AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
   AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))   
  END  
 END   
 -- change Mentis Issue No:0032667 , Nidhi Pandey, DT - 10/04/2024    
 -- change calculation Menzer Index For Mentis Issue No:0011065    
 UPDATE DTE SET DTE.MenzerIndex =    
 case when (isnull(Details.[R.B.C. COUNT],'') <> '' and isnull(Details.[MCV],'') <> '') then    
 case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end    
 --,    
 --DTE.FBS = Details.[F B S],DTE.Cholesterol = Details.[CHOLESTEROL],    
 --DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
 --DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
 --DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
 --DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
 --DTE.SerumCreatinine = Details.[SERUM CREATININE],    
 --DTE.UricAcid = Details.[SERUM URIC ACID]    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId    
 INNER JOIN    
 (    
  SELECT [ExaminationId],Details.[R.B.C. COUNT],Details.[MCV],Details.[F B S],Details.[CHOLESTEROL],    
  Details.[TRIGLYCERIDE],Details.[LDL],Details.[HDL],Details.[SGPT],    
  Details.[ECG],Details.[SONOGRAPHY],Details.[TMT],Details.[ECHO],    
  Details.[HB],Details.[SERUM CREATININE],Details.[SERUM URIC ACID] ,Details.[T3],[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT ExaminationId,[R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],    
   [SGPT],[ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],    
   [SERUM URIC ACID],[T3],[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]       
   FROM    
   (    
    SELECT SPM.Title,TR.SourceId [ExaminationId],    
    TRD.ServiceValue    
    FROM sOrderEntry.tStaticTestParameterMaster AS SPM    
    INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id    
    INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id    
    INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id    
    INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId    
    WHERE SPM.id IN (3, 5, 19, 31, 32, 33, 34, 38, 107, 105, 109, 108, 2, 27, 49,15,52,53,54,58,158,40,126,127)    
   )    
   d PIVOT    
   (    
    MIN(ServiceValue) FOR Title IN    
    (    
     [R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],[SGPT],    
     [ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],[SERUM URIC ACID],[T3] ,[T4],[TSH],[PSA],[TotalBillirubin],[Iron],[Platelets],[VitaminB12],[VitaminD3]    
    )    
   ) piv    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
      
 UPDATE DTE SET DTE.AbnormalXRay = CASE WHEN [XRAY] = 'Abnormal' then 1 else 0 end    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId    
 INNER JOIN    
 (    
  SELECT EXM.Id [ExaminationId],Details.[XRAY]    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT ExaminationId,[XRAY]    
   FROM    
   (    
    SELECT SPM.Title,TR.SourceId [ExaminationId],    
    TRD.ServiceValue    
    FROM sOrderEntry.tStaticTestParameterMaster AS SPM    
    INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id    
    INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id    
    INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id    
    INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId    
    WHERE SPM.id IN (104)    
   )    
   d PIVOT    
   (    
    MIN(ServiceValue) FOR Title IN    
    (    
     [XRAY]    
    )    
   ) piv    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
    
 UPDATE DTE SET DTE.AudiometryACRight = Details.AudiometryACRight,    
 DTE.AudiometryACLeft = Details.AudiometryACLeft    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId    
 INNER JOIN    
 (    
  SELECT EXM.Id [ExaminationId],a.AudiometryACLeft,B.[AudiometryACRight]    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT ADU.SourceId [ExaminationId],ARM.Title [AudiometryACLeft]    
   FROM [sExamination].[tAudiometry] AS ADU    
   INNER JOIN sExamination.tAudiometryResultMaster AS ARM ON ARM.Id = ADU.AudiometryAcResultLeftId AND ARM.Id <> 1    
  ) AS A ON A.[ExaminationId] = EXM.Id    
  INNER JOIN    
  (    
   SELECT ADU.SourceId [ExaminationId],ARM.Title [AudiometryACRight]    
   FROM [sExamination].[tAudiometry] AS ADU    
   INNER JOIN sExamination.tAudiometryResultMaster AS ARM ON ARM.Id = ADU.AudiometryAcResultRightId AND ARM.Id <> 1    
  ) AS B ON B.[ExaminationId] = EXM.Id    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
     
 UPDATE DTE SET DTE.PFT = Details.PFT    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM  ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId    
 INNER JOIN    
 (    
  SELECT EXM.ID [ExaminationId],PLM.PFT    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT SourceId [ExaminationId],    
   CASE WHEN ISNULL(PerOfFEV1ByFVC, 0.00) <> 0.00 THEN CASE WHEN PerOfFEV1ByFVC >= 80 THEN    
   CASE WHEN ISNULL(PerOfPredictedFVC, 0.00) <> 0.00 THEN CASE WHEN PerOfPredictedFVC < 80 THEN 'Restrictive Lung Disease'    
   ELSE NULL END ELSE NULL END ELSE CASE WHEN ISNULL(PerOfPredictedFVC, 0.00) <> 0.00 THEN    
   CASE WHEN PerOfPredictedFVC < 80 THEN 'Mix Lung Disease' ELSE 'Obstructive Lung Disease' END    
   ELSE NULL END END ELSE NULL END AS [PFT]    
   FROM sExamination.tPulmonary    
  ) AS PLM ON PLM.[ExaminationId] = EXM.ID    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
     
 UPDATE DTE SET DTE.BMI = Details.BMI,DTE.BloodPressure = case when Details.BloodPressure='High Normal' then 'PreHypertension'     
 WHEN (Details.BloodPressure='Stage I HTN' Or Details.BloodPressure='Stage II HTN' Or Details.BloodPressure='Stage III HTN') Then 'Hypertension'     
 when Details.BloodPressure='Optimal' then ''    
 when Details.BloodPressure='Normal' then ''     
 Else Details.BloodPressure End    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM  ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId    
 INNER JOIN    
 (    
  SELECT EXM.ID [ExaminationId],Details.[BMI],Details.[BloodPressure]    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT VTL.SourceId [ExaminationId],    
   [sExamination].[fBMIValueGet](ISNULL(BMI, 0)) [BMI],    
   [sExamination].[fBMIBloodPressureResultGet](ISNULL(BloodPressureSystolic, 0),ISNULL(BloodPressureDiastolic, 0),@rOrgId) [BloodPressure]    
   FROM sExamination.tVital AS VTL    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
     
 UPDATE DTE SET DTE.DiabeticExisting = Details.[DM],DTE.HypertensionExisting = Details.[HBP]    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId    
 INNER JOIN    
 (    
  SELECT EXM.Id [ExaminationId],ISNULL(Details.[DM],'') [DM],ISNULL(Details.[HBP],'') [HBP]    
  FROM sExamination.tExamination AS EXM    
  LEFT JOIN    
  (    
   SELECT MDH.ExaminationId,    
   CASE WHEN MDH.[DM] IS NOT NULL THEN 'Diabetic Existing'    
   ELSE '' END AS [DM],    
   CASE WHEN MDH.[HBP] IS NOT NULL THEN 'Hypertension Existing'    
   ELSE '' END AS [HBP]    
   FROM    
   (    
    SELECT ExaminationId,[DM],[HBP]    
    FROM    
    (    
     SELECT SDM.Title,Ed.SourceId [ExaminationId]    
     FROM sExamination.tStaticDiseaseMaster AS SDM    
     INNER JOIN sExamination.tDiseaseMaster AS TDM ON TDM.StaticDiseaseId = SDM.ID AND TDM.OrgId = @rOrgId    
     --INNER JOIN sExamination.tHistoryDetail AS EDD ON EDD.DiseaseId = TDM.Id    
     --INNER JOIN sExamination.tHistory AS ed ON ed.Id = EDD.HistoryId     
  LEFT JOIN sExamination.tExistingDiseaseDetail As EDD ON EDD.DiseaseId = TDM.Id --mantis issue - 32667, DT - 10/04/2024, Nidhi Pandey  
  LEFT JOIN sExamination.tExistingDisease As ED ON ed.Id = EDD.ExistingDiseaseId --mantis issue - 32667, DT - 10/04/2024, Nidhi Pandey    
     WHERE SDM.id IN (7,13) and (IsSelfDeclared = 1 or IsDiagnosed = 1)  --mantis issue - 32667, DT - 10/04/2024, Nidhi Pandey    
    )    
    d PIVOT    
    (    
      MAX(Title) FOR Title IN ([DM],[HBP])    
    ) piv    
   ) AS MDH    
  ) AS Details ON Details.ExaminationId = EXM.Id    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
  
 declare @TrackerUpdateBasedOnconfigval varchar(50)='Value'    
 select @TrackerUpdateBasedOnconfigval=ISNULL(CS.ItemValue,CM.ItemValue)     
 FROM sConfig.tConfigurationMaster CM    
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id     
 where CM.id=336
    
UPDATE DTE
SET DTE.IsNewDiabeticStatus =
        CASE
            -- LTE EXISTS → use LTE logic
            WHEN LTE.ParticipantSourceId IS NOT NULL THEN
                CASE WHEN ISNULL(LTE.DiabeticExisting,'') = '' AND ISNULL(LTE.FBS,'Normal') = 'Normal'
                          AND ISNULL(DTE.FBS,'') = 'Pre Diabetic' THEN 1
                    WHEN ISNULL(LTE.DiabeticExisting,'') = '' AND ISNULL(LTE.FBS,'Normal') IN ('Normal','Pre Diabetic')
                         AND ISNULL(DTE.FBS,'') = 'Diabetic' THEN 2
					WHEN ISNULL(DTE.DiabeticExisting,'') <> '' THEN 0
                    ELSE DTE.IsNewDiabeticStatus END
            -- LTE NOT EXISTS → fallback logic
            ELSE
                CASE WHEN ISNULL(DTE.DiabeticExisting,'') <> '' THEN 0
                    WHEN ISNULL(DTE.FBS,'') = 'Pre Diabetic' THEN 1
					WHEN ISNULL(DTE.FBS,'') = 'Diabetic' THEN 2
                    ELSE DTE.IsNewDiabeticStatus END
        END,
    DTE.IsNewHypertensionStatus =
        CASE
            -- LTE EXISTS → use LTE logic
            WHEN LTE.ParticipantSourceId IS NOT NULL THEN
                CASE WHEN ISNULL(LTE.HypertensionExisting,'') = '' AND ISNULL(LTE.BloodPressure,'') = ''
                          AND ISNULL(DTE.BloodPressure,'') = 'PreHypertension' THEN 1
                    WHEN ISNULL(LTE.HypertensionExisting,'') = '' AND ISNULL(LTE.BloodPressure,'') IN ('','PreHypertension')
                         AND ISNULL(DTE.BloodPressure,'') = 'Hypertension' THEN 2
					WHEN ISNULL(DTE.HypertensionExisting,'') <> '' THEN 0
                    ELSE DTE.IsNewHypertensionStatus END
            -- LTE NOT EXISTS → fallback logic
            ELSE
                CASE WHEN ISNULL(DTE.HypertensionExisting,'') <> '' THEN 0
                    WHEN ISNULL(DTE.BloodPressure,'') = 'PreHypertension' THEN 1
                    WHEN ISNULL(DTE.BloodPressure,'') = 'Hypertension' THEN 2
                    ELSE DTE.IsNewHypertensionStatus END
        END
		FROM sExamination.tDiagnosisTrackerEmployee AS DTE
		INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId
		INNER JOIN sExamination.tExamination AS EXM
			ON EXM.Id = DTE.ExaminationId
		INNER JOIN [sExamination].[tSetupMaster] AS STM
			ON STM.ID = EXM.SetupId
		INNER JOIN [sIp].[tStoreLocationMaster] AS SLM
			ON SLM.Id = EXM.StoreLocationId
		LEFT JOIN [sExamination].[tLSDTrackerEmployee] AS LTE
			ON EXM.ParticipantSourceId = LTE.ParticipantSourceId
		   AND EXM.ParticipantSourceTypeId = LTE.ParticipantSourceTypeId
		WHERE EXM.OrgId = @rOrgId
		  AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)
		  AND EXM.SetupId = @rSetupId
		  AND EXM.StoreLocationId = @rStoreLocationId;
 
 if(@TrackerUpdateBasedOnconfigval = 'Diagnosis')
 BEGIN
		UPDATE DTE SET DTE.IsNewDiabeticStatus = case when Isnull(DIA.IsNewDiabatic,0) = 1 then 2
				 else DTE.IsNewDiabeticStatus end,
			   DTE.IsNewHypertensionStatus=case when Isnull(DIA.IsNewHyperTension,0) = 1 then 2
					  else DTE.IsNewHypertensionStatus end
			   FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
			   INNER JOIN @tbltmp t ON t.t_ExaminationId = DTE.ExaminationId
			   INNER JOIN sExamination.tDiagnosis DIA ON DIA.SourceId = DTE.ExaminationId
			   INNER JOIN sExamination.tExamination AS EXM ON EXM.Id = DIA.SourceId
			   INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId       
			   INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId       
			   WHERE EXM.OrgId=@rOrgId    
			   AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)
			   AND ((EXM.SetupId=@rSetupId))    
			   AND ((EXM.StoreLocationId=@rStoreLocationId))
 END

 if(@rSetupId=0 and @rStoreLocationId=0)    
 begin    
  update sExamination.tSetupMaster set IsDiagnosisTrackerUpdated=1 where SetupGroupId=@rSetupGroupId and OrgId=@rOrgId    
 end    
 else if (@rSetupId=0)    
 begin    
  update sExamination.tSetupMaster set IsDiagnosisTrackerUpdated=1 where SetupGroupId=@rSetupGroupId and OrgId=@rOrgId and StoreLocationId=@rStoreLocationId    
 end    
 else    
 begin    
  update sExamination.tSetupMaster set IsDiagnosisTrackerUpdated=1 where SetupGroupId=@rSetupGroupId and Id=@rSetupId and OrgId=@rOrgId    
 end    
     
 declare @cnt int    
 select @cnt = count(1) from @tbltmp    
     
 select 1  Status,'Diagnosis Tracker Employee ' + convert(varchar,@cnt) + ' Record Updated Successfully..!!' [Message]    
     
 option(recompile)    
END
GO
PRINT N'Altering Procedure [sExamination].[pDiagnosisTrackerEmployeeUpdateALL]...';


GO

ALTER PROC [sExamination].[pDiagnosisTrackerEmployeeUpdateALL]
@rMainTypeId INT,    
@rOrgId INT,    
@rSetupGroupId INT,    
@rSetupId INT,    
@rStoreLocationId INT,    
@rSourceId bigint = 0    
WITH EXECUTE AS CALLER    
AS    
BEGIN     
 INSERT INTO sExamination.tDiagnosisTrackerEmployee    
 (    
  ExaminationId    
 )    
 select EXM.Id    
 from sExamination.tExamination AS EXM    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND (EXM.OrgId=@rOrgId)    
 AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
 AND (SSM.MaINTypeId=@rMaINTypeId)    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
 AND EXM.Id NOT in    
 (    
  SELECT ExaminationId    
  FROM sExamination.tDiagnosisTrackerEmployee ET    
  INNER JOIN sExamination.tExamination E ON ET.ExaminationId = E.Id    
  AND ((E.SetupId=@rSetupId) OR (@rSetupId=0))    
  AND ((E.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
 )    
     
 UPDATE DTE SET DTE.TB = Details.[TB],DTE.IHD = Details.[IHD],    
 DTE.COPD = Details.[COPD]    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId     
 INNER JOIN    
 (    
  SELECT EXM.Id [ExaminationId],Details.[TB],Details.[IHD],Details.[COPD]    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT MDH.ExaminationId,    
   CASE WHEN MDH.[TB] IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [TB],    
   CASE WHEN MDH.[IHD] IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [IHD],    
   CASE WHEN MDH.[COPD] IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [COPD]    
   FROM    
   (    
    SELECT ExaminationId,[TB],[IHD],[COPD]    
    FROM    
    (    
     SELECT SDM.Title,ed.SourceId [ExaminationId]    
     FROM sExamination.tStaticDiseaseMaster AS SDM    
     INNER JOIN sExamination.tDiseaseMaster AS TDM ON TDM.StaticDiseaseId = SDM.ID AND TDM.OrgId = @rOrgId    
     INNER JOIN sExamination.tExistingDiseaseDetail AS EDD ON EDD.DiseaseId = TDM.Id    
     INNER JOIN sExamination.tExistingDisease AS ed ON ed.Id = EDD.ExistingDiseaseId    
     WHERE SDM.id IN (10, 11, 12)    
    )    
    d PIVOT    
    (    
      MAX(Title) FOR Title IN ([TB], [IHD], [COPD])    
    ) piv    
   ) AS MDH    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))     
     
 UPDATE DTE SET DTE.Tobacco = Details.Chewer,    
 DTE.Smoker = Details.Smoker,    
 DTE.Alcohol = Details.Alcohol,    
 DTE.AlcoholSocial = Details.[Alcohol-Social],    
 DTE.Drug = Details.Drugs,    
 DTE.ExTobacco=case when Details.Chewer=0 and Isnull(LTE.Tobacco,0)=1 then 1 else DTE.ExTobacco end,    
 DTE.ExSmoker=case when Details.Smoker=0 and Isnull(LTE.Smoker,0)=1 then 1 else DTE.ExSmoker end,    
 DTE.ExAlcohol=case when Details.Alcohol=0 and Isnull(LTE.Alcohol,0)=1 then 1 else DTE.ExAlcohol end    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 LEFT JOIN [sExamination].[tLSDTrackerEmployee] AS LTE ON EXM.ParticipantSourceId=LTE.ParticipantSourceId and EXM.ParticipantSourceTypeId=LTE.ParticipantSourceTypeId    
 LEFT JOIN    
 (    
  SELECT EXM.Id [ExaminationId],ISNULL(Details.Alcohol,0) as Alcohol,ISNULL(Details.[Alcohol-Social],0) as [Alcohol-Social],
  ISNULL(Details.Chewer,0) as Chewer, ISNULL(Details.Smoker, 0) as Smoker, ISNULL(Details.Drugs,0) as Drugs 
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT MDH.ExaminationId,    
   CASE WHEN MDH.Alcohol IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [Alcohol],    
   CASE WHEN MDH.[Alcohol-Social] IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [Alcohol-Social],    
   CASE WHEN MDH.Chewer IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit)END AS Chewer,    
   CASE WHEN MDH.Smoker IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS Smoker,    
   CASE WHEN MDH.Drugs IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS Drugs    
   FROM    
   (    
    SELECT ExaminationId,[Alcohol],[Alcohol-Social],[Chewer],[Smoker],[Drugs]    
    FROM    
    (    
     SELECT SHM.Title,HHM.SourceId [ExaminationId]    
     FROM sExamination.tStaticHabitHygineMaster AS SHM    
     INNER JOIN sExamination.tHabitTypeMaster AS HTM ON HTM.StaticHabitHygineId = SHM.Id    
     INNER JOIN sExamination.tHabitHygineDetail AS HHD ON HHD.HabitId = HTM.Id    
     INNER JOIN sExamination.tHabitHygine AS HHM ON HHM.Id = HHD.HabitHygineId    
     WHERE SHM.Id IN (3, 5, 1, 2, 7)    
    )    
    d PIVOT    
    (    
     MAX(Title) FOR Title IN ([Alcohol],[Alcohol-Social],[Chewer],[Smoker],[Drugs])    
    ) piv    
   ) AS MDH    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
  
 IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp;  
  
 create table #tmp (tid int identity(1,1),[ExaminationId] bigint,[R.B.C. COUNT] nvarchar(100),[MCV] nvarchar(100),[F B S] nvarchar(100),[CHOLESTEROL] nvarchar(100),    
 [TRIGLYCERIDE] nvarchar(100),[LDL] nvarchar(100),[HDL] nvarchar(100),[SGPT] nvarchar(100),[ECG] nvarchar(100),[SONOGRAPHY] nvarchar(100),[TMT] nvarchar(100),    
 [ECHO] nvarchar(100),[HB] nvarchar(100),[SERUM CREATININE] nvarchar(100),[SERUM URIC ACID] nvarchar(100),[P P B S] nvarchar(100),[HBA1C] nvarchar(100),[R B S] nvarchar(100),[T3] nvarchar(50)
 ,[T4] nvarchar(50),[TSH] nvarchar(50),[PSA] nvarchar(50) ,[TotalBillirubin] nvarchar(100) ,[Iron] nvarchar(50) ,[Platelets] nvarchar(50),[VitaminB12] nvarchar(100),[VitaminD3]  nvarchar(100) )    
    
 insert into #tmp    
 SELECT [ExaminationId],Details.[R.B.C. COUNT],Details.[MCV],Details.[F B S],Details.[CHOLESTEROL],    
  Details.[TRIGLYCERIDE],Details.[LDL],Details.[HDL],Details.[SGPT],    
  Details.[ECG],Details.[SONOGRAPHY],Details.[TMT],Details.[ECHO],    
  Details.[HB],Details.[SERUM CREATININE],Details.[SERUM URIC ACID],Details.[P P B S],Details.[HBA1C],Details.[R B S] ,Details.[T3] ,Details.[T4],Details.[TSH],Details.[PSA],Details.[TotalBillirubin],Details.[Iron],Details.[Platelets],Details.[VitaminB12],Details.[VitaminD3]  
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT ExaminationId,[R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],    
   [SGPT],[ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],    
   [SERUM URIC ACID],[P P B S],[HBA1C],[R B S] ,[T3] ,[T4],[TSH],[PSA],[TOTAL BILIRUBIN] as [TotalBillirubin],[Iron],
   [Platelets],[Vitamin B12] as [VitaminB12],[Vitamin D3] as [VitaminD3]
   FROM    
   (    
    SELECT SPM.Title,TR.SourceId [ExaminationId],    
    Case when SPM.id IN (19, 20, 21, 25, 31, 33, 34) then     
    case when Isnull(TRD.Diagnosis,'')='' and Isnull(TRD.ServiceValue,'')<>'' then 'Normal'    
    when Isnull(TRD.Diagnosis,'')='' and Isnull(TRD.ServiceValue,'')='' then Null    
    else TRD.Diagnosis end else TRD.Diagnosis end as Diagnosis    
    FROM sOrderEntry.tStaticTestParameterMaster AS SPM    
    INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id    
    INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id    
    INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id    
    INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId    
    WHERE SPM.id IN (3, 5, 19, 20, 21, 25, 31, 32, 33, 34, 38,40, 107, 105, 109, 108, 2, 27, 49,15,52,53,54,58,158,126,127)   
   )    
   d PIVOT    
   (    
    MIN(Diagnosis) FOR Title IN    
    (    
     [R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],[SGPT],    
     [ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],[SERUM URIC ACID],[P P B S],[HBA1C],[R B S],[T3],[T4],[TSH],[PSA],
	 [TOTAL BILIRUBIN],[Iron],[Platelets],[Vitamin B12],[Vitamin D3]   
    )    
   ) piv    
  ) AS Details ON Details.ExaminationId = EXM.ID    
   -- select * from #tmp where [ExaminationId] = 21249;
  declare @DiabeticProfileTestConfig varchar(10)='FBS'    
  select @DiabeticProfileTestConfig = case when Isnull(CS.ItemValue,CM.ItemValue)='HBA1C' then 'HBA1C' Else 'FBS' End    
  from sConfig.tConfigurationMaster CM    
  LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id     
  where CM.id=232    
  
  -- changes done my MS : 2023-03-17 Mensti issue :23971  
  declare @d_configval varchar(50)='Independent'    
 select @d_configval=ISNULL(CS.ItemValue,CM.ItemValue)     
 FROM sConfig.tConfigurationMaster CM    
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id     
 where CM.id=190  
    
    
   
 -- change Mentis Issue No:0032667 , Nidhi Pandey, DT - 10/04/2024   
 If(@DiabeticProfileTestConfig = 'HBA1C')  
 BEGIN  
   UPDATE DTE SET     
  --DTE.MenzerIndex =    
  --case when isnull(Details.[MCV],'') <> '' then    
  --case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
  DTE.FBS = Details.[HBA1C],    
  DTE.Cholesterol = Details.[CHOLESTEROL],    
  DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
  DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
  DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
  DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
  DTE.SerumCreatinine = Details.[SERUM CREATININE],    
  DTE.UricAcid = Details.[SERUM URIC ACID],
  DTE.T3 = Details.[T3],
  DTE.T4 = Details.[T4],
  DTE.TSH =  Details.[TSH],
  DTE.PSA =  Details.[PSA],
  DTE.TotalBillirubin =  Details.[TotalBillirubin],
  DTE.Iron  =  Details.[Iron],
  DTE.Platelets =  Details.[Platelets],
  DTE.VitaminB12 =  Details.[VitaminB12],
  DTE.VitaminD3  =  Details.[VitaminD3]
  FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
  INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
  INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
  INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
  INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
  INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
  INNER JOIN #tmp AS Details ON Details.ExaminationId = DTE.ExaminationId    
  WHERE EXM.ParticipantSourceTypeId=95    
  AND EXM.OrgId=@rOrgId    
  AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
  AND SSM.MaINTypeId=@rMaINTypeId    
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
  AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
  AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))   
 END  
 ELSE  
 BEGIN  
 if (@d_configval ='Independent')  
 BEGIN  
   UPDATE DTE SET     
   --DTE.MenzerIndex =    
   --case when isnull(Details.[MCV],'') <> '' then    
   --case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
   DTE.FBS = Details.[F B S] ,    
   DTE.Cholesterol = Details.[CHOLESTEROL],    
   DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
   DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
   DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
   DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
   DTE.SerumCreatinine = Details.[SERUM CREATININE],    
   DTE.UricAcid = Details.[SERUM URIC ACID] ,
   DTE.T3 =  Details.[T3],
   DTE.T4 = Details.[T4],
   DTE.TSH =  Details.[TSH],
   DTE.PSA =  Details.[PSA],
   DTE.TotalBillirubin =  Details.[TotalBillirubin],
   DTE.Iron  =  Details.[Iron],
   DTE.Platelets =  Details.[Platelets],
   DTE.VitaminB12 =  Details.[VitaminB12],
   DTE.VitaminD3  =  Details.[VitaminD3]
   FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
   INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
   INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
   INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
   INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
   INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
   INNER JOIN #tmp AS Details ON Details.ExaminationId = DTE.ExaminationId    
   WHERE EXM.ParticipantSourceTypeId=95    
   AND EXM.OrgId=@rOrgId    
   AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
   AND SSM.MaINTypeId=@rMaINTypeId    
   AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
   AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
   AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
  END  
  else if (@d_configval ='Priority Abnormal')  
  BEGIN  
   UPDATE DTE SET     
   --DTE.MenzerIndex =    
   --case when isnull(Details.[MCV],'') <> '' then    
   --case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
   DTE.FBS = case when Details.[HBA1C]<>'Normal' then Details.[HBA1C] else    
    case when Details.[F B S]<>'Normal' then Details.[F B S] else   
    case when Details.[P P B S]<>'Normal' then Details.[P P B S] else Details.[R B S] end end end,    
   DTE.Cholesterol = Details.[CHOLESTEROL],    
   DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
   DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
   DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
   DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
   DTE.SerumCreatinine = Details.[SERUM CREATININE],    
   DTE.UricAcid = Details.[SERUM URIC ACID], 
   DTE.T3 = Details.[T3]  ,
   DTE.T4 = Details.[T4],
   DTE.TSH =  Details.[TSH],
   DTE.PSA =  Details.[PSA],
   DTE.TotalBillirubin =  Details.[TotalBillirubin],
   DTE.Iron  =  Details.[Iron],
   DTE.Platelets =  Details.[Platelets],
   DTE.VitaminB12 =  Details.[VitaminB12],
   DTE.VitaminD3  =  Details.[VitaminD3]
   FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
   INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
   INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
   INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
   INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
   INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
   INNER JOIN #tmp AS Details ON Details.ExaminationId = DTE.ExaminationId    
   WHERE EXM.ParticipantSourceTypeId=95    
   AND EXM.OrgId=@rOrgId    
   AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
   AND SSM.MaINTypeId=@rMaINTypeId    
   AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
   AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
   AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))   
  END  
  else if (@d_configval ='Priority')  
  BEGIN  
   UPDATE DTE SET     
   --DTE.MenzerIndex =    
   --case when isnull(Details.[MCV],'') <> '' then    
   --case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
  DTE.FBS = case when ISNULL(Details.[HBA1C],'')<>'' then Details.[HBA1C] else    
    case when ISNULL(Details.[F B S],'')<>'' then Details.[F B S] else   
    case when ISNULL(Details.[P P B S],'')<>'' then Details.[P P B S] else Details.[R B S] end end end,   
  DTE.Cholesterol = Details.[CHOLESTEROL],    
  DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
  DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
  DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
  DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
  DTE.SerumCreatinine = Details.[SERUM CREATININE],    
  DTE.UricAcid = Details.[SERUM URIC ACID],
  DTE.T3 = Details.[T3] ,
  DTE.T4 = Details.[T4],
  DTE.TSH =  Details.[TSH],
  DTE.PSA =  Details.[PSA],
  DTE.TotalBillirubin =  Details.[TotalBillirubin],
  DTE.Iron  =  Details.[Iron],
  DTE.Platelets =  Details.[Platelets],
  DTE.VitaminB12 =  Details.[VitaminB12],
  DTE.VitaminD3  =  Details.[VitaminD3]
  FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
  INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
  INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
  INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
  INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
  INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
  INNER JOIN #tmp AS Details ON Details.ExaminationId = DTE.ExaminationId    
  WHERE EXM.ParticipantSourceTypeId=95    
  AND EXM.OrgId=@rOrgId    
  AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
  AND SSM.MaINTypeId=@rMaINTypeId    
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
  AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
  AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
  END  
 END   
  -- change END Mentis Issue No:0032667 , Nidhi Pandey, DT - 10/04/2024   
 -- changes END done my MS : 2023-03-17 Mensti issue :23971  
  
 -- change calculation Menzer Index For Mentis Issue No:0011065    
  
 IF OBJECT_ID('tempdb..#tmp1') IS NOT NULL DROP TABLE #tmp1;  
  
 create table #tmp1 (tid int identity(1,1),[ExaminationId] bigint,[R.B.C. COUNT] nvarchar(100),[MCV] nvarchar(100),[XRAY] nvarchar(100))    
    
 insert into #tmp1    
 SELECT [ExaminationId],Isnull(Details.[R.B.C. COUNT],'0'),Isnull(Details.[MCV],'0'),Isnull(Details.[XRAY],'0')    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
  INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
  INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
  INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
  INNER JOIN    
  (    
   SELECT ExaminationId,[R.B.C. COUNT],[MCV],[XRAY]    
   FROM    
   (    
    SELECT SPM.Title,TR.SourceId [ExaminationId],    
    TRD.ServiceValue    
    FROM sOrderEntry.tStaticTestParameterMaster AS SPM    
    INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id    
    INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id    
    INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id    
    INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId    
    WHERE SPM.id IN (3, 5, 104)    
   )    
   d PIVOT    
   (    
    MIN(ServiceValue) FOR Title IN    
    (    
     [R.B.C. COUNT],[MCV],[XRAY]    
    )    
   ) piv    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
    
 UPDATE DTE SET DTE.MenzerIndex =    
 case when (isnull(Details.[R.B.C. COUNT],'') <> '' and isnull(Details.[MCV],'') <> '') then    
 case when isnull(convert(float,Details.[MCV]),0)/isnull(convert(float,Details.[R.B.C. COUNT]),1) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
 DTE.AbnormalXRay = CASE WHEN [XRAY] = 'Abnormal' then 1 else 0 end     
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN #tmp1 AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
 AND ISNULL(convert(float,Details.[R.B.C. COUNT]),0)<>0    
     
 --UPDATE DTE SET DTE.AbnormalXRay = CASE WHEN [XRAY] = 'Abnormal' then 1 else 0 end    
 --FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 --INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 --INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 --INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 --INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 --INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 --INNER JOIN    
 --(    
 -- SELECT EXM.Id [ExaminationId],Details.[XRAY]    
 -- FROM sExamination.tExamination AS EXM    
 -- INNER JOIN    
 -- (    
 --  SELECT ExaminationId,[XRAY]    
 --  FROM    
 --  (    
 --   SELECT SPM.Title,TR.SourceId [ExaminationId],    
 --   TRD.ServiceValue    
 --   FROM sOrderEntry.tStaticTestParameterMaster AS SPM    
 --   INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id    
 --   INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id    
 --   INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id    
 --   INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId    
 --   WHERE SPM.id = 104    
 --  )    
 --  d PIVOT    
 --  (    
 --   MIN(ServiceValue) FOR Title IN    
 --   (    
 --    [XRAY]    
 --   )    
 --  ) piv    
 -- ) AS Details ON Details.ExaminationId = EXM.ID    
 --) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 --WHERE EXM.ParticipantSourceTypeId=95    
 --AND EXM.OrgId=@rOrgId    
 --AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
 --AND SSM.MaINTypeId=@rMaINTypeId    
 --AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 --AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 --AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
    
 UPDATE DTE SET DTE.AudiometryACRight = Details.AudiometryACRight,    
 DTE.AudiometryACLeft = Details.AudiometryACLeft    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN    
 (    
  SELECT EXM.Id [ExaminationId],a.AudiometryACLeft,B.[AudiometryACRight]    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT ADU.SourceId [ExaminationId],ARM.Title [AudiometryACLeft]    
   FROM [sExamination].[tAudiometry] AS ADU    
   INNER JOIN sExamination.tAudiometryResultMaster AS ARM ON ARM.Id = ADU.AudiometryAcResultLeftId AND ARM.Id <> 1    
  ) AS A ON A.[ExaminationId] = EXM.Id    
  INNER JOIN    
  (    
   SELECT ADU.SourceId [ExaminationId],ARM.Title [AudiometryACRight]    
   FROM [sExamination].[tAudiometry] AS ADU    
   INNER JOIN sExamination.tAudiometryResultMaster AS ARM ON ARM.Id = ADU.AudiometryAcResultRightId AND ARM.Id <> 1    
  ) AS B ON B.[ExaminationId] = EXM.Id    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
     
 UPDATE DTE SET DTE.PFT = Details.PFT    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM  ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN    
 (    
  SELECT EXM.ID [ExaminationId],PLM.PFT    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT SourceId [ExaminationId],    
   --CASE WHEN ISNULL(PerOfFEV1ByFVC, 0.00) <> 0.00 THEN CASE WHEN PerOfFEV1ByFVC >= 80 THEN    
   --CASE WHEN ISNULL(PerOfPredictedFVC, 0.00) <> 0.00 THEN CASE WHEN PerOfPredictedFVC < 80 THEN 'Restrictive Lung Disease'    
   --ELSE NULL END ELSE NULL END ELSE CASE WHEN ISNULL(PerOfPredictedFVC, 0.00) <> 0.00 THEN    
   --CASE WHEN PerOfPredictedFVC < 80 THEN 'Mix Lung Disease' ELSE 'Obstructive Lung Disease' END    
   --ELSE NULL END END ELSE NULL END AS [PFT]    
   isnull(PulmonaryResulIntensity,'')+' ' + Isnull(PulmonaryResult,'') AS [PFT]    
   FROM sExamination.tPulmonary    
  ) AS PLM ON PLM.[ExaminationId] = EXM.ID   
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
     
 UPDATE DTE SET DTE.BMI = Details.BMI,DTE.BloodPressure = case when Details.BloodPressure='High Normal' then 'PreHypertension'     
 WHEN (Details.BloodPressure='Stage I HTN' Or Details.BloodPressure='Stage II HTN' Or Details.BloodPressure='Stage III HTN') Then 'Hypertension'    
 when Details.BloodPressure='Optimal' then ''    
 when Details.BloodPressure='Normal' then ''     
 Else Details.BloodPressure End    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM  ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN    
 (    
  SELECT EXM.ID [ExaminationId],Details.[BMI],Details.[BloodPressure]    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT VTL.SourceId [ExaminationId],    
   [sExamination].[fBMIValueGet](ISNULL(BMI, 0)) [BMI],    
   [sExamination].[fBMIBloodPressureResultGet](ISNULL(BloodPressureSystolic, 0),ISNULL(BloodPressureDiastolic, 0),@rOrgId) [BloodPressure]    
   FROM sExamination.tVital AS VTL    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
     
 UPDATE DTE SET DTE.DiabeticExisting = Details.[DM],DTE.HypertensionExisting = Details.[HBP]    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN    
 (    
  SELECT EXM.Id [ExaminationId],ISNULL(Details.[DM],'') [DM],ISNULL(Details.[HBP],'') [HBP]  
  FROM sExamination.tExamination AS EXM    
  LEFT JOIN    
  (    
   SELECT MDH.ExaminationId,    
   CASE WHEN MDH.[DM] IS NOT NULL THEN 'Diabetic Existing'    
   ELSE '' END AS [DM],    
   CASE WHEN MDH.[HBP] IS NOT NULL THEN 'Hypertension Existing'    
   ELSE '' END AS [HBP]    
   FROM    
   (    
    SELECT ExaminationId,[DM],[HBP]    
    FROM    
    (    
     SELECT SDM.Title,Ed.SourceId [ExaminationId]    
     FROM sExamination.tStaticDiseaseMaster AS SDM    
     INNER JOIN sExamination.tDiseaseMaster AS TDM ON TDM.StaticDiseaseId = SDM.ID AND TDM.OrgId = @rOrgId    
     --INNER JOIN sExamination.tHistoryDetail AS EDD ON EDD.DiseaseId = TDM.Id    
     --INNER JOIN sExamination.tHistory AS ed ON ed.Id = EDD.HistoryId         
  LEFT JOIN sExamination.tExistingDiseaseDetail As EDD ON EDD.DiseaseId = TDM.Id --mantis issue - 32667, DT - 10/04/2024, Nidhi Pandey  
  LEFT JOIN sExamination.tExistingDisease As ED ON ed.Id = EDD.ExistingDiseaseId --mantis issue - 32667, DT - 10/04/2024, Nidhi Pandey  
     WHERE SDM.id IN (7,13) and (IsSelfDeclared = 1 or IsDiagnosed = 1)  --mantis issue - 32667, DT - 10/04/2024, Nidhi Pandey     
    )    
    d PIVOT    
    (    
      MAX(Title) FOR Title IN ([DM],[HBP])    
    ) piv    
   ) AS MDH    
  ) AS Details ON Details.ExaminationId = EXM.Id    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))   
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
 
 declare @TrackerUpdateBasedOnconfigval varchar(50)='Value'    
 select @TrackerUpdateBasedOnconfigval=ISNULL(CS.ItemValue,CM.ItemValue)     
 FROM sConfig.tConfigurationMaster CM    
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id     
 where CM.id=336

UPDATE DTE
SET DTE.IsNewDiabeticStatus =
        CASE
            -- LTE EXISTS → use LTE logic
            WHEN LTE.ParticipantSourceId IS NOT NULL THEN
                CASE WHEN ISNULL(LTE.DiabeticExisting,'') = '' AND ISNULL(LTE.FBS,'Normal') = 'Normal'
                          AND ISNULL(DTE.FBS,'') = 'Pre Diabetic' THEN 1
                    WHEN ISNULL(LTE.DiabeticExisting,'') = '' AND ISNULL(LTE.FBS,'Normal') IN ('Normal','Pre Diabetic')
                         AND ISNULL(DTE.FBS,'') = 'Diabetic' THEN 2
					WHEN ISNULL(DTE.DiabeticExisting,'') <> '' THEN 0
                    ELSE DTE.IsNewDiabeticStatus END
            -- LTE NOT EXISTS → fallback logic
            ELSE
                CASE WHEN ISNULL(DTE.DiabeticExisting,'') <> '' THEN 0
                    WHEN ISNULL(DTE.FBS,'') = 'Pre Diabetic' THEN 1
					WHEN ISNULL(DTE.FBS,'') = 'Diabetic' THEN 2
                    ELSE DTE.IsNewDiabeticStatus END
        END,
    DTE.IsNewHypertensionStatus =
        CASE
            -- LTE EXISTS → use LTE logic
            WHEN LTE.ParticipantSourceId IS NOT NULL THEN
                CASE WHEN ISNULL(LTE.HypertensionExisting,'') = '' AND ISNULL(LTE.BloodPressure,'') = ''
                          AND ISNULL(DTE.BloodPressure,'') = 'PreHypertension' THEN 1
                    WHEN ISNULL(LTE.HypertensionExisting,'') = '' AND ISNULL(LTE.BloodPressure,'') IN ('','PreHypertension')
                         AND ISNULL(DTE.BloodPressure,'') = 'Hypertension' THEN 2
					WHEN ISNULL(DTE.HypertensionExisting,'') <> '' THEN 0
                    ELSE DTE.IsNewHypertensionStatus END
            -- LTE NOT EXISTS → fallback logic
            ELSE
                CASE WHEN ISNULL(DTE.HypertensionExisting,'') <> '' THEN 0
                    WHEN ISNULL(DTE.BloodPressure,'') = 'PreHypertension' THEN 1
                    WHEN ISNULL(DTE.BloodPressure,'') = 'Hypertension' THEN 2
                    ELSE DTE.IsNewHypertensionStatus END
        END
		FROM sExamination.tDiagnosisTrackerEmployee AS DTE
		INNER JOIN sExamination.tExamination AS EXM
			ON EXM.Id = DTE.ExaminationId
		INNER JOIN [sExamination].[tSetupMaster] AS STM
			ON STM.ID = EXM.SetupId
		INNER JOIN [sIp].[tStoreLocationMaster] AS SLM
			ON SLM.Id = EXM.StoreLocationId
		LEFT JOIN [sExamination].[tLSDTrackerEmployee] AS LTE
			ON EXM.ParticipantSourceId = LTE.ParticipantSourceId
		   AND EXM.ParticipantSourceTypeId = LTE.ParticipantSourceTypeId
		WHERE EXM.OrgId = @rOrgId
		  AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)
		  AND EXM.SetupId = @rSetupId
		  AND EXM.StoreLocationId = @rStoreLocationId;
 
 if(@TrackerUpdateBasedOnconfigval = 'Diagnosis')
 BEGIN
		UPDATE DTE SET DTE.IsNewDiabeticStatus = case when Isnull(DIA.IsNewDiabatic,0) = 1 then 2
				 else DTE.IsNewDiabeticStatus end,
			   DTE.IsNewHypertensionStatus=case when Isnull(DIA.IsNewHyperTension,0) = 1 then 2
					  else DTE.IsNewHypertensionStatus end
			   FROM sExamination.tDiagnosisTrackerEmployee AS DTE
			   INNER JOIN sExamination.tDiagnosis DIA ON DIA.SourceId = DTE.ExaminationId
			   INNER JOIN sExamination.tExamination AS EXM ON EXM.Id = DIA.SourceId
			   INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId       
			   INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId       
			   WHERE EXM.OrgId=@rOrgId    
			   AND (EXM.Id = @rSourceId or isnull(@rSourceId,0) = 0)
			   AND ((EXM.SetupId=@rSetupId))    
			   AND ((EXM.StoreLocationId=@rStoreLocationId))
 END 
    
 if(@rSetupId=0 and @rStoreLocationId=0)    
 begin    
  update sExamination.tSetupMaster set IsDiagnosisTrackerUpdated=1 where SetupGroupId=@rSetupGroupId and OrgId=@rOrgId    
 end    
 else if (@rSetupId=0)    
 begin    
  update sExamination.tSetupMaster set IsDiagnosisTrackerUpdated=1 where SetupGroupId=@rSetupGroupId and OrgId=@rOrgId and StoreLocationId=@rStoreLocationId    
 end    
 else    
 begin    
  update sExamination.tSetupMaster set IsDiagnosisTrackerUpdated=1 where SetupGroupId=@rSetupGroupId and Id=@rSetupId and OrgId=@rOrgId    
 end    
     
 declare @cnt int    
 select @cnt = count(1)     
 from sExamination.tDiagnosisTrackerEmployee DTE    
 INNER Join sExamination.tExamination AS EXM On EXM.id=DTE.Examinationid    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND (EXM.OrgId=@rOrgId)    
 AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
 AND (SSM.MaINTypeId=@rMaINTypeId)    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
     
 select 1  Status,'Diagnosis Tracker Employee ' + convert(varchar,@cnt) + ' Record Updated Successfully..!!' [Message]    
     
 option(recompile)    
END
GO
PRINT N'Altering Procedure [sExamination].[pDiagnosisTrackerEmployeeUpdateALLBySourceIds]...';


GO

ALTER  PROC [sExamination].[pDiagnosisTrackerEmployeeUpdateALLBySourceIds]    
@rMainTypeId INT,    
@rOrgId INT,    
@rSetupGroupId INT,    
@rSetupId INT,    
@rStoreLocationId INT,    
@rSourceIds nvarchar(max) = '' 
WITH EXECUTE AS CALLER    
AS    
BEGIN     
SET NOCOUNT ON;

    -- Split the comma-separated IDs into a table
    DECLARE @SourceIdTable TABLE (SourceId BIGINT);

    INSERT INTO @SourceIdTable (SourceId)
    SELECT CAST(Item AS BIGINT)
    FROM dbo.fSplitStr(@rSourceIds, ',')
    WHERE ISNUMERIC(Item) = 1;

 INSERT INTO sExamination.tDiagnosisTrackerEmployee    
 (    
  ExaminationId    
 )    
 select EXM.Id    
 from sExamination.tExamination AS EXM    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND (EXM.OrgId=@rOrgId)    
 --AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0)) 
 AND (
	EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	OR (ISNULL(@rSourceIds, '') = '')
 )
 AND (SSM.MaINTypeId=@rMaINTypeId)    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
 AND EXM.Id NOT in    
 (    
  SELECT ExaminationId    
  FROM sExamination.tDiagnosisTrackerEmployee ET    
  INNER JOIN sExamination.tExamination E ON ET.ExaminationId = E.Id    
  AND ((E.SetupId=@rSetupId) OR (@rSetupId=0))    
  AND ((E.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
 )    
     
 UPDATE DTE SET DTE.TB = Details.[TB],DTE.IHD = Details.[IHD],    
 DTE.COPD = Details.[COPD]    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId     
 INNER JOIN    
 (    
  SELECT EXM.Id [ExaminationId],Details.[TB],Details.[IHD],Details.[COPD]    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT MDH.ExaminationId,    
   CASE WHEN MDH.[TB] IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [TB],    
   CASE WHEN MDH.[IHD] IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [IHD],    
   CASE WHEN MDH.[COPD] IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [COPD]    
   FROM    
   (    
    SELECT ExaminationId,[TB],[IHD],[COPD]    
    FROM    
    (    
     SELECT SDM.Title,ed.SourceId [ExaminationId]    
     FROM sExamination.tStaticDiseaseMaster AS SDM    
     INNER JOIN sExamination.tDiseaseMaster AS TDM ON TDM.StaticDiseaseId = SDM.ID AND TDM.OrgId = @rOrgId    
     INNER JOIN sExamination.tExistingDiseaseDetail AS EDD ON EDD.DiseaseId = TDM.Id    
     INNER JOIN sExamination.tExistingDisease AS ed ON ed.Id = EDD.ExistingDiseaseId    
     WHERE SDM.id IN (10, 11, 12)    
    )    
    d PIVOT    
    (    
      MAX(Title) FOR Title IN ([TB], [IHD], [COPD])    
    ) piv    
   ) AS MDH    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (
	EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	OR (ISNULL(@rSourceIds, '') = '')
 )  
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))     
     
 UPDATE DTE SET DTE.Tobacco = Details.Chewer,    
 DTE.Smoker = Details.Smoker,    
 DTE.Alcohol = Details.Alcohol,    
 DTE.AlcoholSocial = Details.[Alcohol-Social],    
 DTE.Drug = Details.Drugs,    
 DTE.ExTobacco=case when Details.Chewer=0 and Isnull(LTE.Tobacco,0)=1 then 1 else DTE.ExTobacco end,    
 DTE.ExSmoker=case when Details.Smoker=0 and Isnull(LTE.Smoker,0)=1 then 1 else DTE.ExSmoker end,    
 DTE.ExAlcohol=case when Details.Alcohol=0 and Isnull(LTE.Alcohol,0)=1 then 1 else DTE.ExAlcohol end    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 LEFT JOIN [sExamination].[tLSDTrackerEmployee] AS LTE ON EXM.ParticipantSourceId=LTE.ParticipantSourceId and EXM.ParticipantSourceTypeId=LTE.ParticipantSourceTypeId    
 LEFT JOIN    
 (    
  SELECT EXM.Id [ExaminationId],ISNULL(Details.Alcohol,0) as Alcohol,ISNULL(Details.[Alcohol-Social],0) as [Alcohol-Social],
  ISNULL(Details.Chewer,0) as Chewer, ISNULL(Details.Smoker, 0) as Smoker, ISNULL(Details.Drugs,0) as Drugs 
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT MDH.ExaminationId,    
   CASE WHEN MDH.Alcohol IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [Alcohol],    
   CASE WHEN MDH.[Alcohol-Social] IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS [Alcohol-Social],    
   CASE WHEN MDH.Chewer IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit)END AS Chewer,    
   CASE WHEN MDH.Smoker IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS Smoker,    
   CASE WHEN MDH.Drugs IS NOT NULL THEN CAST(1 AS bit)    
   ELSE CAST(0 AS bit) END AS Drugs    
   FROM    
   (    
    SELECT ExaminationId,[Alcohol],[Alcohol-Social],[Chewer],[Smoker],[Drugs]    
    FROM    
    (    
     SELECT SHM.Title,HHM.SourceId [ExaminationId]    
     FROM sExamination.tStaticHabitHygineMaster AS SHM    
     INNER JOIN sExamination.tHabitTypeMaster AS HTM ON HTM.StaticHabitHygineId = SHM.Id    
     INNER JOIN sExamination.tHabitHygineDetail AS HHD ON HHD.HabitId = HTM.Id    
     INNER JOIN sExamination.tHabitHygine AS HHM ON HHM.Id = HHD.HabitHygineId    
     WHERE SHM.Id IN (3, 5, 1, 2, 7)    
    )    
    d PIVOT    
    (    
     MAX(Title) FOR Title IN ([Alcohol],[Alcohol-Social],[Chewer],[Smoker],[Drugs])    
    ) piv    
   ) AS MDH    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (
	EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	OR (ISNULL(@rSourceIds, '') = '')
 )
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
  
 IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp;  
  
 create table #tmp (tid int identity(1,1),[ExaminationId] bigint,[R.B.C. COUNT] nvarchar(100),[MCV] nvarchar(100),[F B S] nvarchar(100),[CHOLESTEROL] nvarchar(100),    
 [TRIGLYCERIDE] nvarchar(100),[LDL] nvarchar(100),[HDL] nvarchar(100),[SGPT] nvarchar(100),[ECG] nvarchar(100),[SONOGRAPHY] nvarchar(100),[TMT] nvarchar(100),    
 [ECHO] nvarchar(100),[HB] nvarchar(100),[SERUM CREATININE] nvarchar(100),[SERUM URIC ACID] nvarchar(100),[P P B S] nvarchar(100),[HBA1C] nvarchar(100),[R B S] nvarchar(100),[T3] nvarchar(50)
 ,[T4] nvarchar(50),[TSH] nvarchar(50),[PSA] nvarchar(50) ,[TotalBillirubin] nvarchar(100) ,[Iron] nvarchar(50) ,[Platelets] nvarchar(50),[VitaminB12] nvarchar(100),[VitaminD3]  nvarchar(100) )    
    
 insert into #tmp    
 SELECT [ExaminationId],Details.[R.B.C. COUNT],Details.[MCV],Details.[F B S],Details.[CHOLESTEROL],    
  Details.[TRIGLYCERIDE],Details.[LDL],Details.[HDL],Details.[SGPT],    
  Details.[ECG],Details.[SONOGRAPHY],Details.[TMT],Details.[ECHO],    
  Details.[HB],Details.[SERUM CREATININE],Details.[SERUM URIC ACID],Details.[P P B S],Details.[HBA1C],Details.[R B S] ,Details.[T3] ,Details.[T4],Details.[TSH],Details.[PSA],Details.[TotalBillirubin],Details.[Iron],Details.[Platelets],Details.[VitaminB12],Details.[VitaminD3]  
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT ExaminationId,[R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],    
   [SGPT],[ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],    
   [SERUM URIC ACID],[P P B S],[HBA1C],[R B S] ,[T3] ,[T4],[TSH],[PSA],[TOTAL BILIRUBIN] as [TotalBillirubin],[Iron],
   [Platelets],[Vitamin B12] as [VitaminB12],[Vitamin D3] as [VitaminD3]
   FROM    
   (    
    SELECT SPM.Title,TR.SourceId [ExaminationId],    
    Case when SPM.id IN (19, 20, 21, 25, 31, 33, 34) then     
    case when Isnull(TRD.Diagnosis,'')='' and Isnull(TRD.ServiceValue,'')<>'' then 'Normal'    
    when Isnull(TRD.Diagnosis,'')='' and Isnull(TRD.ServiceValue,'')='' then Null    
    else TRD.Diagnosis end else TRD.Diagnosis end as Diagnosis    
    FROM sOrderEntry.tStaticTestParameterMaster AS SPM    
    INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id    
    INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id    
    INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id    
    INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId    
    WHERE SPM.id IN (3, 5, 19, 20, 21, 25, 31, 32, 33, 34, 38,40, 107, 105, 109, 108, 2, 27, 49,15,52,53,54,58,158,126,127)   
   )    
   d PIVOT    
   (    
    MIN(Diagnosis) FOR Title IN    
    (    
     [R.B.C. COUNT],[MCV],[F B S],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],[SGPT],    
     [ECG],[SONOGRAPHY],[TMT],[ECHO],[HB],[SERUM CREATININE],[SERUM URIC ACID],[P P B S],[HBA1C],[R B S],[T3],[T4],[TSH],[PSA],
	 [TOTAL BILIRUBIN],[Iron],[Platelets],[Vitamin B12],[Vitamin D3]   
    )    
   ) piv    
  ) AS Details ON Details.ExaminationId = EXM.ID    
   -- select * from #tmp where [ExaminationId] = 21249;
  declare @DiabeticProfileTestConfig varchar(10)='FBS'    
  select @DiabeticProfileTestConfig = case when Isnull(CS.ItemValue,CM.ItemValue)='HBA1C' then 'HBA1C' Else 'FBS' End    
  from sConfig.tConfigurationMaster CM    
  LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id     
  where CM.id=232    
  
  -- changes done my MS : 2023-03-17 Mensti issue :23971  
  declare @d_configval varchar(50)='Independent'    
 select @d_configval=ISNULL(CS.ItemValue,CM.ItemValue)     
 FROM sConfig.tConfigurationMaster CM    
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id     
 where CM.id=190  
    
    
   
 -- change Mentis Issue No:0032667 , Nidhi Pandey, DT - 10/04/2024   
 If(@DiabeticProfileTestConfig = 'HBA1C')  
 BEGIN  
   UPDATE DTE SET     
  --DTE.MenzerIndex =    
  --case when isnull(Details.[MCV],'') <> '' then    
  --case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
  DTE.FBS = Details.[HBA1C],    
  DTE.Cholesterol = Details.[CHOLESTEROL],    
  DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
  DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
  DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
  DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
  DTE.SerumCreatinine = Details.[SERUM CREATININE],    
  DTE.UricAcid = Details.[SERUM URIC ACID],
  DTE.T3 = Details.[T3],
  DTE.T4 = Details.[T4],
  DTE.TSH =  Details.[TSH],
  DTE.PSA =  Details.[PSA],
  DTE.TotalBillirubin =  Details.[TotalBillirubin],
  DTE.Iron  =  Details.[Iron],
  DTE.Platelets =  Details.[Platelets],
  DTE.VitaminB12 =  Details.[VitaminB12],
  DTE.VitaminD3  =  Details.[VitaminD3]
  FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
  INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
  INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
  INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
  INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
  INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
  INNER JOIN #tmp AS Details ON Details.ExaminationId = DTE.ExaminationId    
  WHERE EXM.ParticipantSourceTypeId=95    
  AND EXM.OrgId=@rOrgId    
  AND (
	EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	OR (ISNULL(@rSourceIds, '') = '')
  )   
  AND SSM.MaINTypeId=@rMaINTypeId    
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
  AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
  AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))   
 END  
 ELSE  
 BEGIN  
 if (@d_configval ='Independent')  
 BEGIN  
   UPDATE DTE SET     
   --DTE.MenzerIndex =    
   --case when isnull(Details.[MCV],'') <> '' then    
   --case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
   DTE.FBS = Details.[F B S] ,    
   DTE.Cholesterol = Details.[CHOLESTEROL],    
   DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
   DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
   DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
   DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
   DTE.SerumCreatinine = Details.[SERUM CREATININE],    
   DTE.UricAcid = Details.[SERUM URIC ACID] ,
   DTE.T3 =  Details.[T3],
   DTE.T4 = Details.[T4],
   DTE.TSH =  Details.[TSH],
   DTE.PSA =  Details.[PSA],
   DTE.TotalBillirubin =  Details.[TotalBillirubin],
   DTE.Iron  =  Details.[Iron],
   DTE.Platelets =  Details.[Platelets],
   DTE.VitaminB12 =  Details.[VitaminB12],
   DTE.VitaminD3  =  Details.[VitaminD3]
   FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
   INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
   INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
   INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
   INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
   INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
   INNER JOIN #tmp AS Details ON Details.ExaminationId = DTE.ExaminationId    
   WHERE EXM.ParticipantSourceTypeId=95    
   AND EXM.OrgId=@rOrgId    
   AND (
		EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
		OR (ISNULL(@rSourceIds, '') = '')
	)    
   AND SSM.MaINTypeId=@rMaINTypeId    
   AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
   AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
   AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
  END  
  else if (@d_configval ='Priority Abnormal')  
  BEGIN  
   UPDATE DTE SET     
   --DTE.MenzerIndex =    
   --case when isnull(Details.[MCV],'') <> '' then    
   --case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
   DTE.FBS = case when Details.[HBA1C]<>'Normal' then Details.[HBA1C] else    
    case when Details.[F B S]<>'Normal' then Details.[F B S] else   
    case when Details.[P P B S]<>'Normal' then Details.[P P B S] else Details.[R B S] end end end,    
   DTE.Cholesterol = Details.[CHOLESTEROL],    
   DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
   DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
   DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
   DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
   DTE.SerumCreatinine = Details.[SERUM CREATININE],    
   DTE.UricAcid = Details.[SERUM URIC ACID], 
   DTE.T3 = Details.[T3]  ,
   DTE.T4 = Details.[T4],
   DTE.TSH =  Details.[TSH],
   DTE.PSA =  Details.[PSA],
   DTE.TotalBillirubin =  Details.[TotalBillirubin],
   DTE.Iron  =  Details.[Iron],
   DTE.Platelets =  Details.[Platelets],
   DTE.VitaminB12 =  Details.[VitaminB12],
   DTE.VitaminD3  =  Details.[VitaminD3]
   FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
   INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
   INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
   INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
   INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
   INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
   INNER JOIN #tmp AS Details ON Details.ExaminationId = DTE.ExaminationId    
   WHERE EXM.ParticipantSourceTypeId=95    
   AND EXM.OrgId=@rOrgId    
   AND (
	 EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	 OR (ISNULL(@rSourceIds, '') = '')
	)
   AND SSM.MaINTypeId=@rMaINTypeId    
   AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
   AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
   AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))   
  END  
  else if (@d_configval ='Priority')  
  BEGIN  
   UPDATE DTE SET     
   --DTE.MenzerIndex =    
   --case when isnull(Details.[MCV],'') <> '' then    
   --case when convert(float,Details.[MCV])/convert(float,Details.[R.B.C. COUNT]) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
  DTE.FBS = case when ISNULL(Details.[HBA1C],'')<>'' then Details.[HBA1C] else    
    case when ISNULL(Details.[F B S],'')<>'' then Details.[F B S] else   
    case when ISNULL(Details.[P P B S],'')<>'' then Details.[P P B S] else Details.[R B S] end end end,   
  DTE.Cholesterol = Details.[CHOLESTEROL],    
  DTE.Triglyceride = Details.[TRIGLYCERIDE],DTE.LDL = Details.[LDL],    
  DTE.HDL = Details.[HDL],DTE.SGPT = Details.[SGPT],DTE.ECG = Details.[ECG],    
  DTE.Sonography = Details.[SONOGRAPHY],DTE.TMT = Details.[TMT],    
  DTE.ECHO = Details.[ECHO],DTE.Hb = Details.[HB],    
  DTE.SerumCreatinine = Details.[SERUM CREATININE],    
  DTE.UricAcid = Details.[SERUM URIC ACID],
  DTE.T3 = Details.[T3] ,
  DTE.T4 = Details.[T4],
  DTE.TSH =  Details.[TSH],
  DTE.PSA =  Details.[PSA],
  DTE.TotalBillirubin =  Details.[TotalBillirubin],
  DTE.Iron  =  Details.[Iron],
  DTE.Platelets =  Details.[Platelets],
  DTE.VitaminB12 =  Details.[VitaminB12],
  DTE.VitaminD3  =  Details.[VitaminD3]
  FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
  INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
  INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
  INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
  INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
  INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
  INNER JOIN #tmp AS Details ON Details.ExaminationId = DTE.ExaminationId    
  WHERE EXM.ParticipantSourceTypeId=95    
  AND EXM.OrgId=@rOrgId    
  AND (
	EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	OR (ISNULL(@rSourceIds, '') = '')
  )   
  AND SSM.MaINTypeId=@rMaINTypeId    
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
  AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
  AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
  END  
 END   
  -- change END Mentis Issue No:0032667 , Nidhi Pandey, DT - 10/04/2024   
 -- changes END done my MS : 2023-03-17 Mensti issue :23971  
  
 -- change calculation Menzer Index For Mentis Issue No:0011065    
  
 IF OBJECT_ID('tempdb..#tmp1') IS NOT NULL DROP TABLE #tmp1;  
  
 create table #tmp1 (tid int identity(1,1),[ExaminationId] bigint,[R.B.C. COUNT] nvarchar(100),[MCV] nvarchar(100),[XRAY] nvarchar(100))    
    
 insert into #tmp1    
 SELECT [ExaminationId],Isnull(Details.[R.B.C. COUNT],'0'),Isnull(Details.[MCV],'0'),Isnull(Details.[XRAY],'0')    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
  INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
  INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
  INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
  INNER JOIN    
  (    
   SELECT ExaminationId,[R.B.C. COUNT],[MCV],[XRAY]    
   FROM    
   (    
    SELECT SPM.Title,TR.SourceId [ExaminationId],    
    TRD.ServiceValue    
    FROM sOrderEntry.tStaticTestParameterMaster AS SPM    
    INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id    
    INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id    
    INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id    
    INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId    
    WHERE SPM.id IN (3, 5, 104)    
   )    
   d PIVOT    
   (    
    MIN(ServiceValue) FOR Title IN    
    (    
     [R.B.C. COUNT],[MCV],[XRAY]    
    )    
   ) piv    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (
	EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	OR (ISNULL(@rSourceIds, '') = '')
 )   
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
    
 UPDATE DTE SET DTE.MenzerIndex =    
 case when (isnull(Details.[R.B.C. COUNT],'') <> '' and isnull(Details.[MCV],'') <> '') then    
 case when isnull(convert(float,Details.[MCV]),0)/isnull(convert(float,Details.[R.B.C. COUNT]),1) < 13 then 'Mentzer < 13' else 'Mentzer > 13' end else '' end,    
 DTE.AbnormalXRay = CASE WHEN [XRAY] = 'Abnormal' then 1 else 0 end     
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN #tmp1 AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (
	EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	OR (ISNULL(@rSourceIds, '') = '')
 )    
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
 AND ISNULL(convert(float,Details.[R.B.C. COUNT]),0)<>0    
     
 --UPDATE DTE SET DTE.AbnormalXRay = CASE WHEN [XRAY] = 'Abnormal' then 1 else 0 end    
 --FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 --INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 --INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 --INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 --INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 --INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 --INNER JOIN    
 --(    
 -- SELECT EXM.Id [ExaminationId],Details.[XRAY]    
 -- FROM sExamination.tExamination AS EXM    
 -- INNER JOIN    
 -- (    
 --  SELECT ExaminationId,[XRAY]    
 --  FROM    
 --  (    
 --   SELECT SPM.Title,TR.SourceId [ExaminationId],    
 --   TRD.ServiceValue    
 --   FROM sOrderEntry.tStaticTestParameterMaster AS SPM    
 --   INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id    
 --   INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id    
 --   INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id    
 --   INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId    
 --   WHERE SPM.id = 104    
 --  )    
 --  d PIVOT    
 --  (    
 --   MIN(ServiceValue) FOR Title IN    
 --   (    
 --    [XRAY]    
 --   )    
 --  ) piv    
 -- ) AS Details ON Details.ExaminationId = EXM.ID    
 --) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 --WHERE EXM.ParticipantSourceTypeId=95    
 --AND EXM.OrgId=@rOrgId    
 --AND ((EXM.Id = @rSourceId) or (isnull(@rSourceId,0) = 0))    
 --AND SSM.MaINTypeId=@rMaINTypeId    
 --AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 --AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 --AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
    
 UPDATE DTE SET DTE.AudiometryACRight = Details.AudiometryACRight,    
 DTE.AudiometryACLeft = Details.AudiometryACLeft    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN    
 (    
  SELECT EXM.Id [ExaminationId],a.AudiometryACLeft,B.[AudiometryACRight]    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT ADU.SourceId [ExaminationId],ARM.Title [AudiometryACLeft]    
   FROM [sExamination].[tAudiometry] AS ADU    
   INNER JOIN sExamination.tAudiometryResultMaster AS ARM ON ARM.Id = ADU.AudiometryAcResultLeftId AND ARM.Id <> 1    
  ) AS A ON A.[ExaminationId] = EXM.Id    
  INNER JOIN    
  (    
   SELECT ADU.SourceId [ExaminationId],ARM.Title [AudiometryACRight]    
   FROM [sExamination].[tAudiometry] AS ADU    
   INNER JOIN sExamination.tAudiometryResultMaster AS ARM ON ARM.Id = ADU.AudiometryAcResultRightId AND ARM.Id <> 1    
  ) AS B ON B.[ExaminationId] = EXM.Id    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (
	EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	OR (ISNULL(@rSourceIds, '') = '')
 )   
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
     
 UPDATE DTE SET DTE.PFT = Details.PFT    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM  ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN    
 (    
  SELECT EXM.ID [ExaminationId],PLM.PFT    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT SourceId [ExaminationId],    
   --CASE WHEN ISNULL(PerOfFEV1ByFVC, 0.00) <> 0.00 THEN CASE WHEN PerOfFEV1ByFVC >= 80 THEN    
   --CASE WHEN ISNULL(PerOfPredictedFVC, 0.00) <> 0.00 THEN CASE WHEN PerOfPredictedFVC < 80 THEN 'Restrictive Lung Disease'    
   --ELSE NULL END ELSE NULL END ELSE CASE WHEN ISNULL(PerOfPredictedFVC, 0.00) <> 0.00 THEN    
   --CASE WHEN PerOfPredictedFVC < 80 THEN 'Mix Lung Disease' ELSE 'Obstructive Lung Disease' END    
   --ELSE NULL END END ELSE NULL END AS [PFT]    
   isnull(PulmonaryResulIntensity,'')+' ' + Isnull(PulmonaryResult,'') AS [PFT]    
   FROM sExamination.tPulmonary    
  ) AS PLM ON PLM.[ExaminationId] = EXM.ID   
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (
	EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	OR (ISNULL(@rSourceIds, '') = '')
 )  
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
     
 UPDATE DTE SET DTE.BMI = Details.BMI,DTE.BloodPressure = case when Details.BloodPressure='High Normal' then 'PreHypertension'     
 WHEN (Details.BloodPressure='Stage I HTN' Or Details.BloodPressure='Stage II HTN' Or Details.BloodPressure='Stage III HTN') Then 'Hypertension'    
 when Details.BloodPressure='Optimal' then ''    
 when Details.BloodPressure='Normal' then ''     
 Else Details.BloodPressure End    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM  ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN    
 (    
  SELECT EXM.ID [ExaminationId],Details.[BMI],Details.[BloodPressure]    
  FROM sExamination.tExamination AS EXM    
  INNER JOIN    
  (    
   SELECT VTL.SourceId [ExaminationId],    
   [sExamination].[fBMIValueGet](ISNULL(BMI, 0)) [BMI],    
   [sExamination].[fBMIBloodPressureResultGet](ISNULL(BloodPressureSystolic, 0),ISNULL(BloodPressureDiastolic, 0),@rOrgId) [BloodPressure]    
   FROM sExamination.tVital AS VTL    
  ) AS Details ON Details.ExaminationId = EXM.ID    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (
	EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	OR (ISNULL(@rSourceIds, '') = '')
 ) 
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
     
 UPDATE DTE SET DTE.DiabeticExisting = Details.[DM],DTE.HypertensionExisting = Details.[HBP]    
 FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
 INNER JOIN sExamination.tExamination AS EXM ON EXM.Id=DTE.ExaminationId    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 INNER JOIN    
 (    
  SELECT EXM.Id [ExaminationId],ISNULL(Details.[DM],'') [DM],ISNULL(Details.[HBP],'') [HBP]  
  FROM sExamination.tExamination AS EXM    
  LEFT JOIN    
  (    
   SELECT MDH.ExaminationId,    
   CASE WHEN MDH.[DM] IS NOT NULL THEN 'Diabetic Existing'    
   ELSE '' END AS [DM],    
   CASE WHEN MDH.[HBP] IS NOT NULL THEN 'Hypertension Existing'    
   ELSE '' END AS [HBP]    
   FROM    
   (    
    SELECT ExaminationId,[DM],[HBP]    
    FROM    
    (    
     SELECT SDM.Title,Ed.SourceId [ExaminationId]    
     FROM sExamination.tStaticDiseaseMaster AS SDM    
     INNER JOIN sExamination.tDiseaseMaster AS TDM ON TDM.StaticDiseaseId = SDM.ID AND TDM.OrgId = @rOrgId    
     --INNER JOIN sExamination.tHistoryDetail AS EDD ON EDD.DiseaseId = TDM.Id    
     --INNER JOIN sExamination.tHistory AS ed ON ed.Id = EDD.HistoryId         
  LEFT JOIN sExamination.tExistingDiseaseDetail As EDD ON EDD.DiseaseId = TDM.Id --mantis issue - 32667, DT - 10/04/2024, Nidhi Pandey  
  LEFT JOIN sExamination.tExistingDisease As ED ON ed.Id = EDD.ExistingDiseaseId --mantis issue - 32667, DT - 10/04/2024, Nidhi Pandey  
     WHERE SDM.id IN (7,13) and (IsSelfDeclared = 1 or IsDiagnosed = 1)  --mantis issue - 32667, DT - 10/04/2024, Nidhi Pandey     
    )    
    d PIVOT    
    (    
      MAX(Title) FOR Title IN ([DM],[HBP])    
    ) piv    
   ) AS MDH    
  ) AS Details ON Details.ExaminationId = EXM.Id    
 ) AS Details ON Details.ExaminationId = DTE.ExaminationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND EXM.OrgId=@rOrgId    
 AND (
	EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	OR (ISNULL(@rSourceIds, '') = '')
 ) 
 AND SSM.MaINTypeId=@rMaINTypeId    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))   
 
     -- changes done my MS : 2025-09-22 Mensti issue :23971  
  declare @TrackerUpdateBasedOnconfigval varchar(50)='Value'    
 select @TrackerUpdateBasedOnconfigval=ISNULL(CS.ItemValue,CM.ItemValue)     
 FROM sConfig.tConfigurationMaster CM    
 LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id     
 where CM.id=336
    
 UPDATE DTE
SET DTE.IsNewDiabeticStatus =
        CASE
            -- LTE EXISTS → use LTE logic
            WHEN LTE.ParticipantSourceId IS NOT NULL THEN
                CASE WHEN ISNULL(LTE.DiabeticExisting,'') = '' AND ISNULL(LTE.FBS,'Normal') = 'Normal'
                          AND ISNULL(DTE.FBS,'') = 'Pre Diabetic' THEN 1
                    WHEN ISNULL(LTE.DiabeticExisting,'') = '' AND ISNULL(LTE.FBS,'Normal') IN ('Normal','Pre Diabetic')
                         AND ISNULL(DTE.FBS,'') = 'Diabetic' THEN 2
					WHEN ISNULL(DTE.DiabeticExisting,'') <> '' THEN 0
                    ELSE DTE.IsNewDiabeticStatus END
            -- LTE NOT EXISTS → fallback logic
            ELSE
                CASE WHEN ISNULL(DTE.DiabeticExisting,'') <> '' THEN 0
                    WHEN ISNULL(DTE.FBS,'') = 'Pre Diabetic' THEN 1
					WHEN ISNULL(DTE.FBS,'') = 'Diabetic' THEN 2
                    ELSE DTE.IsNewDiabeticStatus END
        END,
    DTE.IsNewHypertensionStatus =
        CASE
            -- LTE EXISTS → use LTE logic
            WHEN LTE.ParticipantSourceId IS NOT NULL THEN
                CASE WHEN ISNULL(LTE.HypertensionExisting,'') = '' AND ISNULL(LTE.BloodPressure,'') = ''
                          AND ISNULL(DTE.BloodPressure,'') = 'PreHypertension' THEN 1
                    WHEN ISNULL(LTE.HypertensionExisting,'') = '' AND ISNULL(LTE.BloodPressure,'') IN ('','PreHypertension')
                         AND ISNULL(DTE.BloodPressure,'') = 'Hypertension' THEN 2
					WHEN ISNULL(DTE.HypertensionExisting,'') <> '' THEN 0
                    ELSE DTE.IsNewHypertensionStatus END
            -- LTE NOT EXISTS → fallback logic
            ELSE
                CASE WHEN ISNULL(DTE.HypertensionExisting,'') <> '' THEN 0
                    WHEN ISNULL(DTE.BloodPressure,'') = 'PreHypertension' THEN 1
                    WHEN ISNULL(DTE.BloodPressure,'') = 'Hypertension' THEN 2
                    ELSE DTE.IsNewHypertensionStatus END
        END
		FROM sExamination.tDiagnosisTrackerEmployee AS DTE
		INNER JOIN sExamination.tExamination AS EXM
			ON EXM.Id = DTE.ExaminationId
		INNER JOIN [sExamination].[tSetupMaster] AS STM
			ON STM.ID = EXM.SetupId
		INNER JOIN [sIp].[tStoreLocationMaster] AS SLM
			ON SLM.Id = EXM.StoreLocationId
		LEFT JOIN [sExamination].[tLSDTrackerEmployee] AS LTE
			ON EXM.ParticipantSourceId = LTE.ParticipantSourceId
		   AND EXM.ParticipantSourceTypeId = LTE.ParticipantSourceTypeId
		WHERE EXM.OrgId = @rOrgId
		  AND (
				EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
				OR ISNULL(@rSourceIds,'') = ''
			  )
		  AND EXM.SetupId = @rSetupId
		  AND EXM.StoreLocationId = @rStoreLocationId;
 
 if(@TrackerUpdateBasedOnconfigval = 'Diagnosis')
 BEGIN
		UPDATE DTE SET DTE.IsNewDiabeticStatus = case when Isnull(DIA.IsNewDiabatic,0) = 1 then 2
				 else DTE.IsNewDiabeticStatus end,
			   DTE.IsNewHypertensionStatus=case when Isnull(DIA.IsNewHyperTension,0) = 1 then 2
					  else DTE.IsNewHypertensionStatus end
			   FROM sExamination.tDiagnosisTrackerEmployee AS DTE    
			   INNER JOIN sExamination.tDiagnosis DIA ON DIA.SourceId = DTE.ExaminationId
			   INNER JOIN sExamination.tExamination AS EXM ON EXM.Id = DIA.SourceId
			   INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId       
			   INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId       
			   WHERE EXM.OrgId=@rOrgId    
			   AND (
					EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
					OR (ISNULL(@rSourceIds, '') = '')
				 )
			   AND ((EXM.SetupId=@rSetupId))    
			   AND ((EXM.StoreLocationId=@rStoreLocationId))
 END
    
    
 if(@rSetupId=0 and @rStoreLocationId=0)    
 begin    
  update sExamination.tSetupMaster set IsDiagnosisTrackerUpdated=1 where SetupGroupId=@rSetupGroupId and OrgId=@rOrgId    
 end    
 else if (@rSetupId=0)    
 begin    
  update sExamination.tSetupMaster set IsDiagnosisTrackerUpdated=1 where SetupGroupId=@rSetupGroupId and OrgId=@rOrgId and StoreLocationId=@rStoreLocationId    
 end    
 else    
 begin    
  update sExamination.tSetupMaster set IsDiagnosisTrackerUpdated=1 where SetupGroupId=@rSetupGroupId and Id=@rSetupId and OrgId=@rOrgId    
 end    
     
 declare @cnt int    
 select @cnt = count(1)     
 from sExamination.tDiagnosisTrackerEmployee DTE    
 INNER Join sExamination.tExamination AS EXM On EXM.id=DTE.Examinationid    
 INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID=EXM.SetupId    
 INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id=STM.SetupGroupId    
 INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId    
 INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId    
 WHERE EXM.ParticipantSourceTypeId=95    
 AND (EXM.OrgId=@rOrgId)    
 AND (
	EXISTS (SELECT 1 FROM @SourceIdTable t WHERE t.SourceId = EXM.Id)
	OR (ISNULL(@rSourceIds, '') = '')
 )   
 AND (SSM.MaINTypeId=@rMaINTypeId)    
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))    
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))    
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))    
     
 select 1  Status,'Diagnosis Tracker Employee ' + convert(varchar,@cnt) + ' Record Updated Successfully..!!' [Message]    
     
 option(recompile)    
END
GO
PRINT N'Altering Procedure [sExamination].[pExaminationEmployeeDetailGet]...';


GO
-- EXEC [sExamination].[pExaminationEmployeeDetailGet] 3001000000860,999900001,3001  
-- DROP PROC [sExamination].[pExaminationEmployeeDetailGet]  
ALTER PROC [sExamination].[pExaminationEmployeeDetailGet]   
@rEmployeeID bigint,  
@rStoreLocationId int,  
@rOrgID int,  
@rAbnoraml int =1   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
 DECLARE @SetupName AS nvarchar(max) = '',@DynamicPivotQuery AS nvarchar(max) = ''  
  
  Declare @lConfDiseaseEvaluation varchar(20);
	select Top 1 @lConfDiseaseEvaluation = ISNULL(CS.ItemValue,CM.ItemValue)
	from sConfig.tConfigurationMaster as CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id
	where CM.ItemKey = 'Examination.DiagnosisEvaluation'

 IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL  
 BEGIN  
  DROP TABLE #TableOne  
 END  
  
 CREATE TABLE #TableOne  
 (  
  ExaminationId bigint,SetupId int,SetupName varchar(500),ExaminationDate date,ParameterId int,  
  Parameter varchar(500),value nvarchar(2000),eType nvarchar(500),IsHistory int,orderIndex int,  
  SortOrder int,IsNormal int , Remark nvarchar(2000)  
 )  
 INSERT INTO #TableOne  
 SELECT EXM.Id,EXM.SetupId,UPPER(STP.Title),EXM.ExaminationDate,  
 Vital.ParameterId,Vital.Parameter,CONVERT(varchar(200),Vital.value),  
 'Vital',Vital.IsHistory, 1,2,0,''  
 FROM [sExamination].[tExamination] AS EXM  
 INNER JOIN [sExamination].[tSetupMaster] AS STP ON STP.ID = EXM.SetupId  
 INNER JOIN sExamination.tSetupGroupMaster SGM ON SGM.Id = STP.SetupGroupId  
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.Id = EXM.ParticipantSourceId  
 INNER JOIN [sExamination].[tVital] AS VTL ON VTL.SourceId = EXM.Id  
 INNER JOIN  
 (  
  SELECT t.*  
  FROM sExamination.tVital v  
  CROSS APPLY  
  (  
   VALUES  
   (  
    SourceId, 1, 100000, 'Height', Height  
   ),  
   (  
    SourceId, 2, 200000, 'Weight', BodyWeight  
   ),  
   (  
    SourceId, 3, 300000, 'BMI', BMI  
   ),  
   (  
    SourceId, 4, 400000, 'Pulse', Pulse  
   ),  
   (  
    SourceId, 5, 500000, 'BP Sys (mmHg)', BloodPressureSystolic  
   ),  
   (  
    SourceId, 6, 600000, 'BP Dia (mmHg)', BloodPressureDiastolic  
   ),  
   (  
    SourceId, 7, 700000, 'Respiration (/Min)', Respiration  
   )  
  ) t  
  (  
   SourceId, ParameterId, IsHistory, Parameter, value  
  )  
 ) AS Vital ON Vital.SourceId = EXM.ID  
 WHERE EXM.OrgID = @rOrgID  
 AND EXM.ParticipantSourceTypeId = 95  
 AND EXM.ParticipantSourceId = @rEmployeeID  
 AND SGM.MainTypeId IN (1,2,6)  
  
 UNION ALL  
  
 SELECT EXM.Id,EXM.SetupId,UPPER(STP.Title),EXM.ExaminationDate,8,TPM.Title,  
 --CASE WHEN ISNULL(TRD.IsAbnormal, 0)= 1 THEN '<span style="background-color:gold;">'+TRD.ServiceValue+'</span>' ELSE TRD.ServiceValue END ,
 TRD.ServiceValue,
 'Test',  
 CASE WHEN SPM.Id IN (2, 3, 8, 17, 30, 31, 32, 34, 35) THEN SPM.Id ELSE 0 END,  
 TPM.OrderIndex,3,ISNULL(TRD.IsAbnormal, 0),
 TRD.Remark
 FROM [sExamination].[tExamination] AS EXM  
 INNER JOIN [sExamination].[tSetupMaster] AS STP ON STP.ID = EXM.SetupId  
 INNER JOIN sExamination.tSetupGroupMaster SGM ON SGM.Id = STP.SetupGroupId  
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.Id = EXM.ParticipantSourceId  
 INNER JOIN sExamination.tTestRequest AS TSR ON TSR.SourceId = EXM.Id  
 INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestRequestId = TSR.Id  
 INNER JOIN sOrderEntry.tTestDetail AS TDL ON TDL.id = TestDetailId  
 INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.Id = TDL.TestParameterId  
 INNER JOIN sOrderEntry.tStaticTestParameterMaster AS SPM ON SPM.Id = TPM.StaticTestParameterId  
 WHERE EXM.OrgID = @rOrgID  
 AND EXM.ParticipantSourceTypeId = 95  
 AND EXM.ParticipantSourceId = @rEmployeeID  
 AND SGM.MainTypeId IN (1,2, 6)   
 AND ISNULL(TPM.IsObsolete, 0) = 0  
 AND ((ISNULL(TRD.IsAbnormal, 0) = @rAbnoraml) Or (@rAbnoraml=0))  
  
 UNION ALL  
  
 SELECT EXM.Id, EXM.SetupId,UPPER(STP.Title),EXM.ExaminationDate,9,  
 GTP.Title,GTD.ParameterValue,'General',0,B.OrderIndex,6,ISNULL(GTD.IsAbnormal, 0),''  
 FROM [sExamination].[tExamination] AS EXM  
 INNER JOIN [sExamination].[tSetupMaster] AS STP ON STP.ID = EXM.SetupId  
 INNER JOIN sExamination.tSetupGroupMaster SGM ON SGM.Id = STP.SetupGroupId  
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.Id = EXM.ParticipantSourceId  
 INNER JOIN sExamination.tGeneralTemplateExamination AS GTE ON GTE.SourceId = EXM.Id  
 INNER JOIN [sExamination].[tGeneralTemplateExaminationDetail] AS GTD ON GTD.GeneralTemplateExaminationId = GTE.ID  
 INNER JOIN [sExamination].[tGeneralTemplateParameter] AS GTP ON GTP.Id = GeneralTemplateParameterId  
 LEFT JOIN sExamination.tStaticGeneralTemplateParameter B ON b.Id = GTP.StaticGeneralTemplateParameterId  
 WHERE EXM.OrgID = @rOrgID  
 AND EXM.ParticipantSourceTypeId = 95  
 AND EXM.ParticipantSourceId = @rEmployeeID  
 AND SGM.MainTypeId IN (1,2, 6)  
 AND ISNULL(GTP.IsObsolete, 0) = 0  
 AND ((ISNULL(GTD.IsAbnormal, 0) = @rAbnoraml) or (@rAbnoraml=0))  
  
 UNION ALL  
  
 SELECT EXM.Id,EXM.SetupId,UPPER(STP.Title),EXM.ExaminationDate,10,Vital.Parameter,  
 CONVERT(varchar(200),Vital.value),'Audiometry',0,ParameterId,4,0,''  
 FROM [sExamination].[tExamination] AS EXM  
 INNER JOIN [sExamination].[tSetupMaster] AS STP ON STP.ID = EXM.SetupId  
 INNER JOIN sExamination.tSetupGroupMaster SGM ON SGM.Id = STP.SetupGroupId  
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.Id = EXM.ParticipantSourceId  
 INNER JOIN  
 (  
  SELECT AUD.*, AMR.Title Value  
  FROM  
  (  
   SELECT t.* FROM [sExamination].[tAudiometry] AS AUD  
   CROSS APPLY  
   (  
    VALUES(SourceId, 10, 'Left Ac Result', AudiometryAcResultLeftId),  
    (SourceId, 11, 'Left Bc Result', AudiometryBcResultLeftId),  
    (SourceId, 13, 'Right Ac Result', AudiometryAcResultRightId),  
    (SourceId, 14, 'Right Bc Result', AudiometryBcResultRightId)  
   ) t  
   (SourceId, ParameterId, Parameter, ValueId)  
  ) AS AUD INNER JOIN sExamination.tAudiometryResultMaster AS AMR ON AMR.Id = AUD.ValueId  
  UNION ALL  
  SELECT AUD.*, AMR.Title Value  
  FROM  
  (  
   SELECT t.* FROM [sExamination].[tAudiometry] AS AUD  
   CROSS APPLY  
   (  
    VALUES  
    (SourceId, 12, 'Left Remark Result', AudiometryResultRemarkLeftId),  
    (SourceId, 15, 'Right Remark Result', AudiometryResultRemarkRightId)  
   ) t (SourceId, ParameterId, Parameter, ValueId)  
  ) AS AUD INNER JOIN sExamination.tAudioMetryRemarkMaster AS AMR ON AMR.Id = AUD.ValueId  
 ) AS Vital ON Vital.SourceId = EXM.ID  
 WHERE EXM.OrgID = @rOrgID  
 AND EXM.ParticipantSourceTypeId = 95  
 AND EXM.ParticipantSourceId = @rEmployeeID  
 AND SGM.MainTypeId IN (1,2, 6)  
   
 UNION ALL  
  
 SELECT EXM.Id, EXM.SetupId,UPPER(STP.Title),EXM.ExaminationDate,11,Vital.Parameter,  
 CONVERT(varchar(200),Vital.value), 'Pulmonary',  
 CASE WHEN ParameterId IN (800000, 900000, 1000000, 1100000) THEN ParameterId ELSE 0 END,  
 ParameterId,5,0,''
 FROM [sExamination].[tExamination] AS EXM  
 INNER JOIN [sExamination].[tSetupMaster] AS STP ON STP.ID = EXM.SetupId  
 INNER JOIN sExamination.tSetupGroupMaster SGM ON SGM.Id = STP.SetupGroupId  
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.Id = EXM.ParticipantSourceId  
 INNER JOIN  
 (  
  SELECT t.* FROM sExamination.tPulmonary AS PLM CROSS APPLY  
  (  
   VALUES (SourceId, 800000, 'FVC%', CONVERT(varchar, PerOfPredictedFVC)),  
   (SourceId, 900000, 'FEV1%', CONVERT(varchar, PerOfFEV1)),  
   (SourceId, 1000000, 'FEV1/FVc%', CONVERT(varchar, PerOfFEV1ByFVC)),  
   (SourceId, 1100000, 'PEFR%', CONVERT(varchar, PerPEFR)),  
   (SourceId, 1200000, 'RESULT', [sExamination].[fGetPulmonaryResultNew](SourceId))  
  ) t (SourceId, ParameterId, Parameter, value)  
 ) AS Vital ON Vital.SourceId = EXM.ID  
 WHERE EXM.OrgID = @rOrgID  
 AND EXM.ParticipantSourceTypeId = 95  
 AND EXM.ParticipantSourceId = @rEmployeeID  
 AND SGM.MainTypeId IN (1,2, 6)  
   
 UNION ALL  
   
 SELECT EXM.Id, EXM.SetupId,UPPER(STP.Title),EXM.ExaminationDate,12,Diagnosis.Parameter,  
 CONVERT(varchar(500),Diagnosis.value),'Diagnosis',0,ParameterId,1,0,''  
 FROM [sExamination].[tExamination] AS EXM  
 INNER JOIN [sExamination].[tSetupMaster] AS STP ON STP.ID = EXM.SetupId  
 INNER JOIN sExamination.tSetupGroupMaster SGM ON SGM.Id = STP.SetupGroupId  
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.Id = EXM.ParticipantSourceId  
 INNER JOIN  
 (  
  SELECT t.* FROM sExamination.tDiagnosis  
  CROSS APPLY  
  (  
   VALUES (SourceId, 1, 'Diagnosis', (Case When @lConfDiseaseEvaluation ='True' Then [sExamination].[fReplaceDiagnosisRemark](DiagnosisRemark) ELSE DiagnosisRemark END)),  
   (SourceId, 2, 'Recommendation', RecommendationEnglish),  
   (SourceId, 3, 'HealthIndexPercentage', Convert(varchar(200),HealthIndex)),  
   (SourceId, 4, 'CounsellingRemark', Isnull(CounsellingRemark,''))  
  ) t (SourceId, ParameterId, Parameter, value)  
 ) AS Diagnosis ON Diagnosis.SourceId = EXM.ID  
 WHERE EXM.OrgID = @rOrgID  
 AND EXM.ParticipantSourceTypeId = 95  
 AND EXM.ParticipantSourceId = @rEmployeeID  
 AND SGM.MainTypeId IN (1,2, 6)  
 ORDER BY EXM.ExaminationDate DESC  
   
  
 DECLARE @Count int = 0  
   
 DECLARE @SetupNameTable TABLE  
 (  
  tId int IDENTITY (1, 1), SetupName nvarchar(250)  
 )  
 INSERT INTO @SetupNameTable  
 SELECT Title FROM [sExamination].[tSetupMaster] SM  
 --inner join sExamination.tExamination EXM On EXM.SetupID = SM.Id and EXM.OrgID = @rOrgID AND EXM.ParticipantSourceTypeId = 95 AND EXM.ParticipantSourceId = @rEmployeeID  
 WHERE SM.id IN  
 (  
  SELECT DISTINCT SetupId FROM #TableOne   
 )  
 order by ToDate   
   
 --select * from @SetupNameTable  
  
 SELECT @Count = COUNT(0) FROM @SetupNameTable  
  
 WHILE (@Count <> 0)  
 BEGIN  
  SELECT @SetupName = @SetupName + '[' + ISNULL(UPPER(SetupName), '') + '],'  
  FROM @SetupNameTable WHERE tId = @Count  
    
  SET @Count = @Count - 1  
 END  
   
 SET @SetupName = SUBSTRING(@SetupName, 0, LEN(@SetupName))  
   
 --select @SetupName  
  
 insert into #TableOne  
 SELECT DISTINCT 0,SM.id,SM.Title,EXM.ExaminationDate,0,'Examination Date',Convert(varchar,EXM.ExaminationDate,103),'Examination Date',0,1,1,0,''  
 FROM [sExamination].[tSetupMaster] SM  
 inner join sExamination.tExamination EXM On EXM.SetupID = SM.Id and EXM.OrgID = @rOrgID AND EXM.ParticipantSourceTypeId = 95 AND EXM.ParticipantSourceId = @rEmployeeID  
 WHERE SM.id IN  
 (  
  SELECT DISTINCT SetupId FROM #TableOne  
 )  
   
  
 --SELECT * FROM #TableOne  
  
 IF (@SetupName <> '')  
 BEGIN  
 SET @DynamicPivotQuery = '
SELECT eType AS "Examination Type", Parameter,  
  CASE WHEN IsHistory > 0 THEN 
      ''<a style="cursor:pointer;" onclick="Javascript:GetChartDetails('' + CONVERT(varchar, IsHistory) + '');">View History</a>''
    ELSE 
      '''' 
  END AS History, 
  ' + @SetupName + '
FROM  
(  
    SELECT ParameterId, Parameter, 
    CASE 
       WHEN Parameter IN (''ECG'', ''SONOGRAPHY'', ''ECHO'', ''XRAY'') AND value = ''Abnormal'' or (Parameter = ''TMT'') and value = ''Positive'' THEN 
            CASE 
  WHEN Parameter = ''TMT'' AND value = ''Positive'' THEN ''Positive '' + CASE WHEN ISNULL(Remark, '''') = '''' THEN '''' ELSE ''- '' + ISNULL(Remark, '''') END
                WHEN value = ''Abnormal'' THEN ''Abnormal '' + CASE WHEN ISNULL(Remark, '''') = '''' THEN '''' ELSE ''- '' + ISNULL(Remark, '''') END
                ELSE value
            END
        ELSE value
    END AS value, 
    SetupName, eType, IsHistory, orderIndex, SortOrder 
    FROM #TableOne  
) AS Tab1  
PIVOT (MAX(value) FOR SetupName IN (' + @SetupName + ')) AS PVT 
ORDER BY SortOrder, ParameterId, orderIndex;';
  PRINT @DynamicPivotQuery  
  EXECUTE (@DynamicPivotQuery)  
  --Case When IsNormal=0 then '''' Else ''Yes'' End As IsAbnormal,  
 END  
END
GO
PRINT N'Altering Procedure [sExamination].[pExportAdaniExaminations]...';


GO

ALTER proc [sExamination].[pExportAdaniExaminations]  
@rOrgId int,  
@rStoreLocationId int,  
@rLocationId int,  
@rSetupGroupId int,  
@rSetupId int,  
@rMainTypeId int,  
@rSectorId int,  
@rVerticalId int,  
@rCompanyGroupId int,  
@rCompanyId int,  
@rEmployeeTypeGroupId int,  
@rEmployeeTypeId int,  
@rEmployeeSubTypeId int,  
@rFromDate varchar(50)='',  
@rTodate varchar(50)='',  
@rCode varchar(200) = null,  
@rLocation nvarchar(max)='',  
@rFromLocationid bigint=0,  
@rToLocationid bigint=0 ,
@rIsBusinessWise bit, -- mantis id - 29445, Nidhi Pandey dt - 09/01/2024 
@rStatusId int = 0,-- mantis id - 31146, Yogesh Banwe dt - 14/02/2024
@rUserId bigint = 0-- mantis id - 43716, Yogesh Banwe dt - 01/12/2025
as  
begin  
 SELECT @rFromDate = case when @rFromDate <> '' then CONVERT(varchar(10), CONVERT(date, @rFromDate, 105), 23) else '' end  
    SELECT @rToDate = case when @rToDate <> '' then CONVERT(varchar(10), CONVERT(date, @rToDate, 105), 23) else '' end  
   
 IF OBJECT_ID('tempdb..#tblExaminationAll') IS NOT NULL  
  DROP TABLE #tblExaminationAll  
    
 create table #tblExaminationAll  
 (  
  tid int identity(1,1),ExaminationId bigint,[Examination Type] varchar(max),[Round Name] varchar(max),  
  [Sub Location] varchar(max),[Examination Date] varchar(max),[Employee Code] varchar(max),[Full Name] varchar(max),  
  Department varchar(max),[Department Group] varchar(max),[Function] varchar(max),Company varchar(max),  
  [Company Group] varchar(max),Vertical varchar(max),Business varchar(max),[Employee Type] varchar(max),  
  Grade varchar(max),Designation varchar(max),BirthDate varchar(max),Age int,[Join Date] varchar(max),  
  Duration int,Gender varchar(max),MobileNo varchar(max),Email varchar(max),BloodGroup varchar(max),  
  Skill varchar(max),ProcessType varchar(max),Height varchar(10),[Weight] varchar(10),BMI varchar(max),  
  MailSend varchar(max),EntryPending varchar(max),comDiagnosis varchar(max),comRecommandEng varchar(max),  
  conFit varchar(max),comUnfit varchar(max),conUnfitDate varchar(max),comUnfitReason varchar(max),  
  comUnfitPeriod varchar(max),comRefitDate varchar(max),Agency varchar(max),Systolic varchar(max),  
  Diastilic varchar(max),Status varchar(max),ProviderName nvarchar(max),HealthIndicator nvarchar(max), 
  ProviderAppointmentStatus nvarchar(max), CentralDoctor nvarchar(max), SiteDoctor nvarchar(max),
  CentralSpoc nvarchar(max), SiteSpoc nvarchar(max))
 insert into #tblExaminationAll  
 select ED.Id,  
 MT.Title,  
 SSM.Title, 
 SLM.Title,  
 convert(varchar,ED.ExaminationDate,103),  
 EM.Code,  
 EM.FirstName + ' ' + isnull(EM.LastName,''),  
 ODM.Title,  
 DM.Title,  
 FM.Title,  
 case when @rOrgId<>3001 then isnull(CM.Title,'') else isnull(LEM.title,'') end,  
 CGM.Title,  
 VM.Title,  
 S.Title,  
 TM.Title,  
 GRD.Title,  
 DGM.Title,  
 CONVERT(VARCHAR,EP.DateOfBirth, 103),  --mantis:0032711 by shivam (05/04/2024)
 datediff(yy,EP.DateOfBirth,getdate()),  
 convert(varchar,EJD.DateOfJoining,103),  
 datediff(yy,EJD.DateOfJoining,getdate()),  
 case EP.GenderId when 1 then 'Male' when 2 then 'Female' when 3 then 'Not Known' end,  
 EC.MobileNumber,  
 EC.CompanyEmail,  
 BGM.Title,  
 SM.Title,  
 PT.Title,  
 case when isnull(V.Height,0) > 0 then V.Height else null end,  
 case when isnull(V.BodyWeight,0) > 0 then V.BodyWeight else null end,  
 case when isnull(V.BMI,0) > 0 then V.BMI else null end,  
 '',  
 '',  
 D.DiagnosisRemark,  
 D.RecommendationEnglish,  
 case when isnull(D.FitUnfitId,1) = 1 then 1 else 0 end,  
 case when isnull(D.FitUnfitId,1) = 1 then 0 else 1 end,  
 case when D.ActionDate <> '1900-01-01' then convert(varchar,D.ActionDate,103) else '' end,  
 D.Reason,  
 '',  
 '',  
 MAM.Title,  
 case when isnull(V.BloodPressureSystolic,0) > 0 then V.BloodPressureSystolic else null end,  
 case when isnull(V.BloodPressureDiastolic,0) > 0 then V.BloodPressureDiastolic else null end , 
  esm.Title, PM.Title, HI.Title, PAS.Title, 
  ISNULL(CD.FirstName, '') + ' ' + ISNULL(CD.LastName, ''), ISNULL(SD.FirstName, '') + ' ' + ISNULL(SD.LastName, ''), 
  ISNULL(CS.FirstName, '') + ' ' + ISNULL(CS.LastName, ''), ISNULL(CS.FirstName, '') + ' ' + ISNULL(CS.LastName, '')
 from sExamination.tExamination ED  
 inner join sExamination.tSetupMaster SSM on ED.SetupId = SSM.Id  
 inner join sExamination.tSubTypeMaster STM on SSM.SubTypeId = STM.Id  
 inner join sExamination.tMainTypeMaster MT on STM.MainTypeId = MT.Id  
 inner join sIp.tStoreLocationMaster SLM on ED.StoreLocationId = SLM.Id  
 inner join sHrm.tEmployeeMaster EM on ED.ParticipantSourceId = EM.Id  
 inner join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=ED.ParticipantSourceId  
 
 left join sExamination.tSetupEmployee SE ON SE.EmployeeId = ED.ParticipantSourceId and SE.SetupId = ED.SetupId
 left join sHrm.tEmployeeMaster CD on CD.Id = SE.CentralDoctorId
 left join sHrm.tEmployeeMaster SD on SD.Id = SE.SiteDoctorId
 left join sHrm.tEmployeeMaster CS on CS.Id = SE.CentralSpocId
 left join sHrm.tEmployeeMaster SS on SS.Id = SE.SiteSpocId
 left join sSupport.tProviderAppointment PA on PA.PatientSourceId = ED.ParticipantSourceId and PA.SetupId = ED.SetupId
 left join sSupport.tProviderMaster PM ON PM.Id = PA.ProviderId
 left join sCommon.tStatusMaster HI ON HI.Id = PA.HealthIndicatorId and HI.StatusTypeId = 122
 left join sCommon.tStatusMaster PAS ON PAS.Id = PA.StatusId and PAS.StatusTypeId = 118
 left join sCommon.tMedicalAgencyMaster MAM on ED.MedicalAgencyId = MAM.Id  
 left join sCommon.tProcessTypeMaster PT on EJD.ProcessTypeId = PT.Id  
 left join sHrm.tEmployeePersonalDetail EP on EP.EmployeeId = ED.ParticipantSourceId  
 left join sCommon.tBloodGroupMaster BGM on EP.BloodGroupId = BGM.Id  
 left join sCommon.tOrganizationDepartmentMaster ODM on ED.OrganizationDepartmentId = ODM.Id  
 left join sCommon.tDepartmentGroupMaster DM on ODM.DepartmentGroupId=DM.Id  
 left join sCommon.tFunctionMaster FM on FM.Id=DM.FunctionId  
 left join sHrm.tEmployeeCompanyMaster CM on  CM.Id=(case when @rIsBusinessWise=0 then ED.EmployeeCompanyId else EJD.EmployeeCompanyId end)   -- mantis id - 0029445, Nidhi Pandey dt - 09/01/2024     
 left join sHrm.tCompanyGroupMaster CGM on CGM.Id=CM.CompanyGroupId  
 left join sHrm.tVerticalMaster VM on VM.Id=CGM.VerticalId  
 left join sHrm.tSectorMaster S on S.Id=VM.SectorId  
 left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id  
 left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId   
 left join sExamination.tVital V on V.SourceId=ED.Id  
 left join sHrm.tSkillMaster SM on SM.Id= EJD.SkillId  
 left join sExamination.tNatureOfWorkMaster NWM on NWM.Id=V.NatureOfWorkId  
 left join sHrm.tGradeMaster GRD on ED.GradeId = GRD.Id  
 left join sExamination.tDiagnosis D on D.SourceId = ED.Id  
 left join sHrm.tEmployeeDesignationMaster DGM on EJD.EmployeeDesignationId = DGM.Id  
 left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId  
 left join sHrm.tEmployeeLegalEntitymaster LEM on LEM.Id=ED.LegalEntityId 
 inner join sExamination.tStatusMaster ESM on esm.Id = ed.StatusId
 inner JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = ED.StoreLocationId
 where ED.OrgId=@rOrgId and STM.MainTypeId <> 8 and Isnull(EM.IsObsolete,0)=0  
 and ED.ParticipantSourceTypeId = 95  
 and (ED.SetupId = @rSetupId or @rSetupId = 0)  
 and (ED.StoreLocationId = @rStoreLocationId or @rStoreLocationId = 0)  
 --and (SLM.LocationId = @rLocationId or @rLocationId = 0)  
 and (SSM.SetupGroupId = @rSetupGroupId or @rSetupGroupId = 0)  
 and (STM.MainTypeId = @rMainTypeId or @rMainTypeId = 0)  
 and (ED.EmployeeCompanyId = @rCompanyId or @rCompanyId = 0)  
 and (CM.CompanyGroupId = @rCompanyGroupId or @rCompanyGroupId = 0)  
 and (CGM.VerticalId = @rVerticalId or @rVerticalId = 0)  
 and (VM.SectorId = @rSectorId or @rSectorId = 0)  
 and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)  
 and (TM.Id = @rEmployeeTypeId or @rEmployeeTypeId = 0)  
 and (EJD.EmployeeSubTypeId = @rEmployeeSubTypeId or @rEmployeeSubTypeId = 0)  
 and (datediff(day,@rFromDate,ED.ExaminationDate) >= 0 or isnull(@rFromDate,'') = '')  
 and (datediff(day,ED.ExaminationDate,@rToDate) >= 0 or isnull(@rToDate,'') = '')  
 AND 
(
    EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@rCode, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @rCode) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @rCode) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR EXISTS 
    (
        SELECT 1
        FROM sCommon.fnsplit(@rCode, ',') AS SplitValues
        WHERE 
            (CHARINDEX(',', @rCode) = 0 AND EM.Code LIKE SplitValues.item + '%') -- Use LIKE if no comma exists
            OR 
            (CHARINDEX(',', @rCode) > 0 AND EM.Code = SplitValues.item)          -- Use exact match if comma exists
    )
    OR ISNULL(@rCode, '') = ''
)  
 and (ISNULL(SLM.LocationId,0) IN(SELECT item FROM sCommon.fnsplit(@rLocation,',')) OR ISNULL(@rLocation,'')='')  
 and (ED.id>=@rFromLocationid Or @rFromLocationid=0)  
 and (ED.id<=@rToLocationid Or @rToLocationid=0)  
  AND (ED.StatusId = @rStatusId or @rStatusId=0)
   and   UL.UserId = @rUserId 
	order by ED.id asc
 IF OBJECT_ID('tempdb..#tblHabitHygine') IS NOT NULL  
  DROP TABLE #tblHabitHygine  
    
 create table #tblHabitHygine(tid int identity(1,1),h_ExaminationId bigint,h_HabitId int,  
 h_HabitName varchar(300),h_Type int)  
 insert into #tblHabitHygine  
 select ED.Id,HTM.Id,HTM.Title + 'hab',case when isnull(HTM.Title,'')<>'' then 1 else 0 end   
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId  
 left join sExamination.tHabitHygine HH on ED.Id = HH.SourceId  
 left join sExamination.tHabitHygineDetail HHD on HH.Id = HHD.HabitHygineId  
 left join sExamination.tHabitTypeMaster HTM on HHD.HabitId = HTM.Id  
   
 declare @ExistingCols varchar(max)='',@ExistingCols1 varchar(max)='',@lQueryExisting varchar(max)=''  
 select @ExistingCols = STUFF(  
 (  
  SELECT Distinct ',' + QUOTENAME(Title + 'hab') from sExamination.tHabitTypeMaster where OrgId = @rOrgId  
  and title in ('Alcohol','Chewer','Smoker')  
        FOR XML PATH(''),TYPE  
     ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
       
    select @ExistingCols1 = STUFF(  
 (  
  SELECT Distinct ',' + QUOTENAME(Title + 'hab') + ' varchar(300)'  from sExamination.tHabitTypeMaster where OrgId = @rOrgId  
  and title in ('Alcohol','Chewer','Smoker')  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    IF OBJECT_ID('tempdb..##tblHabit') IS NOT NULL  
  DROP TABLE ##tblHabit  
      
 select @lQueryExisting = @lQueryExisting + 'create table ##tblHabit(tid int identity(1,1),t_ExamId bigint,' + @ExistingCols1 + ')'  
   
 exec(@lQueryExisting)  
   
 select @lQueryExisting = '  
 insert into ##tblHabit  
 select h_ExaminationId,' + @ExistingCols + '  
 from  
 (  
  select h_ExaminationId,h_HabitName,h_type from #tblHabitHygine  
 ) src   
 pivot  
 (  
   max(h_type) for h_HabitName in (' + @ExistingCols + ')  
 ) piv;'  
    
 exec (@lQueryExisting)  
   
 IF OBJECT_ID('tempdb..#tblExistingDisease') IS NOT NULL  
  DROP TABLE #tblExistingDisease  
   
 create table #tblExistingDisease(tid int identity(1,1),d_ExaminationId bigint,d_DiseaseId int,  
 d_DiseaseName varchar(300),d_type int)  
 insert into #tblExistingDisease  
 select ED.Id,DM.Id,DM.Title,case when isnull(DM.Title,'')<>'' then 1 else 0 end  
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId  
 left join sExamination.tExistingDisease EDD on ED.Id = EDD.SourceId  
 left join sExamination.tExistingDiseaseDetail EDDD on EDD.Id = EDDD.ExistingDiseaseId  
 left join sExamination.tDiseaseMaster DM on EDDD.DiseaseId = DM.Id  
 where DM.IsCommonForExamination = 1 and DM.IsObsolete = 0  
   
 declare @DiseaseCols varchar(max)='',@DiseaseCols1 varchar(max)=''  
 select @DiseaseCols = '[Disease] varchar(max),OtherDiseaseDetail varchar(max)'  
    
 IF OBJECT_ID('tempdb..##tblDisease') IS NOT NULL  
  DROP TABLE ##tblDisease  
   
 select @lQueryExisting = 'create table ##tblDisease(tid int identity(1,1),d_ExamId bigint,' + @DiseaseCols + ')'  
   
 exec(@lQueryExisting)  
   
 insert into ##tblDisease  
 select d_ExaminationId,'','' from #tblExistingDisease group by d_ExaminationId  
   
 select @DiseaseCols1 = '[Disease],OtherDiseaseDetail'  
   
 declare @dcnt int,@di int  
 select @di = 1,@dcnt = count(*) from ##tblDisease  
   
 while @di <= @dcnt  
 begin  
  declare @dis varchar(max)='',@examinationid bigint,@len int  
  select @examinationid = d_ExamId from ##tblDisease where tid = @di  
  select @dis = @dis + d_DiseaseName + '+' from #tblExistingDisease where d_ExaminationId = @examinationid  
  select @len = len(@dis)  
  select @dis = case when isnull(@dis,'') <> '' then left(@dis,@len-1) else isnull(@dis,'') end  
  update ##tblDisease set [Disease] = @dis where tid = @di    
  select @di = @di + 1  
 end  
   
 IF OBJECT_ID('tempdb..#tblPastHistory') IS NOT NULL  
  DROP TABLE #tblPastHistory  
   
 create table #tblPastHistory(tid int identity(1,1),h_ExaminationId bigint,h_DiseaseId int,  
 h_HistoryName varchar(300),d_type int,d_RelationId int,d_RelationName varchar(300),PastSurgicalHistorySelf varchar(max))  
 insert into #tblPastHistory  
 select ED.Id,DM.Id,DM.Title,case when isnull(DM.Title,'')<>'' then 1 else 0 end,  
 HD.RelationshipId,R.Title + DM.Title, HI.SurgeryRemark
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId  
 left join sExamination.tHistory HI on ED.ParticipantSourceId = HI.ParticipantSourceId  
 left join sExamination.tHistoryDetail HD on HI.Id = HD.HistoryId  
 left join sExamination.tDiseaseMaster DM on HD.DiseaseId = DM.Id  
 left join sCommon.tRelationshipMaster R on R.Id = HD.RelationshipId  
 where DM.IsCommonForExamination = 1 and DM.IsObsolete = 0  
   
 declare @HistoryCols varchar(max)='',@HistoryCols1 varchar(max)=''  
 select @HistoryCols = 'phSelf varchar(max),phFather varchar(max),phMother varchar(max),PastMedicalHistorySelf varchar(max),PastSurgicalHistorySelf varchar(max)'  
 select @HistoryCols1 = 'phSelf,phFather,phMother,PastMedicalHistorySelf,PastSurgicalHistorySelf'  
   
 IF OBJECT_ID('tempdb..##tblHistory') IS NOT NULL  
  DROP TABLE ##tblHistory  
   
 select @lQueryExisting = 'create table ##tblHistory(tid int identity(1,1),d_ExamId bigint,' + @HistoryCols + ')'  
   
 exec(@lQueryExisting)  
   
 insert into ##tblHistory  
 select h_ExaminationId,'','','','','' from #tblPastHistory group by h_ExaminationId  ,PastSurgicalHistorySelf
   
 declare @cnt int,@i int  
 select @cnt = COUNT(*),@i = 1 from ##tblHistory  
   
 while @i <= @cnt  
 begin  
  declare @self varchar(max)='',@mother varchar(max)='',@father varchar(max)='',@brother varchar(max)='',@sister varchar(max)='',  
  @ExamId bigint,@len1 int  ,@PastMedicalHistorySelf varchar(max)='' 
  select @ExamId = d_ExamId from ##tblHistory where tid = @i  
  select @self = @self + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 1 and h_ExaminationId = @ExamId 
  select @PastMedicalHistorySelf = @PastMedicalHistorySelf + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 1 and h_ExaminationId = @ExamId 
  select @mother = @mother + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 3 and h_ExaminationId = @ExamId  
  select @father = @father + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 2 and h_ExaminationId = @ExamId  
  select @brother = @brother + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 7 and h_ExaminationId = @ExamId  
  select @sister = @sister + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 8 and h_ExaminationId = @ExamId  
    
  select @len1 = len(@self)  
  select @self = case when isnull(@self,'') <> '' then left(@self,@len1-1) else isnull(@self,'') end  
    select @PastMedicalHistorySelf = case when isnull(@PastMedicalHistorySelf,'') <> '' then left(@PastMedicalHistorySelf,@len1-1) else isnull(@PastMedicalHistorySelf,'') end  
    
  select @len1 = len(@mother)  
  select @mother = case when isnull(@mother,'') <> '' then left(@mother,@len1-1) else isnull(@mother,'') end  
    
  select @len1 = len(@father)  
  select @father = case when isnull(@father,'') <> '' then left(@father,@len1-1) else isnull(@father,'') end  
     
    
  update ##tblHistory set phSelf = @self,phMother = @mother,phFather = @father where tid = @i    
  select @i = @i + 1  
 end  
   
 create table #tblExaminationTests(tid int identity(1,1),g_ExaminationId bigint,  
 g_Value varchar(500),g_Remark varchar(500),g_Title varchar(300))  
 insert into #tblExaminationTests  
 select ED.Id,GED.ServiceValue,GED.Remark,GP.Title  
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId   
 left join sExamination.tTestRequest GE on ED.Id = GE.SourceId  
 left join sExamination.tTestRequestDetail GED on GE.Id = GED.TestRequestId  
 left join sOrderEntry.tTestDetail TD on TD.Id = GED.TestDetailId  
 left join sOrderEntry.tTestParameterMaster GP on GP.Id = TD.TestParameterId  
 where GP.IsObsolete = 0  
   
 declare @tblExaminationT table(tid int identity(1,1),t_Exid bigint)  
 insert into @tblExaminationT  
 select distinct g_ExaminationId from #tblExaminationTests  
   
 declare @tIncr int,@tCnt int  
 select @tIncr = 1,@tCnt = count(*) from @tblExaminationT  

--------------------------------------- OLD --------------------------------------   
 --while @tIncr <= @tCnt  
 --begin  
 -- declare @tExamId bigint,@tRem varchar(200)=''  
 -- select @tExamId = t_Exid from @tblExaminationT where tid = @tIncr  
    
 -- select @tRem = ''  
    
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'SMEAR STUDY'  
 -- insert into #tblExaminationTests  
 -- select @tExamId,@tRem,'','SMEAR STUDY_Remark'  
    
 -- select @tRem = ''  
    
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'XRAY'  
 -- insert into #tblExaminationTests  
 -- select @tExamId,@tRem,'','XRAY_Remark'  
    
 -- select @tRem = ''  
    
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'SONOGRAPHY'  
 -- insert into #tblExaminationTests  
 -- select @tExamId,@tRem,'','SONOGRAPHY_Remark'  
    
 -- select @tRem = ''  
    
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'ECG'  
 -- insert into #tblExaminationTests  
 -- select @tExamId,@tRem,'','ECG_Remark'  
    
 -- select @tRem = ''  
    
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'ECHO'  
 -- insert into #tblExaminationTests  
 -- select @tExamId,@tRem,'','ECHO_Remark'  
    
 -- select @tRem = ''  
    
 -- select @tRem = g_Remark from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'TMT'  
 -- insert into #tblExaminationTests  
 -- select @tExamId,@tRem,'','TMT_Remark'  
    
 -- select @tIncr = @tIncr + 1  
 --end 
 --------------------------------------- OLD END--------------------------------------

 --------------------------------------- NEW OPtimized (Added by NP; Dt - 09/04/2025 mantis - 0041715)--------------------------------------
 insert into #tblExaminationTests
select 
    t.t_Exid as g_ExaminationId,
    -- Use CASE to get the remarks based on title
    CASE 
        WHEN tt.g_Title = 'SMEAR STUDY' THEN tt.g_Remark
        WHEN tt.g_Title = 'XRAY' THEN tt.g_Remark
        WHEN tt.g_Title = 'SONOGRAPHY' THEN tt.g_Remark
        WHEN tt.g_Title = 'ECG' THEN tt.g_Remark
        WHEN tt.g_Title = 'ECHO' THEN tt.g_Remark
        WHEN tt.g_Title = 'TMT' THEN tt.g_Remark
        ELSE '' -- Default empty remark if no title matches
    END as g_Remark,
	'',
    -- Set custom title for the remarks
    CASE 
        WHEN tt.g_Title = 'SMEAR STUDY' THEN 'SMEAR STUDY_Remark'
        WHEN tt.g_Title = 'XRAY' THEN 'XRAY_Remark'
        WHEN tt.g_Title = 'SONOGRAPHY' THEN 'SONOGRAPHY_Remark'
        WHEN tt.g_Title = 'ECG' THEN 'ECG_Remark'
        WHEN tt.g_Title = 'ECHO' THEN 'ECHO_Remark'
        WHEN tt.g_Title = 'TMT' THEN 'TMT_Remark'
        ELSE ''
    END as g_Title
from 
    @tblExaminationT t
join 
    #tblExaminationTests tt on t.t_Exid = tt.g_ExaminationId
where 
    tt.g_Title in ('SMEAR STUDY', 'XRAY', 'SONOGRAPHY', 'ECG', 'ECHO', 'TMT');

--------------------------------------- NEW OPtimized END (Added by NP; Dt - 09/04/2025 mantis - 0041715) --------------------------------------
   
 declare @TestCols varchar(max)='',@TestCols1 varchar(max)=''  
 select @TestCols = STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   19,20,21,22,23,24  
  )  
  and IsObsolete = 0  
   FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   19,20,21,22,23,24  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   31,32,33,34,38,43,49  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   31,32,33,34,38,43,49  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
          
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   26,27  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   26,27  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title)  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   2,8,17  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   2,8,17  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title)  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   9,10,11,12,13  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   9,10,11,12,13  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title)  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   3,15  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   3,15  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT CASE StaticTestParameterId WHEN 16 THEN ',' + QUOTENAME(Title) + ',' + QUOTENAME(Title + '_Remark')  
  ELSE ',' + QUOTENAME(Title) END  
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   5,16,58,64,65,69,72,73  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT CASE StaticTestParameterId WHEN 16 THEN ',' + QUOTENAME(Title) + ' varchar(400)' + ',' + QUOTENAME(Title + '_Remark') + ' varchar(400)'  
  ELSE ',' + QUOTENAME(Title) + ' varchar(400)' END  
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   5,16,58,64,65,69,72,73  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title)  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   71  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   71  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title)  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   67,68,70,113  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   67,68,70,113  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title)  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   56,57,94  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   56,57,94  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ',' + QUOTENAME(Title + '_Remark') from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   107,108,109  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' + ',' + QUOTENAME(Title + '_Remark') + ' varchar(400)'  
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   107,108,109  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
 ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ',' + QUOTENAME(Title + '_Remark') from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   104,105  
  )  
  and IsObsolete = 0 order by Id  
  FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' + ',' + QUOTENAME(Title + '_Remark') + ' varchar(400)'  
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   104,105  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
  
 declare @TestColsNew varchar(max)='',@TestColsNew1 varchar(max)=''  
 select @TestColsNew = STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   25,54,126,127   
  )  
  and IsObsolete = 0  
   FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestColsNew1 = STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   25,54,126,127  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
  
 ---new Tests  
 select @TestColsNew = @TestColsNew + ',' + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   39,40,41,42,44,48,52,53,148,158,159  
  )  
  and IsObsolete = 0  
   FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
   
 select @TestColsNew1 = @TestColsNew1 + ',' + STUFF(  
 (  
  SELECT ',' + QUOTENAME(Title) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   39,40,41,42,44,48,52,53,148,158,159  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
 --  
   
 IF OBJECT_ID('tempdb..##tblTests') IS NOT NULL  
  DROP TABLE ##tblTests  
   
 select @lQueryExisting = 'create table ##tblTests(tid int identity(1,1),d_ExamId bigint,' + @TestCols1 + ',' + @TestColsNew1 + ')'  
 print @lQueryExisting  
 exec(@lQueryExisting)  
   
 select @lQueryExisting = '  
 insert into ##tblTests  
 select g_ExaminationId,' + @TestCols + ',' + @TestColsNew + '  
 from  
 (  
  select g_ExaminationId,g_Value,g_Title from #tblExaminationTests group by g_ExaminationId,g_Value,g_Remark,g_Title  
 ) src   
 pivot  
 (  
   max(g_Value) for g_Title in (' + @TestCols  + ',' + @TestColsNew + ')  
 ) piv;'  
 print @lQueryExisting  
 exec (@lQueryExisting)  
   
 IF OBJECT_ID('tempdb..#tblExaminationGeneralTemplates') IS NOT NULL  
  DROP TABLE #tblExaminationGeneralTemplates  
   
 create table #tblExaminationGeneralTemplates(tid int identity(1,1),g_ExaminationId bigint,  
 g_Value varchar(500),g_Remark varchar(500),g_Title varchar(300))  
 insert into #tblExaminationGeneralTemplates  
 select ED.Id,GED.ParameterValue,GED.Remark,GP.Title  
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId   
 left join sExamination.tGeneralTemplateExamination GE on ED.Id = GE.SourceId  
 left join sExamination.tGeneralTemplateExaminationDetail GED on GE.Id = GED.GeneralTemplateExaminationId  
 left join sExamination.tGeneralTemplateParameter GP on GP.Id = GED.GeneralTEmplateParameterId  
 where GP.IsObsolete = 0 and GP.StaticGeneralTemplateParameterId = 328  
   
 declare @GeneralCols varchar(max)='',@GeneralCols1 varchar(max)=''  
 select @GeneralCols = STUFF(  
 (  
  SELECT Distinct ',' + QUOTENAME(Title)  from sExamination.tGeneralTemplateParameter where OrgId = @rOrgId and IsObsolete = 0  
  and StaticGeneralTemplateParameterId in (328)  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
       
    select @GeneralCols1 = STUFF(  
 (  
  SELECT Distinct ',' + QUOTENAME(Title) + ' varchar(300)'  from sExamination.tGeneralTemplateParameter where OrgId = @rOrgId and IsObsolete = 0  
  and StaticGeneralTemplateParameterId in (328)  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    IF OBJECT_ID('tempdb..##tblGeneral') IS NOT NULL  
  DROP TABLE ##tblGeneral  
      
 select @lQueryExisting = 'create table ##tblGeneral(tid int identity(1,1),d_ExamId bigint,' + @GeneralCols1 + ')'  
   
 exec(@lQueryExisting)  
   
 select @lQueryExisting = '  
 insert into ##tblGeneral  
 select g_ExaminationId,' + @GeneralCols + '  
 from  
 (  
  select g_ExaminationId,g_Value,g_Title from #tblExaminationGeneralTemplates group by g_ExaminationId,g_Value,g_Remark,g_Title  
 ) src   
 pivot  
 (  
   max(g_Value) for g_Title in (' + @GeneralCols + ')  
 ) piv;'  
   
 exec (@lQueryExisting)  
   
 IF OBJECT_ID('tempdb..#tblExaminationAudiometrys') IS NOT NULL  
  DROP TABLE #tblExaminationAudiometrys  
   
 create table #tblExaminationAudiometrys(tid int identity(1,1),AudiometryId bigint,ExaminationId bigint,IsDoneLeft bit,  
 IsDoneRight bit,AcValueLeft int,AcValueRight int,FrequencyId int,AudiometryAcResultLeftId int,AudiometryAcResultRightId int,  
 AudiometryResultRemarkLeftId nvarchar(200),AudiometryResultRemarkRightId nvarchar(200))  
 insert into #tblExaminationAudiometrys  
 select ISNULL(A.Id,0) AS AudiometryId,ED.Id,  
 ISNULL(A.IsDoneLeft,0) AS IsDoneLeft,  
 ISNULL(A.IsDoneRight,0) AS IsDoneRight,  
 AD.AcValueLeft AS AcValueLeft,  
 AD.AcValueRight AS AcValueRight,  
 ISNULL(AD.FrequencyId,0) AS FrequencyId,  
 ISnull(A.AudiometryAcResultLeftId,0) AS AudiometryAcResultLeftId,  
 ISnull(A.AudiometryAcResultRightId,0) AS AudiometryAcResultRightId,  
 ISnull(A.AudiometryResultRemarkLeftId,0) AS AudiometryResultRemarkLeftId,  
 ISnull(A.AudiometryResultRemarkRightId,0) AS AudiometryResultRemarkRightId  
 from sExamination.tExamination ED  
 inner join #tblExaminationAll AA on ED.Id = AA.ExaminationId  
 left join sExamination.tAudiometry A on A.SourceId = ED.Id  
 left join sExamination.tAudiometryDetail AD on AD.AudiomentryId = A.Id  
 left join sExamination.tAudiometryResultMaster RM on A.AudiometryAcResultLeftId = RM.Id  
 left join sExamination.tAudiometryResultMaster RM1 on A.AudiometryBcResultLeftId = RM.Id  
 left join sExamination.tAudiometryResultMaster RM2 on A.AudiometryAcResultRightId = RM.Id  
 left join sExamination.tAudiometryResultMaster RM3 on A.AudiometryBcResultRightId = RM.Id   
   
 IF OBJECT_ID('tempdb..##tblAudiometry') IS NOT NULL  
  DROP TABLE ##tblAudiometry  
   
 select @lQueryExisting = 'create table ##tblAudiometry(a_ExamId bigint,IsDoneLeft bit,  
 AudiometryAcResultLeft varchar(300),AudiometryResultRemarkLeft varchar(300),L250 varchar(200),L500 varchar(200),  
 L1000 varchar(200),L2000 varchar(200),L4000 varchar(200),L6000 varchar(200),L8000 varchar(200),  
 IsDoneRight bit,AudiometryAcResultRight varchar(300),AudiometryResultRemarkRight varchar(300),  
 R250 varchar(200),R500 varchar(200),R1000 varchar(200),R2000 varchar(200),R4000 varchar(200),R6000 varchar(200),R8000 varchar(200))'  
   
 exec(@lQueryExisting)  
   
 select @lQueryExisting = '  
 insert into ##tblAudiometry(a_ExamId,IsDoneLeft,AudiometryAcResultLeft,AudiometryResultRemarkLeft,L250,L500,  
 L1000,L2000,L4000,L6000,L8000,IsDoneRight,AudiometryAcResultRight,AudiometryResultRemarkRight,R250,R500,R1000,R2000,R4000,R6000,R8000)  
 Select LeftPivot.ExaminationId,CASE WHEN LeftPivot.IsDoneLeft = 1 THEN ''TRUE'' ELSE ''FALSE'' END as IsDoneLeft,  
 ISNULL(LeftPivot.AudiometryAcResultLeft,'''') as AudiometryAcResultLeft,  
 ISNULL(LeftPivot.AudiometryResultRemarkLeft,'''') as AudiometryResultRemarkLeft,  
 LeftPivot.[250] as L250,LeftPivot.[500] as L500,LeftPivot.[1000] as L1000,LeftPivot.[2000] as L2000,  
 LeftPivot.[4000] as L4000,LeftPivot.[6000] as L6000,LeftPivot.[8000] as L8000,  
 CASE WHEN RightPivot.IsDoneRight = 1 THEN ''TRUE'' ELSE ''FALSE'' END as IsDoneRight,  
 RightPivot.AudiometryAcResultRight as AudiometryAcResultRight,  
 RightPivot.AudiometryResultRemarkRight as AudiometryResultRemarkRight,  
 RightPivot.[250] as R250,RightPivot.[500] as R500,RightPivot.[1000] as R1000,RightPivot.[2000] as R2000,  
 RightPivot.[4000] as R4000,RightPivot.[6000] as R6000,RightPivot.[8000] as R8000  
 From  
 (  
  select pvt.AudiometryId AS AudiometryId,  
  ISNULL(pvt.AudiometryLeftResult,'''') AS AudiometryAcResultLeft,  
  ISNULL(pvt.AudiometryLeftRemark,'''') AS AudiometryResultRemarkLeft,  
  pvt.IsDoneLeft,pvt.[250],pvt.[500],pvt.[1000],pvt.ExaminationId,pvt.[2000],pvt.[4000],pvt.[6000],pvt.[8000]  
  from  
  (  
   Select AudiometryId,TC.ExaminationId,IsDoneLeft,AcValueLeft,  
   FrequencyId,RS.Title AS AudiometryLeftResult,  
   RM.Title AS AudiometryLeftRemark  
   FROM #tblExaminationAudiometrys TC LEFT JOIN sExamination.tAudiometryResultMaster RS ON RS.Id = TC.AudiometryAcResultLeftId  
   LEFT JOIN sExamination.tAudioMetryRemarkMaster RM ON RM.Id = TC.AudiometryResultRemarkLeftId  
  )t   
  PIVOT (MIN(AcValueLeft) FOR FrequencyId IN([250],[500],[1000],[2000],[4000],[6000],[8000])) AS pvt  
 ) LeftPivot  
 INNER JOIN  
 (  
  select pvt.AudiometryId AS AudiometryId,  
  ISNULL(pvt.AudiometryRightResult,'''') AS AudiometryAcResultRight,  
  ISNULL(pvt.AudiometryRightRemark,'''') AS AudiometryResultRemarkRight, pvt.IsDoneRight,  
  pvt.[250],pvt.[500],pvt.[1000],pvt.ExaminationId,pvt.[2000],pvt.[4000],pvt.[6000],pvt.[8000]  
  from  
  (  
   Select AudiometryId,TC.ExaminationId,IsDoneRight,AcValueRight,  
   FrequencyId,RS.Title AS AudiometryRightResult,  
   RM.Title AS AudiometryRightRemark  
   FROM #tblExaminationAudiometrys TC LEFT JOIN sExamination.tAudiometryResultMaster RS ON RS.Id = TC.AudiometryAcResultRightId  
   LEFT JOIN sExamination.tAudioMetryRemarkMaster RM ON RM.Id = TC.AudiometryResultRemarkRightId  
  )t  
  PIVOT (MIN(AcValueRight) FOR FrequencyId IN([250],[500],[1000],[2000],[4000],[6000],[8000])  
 ) AS pvt ) RightPivot ON LeftPivot.ExaminationId = RightPivot.ExaminationId'  
   
 exec (@lQueryExisting)  
   
 declare @lMainQuery varchar(max)=''  
   
 IF OBJECT_ID('tempdb..##tblMainExamination1') IS NOT NULL  
  DROP TABLE ##tblMainExamination1  
   
 select @lMainQuery = 'create table ##tblMainExamination1(ExaminationId bigint,[Examination Type] varchar(max),[Round Name] varchar(max),
 [Sub Location] varchar(max),[Examination Date] varchar(max),[Employee Code] varchar(max),[Full Name] varchar(max),  
 Department varchar(max),[Department Group] varchar(max),[Function] varchar(max),Company varchar(max),  
 [Company Group] varchar(max),Vertical varchar(max),Business varchar(max),[Employee Type] varchar(max),  
 Grade varchar(max),Designation varchar(max),BirthDate varchar(max),Age int,[Join Date] varchar(max),  
 Duration int,Gender varchar(max),MobileNo varchar(max),Email varchar(max),BloodGroup varchar(max),  
 Skill varchar(max),ProcessType varchar(max),Height varchar(max),[Weight] varchar(max),BMI varchar(max),  
 ' + case when @ExistingCols1 is not null then isnull(@ExistingCols1,'') + ',' else '' end + '  
 ' + case when @DiseaseCols is not null then isnull(@DiseaseCols,'') + ',' else '' end + '  
 ' + case when @HistoryCols is not null then isnull(@HistoryCols,'') + ',' else '' end + 'Systolic varchar(max),Diastilic varchar(max),  Status varchar(max) ,
 ' + case when @TestCols1 is not null then isnull(@TestCols1,'') + ',' else '' end +'  
 ' + case when @GeneralCols1 is not null then isnull(@GeneralCols1,'') + ',' else '' end + '  
 FVCPredicted varchar(200),FVCObserved varchar(200),PerOfPredictedFVC varchar(200),FEV1Predicted varchar(200),FEV1Observed varchar(200),  
 PerOfFEV1 varchar(200),PerOfFEV1ByFVC varchar(200),FEV5Observed varchar(200),PerOfFEV1ByFEV5 varchar(200),  
 MVVObserved varchar(200),MVVPredicted varchar(200),PerOfMVV varchar(200),PEFRPredicted varchar(200),  
 PEFRObserved varchar(200),PerPEFR varchar(200),PulmonaryResult varchar(200),NotDoneReason varchar(50),  
 IsDoneLeft bit,AudiometryAcResultLeft varchar(300),AudiometryResultRemarkLeft varchar(300),L250 varchar(200),L500 varchar(200),  
 L1000 varchar(200),L2000 varchar(200),L4000 varchar(200),L6000 varchar(200),L8000 varchar(200),  
 IsDoneRight bit,AudiometryAcResultRight varchar(300),AudiometryResultRemarkRight varchar(300),  
 R250 varchar(200),R500 varchar(200),R1000 varchar(200),R2000 varchar(200),R4000 varchar(200),R6000 varchar(200),R8000 varchar(200),  
 MailSend varchar(50),EntryPending varchar(50),comDiagnosis varchar(max),comRecommandEng varchar(max),  
 conFit varchar(10),comUnfit varchar(10),conUnfitDate varchar(50),comUnfitReason varchar(max),  
 comUnfitPeriod varchar(10),comRefitDate varchar(50),Agency varchar(300),  
 ' + case when @TestColsNew1 is not null then isnull(@TestColsNew1,'') + '' else '' end + ',ProviderName nvarchar(max),
 HealthIndicator nvarchar(max),ProviderAppointmentStatus nvarchar(max),CentralDoctor nvarchar(max), SiteDoctor nvarchar(max),
 CentralSpoc nvarchar(max), SiteSpoc nvarchar(max)' + ')'
   
 select @lMainQuery = replace(@lMainQuery,'OVA','Stool for ova and cyst')  
 print @lMainQuery  
 exec(@lMainQuery)  
   
 declare @lMainExecuteQuery varchar(max)=''   
   
 select @lMainExecuteQuery = 'insert into ##tblMainExamination1 select ExaminationId,[Examination Type],[Round Name], 
 [Sub Location],[Examination Date],[Employee Code],[Full Name],Department,[Department Group],[Function],Company,  
 [Company Group],Vertical,Business,[Employee Type],Grade,Designation,BirthDate,Age,[Join Date],  
 Duration,Gender,MobileNo,Email,BloodGroup,Skill,ProcessType,Height,[Weight],BMI,  
 ' + @ExistingCols + ',' + @DiseaseCols1 + ',' + @HistoryCols1 + ',Systolic,Diastilic,Status,' + @TestCols + ',' + @GeneralCols + ',  
 FVCPredicted,FVCObserved,PerOfPredictedFVC,FEV1Predicted,FEV1Observed,PerOfFEV1,PerOfFEV1ByFVC,FEV5Observed,PerOfFEV1ByFEV5,  
 MVVObserved,MVVPredicted,PerOfMVV,PEFRPredicted,PEFRObserved,PerPEFR,  
 PulmonaryResult = P.PulmonaryResulIntensity + '' '' + P.PulmonaryResult,'''',  
 IsDoneLeft,AudiometryAcResultLeft,AudiometryResultRemarkLeft,L250,L500,L1000,L2000,L4000,L6000,L8000,  
 IsDoneRight,AudiometryAcResultRight,AudiometryResultRemarkRight,R250,R500,R1000,R2000,R4000,R6000,R8000,  
 MailSend,EntryPending,comDiagnosis,comRecommandEng,conFit,comUnfit,conUnfitDate,comUnfitReason,  
 comUnfitPeriod,comRefitDate,Agency,' + @TestColsNew + ',ProviderName,HealthIndicator,ProviderAppointmentStatus,
 CentralDoctor,SiteDoctor,CentralSpoc,SiteSpoc' + '
 from #tblExaminationAll EA  
 left join tempdb.##tblHabit EE on EA.ExaminationId = EE.t_ExamId  
 left join tempdb.##tblDisease ED on EA.ExaminationId = ED.d_ExamId  
 left join tempdb.##tblHistory HE on EA.ExaminationId = HE.d_ExamId  
 left join tempdb.##tblGeneral GE on EA.ExaminationId = GE.d_ExamId  
 left join tempdb.##tblTests TE on EA.ExaminationId = TE.d_ExamId  
 left join tempdb.##tblAudiometry AA on EA.ExaminationId = AA.a_ExamId  
 left join sExamination.tPulmonary P on EA.ExaminationId = P.SourceId'  
   
 print @lMainExecuteQuery  
 exec (@lMainExecuteQuery)  
   
 update ##tblMainExamination1 set OtherDiseaseDetail = Remark from sExamination.tExistingDisease where ExaminationId = SourceId  
   
 select * from  ##tblMainExamination1  
end
GO
PRINT N'Altering Procedure [sExamination].[pExportExaminationBasedOnDate]...';


GO

ALTER proc [sExamination].[pExportExaminationBasedOnDate]  
@rOrgId int,  
@rFromDate varchar(50)='',  
@rToDate varchar(50)=''  
as  
begin    
  
 SELECT @rFromDate = case when @rFromDate <> '' then CONVERT(varchar(10), CONVERT(date, @rFromDate, 111), 23) else '' end  
    SELECT @rToDate = case when @rToDate <> '' then CONVERT(varchar(10), CONVERT(date, @rToDate, 111), 23) else '' end  
  
 DECLARE @DateDiff int = DATEDIFF(DAY, @rFromDate, @rToDate) + 1;
 IF(@DateDiff > 7)  
 BEGIN
  Select 'Please select a date range within 7 days!' AS Result  
  Return;
 END  
     
 IF OBJECT_ID('tempdb..#tblExaminationAll') IS NOT NULL    
  DROP TABLE #tblExaminationAll  
      
 create table #tblExaminationAll    
 (    
  tid int identity(1,1),ExaminationId bigint,[Examination Type] varchar(max),[Round Name] varchar(max),    
  [Sub Location] varchar(max),[Examination Date] varchar(max),[Employee Code] varchar(max),[Full Name] varchar(max),    
  Department varchar(max),[Department Group] varchar(max),[Function] varchar(max),Company varchar(max),    
  [Company Group] varchar(max),Vertical varchar(max),Business varchar(max),[Employee Type] varchar(max),    
  Grade varchar(max),Designation varchar(max),BirthDate varchar(max),Age int,[Join Date] varchar(max),    
  Duration int,Gender varchar(max),MobileNo varchar(max),Email varchar(max),BloodGroup varchar(max),    
  Skill varchar(max),ProcessType varchar(max),Height varchar(10),[Weight] varchar(10),BMI varchar(max),    
  MailSend varchar(max),EntryPending varchar(max),comDiagnosis varchar(max),comRecommandEng varchar(max),    
  conFit varchar(max),comUnfit varchar(max),conUnfitDate varchar(max),comUnfitReason varchar(max),    
  comUnfitPeriod varchar(max),comRefitDate varchar(max),Agency varchar(max),Systolic varchar(max),    
  Diastilic varchar(max),Status varchar(max),ProviderName nvarchar(max),HealthIndicator nvarchar(max), 
  ProviderAppointmentStatus nvarchar(max))    
 insert into #tblExaminationAll    
 select ED.Id,    
 isnull(MT.Title,''),    
 isnull(SSM.Title,''),  
 isnull(SLM.Title,''),    
 isnull(convert(varchar,ED.ExaminationDate,103),''),    
 isnull(EM.Code,''),    
 isnull((EM.FirstName + ' ' + isnull(EM.LastName,'')),''),  
 isnull(ODM.Title,''),  
 isnull(DM.Title,''),  
 isnull(FM.Title,''),  
 isnull((case when @rOrgId<>3001 then isnull(CM.Title,'') else isnull(LEM.title,'') end), ''),  
 isnull(CGM.Title,''),  
 isnull(VM.Title,''),  
 isnull(S.Title,''),  
 isnull(TM.Title,''),  
 isnull(GRD.Title,''),   
 isnull(DGM.Title,''),  
 isnull(CONVERT(VARCHAR,EP.DateOfBirth, 103),''),  --mantis:0032711 by shivam (05/04/2024)  
 isnull(datediff(yy,EP.DateOfBirth,getdate()),0),  
 isnull(convert(varchar,EJD.DateOfJoining,103),''),    
 isnull(datediff(yy,EJD.DateOfJoining,getdate()),0),  
 isnull((case EP.GenderId when 1 then 'Male' when 2 then 'Female' when 3 then 'Not Known' end),''),    
 isnull(EC.MobileNumber,''),    
 isnull(EC.CompanyEmail,''),    
 isnull(BGM.Title,''),    
 isnull(SM.Title,''),  
 isnull(PT.Title,''),  
 isnull((case when isnull(V.Height,0) > 0 then V.Height else null end),0),  
 isnull((case when isnull(V.BodyWeight,0) > 0 then V.BodyWeight else null end),0),  
 isnull((case when isnull(V.BMI,0) > 0 then V.BMI else null end),0),  
 '',  
 '',  
 isnull(D.DiagnosisRemark,''),  
 isnull(D.RecommendationEnglish,''),  
 isnull(case when isnull(D.FitUnfitId,1) = 1 then 1 else 0 end,''),  
 isnull(case when isnull(D.FitUnfitId,1) = 1 then 0 else 1 end,''),  
 isnull(case when D.ActionDate <> '1900-01-01' then convert(varchar,D.ActionDate,103) else '' end,''),    
 isnull(D.Reason,''),    
 '',    
 '',    
 isnull(MAM.Title,''),    
 isnull(case when isnull(V.BloodPressureSystolic,0) > 0 then V.BloodPressureSystolic else null end,''),    
 isnull(case when isnull(V.BloodPressureDiastolic,0) > 0 then V.BloodPressureDiastolic else null end,''),   
 isnull(esm.Title,''), PM.Title, HI.Title, PAS.Title  
 from sExamination.tExamination ED    
 inner join sExamination.tSetupMaster SSM on ED.SetupId = SSM.Id    
 inner join sExamination.tSubTypeMaster STM on SSM.SubTypeId = STM.Id    
 inner join sExamination.tMainTypeMaster MT on STM.MainTypeId = MT.Id    
 inner join sIp.tStoreLocationMaster SLM on ED.StoreLocationId = SLM.Id    
 inner join sHrm.tEmployeeMaster EM on ED.ParticipantSourceId = EM.Id    
 inner join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=ED.ParticipantSourceId    
     
 left join sSupport.tProviderAppointment PA on PA.PatientSourceId = ED.ParticipantSourceId and PA.SetupId = ED.SetupId
 left join sSupport.tProviderMaster PM ON PM.Id = PA.ProviderId
 left join sCommon.tStatusMaster HI ON HI.Id = PA.HealthIndicatorId and HI.StatusTypeId = 122
 left join sCommon.tStatusMaster PAS ON PAS.Id = PA.StatusId and PAS.StatusTypeId = 118
 left join sCommon.tMedicalAgencyMaster MAM on ED.MedicalAgencyId = MAM.Id    
 left join sCommon.tProcessTypeMaster PT on EJD.ProcessTypeId = PT.Id    
 left join sHrm.tEmployeePersonalDetail EP on EP.EmployeeId = ED.ParticipantSourceId    
 left join sCommon.tBloodGroupMaster BGM on EP.BloodGroupId = BGM.Id    
 left join sCommon.tOrganizationDepartmentMaster ODM on ED.OrganizationDepartmentId = ODM.Id    
 left join sCommon.tDepartmentGroupMaster DM on ODM.DepartmentGroupId=DM.Id    
 left join sCommon.tFunctionMaster FM on FM.Id=DM.FunctionId    
 left join sHrm.tEmployeeCompanyMaster CM on CM.Id = ED.EmployeeCompanyId  
 left join sHrm.tCompanyGroupMaster CGM on CGM.Id=CM.CompanyGroupId  
 left join sHrm.tVerticalMaster VM on VM.Id=CGM.VerticalId  
 left join sHrm.tSectorMaster S on S.Id=VM.SectorId  
 left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id    
 left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId     
 left join sExamination.tVital V on V.SourceId=ED.Id    
 left join sHrm.tSkillMaster SM on SM.Id= EJD.SkillId    
 left join sExamination.tNatureOfWorkMaster NWM on NWM.Id=V.NatureOfWorkId    
 left join sHrm.tGradeMaster GRD on ED.GradeId = GRD.Id    
 left join sExamination.tDiagnosis D on D.SourceId = ED.Id    
 left join sHrm.tEmployeeDesignationMaster DGM on EJD.EmployeeDesignationId = DGM.Id    
 left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId    
 left join sHrm.tEmployeeLegalEntitymaster LEM on LEM.Id=ED.LegalEntityId   
 inner join sExamination.tStatusMaster ESM on esm.Id = ed.StatusId  
 where ED.OrgId=@rOrgId and STM.MainTypeId <> 8 and Isnull(EM.IsObsolete,0)=0  
 and ED.ParticipantSourceTypeId = 95  
 and (datediff(day,@rFromDate,ED.CreatedDateTime) >= 0 or isnull(@rFromDate,'') = '')    
 and (datediff(day,ED.CreatedDateTime, @rToDate) >= 0 or isnull(@rToDate,'') = '')  
 order by ED.id asc  
  
 IF OBJECT_ID('tempdb..#tblHabitHygine') IS NOT NULL  
  DROP TABLE #tblHabitHygine    
      
 create table #tblHabitHygine(tid int identity(1,1),h_ExaminationId bigint,h_HabitId int,    
 h_HabitName varchar(300),h_Type int)    
 insert into #tblHabitHygine    
 select ED.Id,HTM.Id,HTM.Title + 'hab',case when isnull(HTM.Title,'')<>'' then 1 else 0 end  
 from sExamination.tExamination ED    
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId    
 left join sExamination.tHabitHygine HH on ED.Id = HH.SourceId    
 left join sExamination.tHabitHygineDetail HHD on HH.Id = HHD.HabitHygineId    
 left join sExamination.tHabitTypeMaster HTM on HHD.HabitId = HTM.Id    
     
 declare @ExistingCols varchar(max)='',@ExistingCols1 varchar(max)='',@lQueryExisting varchar(max)=''    
 select @ExistingCols = STUFF(    
 (    
  SELECT Distinct ',' + QUOTENAME(Title + 'hab') from sExamination.tHabitTypeMaster where OrgId = @rOrgId    
  and title in ('Alcohol','Chewer','Smoker')  
        FOR XML PATH(''),TYPE    
     ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
         
    select @ExistingCols1 = STUFF(    
 (    
  SELECT Distinct ',' + QUOTENAME(isnull(Title,'') + 'hab') + ' varchar(300)'  from sExamination.tHabitTypeMaster where OrgId = @rOrgId    
  and title in ('Alcohol','Chewer','Smoker')    
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    IF OBJECT_ID('tempdb..##tblHabit') IS NOT NULL    
  DROP TABLE ##tblHabit    
        
 select @lQueryExisting = @lQueryExisting + 'create table ##tblHabit(tid int identity(1,1),t_ExamId bigint,' + @ExistingCols1 + ')'    
     
 exec(@lQueryExisting)    
     
 select @lQueryExisting = '  
 insert into ##tblHabit    
 select h_ExaminationId,' + REPLACE(REPLACE(@ExistingCols, '[', 'ISNULL(['), ']', '],'''')') + '  
 from    
 (    
  select h_ExaminationId,h_HabitName,h_type from #tblHabitHygine    
 ) src     
 pivot    
 (    
   max(h_type) for h_HabitName in (' + @ExistingCols + ')  
 ) piv;'    
      
 exec (@lQueryExisting)  
 IF OBJECT_ID('tempdb..#tblExistingDisease') IS NOT NULL    
  DROP TABLE #tblExistingDisease    
     
 create table #tblExistingDisease(tid int identity(1,1),d_ExaminationId bigint,d_DiseaseId int,    
 d_DiseaseName varchar(300),d_type int)    
 insert into #tblExistingDisease    
 select ED.Id,DM.Id,isnull(DM.Title,''),case when isnull(DM.Title,'')<>'' then 1 else 0 end    
 from sExamination.tExamination ED    
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId    
 left join sExamination.tExistingDisease EDD on ED.Id = EDD.SourceId    
 left join sExamination.tExistingDiseaseDetail EDDD on EDD.Id = EDDD.ExistingDiseaseId    
 left join sExamination.tDiseaseMaster DM on EDDD.DiseaseId = DM.Id    
 where DM.IsCommonForExamination = 1 and DM.IsObsolete = 0    
     
 declare @DiseaseCols varchar(max)='',@DiseaseCols1 varchar(max)=''    
 select @DiseaseCols = '[Disease] varchar(max),OtherDiseaseDetail varchar(max)'    
      
 IF OBJECT_ID('tempdb..##tblDisease') IS NOT NULL    
  DROP TABLE ##tblDisease    
     
 select @lQueryExisting = 'create table ##tblDisease(tid int identity(1,1),d_ExamId bigint,' + @DiseaseCols + ')'    
     
 exec(@lQueryExisting)    
     
 insert into ##tblDisease    
 select d_ExaminationId,'','' from #tblExistingDisease group by d_ExaminationId    
     
 select @DiseaseCols1 = '[Disease],OtherDiseaseDetail'    
     
 declare @dcnt int,@di int    
 select @di = 1,@dcnt = count(*) from ##tblDisease    
     
 while @di <= @dcnt    
 begin    
  declare @dis varchar(max)='',@examinationid bigint,@len int    
  select @examinationid = d_ExamId from ##tblDisease where tid = @di    
  select @dis = @dis + d_DiseaseName + '+' from #tblExistingDisease where d_ExaminationId = @examinationid    
  select @len = len(@dis)    
  select @dis = case when isnull(@dis,'') <> '' then left(@dis,@len-1) else isnull(@dis,'') end    
  update ##tblDisease set [Disease] = isnull(@dis,'') where tid = @di      
  select @di = @di + 1    
 end    
     
 IF OBJECT_ID('tempdb..#tblPastHistory') IS NOT NULL    
  DROP TABLE #tblPastHistory    
     
 create table #tblPastHistory(tid int identity(1,1),h_ExaminationId bigint,h_DiseaseId int,    
 h_HistoryName varchar(300),d_type int,d_RelationId int,d_RelationName varchar(300))    
 insert into #tblPastHistory  
 select ED.Id,DM.Id,isnull(DM.Title,''),case when isnull(DM.Title,'')<>'' then 1 else 0 end,    
 HD.RelationshipId,R.Title + DM.Title  
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId  
 left join sExamination.tHistory HI on ED.ParticipantSourceId = HI.ParticipantSourceId  
 left join sExamination.tHistoryDetail HD on HI.Id = HD.HistoryId  
 left join sExamination.tDiseaseMaster DM on HD.DiseaseId = DM.Id  
 left join sCommon.tRelationshipMaster R on R.Id = HD.RelationshipId  
 where DM.IsCommonForExamination = 1 and DM.IsObsolete = 0  
     
 declare @HistoryCols varchar(max)='',@HistoryCols1 varchar(max)=''    
 select @HistoryCols = 'phSelf varchar(max),phFather varchar(max),phMother varchar(max)'  
 select @HistoryCols1 = 'phSelf,phFather,phMother'  
     
 IF OBJECT_ID('tempdb..##tblHistory') IS NOT NULL    
  DROP TABLE ##tblHistory    
     
 select @lQueryExisting = 'create table ##tblHistory(tid int identity(1,1),d_ExamId bigint,' + @HistoryCols + ')'    
     
 exec(@lQueryExisting)    
     
 insert into ##tblHistory    
 select h_ExaminationId,'','','' from #tblPastHistory group by h_ExaminationId    
     
 declare @cnt int,@i int    
 select @cnt = COUNT(*),@i = 1 from ##tblHistory    
     
 while @i <= @cnt    
 begin    
  declare @self varchar(max)='',@mother varchar(max)='',@father varchar(max)='',@brother varchar(max)='',@sister varchar(max)='',    
  @ExamId bigint,@len1 int    
  select @ExamId = d_ExamId from ##tblHistory where tid = @i    
  select @self = @self + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 1 and h_ExaminationId = @ExamId    
  select @mother = @mother + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 3 and h_ExaminationId = @ExamId    
  select @father = @father + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 2 and h_ExaminationId = @ExamId    
  select @brother = @brother + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 7 and h_ExaminationId = @ExamId    
  select @sister = @sister + h_HistoryName + '+' from #tblPastHistory where d_RelationId = 8 and h_ExaminationId = @ExamId    
      
  select @len1 = len(@self)    
  select @self = case when isnull(@self,'') <> '' then left(@self,@len1-1) else isnull(@self,'') end    
      
  select @len1 = len(@mother)    
  select @mother = case when isnull(@mother,'') <> '' then left(@mother,@len1-1) else isnull(@mother,'') end    
      
  select @len1 = len(@father)    
  select @father = case when isnull(@father,'') <> '' then left(@father,@len1-1) else isnull(@father,'') end    
       
      
  update ##tblHistory set phSelf = isnull(@self,''),phMother = isnull(@mother,''),phFather = isnull(@father,'') where tid = @i      
  select @i = @i + 1  
 end  
     
 create table #tblExaminationTests(tid int identity(1,1),g_ExaminationId bigint,  
 g_Value varchar(500),g_Remark varchar(500),g_Title varchar(300))  
 insert into #tblExaminationTests  
 select ED.Id,isnull(GED.ServiceValue,''),isnull(GED.Remark,''),isnull(GP.Title,'')  
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId  
 left join sExamination.tTestRequest GE on ED.Id = GE.SourceId  
 left join sExamination.tTestRequestDetail GED on GE.Id = GED.TestRequestId  
 left join sOrderEntry.tTestDetail TD on TD.Id = GED.TestDetailId  
 left join sOrderEntry.tTestParameterMaster GP on GP.Id = TD.TestParameterId  
 where GP.IsObsolete = 0  
     
 declare @tblExaminationT table(tid int identity(1,1),t_Exid bigint)  
 insert into @tblExaminationT    
 select distinct g_ExaminationId from #tblExaminationTests    
     
 declare @tIncr int,@tCnt int    
 select @tIncr = 1,@tCnt = count(*) from @tblExaminationT  
     
 while @tIncr <= @tCnt    
 begin    
  declare @tExamId bigint,@tRem varchar(200)=''    
  select @tExamId = t_Exid from @tblExaminationT where tid = @tIncr    
      
  select @tRem = ''    
      
  select @tRem = isnull(g_Remark,'') from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'SMEAR STUDY'    
  insert into #tblExaminationTests    
  select @tExamId,@tRem,'','SMEAR STUDY_Remark'    
      
  select @tRem = ''    
      
  select @tRem = isnull(g_Remark,'') from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'XRAY'    
  insert into #tblExaminationTests    
  select @tExamId,@tRem,'','XRAY_Remark'    
      
  select @tRem = ''    
      
  select @tRem = isnull(g_Remark,'') from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'SONOGRAPHY'    
  insert into #tblExaminationTests    
  select @tExamId,@tRem,'','SONOGRAPHY_Remark'    
      
  select @tRem = ''    
      
  select @tRem = isnull(g_Remark,'') from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'ECG'    
  insert into #tblExaminationTests    
  select @tExamId,@tRem,'','ECG_Remark'    
      
  select @tRem = ''    
      
  select @tRem = isnull(g_Remark,'') from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'ECHO'    
  insert into #tblExaminationTests    
  select @tExamId,@tRem,'','ECHO_Remark'    
      
  select @tRem = ''    
      
  select @tRem = isnull(g_Remark,'') from #tblExaminationTests where g_ExaminationId = @tExamId and g_Title = 'TMT'    
  insert into #tblExaminationTests    
  select @tExamId,@tRem,'','TMT_Remark'    
      
  select @tIncr = @tIncr + 1  
 end    
     
 declare @TestCols varchar(max)='',@TestCols1 varchar(max)=''    
 select @TestCols = STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   19,20,21,22,23,24    
  )    
  and IsObsolete = 0    
   FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestCols1 = STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   19,20,21,22,23,24    
  )    
  and IsObsolete = 0    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    select @TestCols = @TestCols + ','    
    select @TestCols1 = @TestCols1 + ','    
        
    select @TestCols = @TestCols + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   31,32,33,34,38,43,49    
  )    
  and IsObsolete = 0 order by Id    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestCols1 = @TestCols1 + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   31,32,33,34,38,43,49    
  )    
  and IsObsolete = 0 order by Id    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    select @TestCols = @TestCols + ','    
    select @TestCols1 = @TestCols1 + ','    
            
    select @TestCols = @TestCols + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   26,27    
  )    
  and IsObsolete = 0 order by Id    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestCols1 = @TestCols1 + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   26,27    
  )    
  and IsObsolete = 0 order by Id    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    select @TestCols = @TestCols + ','    
    select @TestCols1 = @TestCols1 + ','    
        
    select @TestCols = @TestCols + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,''))  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   2,8,17    
  )    
  and IsObsolete = 0 order by Id    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestCols1 = @TestCols1 + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   2,8,17    
  )    
  and IsObsolete = 0    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    select @TestCols = @TestCols + ','    
    select @TestCols1 = @TestCols1 + ','    
        
    select @TestCols = @TestCols + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,''))  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   9,10,11,12,13    
  )    
  and IsObsolete = 0 order by Id    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestCols1 = @TestCols1 + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   9,10,11,12,13    
  )    
  and IsObsolete = 0    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    select @TestCols = @TestCols + ','    
    select @TestCols1 = @TestCols1 + ','    
        
    select @TestCols = @TestCols + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,''))  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   3,15    
  )    
  and IsObsolete = 0 order by Id    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestCols1 = @TestCols1 + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   3,15    
  )    
  and IsObsolete = 0    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestCols = @TestCols + ','    
    select @TestCols1 = @TestCols1 + ','    
        
    select @TestCols = @TestCols + STUFF(    
 (    
  SELECT CASE StaticTestParameterId WHEN 16 THEN ',' + QUOTENAME(isnull(Title,'')) + ',' + QUOTENAME(isnull(Title,'') + '_Remark')    
  ELSE ',' + QUOTENAME(isnull(Title,'')) END  
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in    
  (    
   5,16,58,64,65,69,72,73    
  )    
  and IsObsolete = 0 order by Id    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestCols1 = @TestCols1 + STUFF(    
 (    
  SELECT CASE StaticTestParameterId WHEN 16 THEN ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' + ',' + QUOTENAME(isnull(Title,'') + '_Remark') + ' varchar(400)'    
  ELSE ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' END  
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   5,16,58,64,65,69,72,73    
  )    
  and IsObsolete = 0    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    select @TestCols = @TestCols + ','    
    select @TestCols1 = @TestCols1 + ','    
        
    select @TestCols = @TestCols + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(isnull(Title,''),''))  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   71    
  )    
  and IsObsolete = 0 order by Id    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestCols1 = @TestCols1 + STUFF(    
 (  
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (  
   71  
  )  
  and IsObsolete = 0    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
      
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(isnull(Title,''))  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in    
  (  
   67,68,70,113  
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
     
 select @TestCols1 = @TestCols1 + STUFF(  
 (  
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   67,68,70,113  
  )  
  and IsObsolete = 0  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    select @TestCols = @TestCols + ','  
    select @TestCols1 = @TestCols1 + ','  
        
    select @TestCols = @TestCols + STUFF(  
 (  
  SELECT ',' + QUOTENAME(isnull(Title,''))  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId  
  and StaticTestParameterId in  
  (  
   56,57,94    
  )  
  and IsObsolete = 0 order by Id  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
     
 select @TestCols1 = @TestCols1 + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   56,57,94    
  )    
  and IsObsolete = 0    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    select @TestCols = @TestCols + ','    
    select @TestCols1 = @TestCols1 + ','    
        
    select @TestCols = @TestCols + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ',' + QUOTENAME(isnull(Title,'') + '_Remark') from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   107,108,109    
  )    
  and IsObsolete = 0 order by Id    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestCols1 = @TestCols1 + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' + ',' + QUOTENAME(isnull(Title,'') + '_Remark') + ' varchar(400)'    
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   107,108,109    
  )    
  and IsObsolete = 0    
        FOR XML PATH(''),TYPE    
 ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
        
    select @TestCols = @TestCols + ','    
    select @TestCols1 = @TestCols1 + ','    
        
    select @TestCols = @TestCols + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ',' + QUOTENAME(isnull(Title,'') + '_Remark') from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   104,105    
  )    
  and IsObsolete = 0 order by Id    
  FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestCols1 = @TestCols1 + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' + ',' + QUOTENAME(isnull(Title,'') + '_Remark') + ' varchar(400)'    
  from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   104,105    
  )    
  and IsObsolete = 0    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
    
 declare @TestColsNew varchar(max)='',@TestColsNew1 varchar(max)=''    
 select @TestColsNew = STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   25,54,126,127     
  )    
  and IsObsolete = 0    
   FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestColsNew1 = STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   25,54,126,127    
  )    
  and IsObsolete = 0    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
    
 ---new Tests    
 select @TestColsNew = @TestColsNew + ',' + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   39,40,41,42,44,48,52,53,148,158,159    
  )    
  and IsObsolete = 0    
   FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
     
 select @TestColsNew1 = @TestColsNew1 + ',' + STUFF(    
 (    
  SELECT ',' + QUOTENAME(isnull(Title,'')) + ' varchar(400)' from sOrderEntry.tTestParameterMaster where OrgId = @rOrgId    
  and StaticTestParameterId in    
  (    
   39,40,41,42,44,48,52,53,148,158,159    
  )    
  and IsObsolete = 0    
        FOR XML PATH(''),TYPE    
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')    
 --    
     
 IF OBJECT_ID('tempdb..##tblTests') IS NOT NULL    
  DROP TABLE ##tblTests    
     
 select @lQueryExisting = 'create table ##tblTests(tid int identity(1,1),d_ExamId bigint,' + @TestCols1 + ',' + @TestColsNew1 + ')'    
 print @lQueryExisting    
 exec(@lQueryExisting)    
     
 select @lQueryExisting = '    
 insert into ##tblTests    
 select g_ExaminationId,' + @TestCols + ',' + @TestColsNew + '    
 from    
 (    
  select g_ExaminationId,g_Value,g_Title from #tblExaminationTests group by g_ExaminationId,g_Value,g_Remark,g_Title    
 ) src  
 pivot    
 (    
   max(g_Value) for g_Title in (' + @TestCols  + ',' + @TestColsNew + ')    
 ) piv;'    
 print @lQueryExisting    
 exec (@lQueryExisting)    
     
 IF OBJECT_ID('tempdb..#tblExaminationGeneralTemplates') IS NOT NULL    
  DROP TABLE #tblExaminationGeneralTemplates    
     
 create table #tblExaminationGeneralTemplates(tid int identity(1,1),g_ExaminationId bigint,    
 g_Value varchar(500),g_Remark varchar(500),g_Title varchar(300))  
 insert into #tblExaminationGeneralTemplates    
 select ED.Id,isnull(GED.ParameterValue,''),isnull(GED.Remark,''),isnull(GP.Title,'')  
 from sExamination.tExamination ED  
 inner join #tblExaminationAll A on ED.Id = A.ExaminationId  
 left join sExamination.tGeneralTemplateExamination GE on ED.Id = GE.SourceId  
 left join sExamination.tGeneralTemplateExaminationDetail GED on GE.Id = GED.GeneralTemplateExaminationId  
 left join sExamination.tGeneralTemplateParameter GP on GP.Id = GED.GeneralTEmplateParameterId  
 where GP.IsObsolete = 0 and GP.StaticGeneralTemplateParameterId = 328  
     
 declare @GeneralCols varchar(max)='',@GeneralCols1 varchar(max)=''  
 select @GeneralCols = STUFF(  
 (  
  SELECT Distinct ',' + QUOTENAME(Title)  from sExamination.tGeneralTemplateParameter where OrgId = @rOrgId and IsObsolete = 0  
  and StaticGeneralTemplateParameterId in (328)  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
  
    select @GeneralCols1 = STUFF(  
 (  
  SELECT Distinct ',' + QUOTENAME(Title) + ' varchar(300)'  from sExamination.tGeneralTemplateParameter where OrgId = @rOrgId and IsObsolete = 0  
  and StaticGeneralTemplateParameterId in (328)  
        FOR XML PATH(''),TYPE  
    ).value('.', 'NVARCHAR(MAX)'),1,1,'')  
        
    IF OBJECT_ID('tempdb..##tblGeneral') IS NOT NULL  
  DROP TABLE ##tblGeneral  
        
 select @lQueryExisting = 'create table ##tblGeneral(tid int identity(1,1),d_ExamId bigint,' + @GeneralCols1 + ')'  
     
 exec(@lQueryExisting)  
     
 select @lQueryExisting = '    
 insert into ##tblGeneral  
 select g_ExaminationId,' + @GeneralCols + '    
 from    
 (    
  select g_ExaminationId,g_Value,g_Title from #tblExaminationGeneralTemplates group by g_ExaminationId,g_Value,g_Remark,g_Title    
 ) src  
 pivot    
 (    
   max(g_Value) for g_Title in (' + @GeneralCols + ')    
 ) piv;'    
     
 exec (@lQueryExisting)    
     
 IF OBJECT_ID('tempdb..#tblExaminationAudiometrys') IS NOT NULL    
  DROP TABLE #tblExaminationAudiometrys    
     
 create table #tblExaminationAudiometrys(tid int identity(1,1),AudiometryId bigint,ExaminationId bigint,IsDoneLeft bit,    
 IsDoneRight bit,AcValueLeft int,AcValueRight int,FrequencyId int,AudiometryAcResultLeftId int,AudiometryAcResultRightId int,    
 AudiometryResultRemarkLeftId nvarchar(200),AudiometryResultRemarkRightId nvarchar(200))    
 insert into #tblExaminationAudiometrys    
 select ISNULL(A.Id,0) AS AudiometryId,ED.Id,    
 ISNULL(A.IsDoneLeft,0) AS IsDoneLeft,    
 ISNULL(A.IsDoneRight,0) AS IsDoneRight,    
 ISNULL(AD.AcValueLeft,0) AS AcValueLeft,    
 ISNULL(AD.AcValueRight,0) AS AcValueRight,  
 ISNULL(AD.FrequencyId,0) AS FrequencyId,    
 ISnull(A.AudiometryAcResultLeftId,0) AS AudiometryAcResultLeftId,    
 ISnull(A.AudiometryAcResultRightId,0) AS AudiometryAcResultRightId,    
 ISnull(A.AudiometryResultRemarkLeftId,0) AS AudiometryResultRemarkLeftId,    
 ISnull(A.AudiometryResultRemarkRightId,0) AS AudiometryResultRemarkRightId    
 from sExamination.tExamination ED    
 inner join #tblExaminationAll AA on ED.Id = AA.ExaminationId    
 left join sExamination.tAudiometry A on A.SourceId = ED.Id    
 left join sExamination.tAudiometryDetail AD on AD.AudiomentryId = A.Id    
 left join sExamination.tAudiometryResultMaster RM on A.AudiometryAcResultLeftId = RM.Id    
 left join sExamination.tAudiometryResultMaster RM1 on A.AudiometryBcResultLeftId = RM.Id    
 left join sExamination.tAudiometryResultMaster RM2 on A.AudiometryAcResultRightId = RM.Id    
 left join sExamination.tAudiometryResultMaster RM3 on A.AudiometryBcResultRightId = RM.Id     
     
 IF OBJECT_ID('tempdb..##tblAudiometry') IS NOT NULL    
  DROP TABLE ##tblAudiometry    
     
 select @lQueryExisting = 'create table ##tblAudiometry(a_ExamId bigint,IsDoneLeft bit,    
 AudiometryAcResultLeft varchar(300),AudiometryResultRemarkLeft varchar(300),L250 varchar(200),L500 varchar(200),    
 L1000 varchar(200),L2000 varchar(200),L4000 varchar(200),L6000 varchar(200),L8000 varchar(200),    
 IsDoneRight bit,AudiometryAcResultRight varchar(300),AudiometryResultRemarkRight varchar(300),    
 R250 varchar(200),R500 varchar(200),R1000 varchar(200),R2000 varchar(200),R4000 varchar(200),R6000 varchar(200),R8000 varchar(200))'    
     
 exec(@lQueryExisting)    
     
 select @lQueryExisting = '    
 insert into ##tblAudiometry(a_ExamId,IsDoneLeft,AudiometryAcResultLeft,AudiometryResultRemarkLeft,L250,L500,    
 L1000,L2000,L4000,L6000,L8000,IsDoneRight,AudiometryAcResultRight,AudiometryResultRemarkRight,R250,R500,R1000,R2000,R4000,R6000,R8000)    
 Select LeftPivot.ExaminationId,CASE WHEN LeftPivot.IsDoneLeft = 1 THEN ''TRUE'' ELSE ''FALSE'' END as IsDoneLeft,    
 ISNULL(LeftPivot.AudiometryAcResultLeft,'''') as AudiometryAcResultLeft,    
 ISNULL(LeftPivot.AudiometryResultRemarkLeft,'''') as AudiometryResultRemarkLeft,    
 LeftPivot.[250] as L250,LeftPivot.[500] as L500,LeftPivot.[1000] as L1000,LeftPivot.[2000] as L2000,    
 LeftPivot.[4000] as L4000,LeftPivot.[6000] as L6000,LeftPivot.[8000] as L8000,    
 CASE WHEN RightPivot.IsDoneRight = 1 THEN ''TRUE'' ELSE ''FALSE'' END as IsDoneRight,    
 RightPivot.AudiometryAcResultRight as AudiometryAcResultRight,    
 RightPivot.AudiometryResultRemarkRight as AudiometryResultRemarkRight,    
 RightPivot.[250] as R250,RightPivot.[500] as R500,RightPivot.[1000] as R1000,RightPivot.[2000] as R2000,    
 RightPivot.[4000] as R4000,RightPivot.[6000] as R6000,RightPivot.[8000] as R8000    
 From    
 (    
  select pvt.AudiometryId AS AudiometryId,    
  ISNULL(pvt.AudiometryLeftResult,'''') AS AudiometryAcResultLeft,    
  ISNULL(pvt.AudiometryLeftRemark,'''') AS AudiometryResultRemarkLeft,    
  pvt.IsDoneLeft,pvt.[250],pvt.[500],pvt.[1000],pvt.ExaminationId,pvt.[2000],pvt.[4000],pvt.[6000],pvt.[8000]    
  from    
  (    
   Select AudiometryId,TC.ExaminationId,IsDoneLeft,AcValueLeft,    
   FrequencyId,RS.Title AS AudiometryLeftResult,    
   RM.Title AS AudiometryLeftRemark    
   FROM #tblExaminationAudiometrys TC LEFT JOIN sExamination.tAudiometryResultMaster RS ON RS.Id = TC.AudiometryAcResultLeftId    
   LEFT JOIN sExamination.tAudioMetryRemarkMaster RM ON RM.Id = TC.AudiometryResultRemarkLeftId    
  )t     
  PIVOT (MIN(AcValueLeft) FOR FrequencyId IN([250],[500],[1000],[2000],[4000],[6000],[8000])) AS pvt    
 ) LeftPivot    
 INNER JOIN    
 (    
  select pvt.AudiometryId AS AudiometryId,    
  ISNULL(pvt.AudiometryRightResult,'''') AS AudiometryAcResultRight,    
  ISNULL(pvt.AudiometryRightRemark,'''') AS AudiometryResultRemarkRight, pvt.IsDoneRight,    
  pvt.[250],pvt.[500],pvt.[1000],pvt.ExaminationId,pvt.[2000],pvt.[4000],pvt.[6000],pvt.[8000]    
  from    
  (    
   Select AudiometryId,TC.ExaminationId,IsDoneRight,AcValueRight,    
   FrequencyId,RS.Title AS AudiometryRightResult,    
   RM.Title AS AudiometryRightRemark    
   FROM #tblExaminationAudiometrys TC LEFT JOIN sExamination.tAudiometryResultMaster RS ON RS.Id = TC.AudiometryAcResultRightId    
   LEFT JOIN sExamination.tAudioMetryRemarkMaster RM ON RM.Id = TC.AudiometryResultRemarkRightId    
  )t    
  PIVOT (MIN(AcValueRight) FOR FrequencyId IN([250],[500],[1000],[2000],[4000],[6000],[8000])    
 ) AS pvt ) RightPivot ON LeftPivot.ExaminationId = RightPivot.ExaminationId'    
     
 exec (@lQueryExisting)    
     
 declare @lMainQuery varchar(max)=''    
     
 IF OBJECT_ID('tempdb..##tblMainExamination1') IS NOT NULL    
  DROP TABLE ##tblMainExamination1    
     
 select @lMainQuery = 'create table ##tblMainExamination1(ExaminationId bigint,[Examination Type] varchar(max),[Round Name] varchar(max),  
 [Sub Location] varchar(max),[Examination Date] varchar(max),[Employee Code] varchar(max),[Full Name] varchar(max),    
 Department varchar(max),[Department Group] varchar(max),[Function] varchar(max),Company varchar(max),    
 [Company Group] varchar(max),Vertical varchar(max),Business varchar(max),[Employee Type] varchar(max),    
 Grade varchar(max),Designation varchar(max),BirthDate varchar(max),Age int,[Join Date] varchar(max),    
 Duration int,Gender varchar(max),MobileNo varchar(max),Email varchar(max),BloodGroup varchar(max),    
 Skill varchar(max),ProcessType varchar(max),Height varchar(max),[Weight] varchar(max),BMI varchar(max),    
 ' + case when @ExistingCols1 is not null then isnull(@ExistingCols1,'') + ',' else '' end + '    
 ' + case when @DiseaseCols is not null then isnull(@DiseaseCols,'') + ',' else '' end + '    
 ' + case when @HistoryCols is not null then isnull(@HistoryCols,'') + ',' else '' end + 'Systolic varchar(max),Diastilic varchar(max),  Status varchar(max) ,  
 ' + case when @TestCols1 is not null then isnull(@TestCols1,'') + ',' else '' end +'    
 ' + case when @GeneralCols1 is not null then isnull(@GeneralCols1,'') + ',' else '' end + '    
 FVCPredicted varchar(200),FVCObserved varchar(200),PerOfPredictedFVC varchar(200),FEV1Predicted varchar(200),FEV1Observed varchar(200),    
 PerOfFEV1 varchar(200),PerOfFEV1ByFVC varchar(200),FEV5Observed varchar(200),PerOfFEV1ByFEV5 varchar(200),    
 MVVObserved varchar(200),MVVPredicted varchar(200),PerOfMVV varchar(200),PEFRPredicted varchar(200),    
 PEFRObserved varchar(200),PerPEFR varchar(200),PulmonaryResult varchar(200),NotDoneReason varchar(50),    
 IsDoneLeft bit,AudiometryAcResultLeft varchar(300),AudiometryResultRemarkLeft varchar(300),L250 varchar(200),L500 varchar(200),    
 L1000 varchar(200),L2000 varchar(200),L4000 varchar(200),L6000 varchar(200),L8000 varchar(200),    
 IsDoneRight bit,AudiometryAcResultRight varchar(300),AudiometryResultRemarkRight varchar(300),    
 R250 varchar(200),R500 varchar(200),R1000 varchar(200),R2000 varchar(200),R4000 varchar(200),R6000 varchar(200),R8000 varchar(200),    
 MailSend varchar(50),EntryPending varchar(50),comDiagnosis varchar(max),comRecommandEng varchar(max),    
 conFit varchar(10),comUnfit varchar(10),conUnfitDate varchar(50),comUnfitReason varchar(max),    
 comUnfitPeriod varchar(10),comRefitDate varchar(50),Agency varchar(300),    
 ' + case when @TestColsNew1 is not null then isnull(@TestColsNew1,'') + '' else '' end + ',ProviderName nvarchar(max),
 HealthIndicator nvarchar(max),ProviderAppointmentStatus nvarchar(max)' + ')'    
     
     
 select @lMainQuery = replace(@lMainQuery,'OVA','Stool for ova and cyst')    
 print @lMainQuery    
 exec(@lMainQuery)    
     
 declare @lMainExecuteQuery varchar(max)=''     
     
 select @lMainExecuteQuery = 'insert into ##tblMainExamination1 select ExaminationId,ISNULL([Examination Type],''''),ISNULL([Round Name],''''),   
 ISNULL([Sub Location],''''),ISNULL([Examination Date],''''),ISNULL([Employee Code],''''),ISNULL([Full Name],''''),ISNULL(Department,''''),ISNULL([Department Group],''''),  
 ISNULL([Function],''''),ISNULL(Company,''''),ISNULL([Company Group],''''),ISNULL(Vertical,''''),ISNULL(Business,''''),ISNULL([Employee Type],''''),ISNULL(Grade,''''),  
 ISNULL(Designation,''''),ISNULL(BirthDate,''''),ISNULL(Age,0),ISNULL([Join Date],''''),  
 ISNULL(Duration,0),ISNULL(Gender,''''),ISNULL(MobileNo,''''),ISNULL(Email,''''),ISNULL(BloodGroup,''''),ISNULL(Skill,''''),ISNULL(ProcessType,''''),  
 ISNULL(Height,''''),ISNULL([Weight],''''),ISNULL(BMI,''''),  
 ' + @ExistingCols + ',' + REPLACE(REPLACE(@DiseaseCols1, '[', 'ISNULL(['), ']', '],'''')') + ',' + REPLACE(REPLACE(@HistoryCols1, '[', 'ISNULL(['), ']', '],'''')') + '  
 ,ISNULL(Systolic,''''),ISNULL(Diastilic,''''),ISNULL(Status,''''),' + @TestCols + ',' + @GeneralCols + ',    
 ISNULL(FVCPredicted,0),ISNULL(FVCObserved,0),ISNULL(PerOfPredictedFVC,0),ISNULL(FEV1Predicted,0),ISNULL(FEV1Observed,0),ISNULL(PerOfFEV1,0),  
 ISNULL(PerOfFEV1ByFVC,0),ISNULL(FEV5Observed,0),ISNULL(PerOfFEV1ByFEV5,0),  
 ISNULL(MVVObserved,0),ISNULL(MVVPredicted,0),ISNULL(PerOfMVV,0),ISNULL(PEFRPredicted,0),ISNULL(PEFRObserved,0),ISNULL(PerPEFR,0),  
 PulmonaryResult = ISNULL(P.PulmonaryResulIntensity,'''') + '' '' + ISNULL(P.PulmonaryResult,''''),'''',  
 ISNULL(IsDoneLeft,''''),ISNULL(AudiometryAcResultLeft,''''),ISNULL(AudiometryResultRemarkLeft,''''),ISNULL(L250,0),ISNULL(L500,0),ISNULL(L1000,0),ISNULL(L2000,0),ISNULL(L4000,0),ISNULL(L6000,0),ISNULL(L8000,0),  
ISNULL(IsDoneRight,0),ISNULL(AudiometryAcResultRight,''''),ISNULL(AudiometryResultRemarkRight,''''),ISNULL(R250,0),ISNULL(R500,0),ISNULL(R1000,0),ISNULL(R2000,0),ISNULL(R4000,0),ISNULL(R6000,0),ISNULL(R8000,0),  
ISNULL(MailSend,''''),ISNULL(EntryPending,''''),ISNULL(comDiagnosis,''''),ISNULL(comRecommandEng,''''),ISNULL(conFit,''''),ISNULL(comUnfit,''''),ISNULL(conUnfitDate,''''),ISNULL(comUnfitReason,''''),  
ISNULL(comUnfitPeriod,''''),ISNULL(comRefitDate,''''),ISNULL(Agency,''''),' + @TestColsNew + ',ProviderName,HealthIndicator,ProviderAppointmentStatus' + '  
 from #tblExaminationAll EA    
 left join tempdb.##tblHabit EE on EA.ExaminationId = EE.t_ExamId    
 left join tempdb.##tblDisease ED on EA.ExaminationId = ED.d_ExamId    
 left join tempdb.##tblHistory HE on EA.ExaminationId = HE.d_ExamId    
 left join tempdb.##tblGeneral GE on EA.ExaminationId = GE.d_ExamId  
 left join tempdb.##tblTests TE on EA.ExaminationId = TE.d_ExamId    
 left join tempdb.##tblAudiometry AA on EA.ExaminationId = AA.a_ExamId    
 left join sExamination.tPulmonary P on EA.ExaminationId = P.SourceId'    
     
 print @lMainExecuteQuery    
 exec (@lMainExecuteQuery)    
     
 update ##tblMainExamination1 set OtherDiseaseDetail = Remark from sExamination.tExistingDisease where ExaminationId = SourceId    
     
 --select * from  ##tblMainExamination1  
 DECLARE @SQL nvarchar(MAX);

-- Initialize the @SQL variable
SET @SQL = '';

-- Building the dynamic SQL for updating nulls based on column types from tempdb
SELECT @SQL = @SQL + 
    CASE 
        WHEN t.name IN ('nvarchar', 'varchar', 'char', 'nchar', 'text')
        THEN 'UPDATE ##tblMainExamination1 SET ' + QUOTENAME(c.name) + ' = COALESCE(' + QUOTENAME(c.name) + ', ''''); '
        WHEN t.name IN ('int', 'bit', 'decimal', 'numeric', 'float', 'bigint', 'smallint', 'tinyint', 'money', 'smallmoney')
        THEN 'UPDATE ##tblMainExamination1 SET ' + QUOTENAME(c.name) + ' = COALESCE(' + QUOTENAME(c.name) + ', 0); '
    END
FROM tempdb.sys.columns c
INNER JOIN tempdb.sys.tables tbl ON c.object_id = tbl.object_id
INNER JOIN sys.types t ON c.user_type_id = t.user_type_id
WHERE tbl.name LIKE '##tblMainExamination1%';

-- Execute the dynamic SQL
EXEC sp_executesql @SQL;

DECLARE @FinalResult nvarchar(MAX);
DECLARE @ColumnList TABLE (ColumnName varchar(255));
DECLARE @ExistingColumns TABLE (ColumnName varchar(255));

-- Define the list of all possible columns you want to check
INSERT INTO @ColumnList (ColumnName)
VALUES ('Examination Type'), ('Round Name'), ('Sub Location'), ('Examination Date'),
       ('Employee Code'), ('Full Name'), ('Department'), ('Department Group'),
       ('Function'), ('Company'), ('Company Group'), ('Vertical'), ('Business'),
       ('Employee Type'), ('Grade'), ('Designation'), ('BirthDate'), ('Age'),       
       ('Join Date'), ('Duration'), ('Gender'), ('MobileNo'), ('Email'), 
       ('BloodGroup'), ('Skill'), ('ProcessType'), ('Height'), ('Weight'),
       ('BMI'), ('Alcoholhab'), ('Chewerhab'), ('Smokerhab'), ('Disease'),
       ('OtherDiseaseDetail'), ('phSelf'), ('Systolic'), ('Diastilic'), ('Status'),
       ('F B S'), ('P P B S'), ('R B S'), ('CHOLESTEROL'), ('TRIGLYCERIDE'),
       ('HDL'), ('LDL'), ('SGPT'), ('ALKALINE PHOSPHATASE'), ('SERUM URIC ACID'),
       ('BLOOD UREA'), ('SERUM CREATININE'), ('HB'), ('PSA'), ('ECG'), ('ECG_Remark'),
       ('ECHO'), ('ECHO_Remark'), ('TMT'), ('TMT_Remark'), ('XRAY'), ('XRAY_Remark'),
       ('SONOGRAPHY'), ('SONOGRAPHY_Remark'), ('PulmonaryResult'), ('MailSend'), 
       ('EntryPending'), ('comDiagnosis'), ('comRecommandEng'), ('Agency'), 
       ('HBA1C'), ('TSH'), ('Vitamin B12'), ('Vitamin D3'), ('SGOT'), 
	   ('ProviderName'), ('HealthIndicator'), ('ProviderAppointmentStatus');

-- Retrieve the existing columns from tempdb metadata
INSERT INTO @ExistingColumns (ColumnName)
SELECT c.name
FROM tempdb.sys.columns c
JOIN tempdb.sys.tables t ON c.object_id = t.object_id
WHERE t.name LIKE '##tblMainExamination1%' 
AND c.name COLLATE DATABASE_DEFAULT IN (SELECT ColumnName FROM @ColumnList);

-- Initialize the SQL query
SET @FinalResult = 'SELECT ';

Declare @rExaminationAPIFieldCount int;
select @rExaminationAPIFieldCount = (select Count(Id) from [sExamination].[tExaminationAPIFieldsMapping] where IsObsolete = 0 and IsEnable = 1 and ExaminationType = 'Examination')
IF @rExaminationAPIFieldCount > 0
BEGIN
		DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX);

		SELECT @cols = STUFF((SELECT ',' + QUOTENAME(Fields) 
							FROM [sExamination].[tExaminationAPIFieldsMapping]
							WHERE IsObsolete = 0 AND IsEnable = 1 and ExaminationType = 'Examination'
					FOR XML PATH(''), TYPE
					).value('.', 'NVARCHAR(MAX)') 
				,1,1,'')

		-- Complete the SQL statement
		SET @FinalResult = @FinalResult + @cols + ' FROM ##tblMainExamination1';
END
ELSE
BEGIN
		-- Append each existing column to the SELECT statement
		SELECT @FinalResult = @FinalResult + 'ISNULL([' + ColumnName + '], '''') AS [' + ColumnName + '], '
		FROM @ExistingColumns;

		-- Remove the last comma and space from the SQL string
		SET @FinalResult = LEFT(@FinalResult, LEN(@FinalResult) - 1);
		-- Complete the SQL statement
		SET @FinalResult = @FinalResult + ' FROM ##tblMainExamination1';
END

-- Execute the dynamic SQL
print @FinalResult
EXEC sp_executesql @FinalResult;

-- To check the result
--SELECT * FROM ##tblMainExamination1;




-- SELECT  
--    ISNULL([Examination Type],'') as [Examination Type],  
--    ISNULL([Round Name],'') as [Round Name],  
--    ISNULL([Sub Location],'') as [Sub Location],  
--    ISNULL([Examination Date],'') as [Examination Date],  
--    ISNULL([Employee Code],'') as [Employee Code],  
--    ISNULL([Full Name],'') as [Full Name],  
--    ISNULL([Department],'') as [Department],  
--    ISNULL([Department Group],'') as [Department Group],  
--    ISNULL([Function],'') as [Function],  
--    ISNULL([Company],'') as [Company],  
--    ISNULL([Company Group],'') as [Company Group],  
--    ISNULL([Vertical],'') as [Vertical],  
--    ISNULL([Business],'') as [Business],  
--    ISNULL([Employee Type],'') as [Employee Type],  
--    ISNULL([Grade],'') as [Grade],  
--    ISNULL([Designation],'') as [Designation],  
--    ISNULL([BirthDate],'') as [BirthDate],  
--    ISNULL([Age],0) as [Age],  
--    ISNULL([Join Date],'') as [Join Date],  
--    ISNULL([Duration],0) as [Duration],  
--    ISNULL([Gender],'') as [Gender],  
--    ISNULL([MobileNo],'') as [MobileNo],  
--    ISNULL([Email],'') as [Email],  
--    ISNULL([BloodGroup],'') as [BloodGroup],  
--    ISNULL([Skill],'') as [Skill],  
--    ISNULL([ProcessType],'') as [ProcessType],  
--    ISNULL([Height],0) as [Height],  
--    ISNULL([Weight],0) as [Weight],  
--    ISNULL([BMI],0) as [BMI],  
-- --ISNULL([Alcoholhab],'') as [Alcoholhab],  
--    ISNULL([Chewerhab],'') as [Chewerhab],  
--    ISNULL([Smokerhab],'') as [Smokerhab],  
--    ISNULL([Disease],'') as [Disease],  
--    ISNULL([OtherDiseaseDetail],'') as [OtherDiseaseDetail],  
--    ISNULL([phSelf],'') as [phSelf],  
--    ISNULL([Systolic],'') as [Systolic],  
--    ISNULL([Diastilic],'') as [Diastilic],  
--    ISNULL([Status],'') as [Status],  
--    ISNULL([F B S],'') as [F B S],  
--    ISNULL([P P B S],'') as [P P B S],  
--    ISNULL([R B S],'') as [R B S],  
--    ISNULL([CHOLESTEROL],'') as [CHOLESTEROL],  
--    ISNULL([TRIGLYCERIDE],'') as [TRIGLYCERIDE],  
--    ISNULL([HDL],'') as [HDL],  
--    ISNULL([LDL],'') as [LDL],  
--    ISNULL([SGPT],'') as [SGPT],  
--    ISNULL([ALKALINE PHOSPHATASE],'') as [ALKALINE PHOSPHATASE],  
--    ISNULL([SERUM URIC ACID],'') as [SERUM URIC ACID],  
--    ISNULL([BLOOD UREA],'') as [BLOOD UREA],  
--    ISNULL([SERUM CREATININE],'') as [SERUM CREATININE],  
--    ISNULL([HB],'') as [HB],  
--    ISNULL([PSA],'') as [PSA],  
--    ISNULL([ECG],'') as [ECG],  
--    ISNULL([ECG_Remark],'') as [ECG_Remark],  
--    ISNULL([ECHO],'') as [ECHO],  
--    ISNULL([ECHO_Remark],'') as [ECHO_Remark],  
--    ISNULL([TMT],'') as [TMT],  
--    ISNULL([TMT_Remark],'') as [TMT_Remark],  
--    ISNULL([XRAY],'') as [XRAY],  
--    ISNULL([XRAY_Remark],'') as [XRAY_Remark],  
--    ISNULL([SONOGRAPHY],'') as [SONOGRAPHY],  
--    ISNULL([SONOGRAPHY_Remark],'') as [SONOGRAPHY_Remark],  
--    ISNULL([PulmonaryResult],'') as [PulmonaryResult],  
--    ISNULL([MailSend],'') as [MailSend],  
--    ISNULL([EntryPending],'') as [EntryPending],  
--    ISNULL([comDiagnosis],'') as [comDiagnosis],  
--    ISNULL([comRecommandEng],'') as [comRecommandEng],  
--    ISNULL([Agency],'') as [Agency],  
--    ISNULL([HBA1C],'') as [HBA1C],  
--    ISNULL([TSH],'') as [TSH],  
--    ISNULL([Vitamin B12],'') as [Vitamin B12],  
--    ISNULL([Vitamin D3],'') as [Vitamin D3],  
--    ISNULL([SGOT],'') as [SGOT]  
--FROM   
--    ##tblMainExamination1;  
  
end
GO
PRINT N'Altering Procedure [sExamination].[pGetEmployeepDiagnosisAnalysis]...';


GO

ALTER PROC [sExamination].[pGetEmployeepDiagnosisAnalysis]
 @rMaINTypeId          INT,  
 @rOrgId               INT,  
 @rSetupGroupId        INT,  
 @rSetupId        INT,  
 @rSectorId     INT,  
 @rVerticalId    INT,  
 @rCompanyGroupId      INT,  
 @rEmployeeCompanyId   INT,  
 @rLocationMainGroupId INT,  
 @rLocationSubGroupId  INT,  
 @rLocationId    INT,  
 @rStoreLocationId   INT,  
 @rFunctionId    INT,  
 @rDepartmentGroupId   INT,  
 @rDepartmentId        INT,  
 @rEmployeeCode        VARCHAR(100),  
 @rEmployeeFname       VARCHAR(100),  
 @rEmployeeLname       VARCHAR(100),  
 @rFromDate     varchar(100),  
 @rToDate     varchar(100),  
 @rTargetGroupId       NVARCHAR(MAX)='',  
 @rmtype      INT,  
 @rMasterId     INT,  
 @rColumnName varchar(500) = '',  
 @rUserId bigint,  
 @rIsActiveHealth int,  
 @rIsOPDSetup int,  
 @rDojfromDate varchar(20)='',  
 @rDOJtoDate varchar(20)='',  
 @rIsBusinessWise bit = 0  
AS  
BEGIN  
 DECLARE @res varchar(max) = ''  
  
 IF (@rToDate = '')  
 BEGIN  
  SET @rToDate = '01/06/2050'  
 END  
 IF(@rDOJtoDate='')  
 BEGIN  
  SET @rDOJtoDate=GetDate()  
 END  
 SELECT @rFromDate = CONVERT(varchar(10), CONVERT(date, @rFromDate, 105), 23)   
 SELECT @rToDate = CONVERT(varchar(10), CONVERT(date, @rToDate, 105), 23)  
 select @rDojfromDate = CONVERT(VARCHAR(10), CONVERT(date, @rDojfromDate, 105), 23)  
 select @rDOJtoDate = CONVERT(VARCHAR(10), CONVERT(date, @rDOJtoDate, 105), 23)  

 DECLARE @lExcludeExistingOrNewRecordsFromTracker varchar(5);
      
 select @lExcludeExistingOrNewRecordsFromTracker = sConfig.fConfigurationValueGet('Diagnosis.ExcludeExistingOrNewRecordsFromTracker',@rOrgId,0,0,0);
  
 DECLARE @TableOne TABLE (tId int IDENTITY (1, 1),GroupId int,GroupName nvarchar(100))  
  
 IF (@rmtype = 1)  
 BEGIN  
  INSERT INTO @TableOne (GroupId, GroupName)  
  SELECT distinct SLM.Id,SLM.Title FROM  sExamination.tExamination AS EXM   
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId=EXM.Id  
  INNER JOIN [sExamination].[tSetupMaster]    AS STM ON STM.ID=EXM.SetupId  
  INNER JOIN [sExamination].[tSetupGroupMaster]   AS SGM ON SGM.Id=STM.SetupGroupId  
  INNER JOIN [sExamination].[tSubTypeMaster]    AS SSM ON SSM.Id = STM.SubTypeId   
  INNER JOIN [sHrm].[tEmployeeMaster]      AS EMP ON EMP.ID= EXM.ParticipantSourceId  
  INNER  JOIN [sHrm].[tEmployeeJobDetail]                AS EJD ON EJD.EmployeeId=EMP.ID  
  INNER  JOIN [sHrm].[tEmployeePersonalDetail]           AS EPD ON EPD.EmployeeId=EMP.ID  
  INNER  JOIN [sHrm].[tEmployeeCompanyMaster]    AS ECM ON ECM.Id= (case when @rIsBusinessWise=0 then EXM.EmployeeCompanyId else EJD.EmployeeCompanyId end)  
  INNER  JOIN [sHrm].[tCompanyGroupMaster]     AS CGM ON CGM.Id=ECM.CompanyGroupId  
  INNER  JOIN [sHrm].[tVerticalMaster]      AS VTM ON VTM.ID=CGM.VerticalId  
  INNER  JOIN [sHrm].[tSectorMaster]      AS SCT ON SCT.Id=VTM.SectorId  
  INNER  JOIN [sCommon].[tCompanyInformation]    AS CMP ON CMP.ID=SCT.OrgId  
  INNER JOIN [sIp].[tStoreLocationMaster]     AS SLM ON SLM.Id=EXM.StoreLocationId  
  INNER  JOIN [sCommon].[tLocationMaster]     AS LMN ON LMN.Id=SLM.LocationId    
  INNER  JOIN [sCommon].[tOrganizationDepartmentMaster]  AS DPT ON DPT.Id=EXM.OrganizationDepartmentId  
  INNER  JOIN [sCommon].[tDepartmentGroupMaster]   AS DPG ON DPG.id=DPT.DepartmentGroupId  
  INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId  
  INNER  JOIN [sCommon].[tFunctionMaster]     AS FCN ON FCN.Id=DPG.FunctionId  
  LEFT  JOIN  [sCommon].[tLocationSubGroupMaster]   AS LSG ON LSG.Id=LMN.LocationSubGroupId  AND ((LMN.LocationSubGroupId=@rLocationSubGroupId) OR (@rLocationSubGroupId=0))   
  LEFT  JOIN  [sCommon].[tLocationMainGroupMaster]   AS LMG ON LMG.Id=LSG.LocationMainGroupId AND ((LSG.LocationMainGroupId=@rLocationMainGroupId) OR (@rLocationMainGroupId=0))  
  
  WHERE  EXM.ParticipantSourceTypeId=95  
  AND EXM.OrgId=@rOrgId  
  AND UL.UserId = @rUserId  
  AND SSM.MaINTypeId=@rMaINTypeId   
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))  
  AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))  
  AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))  
  AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))  
  AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))  
  AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))  
  AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))  
  AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))  
  AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))  
  AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))  
  AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((EMP.Code LIKE @rEmployeeCode)OR (@rEmployeeCode = ''))  
  AND ((EMP.FirstName LIKE @rEmployeeFname )OR (@rEmployeeFname = ''))  
  AND ((EMP.LastName LIKE @rEmployeeLname) OR (@rEmployeeLname = ''))  
  --AND ((EXM.TargetGroupId =@rTargetGroupId) OR (@rTargetGroupId=0))  
  AND ((EXM.TargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupId,',') )) or @rTargetGroupId='') --Nidhi DT-17/01/23; id - 0022915  
  AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')  
  AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='')  
  AND (datediff(day,@rDojfromDate,EJD.DateOfJoining)>=0 or @rDojfromDate = '')  
  AND (datediff(day,EJD.DateOfJoining,@rDOJtoDate)>=0 or @rDOJtoDate ='')  
  AND (SLM.IsActiveHealth = @rIsActiveHealth or @rIsActiveHealth = 0)  
  AND (SLM.IsOpdSetup = @rIsOPDSetup or @rIsOPDSetup = 0)  
 END  
 ELSE IF (@rmtype = 2)  
 BEGIN  
  
 INSERT INTO @TableOne (GroupId, GroupName)  
  SELECT distinct DPT.Id,DPT.Title FROM  sExamination.tExamination AS EXM   
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId=EXM.Id  
  INNER JOIN [sExamination].[tSetupMaster]    AS STM ON STM.ID=EXM.SetupId  
  INNER JOIN [sExamination].[tSetupGroupMaster]   AS SGM ON SGM.Id=STM.SetupGroupId  
  INNER JOIN [sExamination].[tSubTypeMaster]    AS SSM ON SSM.Id = STM.SubTypeId   
  INNER JOIN [sHrm].[tEmployeeMaster]      AS EMP ON EMP.ID= EXM.ParticipantSourceId  
  INNER JOIN [sHrm].[tEmployeeJobDetail]                AS EJD ON EJD.EmployeeId=EMP.ID  
  INNER JOIN [sHrm].[tEmployeePersonalDetail]           AS EPD ON EPD.EmployeeId=EMP.ID  
  INNER JOIN [sHrm].[tEmployeeCompanyMaster]    AS ECM ON ECM.Id= (case when @rIsBusinessWise=0 then EXM.EmployeeCompanyId else EJD.EmployeeCompanyId end)  
  INNER JOIN [sHrm].[tCompanyGroupMaster]     AS CGM ON CGM.Id=ECM.CompanyGroupId  
  INNER JOIN [sHrm].[tVerticalMaster]      AS VTM ON VTM.ID=CGM.VerticalId  
  INNER JOIN [sHrm].[tSectorMaster]      AS SCT ON SCT.Id=VTM.SectorId  
  INNER JOIN [sCommon].[tCompanyInformation]    AS CMP ON CMP.ID=SCT.OrgId  
  INNER JOIN [sIp].[tStoreLocationMaster]     AS SLM ON SLM.Id=EXM.StoreLocationId  
  INNER JOIN [sCommon].[tLocationMaster]     AS LMN ON LMN.Id=SLM.LocationId    
  INNER JOIN [sCommon].[tOrganizationDepartmentMaster]  AS DPT ON DPT.Id=EXM.OrganizationDepartmentId  
  INNER JOIN [sCommon].[tDepartmentGroupMaster]   AS DPG ON DPG.id=DPT.DepartmentGroupId  
  INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId  
  INNER JOIN [sCommon].[tFunctionMaster]     AS FCN ON FCN.Id=DPG.FunctionId  
  LEFT  JOIN  [sCommon].[tLocationSubGroupMaster]   AS LSG ON LSG.Id=LMN.LocationSubGroupId  AND ((LMN.LocationSubGroupId=@rLocationSubGroupId) OR (@rLocationSubGroupId=0))   
  LEFT  JOIN  [sCommon].[tLocationMainGroupMaster]   AS LMG ON LMG.Id=LSG.LocationMainGroupId AND ((LSG.LocationMainGroupId=@rLocationMainGroupId) OR (@rLocationMainGroupId=0))  
  
  WHERE  EXM.ParticipantSourceTypeId=95  
  AND EXM.OrgId=@rOrgId  
  AND UL.UserId = @rUserId  
  AND SSM.MaINTypeId=@rMaINTypeId   
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))  
  AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))  
  AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))  
  AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))  
  AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))  
  AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))  
  AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))  
  AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))  
  AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))  
  AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))  
  AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((EMP.Code LIKE @rEmployeeCode)OR (@rEmployeeCode = ''))  
  AND ((EMP.FirstName LIKE @rEmployeeFname )OR (@rEmployeeFname = ''))  
  AND ((EMP.LastName LIKE @rEmployeeLname) OR (@rEmployeeLname = ''))  
  --AND ((EXM.TargetGroupId =@rTargetGroupId) OR (@rTargetGroupId=0))  
  AND ((EXM.TargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupId,',') )) or @rTargetGroupId='') --Nidhi DT-17/01/23; id - 0022915  
  AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')  
  AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='')  
  AND (datediff(day,@rDojfromDate,EJD.DateOfJoining)>=0 or @rDojfromDate = '')  
  AND (datediff(day,EJD.DateOfJoining,@rDOJtoDate)>=0 or @rDOJtoDate ='')  
  AND (SLM.IsActiveHealth = @rIsActiveHealth or @rIsActiveHealth = 0)  
  AND (SLM.IsOpdSetup = @rIsOPDSetup or @rIsOPDSetup = 0)  
  
 END  
 ELSE IF (@rmtype = 3)  
 BEGIN  
 INSERT INTO @TableOne (GroupId, GroupName)  
  SELECT distinct ECM.Id,ECM.Title FROM  sExamination.tExamination AS EXM   
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId=EXM.Id  
  INNER JOIN [sExamination].[tSetupMaster]    AS STM ON STM.ID=EXM.SetupId  
  INNER JOIN [sExamination].[tSetupGroupMaster]   AS SGM ON SGM.Id=STM.SetupGroupId  
  INNER JOIN [sExamination].[tSubTypeMaster]    AS SSM ON SSM.Id = STM.SubTypeId   
  INNER JOIN [sHrm].[tEmployeeMaster]      AS EMP ON EMP.ID= EXM.ParticipantSourceId  
  INNER JOIN [sHrm].[tEmployeeJobDetail]                AS EJD ON EJD.EmployeeId=EMP.ID  
  INNER JOIN [sHrm].[tEmployeePersonalDetail]           AS EPD ON EPD.EmployeeId=EMP.ID  
  INNER JOIN [sHrm].[tEmployeeCompanyMaster]    AS ECM ON ECM.Id= (case when @rIsBusinessWise=0 then EXM.EmployeeCompanyId else EJD.EmployeeCompanyId end)  
  INNER JOIN [sHrm].[tCompanyGroupMaster]     AS CGM ON CGM.Id=ECM.CompanyGroupId  
  INNER JOIN [sHrm].[tVerticalMaster]      AS VTM ON VTM.ID=CGM.VerticalId  
  INNER JOIN [sHrm].[tSectorMaster]      AS SCT ON SCT.Id=VTM.SectorId  
  INNER JOIN [sCommon].[tCompanyInformation]    AS CMP ON CMP.ID=SCT.OrgId  
  INNER JOIN [sIp].[tStoreLocationMaster]     AS SLM ON SLM.Id=EXM.StoreLocationId  
  INNER JOIN [sCommon].[tLocationMaster]     AS LMN ON LMN.Id=SLM.LocationId    
  INNER JOIN [sCommon].[tOrganizationDepartmentMaster]  AS DPT ON DPT.Id=EXM.OrganizationDepartmentId  
  INNER JOIN [sCommon].[tDepartmentGroupMaster]   AS DPG ON DPG.id=DPT.DepartmentGroupId  
  INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId  
  INNER JOIN [sCommon].[tFunctionMaster]     AS FCN ON FCN.Id=DPG.FunctionId  
  LEFT  JOIN  [sCommon].[tLocationSubGroupMaster]   AS LSG ON LSG.Id=LMN.LocationSubGroupId  AND ((LMN.LocationSubGroupId=@rLocationSubGroupId) OR (@rLocationSubGroupId=0))   
  LEFT  JOIN  [sCommon].[tLocationMainGroupMaster]   AS LMG ON LMG.Id=LSG.LocationMainGroupId AND ((LSG.LocationMainGroupId=@rLocationMainGroupId) OR (@rLocationMainGroupId=0))  
  
  WHERE  EXM.ParticipantSourceTypeId=95  
  AND EXM.OrgId=@rOrgId  
  AND UL.UserId = @rUserId  
  AND SSM.MaINTypeId=@rMaINTypeId   
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))  
  AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))  
  AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))  
  AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))  
  AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))  
  AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))  
  AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))  
  AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))  
  AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))  
  AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))  
  AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((EMP.Code LIKE @rEmployeeCode)OR (@rEmployeeCode = ''))  
  AND ((EMP.FirstName LIKE @rEmployeeFname )OR (@rEmployeeFname = ''))  
  AND ((EMP.LastName LIKE @rEmployeeLname) OR (@rEmployeeLname = ''))  
  --AND ((EXM.TargetGroupId =@rTargetGroupId) OR (@rTargetGroupId=0))  
  AND ((EXM.TargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupId,',') )) or @rTargetGroupId='') --Nidhi DT-17/01/23; id - 0022915  
  AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')  
  AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='')  
  AND (datediff(day,@rDojfromDate,EJD.DateOfJoining)>=0 or @rDojfromDate = '')  
  AND (datediff(day,EJD.DateOfJoining,@rDOJtoDate)>=0 or @rDOJtoDate ='')  
  AND (SLM.IsActiveHealth = @rIsActiveHealth or @rIsActiveHealth = 0)  
  AND (SLM.IsOpdSetup = @rIsOPDSetup or @rIsOPDSetup = 0)  
 END  
  
  
  
  
  
  
 DECLARE @tExamination TABLE  
 (  
  tId int IDENTITY (1, 1),Id bigint,StoreLocationId int,OrganizationDepartmentId int,EmployeeCompanyId int  
 )  
 insert into @tExamination  
 SELECT EXM.Id,EXM.StoreLocationId,EXM.OrganizationDepartmentId,EXM.EmployeeCompanyId  
  FROM sExamination.tExamination AS EXM   
  INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE ON DTE.ExaminationId=EXM.Id  
  INNER JOIN [sExamination].[tSetupMaster]    AS STM ON STM.ID=EXM.SetupId  
  INNER JOIN [sExamination].[tSetupGroupMaster]   AS SGM ON SGM.Id=STM.SetupGroupId  
  INNER JOIN [sExamination].[tSubTypeMaster]    AS SSM ON SSM.Id = STM.SubTypeId   
  INNER JOIN [sHrm].[tEmployeeMaster]      AS EMP ON EMP.ID= EXM.ParticipantSourceId  
  INNER JOIN [sHrm].[tEmployeeJobDetail]                AS EJD ON EJD.EmployeeId=EMP.ID  
  INNER JOIN [sHrm].[tEmployeePersonalDetail]           AS EPD ON EPD.EmployeeId=EMP.ID  
  INNER JOIN [sHrm].[tEmployeeCompanyMaster]    AS ECM ON ECM.Id= (case when @rIsBusinessWise=0 then EXM.EmployeeCompanyId else EJD.EmployeeCompanyId end)  
  INNER JOIN [sHrm].[tCompanyGroupMaster]     AS CGM ON CGM.Id=ECM.CompanyGroupId  
  INNER JOIN [sHrm].[tVerticalMaster]      AS VTM ON VTM.ID=CGM.VerticalId  
  INNER JOIN [sHrm].[tSectorMaster]      AS SCT ON SCT.Id=VTM.SectorId  
  INNER JOIN [sCommon].[tCompanyInformation]    AS CMP ON CMP.ID=SCT.OrgId  
  INNER JOIN [sIp].[tStoreLocationMaster]     AS SLM ON SLM.Id=EXM.StoreLocationId  
  INNER JOIN [sCommon].[tLocationMaster]     AS LMN ON LMN.Id=SLM.LocationId    
  INNER JOIN [sCommon].[tOrganizationDepartmentMaster]  AS DPT ON DPT.Id=EXM.OrganizationDepartmentId  
  INNER JOIN [sCommon].[tDepartmentGroupMaster]   AS DPG ON DPG.id=DPT.DepartmentGroupId  
  INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId  
  INNER JOIN [sCommon].[tFunctionMaster]     AS FCN ON FCN.Id=DPG.FunctionId  
  LEFT  JOIN  [sCommon].[tLocationSubGroupMaster]   AS LSG ON LSG.Id=LMN.LocationSubGroupId  AND ((LMN.LocationSubGroupId=@rLocationSubGroupId) OR (@rLocationSubGroupId=0))   
  LEFT  JOIN  [sCommon].[tLocationMainGroupMaster]   AS LMG ON LMG.Id=LSG.LocationMainGroupId AND ((LSG.LocationMainGroupId=@rLocationMainGroupId) OR (@rLocationMainGroupId=0))  
  
  WHERE  EXM.ParticipantSourceTypeId=95  
  AND EXM.OrgId=@rOrgId  
  AND UL.UserId = @rUserId  
  AND SSM.MaINTypeId=@rMaINTypeId   
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))  
  AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))  
  AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))  
  AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))  
  AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))  
  AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))  
  AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))  
  AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))  
  AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))  
  AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))  
  AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((EMP.Code LIKE @rEmployeeCode)OR (@rEmployeeCode = ''))  
  AND ((EMP.FirstName LIKE @rEmployeeFname )OR (@rEmployeeFname = ''))  
  AND ((EMP.LastName LIKE @rEmployeeLname) OR (@rEmployeeLname = ''))  
  --AND ((EXM.TargetGroupId =@rTargetGroupId) OR (@rTargetGroupId=0))  
  AND ((EXM.TargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupId,',') )) or @rTargetGroupId='') --Nidhi DT-17/01/23; id - 0022915  
  AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')  
  AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='')  
  AND (datediff(day,@rDojfromDate,EJD.DateOfJoining)>=0 or @rDojfromDate = '')  
  AND (datediff(day,EJD.DateOfJoining,@rDOJtoDate)>=0 or @rDOJtoDate ='')  
  AND (SLM.IsActiveHealth = @rIsActiveHealth or @rIsActiveHealth = 0)  
  AND (SLM.IsOpdSetup = @rIsOPDSetup or @rIsOPDSetup = 0)  
  
 IF (@rColumnName='Tobacco')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId ) OR (@rMasterId = 0)  
   )AND DTE.Tobacco = 1  
  )  
 END  
 ELSE IF (@rColumnName='Smoker')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.Smoker = 1  
  )  
 END  
 ELSE IF (@rColumnName='Alcohol')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   ) AND DTE.Alcohol = 1  
  )  
 END  
 ELSE IF (@rColumnName='UnderWeight')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.BMI = 'UnderWeight'  
  )  
 END  
 ELSE IF (@rColumnName='OverWeight')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
  
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.BMI = 'OverWeight'  
  )  
 END  
 ELSE IF (@rColumnName='Obese')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.BMI = 'Obese'  
  )  
 END  
 ELSE IF (@rColumnName='TB')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
  
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.TB = 1  
  )  
 END  
 ELSE IF (@rColumnName='COPD')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.COPD = 1  
  )  
 END  
 ELSE IF (@rColumnName='NewPreHypertension')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   ) AND DTE.IsNewHypertensionStatus = 1 
  )  
 END
 ELSE IF (@rColumnName='PreHypertension')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   ) AND DTE.BloodPressure = 'PreHypertension'
   AND ((@lExcludeExistingOrNewRecordsFromTracker = 'False') 
		OR (@lExcludeExistingOrNewRecordsFromTracker = 'True' 
		AND (DTE.HypertensionExisting <> 'Hypertension Existing' OR DTE.HypertensionExisting IS NULL) AND ISNULL(DTE.IsNewHypertensionStatus,0) <> 1))
  )
 END  
 ELSE IF (@rColumnName='NewHypertension')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   ) AND DTE.IsNewHypertensionStatus = 2  
  )  
 END
 ELSE IF (@rColumnName='Hypertension')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   ) AND DTE.BloodPressure = 'Hypertension'
   AND ((@lExcludeExistingOrNewRecordsFromTracker = 'False') 
		OR (@lExcludeExistingOrNewRecordsFromTracker = 'True' 
		AND (DTE.HypertensionExisting <> 'Hypertension Existing' OR DTE.HypertensionExisting IS NULL) AND ISNULL(DTE.IsNewHypertensionStatus,0) <> 2))
  )
 END
 ELSE IF (@rColumnName='NewPreDiabetic')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   ) AND DTE.IsNewDiabeticStatus = 1 
  )  
 END
 ELSE IF (@rColumnName='Pre Diabetic')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   ) AND DTE.FBS = 'Pre Diabetic'
   AND ((@lExcludeExistingOrNewRecordsFromTracker = 'False') 
		OR (@lExcludeExistingOrNewRecordsFromTracker = 'True' 
		AND (DTE.DiabeticExisting <> 'Diabetic Existing' OR DTE.DiabeticExisting IS NULL) AND ISNULL(DTE.IsNewDiabeticStatus,0) <> 1))
  )  
 END 
 ELSE IF (@rColumnName='NewDiabetic')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   ) AND DTE.IsNewDiabeticStatus = 2  
  )  
 END
 ELSE IF (@rColumnName='Diabetic')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)
   ) AND DTE.FBS = 'Diabetic'
   AND ((@lExcludeExistingOrNewRecordsFromTracker = 'False') 
		OR (@lExcludeExistingOrNewRecordsFromTracker = 'True' 
		AND (DTE.DiabeticExisting <> 'Diabetic Existing' OR DTE.DiabeticExisting IS NULL) AND ISNULL(DTE.IsNewDiabeticStatus,0) <> 2))
  )  
 END  
 ELSE IF (@rColumnName='NIHLMild')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.AudiometryACRight = 'Mild hearing loss'  
  )  
 END  
 ELSE IF (@rColumnName='NIHLModerate')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.AudiometryACRight = 'Moderate hearing loss'  
  )  
 END  
 ELSE IF (@rColumnName='NIHLSevere')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
  
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.AudiometryACRight = 'Severe hearing loss'  
  )  
 END  
 ELSE IF (@rColumnName='XrayILO')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.BMI = 'XrayILO'  
  )  
 END  
 ELSE IF (@rColumnName='Low Hb')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId     
  WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.HB = 'Low Hb'  
  )  
 END  
 ELSE IF (@rColumnName='Hypercholesterolemia')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
  
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.Cholesterol = 'Hypercholesterolemia'  
  )  
 END  
 ELSE IF (@rColumnName='Borderline Cholesterol')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.Cholesterol = 'Borderline Cholesterol'  
  )  
 END  
 ELSE IF (@rColumnName='Hypertriglyceridemia')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
  
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.Triglyceride = 'Hypertriglyceridemia'  
  )  
 END  
 ELSE IF (@rColumnName='Borderline Triglyceride')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.Triglyceride = 'Borderline Triglyceride'  
  )  
 END  
 ELSE IF (@rColumnName='Elevated  LDL')  
 BEGIN   
    
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.LDL = 'Elevated  LDL'  
  )  
 END  
 ELSE IF (@rColumnName='Borderline LDL')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
  
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.LDL = 'Borderline LDL'  
  )  
 END  
 ELSE IF (@rColumnName='Low HDL')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.HDL = 'Low HDL'  
  )  
 END  
 ELSE IF (@rColumnName='Elevated  SGPT')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.SGPT = 'Elevated  SGPT'  
  )  
 END  
 ELSE IF (@rColumnName='High Serum Creatinine')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.SerumCreatinine = 'High Serum Creatinine'  
  )  
 END  
 ELSE IF (@rColumnName='Abnormal ECG')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.ECG = 'ECG Abnormal'  
  )  
 END  
 ELSE IF (@rColumnName='Abnormal TMT')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
  
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.TMT = 'TMT Abnormal'  
  )  
 END  
 ELSE IF (@rColumnName='Abnormal ECHO')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
  
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.ECHO = 'ECHO Abnormal'  
  )  
 END  
 ELSE IF (@rColumnName='Abnormal Sonography')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
  
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.Sonography = 'Sonography Abnormal'  
  )  
 END  
 ELSE IF (@rColumnName='ObstructivePFT')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
  
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.PFT like '%Obstructive Pattern%'  
   --AND DTE.PFT = 'Obstructive Lung Disease' Mentis issue no:8825  
     
  )  
 END  
 ELSE IF (@rColumnName='RestructivePFT')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.PFT like '%Restrictive Pattern%'  
   --AND DTE.PFT = 'Restrictive Lung Disease' Mentis issue no:8825  
  )  
 END  
 ELSE IF (@rColumnName='MixPFT')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.PFT like '%Mix Pattern%'  
   --AND DTE.PFT = 'Mix Lung Disease' Mentis issue no:8825  
  )  
 END  
 ELSE IF (@rColumnName='Mentzer Index')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.MenzerIndex = 'Mentzer < 13'  
  )  
 END  
 ELSE IF (@rColumnName='Abnormal XRay')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.AbnormalXRay = 1  
  )  
 END  
 ELSE IF (@rColumnName='Diabetic Existing')  
 BEGIN  
  SELECT @res = @res + '<div class="himssuHeader1WireBox box-body box-solid gridviewfont" >  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.DiabeticExisting = 'Diabetic Existing'  
  )  
 END  
 ELSE IF (@rColumnName='Hypertension Existing')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.HypertensionExisting = 'Hypertension Existing'  
  )  
 END  
 ELSE IF (@rColumnName='IHD')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.IHD = 1  
  )  
 END  
 ELSE IF (@rColumnName='Metabolic Syndrome')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.MetabolicSyndrome = 1  
  )  
 END  
 ELSE IF (@rColumnName='CVD Major RISK')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.CVDMajorRisk = 1  
  )  
 END  
 ELSE IF (@rColumnName='CVD Minor RISK')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.CVDMinorRisk = 1  
  )  
 END  
 ELSE IF (@rColumnName='NCD`s RISK')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.NCDsRisk = 1  
  )  
 END  


 ---- T3-----
 ELSE IF (@rColumnName='Elevated T3')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.T3 ='Elevated T3'  
  )  
 END  
  ELSE IF (@rColumnName='Low T3')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.T3 = 'Low T3'  
  )  
 END  

 ---- T4-----
 ELSE IF (@rColumnName='Elevated T4')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.T4 = 'Elevated T4' 
  )  
 END  
  ELSE IF (@rColumnName='Low T4')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.T4 = 'Low T4'
  )  
 END 
  

  --- ---- TSH-----
 ELSE IF (@rColumnName='Elevated TSH')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.TSH = 'Elevated TSH'
  )  
 END  
  ELSE IF (@rColumnName='Low TSH')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.TSH = 'Low TSH'
  )  
 END 

   --- ---- PSA-----
 ELSE IF (@rColumnName='High PSA')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.PSA = 'High PSA'
  )  
 END  
 -----TotalBILLIRUBIN----
  ELSE IF (@rColumnName='High Serum Billirubin')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.TotalBillirubin = 'High Serum Billirubin' 
  )  
 END 
 -------------Iron------
  ELSE IF (@rColumnName='Iron Deficiency Anaemia')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.Iron ='Iron Deficiency Anaemia'  
  )  
 END 

  -------------Thrombocytopenia------
  ELSE IF (@rColumnName='Thrombocytopenia')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.PLATELETS = 'Thrombocytopenia'
  )  
 END 

 -------------Vitamin B12------
  ELSE IF (@rColumnName='Vitamin B12 Deficiency')  
 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.VitaminB12 = 'Vitamin B12 Deficiency'
  )  
 END 
 
 -------------Vitamin D3------
  ELSE IF (@rColumnName='Vitamin D3 Deficiency')  
  --ELSE IF (LTRIM(RTRIM(@rColumnName)) = 'Vitamin D3 Deficiency')

 BEGIN  
  SELECT @res = @res + '<div class="box-body box-solid gridviewfont">  
  <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;">  
  <tr><th>Sr No</th><th>Employee Code</th><th>Employee Name</th><th>Age</th></tr>'  
    
  select @res = @res + '<tr> <td>' + convert(varchar, row_number()over(order by E.Id)) + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EM1.Code,'')  
  else isnull(CS.Code,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')  
  when E.ParticipantSourceTypeId = 1001 then isnull(EFD.Name,'') else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end + '</td>  
  <td>' + case when E.ParticipantSourceTypeId = 95 then convert(varchar,datediff(yy,EP.DateOfBirth,GETDATE()))   
  when E.ParticipantSourceTypeId = 1001 then convert(varchar,datediff(yy,EFD.DateOfBirth,GETDATE()))   
  else convert(varchar,datediff(yy,cs.DateOfBirth,getdate())) end + '</td></tr>'  
  from sExamination.tExamination E  
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  left join sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  left join sHrm.tCsrBenefiterMaster CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009  
  left join sHrm.tEmployeeMaster EM1 on EFD.EmployeeId = EM1.Id  
  left join sHrm.tEmployeePersonalDetail EP on E.ParticipantSourceId = EP.EmployeeId WHERE E.Id IN  
  (  
   SELECT EXM.Id FROM @tExamination AS EXM INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
   ON DTE.ExaminationId = EXM.Id WHERE  
   (  
    (  
     CASE WHEN @rmtype = 1 THEN EXM.StoreLocationId  
     WHEN @rmtype = 2 THEN EXM.OrganizationDepartmentId  
     WHEN @rmtype = 3 THEN EXM.EmployeeCompanyId END = @rMasterId  
    ) OR (@rMasterId = 0)  
   )AND DTE.VitaminD3 = 'Vitamin D3 Deficiency'
  )  
 END 

 SELECT @res = @res + '</table></div>'  
 SELECT @res AS result  
END
GO
PRINT N'Altering Procedure [sExamination].[pGetMissingParameterTest]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pGetMissingParameterTest]      
@rSetupGroupId bigint,      
@rProviderId int=0
AS  
BEGIN   
      
IF OBJECT_ID('tempdb..#tEmpList') IS NOT NULL begin drop table #tEmpList end      
      
Create table #tEmpList (tid int identity(1,1),eid bigint,empcode nvarchar(40),EmpName nvarchar(250),SetupGroupId int,GenderId int, Age int)      
    
insert into #tEmpList      
SELECT E.Id,ParticipantCode = EM.Code, ParticipantName = ISNULL(EM.FirstName,'') + ' ' + isnull(EM.LastName,''),    
SM.SetupGroupId, EPD.GenderId, isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0)
FROM sExamination.tExamination E
inner join sSupport.tProviderAppointment PA ON PA.PatientSourceId = E.ParticipantSourceId and PA.SetupId = E.SetupId
inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id        
inner join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95      
inner join sHrm.tEmployeePersonalDetail EPD on EPD.EmployeeId = EM.Id
Where SM.SetupGroupId=@rSetupGroupId and (PA.ProviderId=@rProviderId or @rProviderId=0)

Create table #Temptest1 (EmployeeCode nvarchar(500),EmployeeName nvarchar(500),MissingParameter nvarchar(1000))  
Create Table #Temptest2 (EmployeeCode nvarchar(500),EmployeeName nvarchar(500),MissingParameter nvarchar(1000)) 

begin
	insert into #Temptest1  
	Select * from (      
	select Distinct E1.empcode As EmployeeCode,E1.EmpName As EmployeeName, ISNULL(STUFF((SELECT Distinct ',' + TP.Title   
	from sExamination.tTestRequestDetail TRD  
	 inner join sExamination.tTestRequest TR on TRD.TestRequestId = TR.Id  
	 inner join sOrderEntry.tTestMaster TM on TR.TestId = TM.Id  
	 inner join sOrderEntry.tTestDetail TD on TM.Id = TD.TestId and TRD.TestDetailId = TD.Id  
	 inner join sOrderEntry.tTestParameterMaster TP on TD.TestParameterId = TP.Id  
	 inner join #tEmpList E on TR.SourceId = E.eid and E1.eid=E.eid  
	 inner join sOrderEntry.tStaticTestParameterMaster STP On STP.id  = TP.StaticTestParameterId  
	 inner join [sExamination].[tMissingTestParameter] as MTP on MTP.Code COLLATE Latin1_General_CI_AI = STP.ImportCode  
	Where ISNULL(TRD.ServiceValue,'')='' AND MTP.IsEnable = 1
	and ISNULL(TP.StaticTestParameterId,0) <> case when E.GenderId = 1 then 111 else 58 end
	and ISNULL(TP.StaticTestParameterId,0) <> case when E.GenderId = 1 then 122 else 58 end
	and ISNULL(TP.StaticTestParameterId,0) <> case when E.GenderId = 1 then 241 else 58 end
	and ISNULL(TP.StaticTestParameterId,0) <> case when E.GenderId = 1 and E.Age <= 55 then 58 else 0 end
	FOR XML PATH('')  
	), 1, 1, ''), '') As MissingParameterName  
	From #tEmpList E1
	) as t  
	where ISNULL(MissingParameterName,'')<>''  
	Order By t.EmployeeName 
	
	insert into #Temptest2
	Select * from (
	SELECT E1.empcode AS EmployeeCode, E1.EmpName AS EmployeeName,
    CASE WHEN NOT EXISTS (
            SELECT 1
            FROM sExamination.tTestRequestDetail TRD
            INNER JOIN sExamination.tTestRequest TR ON TRD.TestRequestId = TR.Id
            INNER JOIN sOrderEntry.tTestMaster TM ON TR.TestId = TM.Id
            INNER JOIN sOrderEntry.tTestDetail TD ON TM.Id = TD.TestId AND TRD.TestDetailId = TD.Id
            INNER JOIN sOrderEntry.tTestParameterMaster TP ON TD.TestParameterId = TP.Id
            INNER JOIN #tEmpList E ON TR.SourceId = E.eid AND E1.eid = E.eid
            INNER JOIN sOrderEntry.tStaticTestParameterMaster STP ON STP.id = TP.StaticTestParameterId
            inner join [sExamination].[tMissingTestParameter] as MTP on MTP.Code = 'DIABETIC'
            WHERE MTP.IsEnable = 1
              AND STP.ucode IN ('DIABETIC_FBS', 'DIABETIC_HBA1C', 'DIABETIC_RBS', 'DIABETIC_PPBS')
              AND ISNULL(TRD.ServiceValue, '') <> ''
        )
        THEN 'F B S' ELSE '' END AS MissingParameterName
		FROM #tEmpList E1
		) as t
		where ISNULL(MissingParameterName,'')<>''

	insert into #Temptest2
	SELECT ParticipantCode = CASE WHEN EXM.ParticipantSourceTypeId = 95 then EM.Code      
	when EXM.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,      
	ParticipantName = CASE WHEN EXM.ParticipantSourceTypeId = 95 then ISNULL(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')      
	when EXM.ParticipantSourceTypeId = 1001 then ISNULL(EFD.Name,'') else ISNULL(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end,  
	'Height' as MissingParameter
	FROM sExamination.tExamination EXM      
	inner join sExamination.tSetupMaster SM on EXM.SetupId = SM.Id  
	inner join sExamination.tVital EV on EV.SourceId = EXM.Id  
	left join sHrm.tEmployeeMaster EM on EXM.ParticipantSourceId = EM.Id and EXM.ParticipantSourceTypeId = 95      
	left join sHrm.tEmployeeFamilyDetails EFD on EXM.ParticipantSourceId = EFD.Id and EXM.ParticipantSourceTypeId = 1001      
	left join sHrm.tCSRBenefiterMaster CS on EXM.ParticipantSourceId = CS.Id and EXM.ParticipantSourceTypeId = 1009      
	left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	inner join #tEmpList EML on EML.eid = EXM.Id
	inner join [sExamination].[tMissingTestParameter] as MTP on MTP.Code COLLATE Latin1_General_CI_AI = 'Height'
	Where MTP.IsEnable = 1 and (isnull(EV.Height,0) = 0)

	UNION ALL

	SELECT ParticipantCode = CASE WHEN EXM.ParticipantSourceTypeId = 95 then EM.Code      
	when EXM.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,      
	ParticipantName = CASE WHEN EXM.ParticipantSourceTypeId = 95 then ISNULL(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')      
	when EXM.ParticipantSourceTypeId = 1001 then ISNULL(EFD.Name,'') else ISNULL(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end,  
	'Weight' as MissingParameter
	FROM sExamination.tExamination EXM      
	inner join sExamination.tSetupMaster SM on EXM.SetupId = SM.Id  
	inner join sExamination.tVital EV on EV.SourceId = EXM.Id  
	left join sHrm.tEmployeeMaster EM on EXM.ParticipantSourceId = EM.Id and EXM.ParticipantSourceTypeId = 95      
	left join sHrm.tEmployeeFamilyDetails EFD on EXM.ParticipantSourceId = EFD.Id and EXM.ParticipantSourceTypeId = 1001      
	left join sHrm.tCSRBenefiterMaster CS on EXM.ParticipantSourceId = CS.Id and EXM.ParticipantSourceTypeId = 1009      
	left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	inner join #tEmpList EML on EML.eid = EXM.Id
	inner join [sExamination].[tMissingTestParameter] as MTP on MTP.Code COLLATE Latin1_General_CI_AI = 'Weight'
	Where MTP.IsEnable = 1 and (isnull(EV.BodyWeight,0) = 0)

	UNION ALL

	SELECT ParticipantCode = CASE WHEN EXM.ParticipantSourceTypeId = 95 then EM.Code      
	when EXM.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,      
	ParticipantName = CASE WHEN EXM.ParticipantSourceTypeId = 95 then ISNULL(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')      
	when EXM.ParticipantSourceTypeId = 1001 then ISNULL(EFD.Name,'') else ISNULL(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end,  
	'Blood Pressure Systolic' as MissingParameter
	FROM sExamination.tExamination EXM      
	inner join sExamination.tSetupMaster SM on EXM.SetupId = SM.Id  
	inner join sExamination.tVital EV on EV.SourceId = EXM.Id  
	left join sHrm.tEmployeeMaster EM on EXM.ParticipantSourceId = EM.Id and EXM.ParticipantSourceTypeId = 95      
	left join sHrm.tEmployeeFamilyDetails EFD on EXM.ParticipantSourceId = EFD.Id and EXM.ParticipantSourceTypeId = 1001      
	left join sHrm.tCSRBenefiterMaster CS on EXM.ParticipantSourceId = CS.Id and EXM.ParticipantSourceTypeId = 1009      
	left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	inner join #tEmpList EML on EML.eid = EXM.Id
	inner join [sExamination].[tMissingTestParameter] as MTP on MTP.Code COLLATE Latin1_General_CI_AI = 'BPSys'
	Where MTP.IsEnable = 1 and (isnull(EV.BloodPressureSystolic,0) = 0)

	UNION ALL

	SELECT ParticipantCode = CASE WHEN EXM.ParticipantSourceTypeId = 95 then EM.Code      
	when EXM.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,      
	ParticipantName = CASE WHEN EXM.ParticipantSourceTypeId = 95 then ISNULL(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')      
	when EXM.ParticipantSourceTypeId = 1001 then ISNULL(EFD.Name,'') else ISNULL(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end,  
	'Blood Pressure Diastolic' as MissingParameter
	FROM sExamination.tExamination EXM      
	inner join sExamination.tSetupMaster SM on EXM.SetupId = SM.Id  
	inner join sExamination.tVital EV on EV.SourceId = EXM.Id  
	left join sHrm.tEmployeeMaster EM on EXM.ParticipantSourceId = EM.Id and EXM.ParticipantSourceTypeId = 95      
	left join sHrm.tEmployeeFamilyDetails EFD on EXM.ParticipantSourceId = EFD.Id and EXM.ParticipantSourceTypeId = 1001      
	left join sHrm.tCSRBenefiterMaster CS on EXM.ParticipantSourceId = CS.Id and EXM.ParticipantSourceTypeId = 1009      
	left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	inner join #tEmpList EML on EML.eid = EXM.Id
	inner join [sExamination].[tMissingTestParameter] as MTP on MTP.Code COLLATE Latin1_General_CI_AI = 'BPDia'
	Where MTP.IsEnable = 1 and (isnull(EV.BloodPressureDiastolic,0) = 0)

	UNION ALL

	SELECT ParticipantCode = CASE WHEN EXM.ParticipantSourceTypeId = 95 then EM.Code      
	when EXM.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,      
	ParticipantName = CASE WHEN EXM.ParticipantSourceTypeId = 95 then ISNULL(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')      
	when EXM.ParticipantSourceTypeId = 1001 then ISNULL(EFD.Name,'') else ISNULL(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end,  
	'FVC' as MissingParameter
	FROM sExamination.tExamination EXM      
	inner join sExamination.tSetupMaster SM on EXM.SetupId = SM.Id  
	inner join sExamination.tPulmonary PUL on PUL.SourceId = EXM.Id  
	left join sHrm.tEmployeeMaster EM on EXM.ParticipantSourceId = EM.Id and EXM.ParticipantSourceTypeId = 95      
	left join sHrm.tEmployeeFamilyDetails EFD on EXM.ParticipantSourceId = EFD.Id and EXM.ParticipantSourceTypeId = 1001      
	left join sHrm.tCSRBenefiterMaster CS on EXM.ParticipantSourceId = CS.Id and EXM.ParticipantSourceTypeId = 1009      
	left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	inner join #tEmpList EML on EML.eid = EXM.Id
	inner join [sExamination].[tMissingTestParameter] as MTP on MTP.Code COLLATE Latin1_General_CI_AI = 'FVC'
	Where MTP.IsEnable = 1 and (isnull(PUL.FVCObserved,0) = 0)

	UNION ALL

	SELECT ParticipantCode = CASE WHEN EXM.ParticipantSourceTypeId = 95 then EM.Code      
	when EXM.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,      
	ParticipantName = CASE WHEN EXM.ParticipantSourceTypeId = 95 then ISNULL(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')      
	when EXM.ParticipantSourceTypeId = 1001 then ISNULL(EFD.Name,'') else ISNULL(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end,  
	'FEV1' as MissingParameter
	FROM sExamination.tExamination EXM      
	inner join sExamination.tSetupMaster SM on EXM.SetupId = SM.Id  
	inner join sExamination.tPulmonary PUL on PUL.SourceId = EXM.Id  
	left join sHrm.tEmployeeMaster EM on EXM.ParticipantSourceId = EM.Id and EXM.ParticipantSourceTypeId = 95      
	left join sHrm.tEmployeeFamilyDetails EFD on EXM.ParticipantSourceId = EFD.Id and EXM.ParticipantSourceTypeId = 1001      
	left join sHrm.tCSRBenefiterMaster CS on EXM.ParticipantSourceId = CS.Id and EXM.ParticipantSourceTypeId = 1009      
	left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	inner join #tEmpList EML on EML.eid = EXM.Id
	inner join [sExamination].[tMissingTestParameter] as MTP on MTP.Code COLLATE Latin1_General_CI_AI = 'FEV1'
	Where MTP.IsEnable = 1 and (isnull(PUL.FEV1Observed,0) = 0)

	UNION ALL

	SELECT ParticipantCode = CASE WHEN EXM.ParticipantSourceTypeId = 95 then EM.Code      
	when EXM.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,      
	ParticipantName = CASE WHEN EXM.ParticipantSourceTypeId = 95 then ISNULL(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')      
	when EXM.ParticipantSourceTypeId = 1001 then ISNULL(EFD.Name,'') else ISNULL(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end,  
	'PEFR' as MissingParameter
	FROM sExamination.tExamination EXM      
	inner join sExamination.tSetupMaster SM on EXM.SetupId = SM.Id  
	inner join sExamination.tPulmonary PUL on PUL.SourceId = EXM.Id  
	left join sHrm.tEmployeeMaster EM on EXM.ParticipantSourceId = EM.Id and EXM.ParticipantSourceTypeId = 95      
	left join sHrm.tEmployeeFamilyDetails EFD on EXM.ParticipantSourceId = EFD.Id and EXM.ParticipantSourceTypeId = 1001      
	left join sHrm.tCSRBenefiterMaster CS on EXM.ParticipantSourceId = CS.Id and EXM.ParticipantSourceTypeId = 1009      
	left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	inner join #tEmpList EML on EML.eid = EXM.Id
	inner join [sExamination].[tMissingTestParameter] as MTP on MTP.Code COLLATE Latin1_General_CI_AI = 'PEFR'
	Where MTP.IsEnable = 1 and (isnull(PUL.PEFRObserved,0) = 0)
end  

;WITH SourceGrouped AS
(
    SELECT 
        EmployeeCode,
        MAX(EmployeeName) AS EmployeeName,
        STUFF((
            SELECT ',' + t2.MissingParameter
            FROM #Temptest2 t2
            WHERE t2.EmployeeCode = t1.EmployeeCode
            FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS MissingParameter
    FROM #Temptest2 t1
    GROUP BY EmployeeCode
)
MERGE #Temptest1 AS Target  
USING SourceGrouped AS Source  
ON Source.EmployeeCode = Target.EmployeeCode  
WHEN NOT MATCHED BY Target THEN  
    INSERT (EmployeeCode, EmployeeName,MissingParameter)   
    VALUES (Source.EmployeeCode, Source.EmployeeName,Source.MissingParameter)  
  
 WHEN MATCHED THEN UPDATE SET  
    Target.MissingParameter = Target.MissingParameter + ',' + Source.MissingParameter;  
  
--select EmployeeCode,EmployeeName,MissingParameter as MissingParameterName from #Temptest1
SELECT
    t.EmployeeCode,
    t.EmployeeName,
    v.FinalMissingParameter AS MissingParameterName
FROM #Temptest1 t

-- Step 1: F U S ↔ SUGAR
CROSS APPLY (
    SELECT
        CASE
            WHEN t.MissingParameter LIKE '%F U S%'
             AND t.MissingParameter NOT LIKE '%SUGAR%'
            THEN
                REPLACE(
                REPLACE(
                REPLACE(t.MissingParameter, 'F U S,', ''),
                ',F U S', ''),
                'F U S', '')

            WHEN t.MissingParameter LIKE '%SUGAR%'
             AND t.MissingParameter NOT LIKE '%F U S%'
            THEN
                REPLACE(
                REPLACE(
                REPLACE(t.MissingParameter, 'SUGAR,', ''),
                ',SUGAR', ''),
                'SUGAR', '')

            ELSE t.MissingParameter
        END AS Step1
) s

-- Step 2: ECHO ↔ TMT
CROSS APPLY (
    SELECT
        CASE
            WHEN s.Step1 LIKE '%ECHO%'
             AND s.Step1 NOT LIKE '%TMT%'
            THEN
                REPLACE(
                REPLACE(
                REPLACE(s.Step1, 'ECHO,', ''),
                ',ECHO', ''),
                'ECHO', '')

            WHEN s.Step1 LIKE '%TMT%'
             AND s.Step1 NOT LIKE '%ECHO%'
            THEN
                REPLACE(
                REPLACE(
                REPLACE(s.Step1, 'TMT,', ''),
                ',TMT', ''),
                'TMT', '')

            ELSE s.Step1
        END AS FinalMissingParameter
) v
WHERE v.FinalMissingParameter <> '';

Drop table #Temptest1
Drop table #Temptest2
Drop Table #tEmpList 

END
GO
PRINT N'Altering Procedure [sExamination].[pImportALLExaminationDatas]...';


GO

ALTER PROC [sExamination].[pImportALLExaminationDatas]  
@rstrExaminationXML varchar(max),      
@rstrVitalXML varchar(max),      
@rstrDiseaseXML varchar(max),      
@rstrHabitXML varchar(max),      
@rstrHistoryXML varchar(max),      
@rstrDiagnosisXML varchar(max),      
@rstrTestXML varchar(max),      
@rMainTypeId int,      
@rstr varchar(50),      
@rstrGeneralXML varchar(max),      
@rstrPulmonary varchar(max) = null,      
@rstrAudiometry varchar(max) = null,     
@rIsTemplateReview bit = 0,  
@rUserId bigint      
as      
begin       
 declare @loXMLExamination xml,@loXMLVital xml,@loXMLDisease xml,@loXMLHabit xml,@loXMLHistory xml,      
 @loXMLDiagnisis xml,@loXMLTest xml,@loXMLGeneral xml,@loXMLPulmonary xml,@loXMLAudiometry xml      
       
 declare @exceptiondetail varchar(max),@orgid int      
       
  
  
 set @orgid =(select Top 1 Orgid from sExamination.tExamination order by Id desc)   --added cause some cases orgid is picking 0  
   
    -- Mantis: 0036720 by Shivam (20-09-2024)  
 Declare @rConfigBloodGroup int, @rConfigColorVision int = 0, @TitleColorVision NVARCHAR(20), @IdColorVision int;   
 select @rConfigBloodGroup =   
  CASE  
   WHEN sConfig.fConfigurationValueGet('Examination.BloodGroupCarryForwardFromHR',@orgid,0,0,0) = 'True'   
   THEN 1 ELSE 0   
  END  
  
 select @rConfigColorVision =   
  CASE  
   WHEN sConfig.fConfigurationValueGet('Examination.GeneralTestColorVisionCarryForward',@orgid,0,0,0) = 'True'   
   THEN 1 ELSE 0   
  END  
  
 BEGIN TRY       
  SET @loXMLExamination = CAST(@rstrExaminationXML AS xml)      
  SET @loXMLVital = CAST(@rstrVitalXML AS xml)      
  SET @loXMLDisease = CAST(@rstrDiseaseXML AS xml)      
  SET @loXMLHabit = CAST(@rstrHabitXML AS xml)      
  SET @loXMLHistory = CAST(@rstrHistoryXML AS xml)      
  SET @loXMLDiagnisis = CAST(@rstrDiagnosisXML AS xml)       
  SET @loXMLTest = CAST(@rstrTestXML AS xml)      
  SET @loXMLGeneral = CAST(@rstrGeneralXML as xml)      
  SET @loXMLPulmonary = CAST(@rstrPulmonary as xml)      
  SET @loXMLAudiometry = CAST(@rstrAudiometry AS xml)      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select '',0,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>      
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
 IF OBJECT_ID('tempdb..#tbltmpExamination') IS NOT NULL      
 DROP TABLE #tbltmpExamination      
      
  Create table #tbltmpExamination      
  (      
   tid int identity(1,1),e_ParticipantSourceId bigint,e_StoreLocationId int,e_SetupId int,e_NatureId int,      
   e_ExaminationDate varchar(50),e_DoctorName varchar(300),e_DoctorId bigint,e_ProcessTypeId int,e_CriteriaGroupId int,      
   e_CompanyId int,e_TargetGroupId int,e_DesignationId int,e_GradeId int,e_DepartmentId int,e_OrgId int,e_examinationid bigint,      
   e_MedicalId int,e_SetupGroupId int,e_ProcessId int,e_TargetId int,e_ColorVisionId int,e_LegalEntityId int,e_PastHistorySelf nvarchar(2000),
   e_IsNewDiabetic bit, e_IsNewHypertension bit
  )     
  insert into #tbltmpExamination      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@LocationId','int') as LocationId,      
  T.c.value('@SetupId','int') as SetupId,      
  T.c.value('@NatureId','int') as NatureId,      
  T.c.value('@Examination_Date','varchar(200)') as Examination_Date,      
  T.c.value('@Doctor','varchar(200)') as Doctor,      
  T.c.value('@DoctorId','varchar(200)') as DoctorId,      
  0,0,0,0,0,0,0,0,null,T.c.value('@MedicalId','int') as MedicalId,null,      
  T.c.value('@ProcessId','int') as ProcessId,      
  T.c.value('@TargetGroupId','int') as TargetGroupId,      
  T.c.value('@ColorVisionId','int') as ColorVisionId,0,'',0,0
  from @loXMLExamination.nodes('/Examinations/Examination')T(c)      
        
  update #tbltmpExamination set       
  e_ProcessTypeId = JD.ProcessTypeId,      
  e_TargetGroupId = EM.TargetGroupId,      
  e_CompanyId = JD.EmployeeCompanyId,e_DesignationId = JD.EmployeeDesignationId,e_GradeId = JD.GradeId,      
  e_DepartmentId = JD.OrganizationDepartmentId,e_OrgId = EM.OrgId,e_LegalEntityId=JD.LegalEntityId      
  from #tbltmpExamination inner join sHrm.tEmployeeMaster EM on e_ParticipantSourceId = EM.Id      
  inner join sHrm.tEmployeeJobDetail JD on e_ParticipantSourceId = JD.EmployeeId      
          
  update JD Set JD.ProcessTypeId=t.e_ProcessId      
  from sHrm.tEmployeeJobDetail JD      
  inner join #tbltmpExamination t on t.e_ParticipantSourceId = JD.EmployeeId      
  where Isnull(t.e_ProcessId,0)>0      
        
  update JD Set JD.TargetGroupId=t.e_TargetId      
  from shrm.temployeemaster JD      
  inner join #tbltmpExamination t on t.e_ParticipantSourceId = JD.Id      
  inner join sExamination.tSetupMaster SM on SM.Id =t.e_SetupId      
  where Isnull(t.e_TargetId,0)>0 and Isnull(SM.IsTargetGroupRestrictInHR,0)=0      
      
      
  update #tbltmpExamination set e_SetupGroupId = SetupGroupId from sExamination.tSetupMaster where e_SetupId = Id      
         
  MERGE sHrm.tEmployeePersonalDetail AS Target USING       
  (      
   SELECT e_ParticipantSourceId,e_ColorVisionId,tid      
   FROM #tbltmpExamination TT LEFT JOIN sHrm.tEmployeePersonalDetail T ON TT.e_ParticipantSourceId = T.EmployeeId      
  ) AS Source ON Target.EmployeeId = Source.e_ParticipantSourceId      
  WHEN MATCHED THEN      
   UPDATE SET Target.ColorVisionId = case when Isnull(e_ColorVisionId,0) > 0 then e_ColorVisionId else ColorVisionId end; -- as per discussion with raju sir on 18/02/2020 done by MS (Mentis Issue no:10840)      
          
  IF (@rConfigColorVision = 1)  
  BEGIN  
   --SELECT e_ParticipantSourceId, e_ColorVisionId FROM #tbltmpExamination TTE;  
  
   UPDATE EPD   
   SET ColorVisionId = TE.e_ColorVisionId  
   FROM sHrm.tEmployeePersonalDetail EPD  
   LEFT JOIN #tbltmpExamination TE   
    ON TE.e_ParticipantSourceId = EPD.EmployeeId  
   WHERE EPD.EmployeeId = TE.e_ParticipantSourceId and Isnull(TE.e_ColorVisionId,0) > 0 ;  
  END  
  
  declare @cntExam int,@incExam int      
  select @cntExam = count(*),@incExam = 1 from #tbltmpExamination      
        
  update #tbltmpExamination set e_examinationid = Id from sExamination.tExamination where ParticipantSourceId = e_ParticipantSourceId      
  and ParticipantSourceTypeId = 95 and e_SetupId = SetupId      
  IF OBJECT_ID('tempdb..#tbltmpExaminationNull') IS NOT NULL      
  DROP TABLE #tbltmpExaminationNull      
  Create table #tbltmpExaminationNull(tid int identity(1,1),e_ParticipantSourceId bigint,e_SetupId int)      
  insert into #tbltmpExaminationNull      
  select e_ParticipantSourceId,e_SetupId from #tbltmpExamination where isnull(e_examinationid,0) <> 0      
         
  declare @lNextNumber bigint,@lFromNextNumber bigint,@lOrgId int,@lCount int,@IsExaminationDateEdit varchar(200)      
  select top 1 @lOrgId = e_orgid from #tbltmpExamination      
  
  ;WITH LastExaminations AS (
	SELECT
		EXM.*,
		ROW_NUMBER() OVER (
			PARTITION BY EXM.ParticipantSourceId, EXM.ParticipantSourceTypeId 
			ORDER BY EXM.ExaminationDate DESC
		) AS rn
	FROM sExamination.tExamination EXM
	Where EXM.SetupId <> [sCommon].[fGetIntIdForOrg](8, @lOrgId)
	)
	UPDATE t
	SET 
	t.e_IsNewDiabetic = DIA.IsNewDiabatic,
	t.e_IsNewHypertension = DIA.IsNewHypertension
	FROM #tbltmpExamination t
	INNER JOIN LastExaminations EXM
		ON EXM.ParticipantSourceId = t.e_ParticipantSourceId AND EXM.ParticipantSourceTypeId = 95 AND EXM.rn = 1
	INNER JOIN sExamination.tDiagnosis DIA 
		ON DIA.SourceId = EXM.Id
         
  --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tExamination', 0, 1, 1,@outNextNumber = @lNextNumber output       
  --SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tExamination AS Target USING       
  (      
   SELECT Id,e_ParticipantSourceId,e_StoreLocationId,e_SetupId,e_NatureId,      
   e_ExaminationDate,e_DoctorName,e_DoctorId,e_ProcessTypeId,e_CriteriaGroupId,      
   e_CompanyId,e_TargetGroupId,e_DesignationId,e_GradeId,e_DepartmentId,e_OrgId,        
 e_examinationid,e_MedicalId,e_ProcessId,e_TargetId,tid,e_LegalEntityId,e_PastHistorySelf      
   FROM #tbltmpExamination TT LEFT JOIN sExamination.tExamination T ON TT.e_examinationid = T.Id      
  ) AS Source ON Target.Id = Source.e_examinationid      
  WHEN MATCHED THEN      
   UPDATE SET Target.OrgId = e_orgid,Target.ParticipantSourceTypeId  = 95,      
   Target.ParticipantSourceId  = e_ParticipantSourceId,Target.OrganizationDepartmentId = e_DepartmentId,      
   Target.ExaminationDate = case when ((select UPPER(RTRIM(LTRIM(Isnull(CS.ItemValue,CM.ItemValue)))) ------- Nidhi Pandey; Dt- 27/09/2022, Mantis Issue - 21006 --------    
        from sConfig.tConfigurationMaster CM    
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id     
        where CM.ItemKey='Examination.IsExamintionDateEdit' and SourceId = e_StoreLocationId) = 'TRUE') then     
        (case when len(e_ExaminationDate) = 10 then convert(Datetime, e_ExaminationDate, 104) else CONVERT(VARCHAR(10), e_ExaminationDate, 103) end)     
        else Target.ExaminationDate END,      
   Target.DoctorEmployeeId = e_DoctorId,    
   Target.RoundNumber =  0,      
   Target.StatusId =  (CASE WHEN @rIsTemplateReview = 1 AND Target.StatusId = 4 THEN 4 ELSE 1 END),  
   ParentExaminationId = 0,CauseId = null,Target.UpdatedUserId =  1,      
   Target.UpdatedDateTime = sCommon.fGetDate(),      
   Target.ProcessTypeId = case when isnull(e_ProcessId,0) = 0 then e_ProcessTypeId else e_ProcessId end,      
   Target.EmployeeCompanyId = e_CompanyId,Target.GradeId = e_GradeId,      
   Target.TargetGroupId = case when isnull(e_TargetId,0) = 0 then e_TargetGroupId else e_TargetId end,      
   Target.EmployeeDesignationId = e_DesignationId,      
   Target.CriteiraGroupId = e_CriteriaGroupId,      
   Target.MedicalAgencyId = case when e_MedicalId = 0 then MedicalAgencyId else e_MedicalId end,      
   Target.CreatedUserId = @rUserId,      
   Target.LegalEntityId=e_LegalEntityId    
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    OrgId,ParticipantSourceTypeId,ParticipantSourceId,OrganizationDepartmentId,SetupId,      
    RoundNumber,StatusId,ExaminationDate,DoctorEmployeeId,CreatedUserId,CreatedDateTime,      
    UpdatedUserId,UpdatedDateTime,ParentExaminationId,StoreLocationId,CauseId,ProcessTypeId,MedicalAgencyId,      
    EmployeeCompanyId,TargetGroupId,EmployeeDesignationId,CriteiraGroupId,GradeId,LegalEntityId    
   )      
   VALUES      
   (      
    --@lFromNextNumber + tid,      
    e_OrgId,95,e_ParticipantSourceId,e_DepartmentId,      
    e_SetupId,0,1,case when len(e_ExaminationDate) = 10 then convert(Datetime, e_ExaminationDate, 104) else CONVERT(VARCHAR(11), e_ExaminationDate) end,      
    e_DoctorId,@rUserId,sCommon.fGetDate(),      
    @rUserId,sCommon.fGetDate(),0,e_StoreLocationId,null,case when isnull(e_ProcessId,0) = 0 then e_ProcessTypeId else e_ProcessId end,      
    e_MedicalId,e_CompanyId,      
    case when isnull(e_TargetId,0) = 0 then e_TargetGroupId else e_TargetId end,      
    e_DesignationId,e_CriteriaGroupId,e_GradeId,e_LegalEntityId
   );        
         
  select @cntExam = count(*),@incExam = 1 from #tbltmpExamination      
        
  update #tbltmpExamination set e_examinationid = Id from sExamination.tExamination where ParticipantSourceId = e_ParticipantSourceId      
  and ParticipantSourceTypeId = 95 and e_SetupId = SetupId
        
  --select @lCount = COUNT(1) FROM #tbltmpExamination       
  --SET @lNextNumber  = @lCount + @lFromNextNumber       
  --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tExamination', @rCurrentNumber = @lNextNumber        
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrExaminationXML,1,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>      
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
 IF OBJECT_ID('tempdb..#tbltmpVitals') IS NOT NULL      
 DROP TABLE #tbltmpVitals      
      
  Create table #tbltmpVitals      
  (      
   tid int identity(1,1),v_ParticipantSourceId bigint,v_Height varchar(200),v_Weight varchar(200),      
   v_Pulse varchar(200),v_BPSys varchar(200),v_BPDia varchar(200),v_Respiration varchar(200),v_AbdominalGirth varchar(200),      
   v_ChestExpansion varchar(200),v_Waist varchar(200),v_Hip varchar(200),v_ElbowWidth varchar(200),v_Temperature varchar(200),      
   v_id bigint,v_NatureId int,v_examinationid bigint,v_SetupId int,v_OrgId int,v_Inhalation varchar(200),v_Exhalation varchar(200), v_Remark varchar(300)  
  )      
  insert into #tbltmpVitals      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@Height','varchar(200)') as Height,      
  T.c.value('@Weight','varchar(200)') as Weight,      
  T.c.value('@Pulse','varchar(200)') as Pulse,      
  T.c.value('@BPSys','varchar(200)') as BPSys,      
  T.c.value('@BPDia','varchar(200)') as BPDia,      
  T.c.value('@Respiration','varchar(200)') as Respiration,      
  T.c.value('@AbdominalGirth','varchar(200)') as AbdominalGirth,      
  T.c.value('@ChestExpansion','varchar(200)') as ChestExpansion,      
  T.c.value('@Waist','varchar(200)') as Waist,      
  T.c.value('@Hip','varchar(200)') as Hip,      
  T.c.value('@ElbowWidth','varchar(200)') as ElbowWidth,      
  T.c.value('@Temperature','varchar(200)') as Temperature,null,0,0,0,0,      
  T.c.value('@Inhalation','varchar(200)') as Inhalation,      
  T.c.value('@Exhalation','varchar(200)') as Exhalation,     
  T.c.value('@Vital_Remark','varchar(300)') as Vital_Remark  
  from @loXMLVital.nodes('/Vitals/Vital')T(c)      
        
        
  update #tbltmpVitals set v_NatureId = e_NatureId,v_SetupId = e_SetupId,v_OrgId = e_OrgId,v_examinationid = e_examinationid      
  from #tbltmpExamination where e_ParticipantSourceId = v_ParticipantSourceId --and #tbltmpVitals.tid=#tbltmpExamination.tid      
        
  update #tbltmpVitals set v_id = Id from sExamination.tVital inner join #tbltmpExamination on e_examinationid = SourceId      
  inner join #tbltmpVitals on v_examinationId = e_examinationid      
          
  --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tVital', 0, 1, 1,@outNextNumber = @lNextNumber output       
  --SET @lFromNextNumber = @lNextNumber - 1      
  --BloodPressureSystolic = case when isnull(Source.v_BPSys,'') <> '' then Source.v_BPSys else BloodPressureSystolic end,      
  --BloodPressureDiastolic = case when isnull(Source.v_BPDia,'') <> '' then Source.v_BPDia else BloodPressureDiastolic end,        
  -- changes as per Mentis NO:0007538 2018-10-06      
  MERGE sExamination.tVital AS Target USING       
  (      
   SELECT Id,V_id,v_Height,v_Weight,      
   v_Pulse,v_BPSys,v_BPDia,v_Respiration,v_AbdominalGirth,      
   v_ChestExpansion,v_Waist,v_Hip,v_ElbowWidth,v_Temperature,      
   v_NatureId,v_examinationid,v_SetupId,v_OrgId,v_Inhalation,v_Exhalation,tid,v_Remark      
   FROM #tbltmpVitals TT LEFT JOIN sExamination.tVital T ON TT.v_id = T.Id      
  ) AS Source ON Target.Id = Source.v_Id      
  WHEN MATCHED THEN      
   UPDATE SET Pulse = case when isnull(Source.v_pulse,'') <> '' then Source.v_pulse else Pulse end,         
   BloodPressureSystolic = case when isnull(Source.v_BPSys,'') <> '' then Source.v_BPSys else BloodPressureSystolic end,      
   BloodPressureDiastolic = case when isnull(Source.v_BPDia,'') <> '' then Source.v_BPDia else BloodPressureDiastolic end,      
   NatureOfWorkId = Source.v_NatureId,Temperature = case when isnull(Source.v_Temperature,'') <> '' then Source.v_Temperature else Temperature end,      
   Respiration = case when isnull(Source.v_Respiration,'') <> '' then Source.v_Respiration else Respiration end,      
   Height = case when isnull(Source.v_Height,'') <> '' then Source.v_Height else Height end,      
   BodyWeight = case when isnull(Source.v_Weight,'') <> '' then Source.v_Weight else BodyWeight end,      
   BMI = case when Source.v_Height <> '' and Source.v_Weight <> '' then ROUND((CASE WHEN (Source.v_Height) = 0 THEN 0       
   ELSE CONVERT(DECIMAL(14, 6), ((Source.v_Weight) / CAST(SQUARE((CASE WHEN (Source.v_Height) <= 0 THEN 1 ELSE CAST((Source.v_Height)      
   AS DECIMAL(9, 6)) END)/ 100) AS DECIMAL(9, 6)))) END), 3) else BMI end,      
   ChestExpansion = case when isnull(v_Exhalation,'') <> '' and isnull(v_Inhalation,'') <> '' then      
   convert(float,v_Inhalation) - convert(float,v_Exhalation) else ChestExpansion end,      
   ElbowWidth = case when isnull(Source.v_ElbowWidth,'') <> '' then Source.v_ElbowWidth else ElbowWidth end,      
   Waist = case when isnull(Source.v_Waist,'') <> '' then Source.v_Waist else Waist end,      
   Hip = case when isnull(Source.v_Hip,'') <> '' then Source.v_Hip else Hip end,      
   AbdominalGirth = case when isnull(Source.v_AbdominalGirth,'') <> '' then Source.v_AbdominalGirth else AbdominalGirth end,      
   ChestExpansionInhalation = case when isnull(v_Inhalation,'') <> '' then v_Inhalation else ChestExpansionInhalation end,      
   ChestExpansionExhalation = case when isnull(v_Exhalation,'') <> '' then v_Exhalation else ChestExpansionExhalation end,  
   Remark = case when isnull(Source.v_Remark,'') <> '' then Source.v_Remark else Remark end  
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    Id,SourceId,SourceTypeId,NatureOfWorkId,Pulse,Temperature,BloodPressureSystolic,BloodPressureDiastolic,Respiration,Height,      
    BodyWeight,BMI,ChestExpansion,AbdominalGirth,ElbowWidth,Waist,Hip,IsObsolete,CreatedUserId,CreatedDateTime,OrgId,      
    ChestExpansionInhalation,ChestExpansionExhalation,Remark    
   )      
   VALUES      
   (      
    v_examinationid,v_examinationid,1002,v_NatureId,      
    case when isnull(v_pulse,'') = '' then null else v_pulse end,      
    case when isnull(v_Temperature,'')='' then null else v_Temperature end,          
    v_BPSys,      
    v_BPDia,       
    case when isnull(v_Respiration,'')='' then null else v_Respiration end,      
    case when isnull(v_Height,'')='' then null else v_Height end,      
    case when isnull(v_Weight,'')='' then null else v_Weight end,      
    case when v_Height <> '' and v_Weight <> '' then ROUND((CASE WHEN (v_height) = 0 THEN 0       
    ELSE CONVERT(DECIMAL(14, 2),((v_Weight) / CAST(SQUARE((CASE WHEN (v_height) <= 0 THEN 1 ELSE CAST((v_height) AS DECIMAL(9, 2)) END)/ 100) AS DECIMAL(9, 2)))) END), 3) else 0 end,      
    case when isnull(v_Exhalation,'') <> '' and isnull(v_Inhalation,'') <> '' then      
    convert(float,v_Inhalation) - convert(float,v_Exhalation) else null end,      
    case when isnull(v_AbdominalGirth,'')='' then null else v_AbdominalGirth end,      
    case when isnull(v_ElbowWidth,'') = '' then null else v_ElbowWidth end,      
    case when isnull(v_Waist,'')='' then null else v_Waist end,      
    case when isnull(v_Hip,'')='' then null else v_Hip end,0,1,sCommon.fGetDate(),v_OrgId,      
    case when isnull(v_Inhalation,'') <> '' then v_Inhalation else null end,      
    case when isnull(v_Exhalation,'') <> '' then v_Exhalation else null end,  
 isnull(Source.v_Remark, '')  
   );      
          
  --select @lCount = COUNT(1) FROM #tbltmpVitals       
  --SET @lNextNumber  = @lCount + @lFromNextNumber       
  --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tVital', @rCurrentNumber = @lNextNumber       
        
  update #tbltmpVitals set v_id = Id from sExamination.tVital inner join #tbltmpExamination on e_examinationid = SourceId inner join #tbltmpVitals on v_examinationId = e_examinationid       
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrVitalXML,2,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>      
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tbltmpDiagnosis') IS NOT NULL      
  DROP TABLE #tbltmpDiagnosis      
      
  Create table #tbltmpDiagnosis      
  (      
   tid int identity(1,1),d_ParticipantSourceId bigint,d_Diagnosis varchar(1000),      
   d_Recommendation varchar(1000),d_examinationid bigint,d_id bigint,d_date varchar(50)      
  )      
  insert into #tbltmpDiagnosis      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@Diagnosis','varchar(200)') as Diagnosis,      
T.c.value('@Recommendation','varchar(200)') as Recommendation,0,null,''      
  from @loXMLDiagnisis.nodes('/Diagnosiss/Diagnosis')T(c)      
        
  update #tbltmpDiagnosis set d_examinationid = e_examinationid,d_date = e_examinationdate from #tbltmpExamination where e_ParticipantSourceId = d_ParticipantSourceId --and #tbltmpDiagnosis.tid=#tbltmpExamination.tid      
  update #tbltmpDiagnosis set d_id = Id from sExamination.tDiagnosis inner join #tbltmpDiagnosis on d_examinationid = SourceId      
          
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tDiagnosis', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
          
  MERGE sExamination.tDiagnosis AS Target USING       
  (      
   SELECT Id,d_id,d_Diagnosis,d_Recommendation,d_date,d_examinationid,ROW_NUMBER () OVER (ORDER BY T.Id) as rno,      
   (      
    SELECT MAX(T.Id) FROM sExamination.tDiagnosis t      
   ) as maxid      
   FROM #tbltmpDiagnosis TT LEFT JOIN sExamination.tDiagnosis T ON TT.d_id = T.Id      
  ) AS Source ON Target.Id = Source.d_Id      
  WHEN MATCHED THEN      
   UPDATE SET DiagnosisRemark = case when isnull(d_Diagnosis,'') <> '' then [sSetup].[fPortalXMLTagsReplaceReverse](d_Diagnosis) else DiagnosisRemark end,      
   RecommendationEnglish = case when isnull(d_Recommendation,'') <> '' then [sSetup].[fPortalXMLTagsReplaceReverse](d_Recommendation) else RecommendationEnglish end      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],[SourceId],[DiagnosisRemark],[RecommendationEnglish],[FitUnfitId],FitnessDate      
   )      
   VALUES      
   (      
    @lFromNextNumber + rno,d_examinationid,[sSetup].[fPortalXMLTagsReplaceReverse](d_Diagnosis),      
    [sSetup].[fPortalXMLTagsReplaceReverse](d_Recommendation),1,case when len(d_date) = 10 then convert(Datetime, d_date, 104)      
    else CONVERT(VARCHAR(11),d_date) end      
   );      
          
  select @lCount = COUNT(1) FROM #tbltmpDiagnosis       
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tDiagnosis', @rCurrentNumber = @lNextNumber      
  update #tbltmpDiagnosis set d_id = Id from sExamination.tDiagnosis inner join #tbltmpDiagnosis on d_examinationid = SourceId       
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrDiagnosisXML,3,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>      
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tbltmpHabitss') IS NOT NULL      
  DROP TABLE #tbltmpHabitss      
      
  create table #tbltmpHabitss      
  (      
   tid int identity(1,1),h_ParticipantSourceId bigint,h_Alcohol varchar(200),h_Chewer varchar(200),h_Smoker varchar(200),      
   h_AlcoholSocial varchar(200),h_Drug varchar(200),h_AlcoholId int,h_ChewerId int,h_SmokerId int,h_AlcoholSocialId int,      
   h_DrugId int,h_ParticipantAraId bigint,h_AlcoholName varchar(200),h_ChewerName varchar(200),h_SmokerName varchar(200),      
   h_AlcoholSocialName varchar(200),h_DrugName varchar(200),h_examinationid bigint,h_OrgId int,h_HabitId bigint,      
   h_HabitDetailAlcohol bigint,h_HabitDetailChewer bigint,h_HabitDetailSmoker bigint,h_HabitDetialAlcoholSocial bigint,      
   h_HabitDetailDrug bigint,h_AreaId int      
  )      
  insert into #tbltmpHabitss      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@Alcohol','varchar(200)') as Alcohol,      
  T.c.value('@Chewer','varchar(200)') as Chewer,      
  T.c.value('@Smoker','varchar(200)') as Smoker,      
  T.c.value('@AlcoholSocial','varchar(200)') as AlcoholSocial,      
  T.c.value('@Drug','varchar(200)') as Drug,0,0,0,0,0,null,      
  case T.c.value('@Alcohol','varchar(200)') when 'y' then 'Alcohol' when 'yes' then 'Alcohol' when '1' then 'Alcohol' else '' end,      
  case T.c.value('@Chewer','varchar(200)') when 'y' then 'Chewer' when 'yes' then 'Chewer' when '1' then 'Chewer' else '' end,      
  case T.c.value('@Smoker','varchar(200)') when 'y' then 'Smoker' when 'yes' then 'Smoker' when '1' then 'Smoker' else '' end,      
  case T.c.value('@AlcoholSocial','varchar(200)') when 'y' then 'Alcohol-Social' when 'yes' then 'Alcohol-Social' when '1' then 'Alcohol-Social' else '' end,      
  case T.c.value('@Drug','varchar(200)') when 'y' then 'Drugs' when 'yes' then 'Drugs' when '1' then 'Drugs' else '' end,      
  0,0,null,null,null,null,null,null,0      
  from @loXMLHabit.nodes('/Habits/Habit')T(c)       
          
  update #tbltmpHabitss set h_examinationid = e_examinationid,h_OrgId = e_orgid from #tbltmpExamination where e_ParticipantSourceId = h_ParticipantSourceId      
          
  declare @cnt int = 0       
  select @cnt = count(*) from #tbltmpHabitss        
  IF OBJECT_ID('tempdb..#tbltmpHabitsNull') IS NOT NULL    DROP TABLE #tbltmpHabitsNull      
  Create table #tbltmpHabitsNull      
  (      
   tid int identity(1,1),hh_ParticipantSourceId bigint,hh_ExaminationId bigint,hh_SetupId int,      
   hh_OrgId int,hh_HabitHygineId bigint      
  )      
  insert into #tbltmpHabitsNull      
  select H.h_ParticipantSourceId,null,E.e_SetupId,H.h_OrgId,null      
  from #tbltmpHabitss H      
  inner join #tbltmpExaminationNull E on E.e_ParticipantSourceId = H.h_ParticipantSourceId      
  where isnull(h_AlcoholName,'') = '' and isnull(h_ChewerName,'') = ''      
  and isnull(h_SmokerName,'') = '' and isnull(h_AlcoholSocialName,'') = ''      
  and isnull(h_DrugName,'') = ''      
        
  update #tbltmpHabitsNull set hh_ExaminationId = e_examinationid from #tbltmpExamination where e_ParticipantSourceId = hh_ParticipantSourceId      
  IF OBJECT_ID('tempdb..#tbltmpHabitDetailsNull') IS NOT NULL      
  DROP TABLE #tbltmpHabitDetailsNull      
  create table #tbltmpHabitDetailsNull      
  (      
   tid int identity(1,1),hd_HabitId int,hd_OrgId int,hd_ParticipantSourceId bigint,      
   hd_HabitHygineId bigint      
  )      
  insert into #tbltmpHabitDetailsNull      
  select HD.HabitId,HD.OrgId,H.hh_ParticipantSourceId,null      
  from sExamination.tHabitHygineDetail HD       
    INNER JOIN sExamination.tHabitHygine HH ON HD.HabitHygineId = HH.Id      
  INNER JOIN sExamination.tExamination E ON E.Id = HH.SourceId      
  INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id      
  INNER JOIN sExamination.tSubTypeMaster STM ON SM.SubTypeId = STM.Id      
  INNER JOIN #tbltmpHabitsNull H ON E.ParticipantSourceId = H.hh_ParticipantSourceId      
  AND STM.MainTypeId <> 8 and HH.IsObsolete = 0      
  WHERE      
      
      
 HH.OrgId = @lOrgId AND HD.OrgId = @lOrgId      
  AND (HH.SourceTypeId = 1002)      
  AND HH.SourceId =      
  (      
   Select MAX(E.Id) as ExaminationId      
   FROM sExamination.tHabitHygine HH      
   INNER JOIN sExamination.tExamination E ON E.Id = HH.SourceId      
   INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id      
   INNER JOIN sExamination.tSubTypeMaster STM ON SM.SubTypeId = STM.Id      
   INNER JOIN #tbltmpHabitsNull H ON E.ParticipantSourceId = H.hh_ParticipantSourceId      
   AND STM.MainTypeId <> 8 and HH.IsObsolete = 0      
  )      
      
      
      
      
        
  declare @HabitCnt int      
  select @HabitCnt = count(*) from #tbltmpHabitDetailsNull      
        
  if @HabitCnt > 0      
  begin      
   declare @lConfigId int,@lConfigVal varchar(100),@lConfFlag int        
   select @lConfigId = Id,@lConfigVal = ItemValue from sConfig.tConfigurationMaster where ItemKey = 'Examination.IsLastHabitDetailAuto'      
         
   select @lConfFlag = case when @lConfigVal = 'True' then 1 else 0 end      
         
   if @lConfFlag = 1      
   begin      
    update #tbltmpHabitsNull set hh_HabitHygineId = Id from sExamination.tHabitHygine where SourceId = hh_ExaminationId      
       
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tHabitHygine', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1   
  
    MERGE sExamination.tHabitHygine AS Target USING       
    (      
     SELECT tid,hh_ExaminationId,hh_OrgId,hh_HabitHygineId      
     FROM #tbltmpHabitsNull TT LEFT JOIN sExamination.tHabitHygine T ON TT.hh_HabitHygineId = T.Id         
    ) AS Source ON Target.Id = Source.hh_HabitHygineId      
    WHEN MATCHED THEN      
     UPDATE SET IsObsolete = 0      
    WHEN NOT MATCHED THEN      
     INSERT      
     (      
      [Id],SourceTypeId,SourceId,OrgId,IsObsolete      
     )      
     VALUES      
     (      
      @lFromNextNumber + tid,1002,hh_ExaminationId,hh_OrgId,0      
     );      
       
 select @lCount = COUNT(1) FROM #tbltmpHabitsNull       
 SET @lNextNumber  = @lCount + @lFromNextNumber       
 exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tHabitHygine', @rCurrentNumber = @lNextNumber      
  
    update #tbltmpHabitsNull set hh_HabitHygineId = Id from sExamination.tHabitHygine where SourceId = hh_ExaminationId      
    update #tbltmpHabitDetailsNull set hd_HabitHygineId = hh_HabitHygineId from #tbltmpHabitsNull      
    where hd_ParticipantSourceId = hh_ParticipantSourceId      
          
    MERGE sExamination.tHabitHygineDetail AS Target USING       
    (      
     SELECT tid,hd_HabitHygineId,hd_OrgId,hd_HabitId      
     FROM #tbltmpHabitDetailsNull TT LEFT JOIN sExamination.tHabitHygineDetail T ON TT.hd_HabitHygineId = T.HabitHygineId      
     and TT.hd_HabitId = T.HabitId      
    ) AS Source ON Target.HabitHygineId = Source.hd_HabitHygineId and Target.HabitId = Source.hd_HabitId      
    WHEN MATCHED THEN      
     UPDATE SET IsObsolete = 0      
    WHEN NOT MATCHED THEN      
     INSERT      
     (      
      HabitHygineId,HabitId,OrgId,IsObsolete      
     )      
     VALUES      
     (      
      hd_HabitHygineId,hd_HabitId,hd_OrgId,0      
     );      
   end      
  end      
         
  if @cnt > 0      
  begin      
   if exists (select 1 from #tbltmpHabitss where (isnull(h_Alcohol,'') <> '' or h_Chewer <> ''      
   or h_Smoker <> '' or h_AlcoholSocial <> '' or h_Drug <> ''))      
   begin      
    DELETE HD      
    FROM sExamination.tHabitHygineDetail HD      
    INNER JOIN sExamination.tHabitHygine H ON HD.HabitHygineId = H.Id      
    INNER JOIN #tbltmpHabitss S on S.h_examinationid = H.SourceId      
   end      
  end      
      
        
      
  update #tbltmpHabitss set h_examinationid = e_examinationid,h_OrgId = e_orgid from #tbltmpExamination where e_ParticipantSourceId = h_ParticipantSourceId         
  update #tbltmpHabitss set h_AreaId = PA.Id from [sExamination].[tAreaMaster] PA where PA.Title = 'Habit Hygine' and OrgId = h_OrgId         
  update #tbltmpHabitss set h_AlcoholId = h.Id from sExamination.tHabitTypeMaster as h where h_AlcoholName = h.Title COLLATE SQL_Latin1_General_CP1_CI_AS and h.OrgId = h_OrgId         
  update #tbltmpHabitss set h_ChewerId = Id from sExamination.tHabitTypeMaster where h_ChewerName = Title COLLATE SQL_Latin1_General_CP1_CI_AS and OrgId = h_OrgId        
  update #tbltmpHabitss set h_SmokerId = Id from sExamination.tHabitTypeMaster where h_SmokerName = Title COLLATE SQL_Latin1_General_CP1_CI_AS and OrgId = h_OrgId      
  update #tbltmpHabitss set h_AlcoholSocialId = Id from sExamination.tHabitTypeMaster where h_AlcoholSocialName = Title COLLATE SQL_Latin1_General_CP1_CI_AS and OrgId = h_OrgId      
  update #tbltmpHabitss set h_DrugId = Id from sExamination.tHabitTypeMaster where h_DrugName = Title COLLATE SQL_Latin1_General_CP1_CI_AS and OrgId = h_OrgId       
  update #tbltmpHabitss set h_HabitId = Id from sExamination.tHabitHygine where h_examinationid = SourceId and OrgId = h_OrgId      
        
  update #tbltmpHabitss set h_HabitDetailAlcohol = HD.Id from sExamination.tHabitHygine H left join sExamination.tHabitHygineDetail HD      
  on H.Id = HD.HabitHygineId where SourceId = h_examinationid and HD.HabitId = h_AlcoholId      
        
  update #tbltmpHabitss set h_HabitDetailChewer = HD.Id from sExamination.tHabitHygine H left join sExamination.tHabitHygineDetail HD      
  on H.Id = HD.HabitHygineId where SourceId = h_examinationid and HD.HabitId = h_ChewerId      
        
  update #tbltmpHabitss set h_HabitDetailSmoker = HD.Id from sExamination.tHabitHygine H left join sExamination.tHabitHygineDetail HD      
  on H.Id = HD.HabitHygineId where SourceId = h_examinationid and HD.HabitId = h_SmokerId      
        
  update #tbltmpHabitss set h_HabitDetialAlcoholSocial = HD.Id from sExamination.tHabitHygine H left join sExamination.tHabitHygineDetail HD      
  on H.Id = HD.HabitHygineId where SourceId = h_examinationid and HD.HabitId = h_AlcoholSocialId      
        
  update #tbltmpHabitss set h_HabitDetailDrug = HD.Id from sExamination.tHabitHygine H left join sExamination.tHabitHygineDetail HD      
  on H.Id = HD.HabitHygineId where SourceId = h_examinationid and HD.HabitId = h_DrugId      
         
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tHabitHygine', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tHabitHygine AS Target USING       
  (      
   SELECT tid,Id,h_HabitId,h_examinationId,h_OrgId,h_AreaId,h_AlcoholId,h_ChewerId,h_SmokerId,h_AlcoholSocialId,h_DrugId      
   FROM #tbltmpHabitss TT LEFT JOIN sExamination.tHabitHygine T ON TT.h_HabitId = T.Id      
   where (h_AlcoholId > 0 or h_ChewerId > 0 or h_SmokerId > 0 or h_AlcoholSocialId > 0 or h_DrugId > 0)      
  ) AS Source ON Target.Id = Source.h_HabitId      
  WHEN MATCHED THEN      
   UPDATE SET IsObsolete = 0      
  WHEN NOT MATCHED THEN     
   INSERT      
   (      
    [Id],SourceTypeId,SourceId,OrgId,IsObsolete      
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,1002,h_examinationId,h_OrgId,0      
   );      
          
  select @lCount = COUNT(1) FROM #tbltmpHabitss       
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tHabitHygine', @rCurrentNumber = @lNextNumber      
        
  update #tbltmpHabitss set h_HabitId = Id from sExamination.tHabitHygine where h_examinationid = SourceId and OrgId = h_OrgId      
        
  insert into sExamination.tHabitHygineDetail(HabitHygineId,HabitId,OrgId,IsObsolete)      
  select h_HabitId,h_AlcoholId,h_OrgId,0 from #tbltmpHabitss TH left join sExamination.tHabitHygineDetail HD on TH.h_HabitId = HD.HabitHygineId      
  and HD.HabitId = TH.h_AlcoholId where h_HabitDetailAlcohol is null and h_AlcoholId is not null and h_AlcoholId > 0      
        
  insert into sExamination.tHabitHygineDetail(HabitHygineId,HabitId,OrgId,IsObsolete)      
  select h_HabitId,h_ChewerId,h_OrgId,0 from #tbltmpHabitss TH left join sExamination.tHabitHygineDetail HD on TH.h_HabitId = HD.HabitHygineId      
  and HD.HabitId = TH.h_chewerId where h_HabitDetailChewer is null and h_ChewerId is not null and h_ChewerId > 0      
         
  insert into sExamination.tHabitHygineDetail(HabitHygineId,HabitId,OrgId,IsObsolete)      
  select h_HabitId,h_SmokerId,h_OrgId,0 from #tbltmpHabitss TH left join sExamination.tHabitHygineDetail HD on TH.h_HabitId = HD.HabitHygineId      
  and HD.HabitId = TH.h_SmokerId where h_HabitDetailSmoker is null and h_SmokerId is not null and h_SmokerId > 0      
         
  insert into sExamination.tHabitHygineDetail(HabitHygineId,HabitId,OrgId,IsObsolete)      
  select h_HabitId,h_AlcoholSocialId,h_OrgId,0 from #tbltmpHabitss TH left join sExamination.tHabitHygineDetail HD on TH.h_HabitId = HD.HabitHygineId      
  and HD.HabitId = TH.h_AlcoholSocialId where h_HabitDetialAlcoholSocial is null and h_AlcoholSocialId is not null and h_AlcoholSocialId > 0      
        
  insert into sExamination.tHabitHygineDetail(HabitHygineId,HabitId,OrgId,IsObsolete)      
  select h_HabitId,h_DrugId,h_OrgId,0 from #tbltmpHabitss TH left join sExamination.tHabitHygineDetail HD on TH.h_HabitId = HD.HabitHygineId      
  and HD.HabitId = TH.h_DrugId where h_HabitDetailDrug is null and h_DrugId is not null and h_DrugId > 0      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrHabitXML,4,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>      
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tbltmpDisease') IS NOT NULL      
  DROP TABLE #tbltmpDisease      
      
  create table #tbltmpDisease      
  (      
   tid int identity(1,1),d_ParticipantSourceId bigint,d_DiseaseName varchar(500),      
   d_ExaminationId bigint,d_OrgId int,d_AreaId int,d_ParticipantAreaId bigint,d_ExistingDiseaseId bigint,d_OtherDisease varchar(2000)      
  )      
  insert into #tbltmpDisease      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  replace(T.c.value('@ExistingDiseaseSelf','varchar(500)'),'+',',') as DiseaseSelf,0,0,0,0,null,    --mantis:0033673 by shivam(15/05/2024)  
replace(T.c.value('@ExistingOtherDiseaseSelf','varchar(2000)'),'+',',') as OtherDiseaseSelf      
  from @loXMLDisease.nodes('/Diseases/Disease')T(c)       
      
  update #tbltmpDisease set d_ExaminationId = e_examinationid,d_OrgId = e_OrgId from #tbltmpExamination where e_ParticipantSourceId = d_ParticipantSourceId      
        
      
  IF OBJECT_ID('tempdb..#tbltmpDiseaseNull') IS NOT NULL      
  DROP TABLE #tbltmpDiseaseNull      
  Create table #tbltmpDiseaseNull      
  (      
   tid int identity(1,1),dd_ParticipantSourceId bigint,dd_ExaminationId bigint,dd_SetupId int,      
   dd_OrgId int,dd_ExistingDiseaseId bigint      
  )      
  insert into #tbltmpDiseaseNull      
  select H.d_ParticipantSourceId,null,E.e_SetupId,H.d_OrgId,null      
  from #tbltmpDisease H      
  inner join #tbltmpExamination E on E.e_ParticipantSourceId = H.d_ParticipantSourceId      
  --where isnull(d_DiseaseName,'') = ''      
        
  update #tbltmpDiseaseNull set dd_ExaminationId = e_examinationid from #tbltmpExamination where e_ParticipantSourceId = dd_ParticipantSourceId      
        
        
  --select * from #tbltmpExaminationNull      
  --select * from #tbltmpExamination      
  set @cnt = 0      
  select @cnt = count(d_ExistingDiseaseId) from #tbltmpDisease      
        
  if @cnt > 0      
  begin      
   DELETE Hw      
   FROM sExamination.tExistingDiseaseDetail Hw      
   INNER JOIN sExamination.tExistingDisease H ON Hw.ExistingDiseaseId = H.Id      
   INNER JOIN #tbltmpDisease S on S.d_ExaminationId = H.SourceId      
   --where d_DiseaseName <> ''      
  end      
      
  IF OBJECT_ID('tempdb..#tbltmpDiseaseDetailsNull') IS NOT NULL      
  DROP TABLE #tbltmpDiseaseDetailsNull      
  Create table #tbltmpDiseaseDetailsNull       
  (      
   tid int identity(1,1),ed_HabitId int,ed_OrgId int,ed_ParticipantSourceId bigint,      
   ed_ExistingDiseaseId bigint,ed_IsSelfDeclared bit,ed_IsDiagnosed bit  
  )      
  insert into #tbltmpDiseaseDetailsNull      
  select Distinct HD.DiseaseId,HD.OrgId,H.dd_ParticipantSourceId,null,ISNULL(HD.IsSelfDeclared, 0),ISNULL(HD.IsDiagnosed, 0)  
  from sExamination.tExistingDiseaseDetail HD       
  INNER JOIN sExamination.tExistingDisease HH ON HD.ExistingDiseaseId = HH.Id      
  INNER JOIN sExamination.tExamination E ON E.Id = HH.SourceId      
  INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id      
  INNER JOIN sExamination.tSubTypeMaster STM ON SM.SubTypeId = STM.Id      
  INNER JOIN #tbltmpDiseaseNull H ON E.ParticipantSourceId = H.dd_ParticipantSourceId  
  INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = HD.DiseaseId  
  WHERE HH.OrgId = @lOrgId AND HD.OrgId = @lOrgId AND STM.MainTypeId <> 8      
  AND HH.SourceTypeId = 1002  
  AND DM.IsCarryForward = 1  
  AND HH.SourceId in      
  (      
   Select ExaminationId from(      
   Select  Max(E.id) as ExaminationId,E.ParticipantSourceId      
   FROM sExamination.tExistingDisease HH      
   INNER JOIN sExamination.tExamination E ON E.Id = HH.SourceId      
   INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id      
   INNER JOIN sExamination.tSubTypeMaster STM ON SM.SubTypeId = STM.Id      
   INNER JOIN #tbltmpDiseaseNull H ON E.ParticipantSourceId = H.dd_ParticipantSourceId      
   where STM.MainTypeId <> 8 and H.dd_ExaminationId <>E.id         
   Group by E.ParticipantSourceId) as temp      
  )      
        
  declare @DiseaseCnt int      
  select @DiseaseCnt = count(*) from #tbltmpDiseaseDetailsNull      
  --select * from #tbltmpDiseaseNull      
  --select * from #tbltmpDiseaseDetailsNull      
  if @DiseaseCnt > 0      
  begin      
   select @lConfigId = 0,@lConfigVal = '',@lConfFlag = 0      
   select @lConfigId = Id,@lConfigVal = ItemValue from sConfig.tConfigurationMaster where ItemKey = 'Examination.IsLastExistingDiseaseDetailAuto'      
         
   select @lConfFlag = case when @lConfigVal = 'True' then 1 else 0 end      
         
   if @lConfFlag = 1      
   begin      
    update #tbltmpDiseaseNull set dd_ExistingDiseaseId = Id from sExamination.tExistingDisease where SourceId = dd_ExaminationId      
    update #tbltmpDiseaseNull set dd_ExistingDiseaseId = 0 from sExamination.tExistingDisease where dd_ExistingDiseaseId IS null      
    --select * from #tbltmpDiseaseNull      
    exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tExistingDisease', 0, 1, 1,@outNextNumber = @lNextNumber output       
    SET @lFromNextNumber = @lNextNumber - 1       
      
    MERGE sExamination.tExistingDisease AS Target USING       
    (      
     SELECT tid,dd_ExaminationId,dd_OrgId,dd_ExistingDiseaseId      
     FROM #tbltmpDiseaseNull TT LEFT JOIN sExamination.tExistingDisease T ON ISNULL(TT.dd_ExistingDiseaseId,0) = T.Id and T.SourceId=TT.dd_ExaminationId        
    ) AS Source ON Target.Id = ISNULL(Source.dd_ExistingDiseaseId,0) and Target.SourceId=Source.dd_ExaminationId      
    WHEN MATCHED THEN      
     UPDATE SET IsObsolete = 0      
    WHEN NOT MATCHED THEN      
     INSERT      
     (      
      [Id],SourceTypeId,SourceId,OrgId,IsObsolete      
     )      
     VALUES      
     (      
      @lFromNextNumber + tid,1002,dd_ExaminationId,dd_OrgId,0      
     );      
          
    select @lCount = COUNT(1) FROM #tbltmpDiseaseNull      
    SET @lNextNumber  = @lCount + @lFromNextNumber       
    exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tExistingDisease', @rCurrentNumber = @lNextNumber      
      
    update #tbltmpDiseaseNull set dd_ExistingDiseaseId = Id from sExamination.tExistingDisease where SourceId = dd_ExaminationId      
          
    update #tbltmpDiseaseDetailsNull set ed_ExistingDiseaseId = dd_ExistingDiseaseId from #tbltmpDiseaseNull      
    where ed_ParticipantSourceId = dd_ParticipantSourceId      
    --print 'tbltmpDiseaseDetailsNull'      
     --select * from #tbltmpDiseaseDetailsNull      
      
    MERGE sExamination.tExistingDiseaseDetail AS Target USING       
    (      
     SELECT tid,ed_ExistingDiseaseId,ed_OrgId,ed_HabitId,ed_IsSelfDeclared,ed_IsDiagnosed   
     FROM #tbltmpDiseaseDetailsNull TT LEFT JOIN sExamination.tExistingDiseaseDetail T ON TT.ed_ExistingDiseaseId = T.ExistingDiseaseId      
     and TT.ed_HabitId = T.DiseaseId      
    ) AS Source ON Target.ExistingDiseaseId = Source.ed_ExistingDiseaseId and Target.DiseaseId = Source.ed_HabitId      
    WHEN MATCHED THEN      
     UPDATE SET IsObsolete = 0      
    WHEN NOT MATCHED THEN      
     INSERT      
     (      
      ExistingDiseaseId,DiseaseId,OrgId,IsObsolete,IsSelfDeclared,IsDiagnosed  
     )      
     VALUES      
     (      
      ed_ExistingDiseaseId,ed_HabitId,ed_OrgId,0,ed_IsSelfDeclared,ed_IsDiagnosed  
     );      
   end      
  end      
        
  update #tbltmpDisease set d_ExaminationId = e_examinationid,d_OrgId = e_OrgId from #tbltmpExamination where e_ParticipantSourceId = d_ParticipantSourceId      
  IF OBJECT_ID('tempdb..#tbltmpDiseaseN') IS NOT NULL      
  DROP TABLE #tbltmpDiseaseN      
  create table #tbltmpDiseaseN(tid int identity(1,1),d_ParticipantSourceId bigint,d_ExaminationId bigint,d_OrgId int,d_DiseaseName varchar(200),      
  d_Name varchar(200),d_AreaId int,d_ParticipantAreaId bigint,d_DiseaseId int,d_ExistingDiseaseId bigint,d_ExisitingDiseaseDetailId bigint)      
  insert into #tbltmpDiseaseN      
  select d_ParticipantSourceId,d_ExaminationId,d_orgId,Item,'Existing Disease',null,null,null,null,null      
  from #tbltmpDisease cross apply dbo.fSplitStr(d_DiseaseName,',') where Item <> ''      
        
  update #tbltmpDiseaseN set d_AreaId = Id from [sExamination].[tAreaMaster] where d_Name = Title COLLATE SQL_Latin1_General_CP1_CI_AS and OrgId = d_OrgId       
  update #tbltmpDiseaseN set d_DiseaseId = Id from sExamination.tDiseaseMaster where LTRIM(RTRIM(d_DiseaseName)) = Title COLLATE SQL_Latin1_General_CP1_CI_AS and OrgId = d_OrgId      
  update #tbltmpDiseaseN set d_ExistingDiseaseId = Id from sExamination.tExistingDisease where SourceId = d_ExaminationId      
  update #tbltmpDiseaseN set d_ExisitingDiseaseDetailId = Id from sExamination.tExistingDiseaseDetail where ExistingDiseaseId = d_ExistingDiseaseId      
  and DiseaseId = d_DiseaseId      
        
  update e set e.d_AreaId = DD.d_AreaId, e.d_ParticipantAreaId = DD.d_ParticipantAreaId,      
  e.d_ExistingDiseaseId = DD.d_ExistingDiseaseId from #tbltmpDiseaseN DD      
  inner join #tbltmpDisease e on e.d_ExaminationId = DD.d_ExaminationId      
           
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tExistingDisease', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tExistingDisease AS Target USING       
  (      
   SELECT tid,Id,TT.d_ExistingDiseaseId,TT.d_OrgId,TT.d_ExaminationId,TT.d_OtherDisease,TT.d_DiseaseName      
   FROM #tbltmpDisease TT LEFT JOIN sExamination.tExistingDisease T ON TT.d_ExistingDiseaseId = T.Id      
   where (isnull(TT.d_DiseaseName,'') <> '' or isnull(TT.d_OtherDisease,'') <> '')      
  ) AS Source ON Target.Id = Source.d_ExistingDiseaseId and Target.Sourceid = Source.d_ExaminationId      
  WHEN MATCHED THEN      
   UPDATE SET IsObsolete = 0,Remark = d_OtherDisease      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],SourceTypeId,SourceId,OrgId,IsObsolete,Remark      
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,1002,d_ExaminationId,d_OrgId,0,d_OtherDisease      
   );      
         
  --select @lCount = COUNT(1) FROM @tbltmpHabits       
  select @lCount = COUNT(1) FROM #tbltmpDisease      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tExistingDisease', @rCurrentNumber = @lNextNumber      
        
  update #tbltmpDisease set d_ExistingDiseaseId = Id from sExamination.tExistingDisease where SourceId = d_ExaminationId      
  update #tbltmpDiseaseN  set #tbltmpDiseaseN.d_ExistingDiseaseId = #tbltmpDisease.d_ExistingDiseaseId       
  from #tbltmpDisease where #tbltmpDiseaseN.d_ParticipantSourceId = #tbltmpDisease.d_ParticipantSourceId      
          
  --insert into sExamination.tExistingDiseaseDetail(ExistingDiseaseId,DiseaseId,OrgId,IsObsolete,Remark)      
  --select d_ExistingDiseaseId,d_DiseaseId,d_OrgId,0,'' from #tbltmpDiseaseN N left join sExamination.tExistingDiseaseDetail D      
  --on D.ExistingDiseaseId = N.d_ExistingDiseaseId and D.DiseaseId = N.d_DiseaseId and d_ExisitingDiseaseDetailId is null and DiseaseId is not null      
  --select * from #tbltmpDiseaseN      
  MERGE sExamination.tExistingDiseaseDetail AS Target USING      
  (      
   select d_ExistingDiseaseId,d_DiseaseId,d_OrgId      
   from #tbltmpDiseaseN N       
   left join sExamination.tExistingDiseaseDetail D on D.ExistingDiseaseId = N.d_ExistingDiseaseId       
   and D.DiseaseId = N.d_DiseaseId and d_ExisitingDiseaseDetailId is null and DiseaseId is not null      
  ) As Source ON Target.ExistingDiseaseId = Source.d_ExistingDiseaseId and Target.DiseaseId=Source.d_DiseaseId       
  WHEN MATCHED THEN      
   UPDATE SET IsObsolete = 0      
  WHEN NOT MATCHED THEN      
  INSERT      
  (      
   ExistingDiseaseId,DiseaseId,OrgId,IsObsolete,Remark,IsSelfDeclared,IsDiagnosed  
  )      
  VALUES      
  (      
   d_ExistingDiseaseId,d_DiseaseId,d_OrgId,0,'',1,0  
  );      
      
  update #tbltmpDiseaseN set d_ExisitingDiseaseDetailId = Id from sExamination.tExistingDiseaseDetail where ExistingDiseaseId = d_ExistingDiseaseId      
  and DiseaseId = d_DiseaseId      
    
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tExistingDisease', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1  
  
--Mantis: 0042443, To Add Existing Diabetic or Hypertension if previous Examination is new diabetic or new hypertension.
  MERGE sExamination.tExistingDisease AS Target USING       
  (      
   select texm.e_examinationid as d_ExaminationId, ROW_NUMBER() OVER (ORDER BY texm.e_examinationid) AS RowNum
   from #tbltmpExamination texm
	  where texm.e_IsNewDiabetic = 1 or texm.e_IsNewHypertension = 1  
  ) AS Source ON Target.Sourceid = Source.d_ExaminationId
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],SourceTypeId,SourceId,OrgId,IsObsolete,Remark      
   )      
   VALUES      
   (      
    @lFromNextNumber + RowNum,1002,d_ExaminationId,@lOrgId,0,''    
   );
         
  --select @lCount = COUNT(1) FROM @tbltmpHabits       
  select @lCount = COUNT(1) FROM #tbltmpExamination texm where texm.e_IsNewDiabetic = 1 or texm.e_IsNewHypertension = 1      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tExistingDisease', @rCurrentNumber = @lNextNumber

  MERGE sExamination.tExistingDiseaseDetail AS Target USING      
  (      
	  select ED.Id as d_ExistingDiseaseId, ED.OrgId as d_OrgId, * from #tbltmpExamination texm
	  inner join sExamination.tExistingDisease ED ON ED.SourceId = texm.e_examinationid
	  where texm.e_IsNewDiabetic = 1 
  ) As Source ON Target.ExistingDiseaseId = Source.d_ExistingDiseaseId and Target.DiseaseId = [sCommon].[fGetIntIdForOrg](7, @lOrgId)
  WHEN NOT MATCHED THEN
  INSERT      
  (      
   ExistingDiseaseId,DiseaseId,OrgId,IsObsolete,Remark,IsSelfDeclared,IsDiagnosed  
  )      
  VALUES      
  (      
   d_ExistingDiseaseId,[sCommon].[fGetIntIdForOrg](7, @lOrgId),d_OrgId,0,'',0,1  
  );

   MERGE sExamination.tExistingDiseaseDetail AS Target USING      
  (      
	  select ED.Id as d_ExistingDiseaseId, ED.OrgId as d_OrgId, * from #tbltmpExamination texm
	  inner join sExamination.tExistingDisease ED ON ED.SourceId = texm.e_examinationid
	  where texm.e_IsNewHypertension = 1
  ) As Source ON Target.ExistingDiseaseId = Source.d_ExistingDiseaseId and Target.DiseaseId = [sCommon].[fGetIntIdForOrg](13, @lOrgId)
  WHEN NOT MATCHED THEN
  INSERT      
  (      
   ExistingDiseaseId,DiseaseId,OrgId,IsObsolete,Remark,IsSelfDeclared,IsDiagnosed  
  )      
  VALUES      
  (      
   d_ExistingDiseaseId,[sCommon].[fGetIntIdForOrg](13, @lOrgId),d_OrgId,0,'',0,1
  );

 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrDiseaseXML,5,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>        <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  declare @tbltmpHistory table       
  (      
   tid int identity(1,1),h_ParticipantSourceId bigint,h_Self varchar(2000),h_Mother varchar(200),      
   h_Father varchar(200),h_Brother varchar(200),h_Sister varchar(200),h_Surgery varchar(2000),h_ExaminationId bigint,h_OrgId int,      
   h_ParticipantAreaId bigint,h_AreaId int,AreaName varchar(200),h_HistoryId bigint, h_TreatmentHistoryRemark varchar(2000),h_PastHistoryRemark varchar(2000),  
   h_PastMedicalHistorySelf varchar(2000),h_HistoryMother varchar(2000),h_HistoryFather varchar(2000)  
  )      
  insert into @tbltmpHistory      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  replace(T.c.value('@PastHistorySelf','varchar(2000)'),'+',',') as PastHistorySelf,      
  replace(T.c.value('@PastHistoryMother','varchar(200)'),'+',',') as PastHistoryMother,      
  replace(T.c.value('@PastHistoryFather','varchar(200)'),'+',',') as PastHistoryFather,      
  replace(T.c.value('@PastHistoryBrother','varchar(200)'),'+',',') as PastHistoryBrother,      
  replace(T.c.value('@PastHistorySister','varchar(200)'),'+',',') as PastHistorySister,      
  T.c.value('@PastSurgicalHistorySelf','varchar(2000)') as Surgery,0,0,null,null,'Past History',null,T.c.value('@TreatmentHistoryRemark','varchar(2000)') as TreatmentHistoryRemark      
  ,T.c.value('@PastHistoryRemark','varchar(2000)') as PastHistoryRemark,  
  T.c.value('@PastMedicalHistorySelf','varchar(2000)') as PastMedicalHistorySelf,  --mantis:0033673 by shivam(15/05/2024)  
  T.c.value('@HistoryMother','varchar(2000)') as HistoryMother, --Mantis: 0032861, Date: 13/04/2024 by Deval  
  T.c.value('@HistoryFather','varchar(2000)') as HistoryFather --Mantis: 0032861, Date: 13/04/2024 by Deval  
  from @loXMLHistory.nodes('/Historys/History')T(c)
        
  update t  set h_ExaminationId = e_examinationid,h_OrgId = e_OrgId  
  from @tbltmpHistory as t      
  inner join #tbltmpExamination e on t.h_ParticipantSourceId=e.e_ParticipantSourceId --and t.tid=e.tid      
  --where e_ParticipantSourceId = h_ParticipantSourceId         

  -----start update PastHistorySelf-----      
      
  MERGE sExamination.tExamination AS Target USING       
  (      
   SELECT Isnull(T.h_Self,'') h_Self,Isnull(h_PastMedicalHistorySelf,'') h_PastMedicalHistorySelf, TT.e_examinationid,  
   Isnull(T.h_HistoryMother,'') h_HistoryMother,Isnull(T.h_HistoryFather,'') h_HistoryFather  
   FROM #tbltmpExamination TT INNER JOIN @tbltmpHistory T ON TT.e_examinationid = T.h_ExaminationId  
  ) AS Source ON Target.Id = Source.e_examinationid  
  WHEN MATCHED THEN  
   UPDATE SET Target.PastHistorySelf = h_Self +   
    CASE   
        WHEN h_Self != '' AND h_PastMedicalHistorySelf != '' THEN ', '   
        ELSE ''   
    END  + h_PastMedicalHistorySelf, --Mantis:0032687 by shivam on 11/04/2024  
   Target.HistoryMother = h_HistoryMother, Target.HistoryFather = h_HistoryFather; --Mantis: 0032861, Date: 13/04/2024 by Deval  
      
      
  -----end update PastHistorySelf-----      
      
      
  update @tbltmpHistory set h_AreaId = Id from sExamination.tAreaMaster where AreaName = Title and h_OrgId = OrgId         
  update @tbltmpHistory set h_HistoryId = Id from sExamination.tHistory where h_ParticipantSourceId = ParticipantSourceId         
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tHistory', 0, 1, 1,@outNextNumber = @lNextNumber output      
  SET @lFromNextNumber = @lNextNumber - 1      
        
  update @tbltmpHistory set h_HistoryId = Id from sExamination.tHistory where ParticipantSourceId = h_ParticipantSourceId     
        
  MERGE sExamination.tHistory AS Target USING       
  (      
   SELECT tid,Id,h_HistoryId,h_ParticipantSourceId,h_OrgId,h_AreaId,h_Surgery,h_TreatmentHistoryRemark,h_PastHistoryRemark      
   FROM @tbltmpHistory TT       
   LEFT JOIN sExamination.tHistory T ON TT.h_HistoryId = T.Id        
  ) AS Source ON Target.Id = Source.h_HistoryId      
  WHEN MATCHED THEN      
   UPDATE SET IsObsolete = 0,TreatmentHistoryRemark = h_TreatmentHistoryRemark,Remark = h_PastHistoryRemark,IsSurgeryDone = case when h_Surgery <> '' then 1 else 0 end,      
   SurgeryRemark = case when h_Surgery <> '' then       
   case when charindex(h_Surgery,SurgeryRemark)>0 then SurgeryRemark else      
   case when isnull(SurgeryRemark,'')  <> '' then isnull(SurgeryRemark,'') + '+' + h_Surgery else h_Surgery end end else SurgeryRemark end        
      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],ParticipantSourceId,OrgId,IsObsolete,ParticipantSourceTypeId,IsSurgeryDone,SurgeryRemark, TreatmentHistoryRemark, Remark      
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,h_ParticipantSourceId,h_OrgId,0,95,case when h_Surgery <> '' then 1 else 0 end,h_Surgery,h_TreatmentHistoryRemark, h_PastHistoryRemark      
   );      
         
  select @lCount = COUNT(1) FROM @tbltmpHistory      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tHistory', @rCurrentNumber = @lNextNumber
        
  update @tbltmpHistory set h_HistoryId = Id from sExamination.tHistory where ParticipantSourceId = h_ParticipantSourceId      
  IF OBJECT_ID('tempdb..#tbltmpHistorySelf') IS NOT NULL      
  DROP TABLE #tbltmpHistorySelf      
  create table #tbltmpHistorySelf      
  (      
   tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,HistoryDetailId bigint,RelationId int,      
   ExaminationId bigint,s_OrgId int,PatientId bigint,AreaId int,AreaName varchar(200),ParticipantAreaId bigint,Name varchar(200),      
   h_Surgery varchar(1000)      
  )      
  insert into #tbltmpHistorySelf      
  select 0,h_HistoryId,0,1,h_ExaminationId,h_OrgId,h_ParticipantSourceId,h_AreaId,'Past History',h_ParticipantAreaId,Item,h_Surgery      
  from @tbltmpHistory cross apply dbo.fSplitStr(h_Self,',') where Item <> ''      
        
  IF OBJECT_ID('tempdb..#tbltmpHistoryMother') IS NOT NULL      
  DROP TABLE #tbltmpHistoryMother      
  create table #tbltmpHistoryMother      
  (      
   tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,HistoryDetailId bigint,RelationId int,      
   ExaminationId bigint,m_OrgId int,PatientId bigint,AreaId int,AreaName varchar(200),ParticipantAreaId bigint,Name varchar(200),      
   h_Surgery varchar(1000)      
  )      
  insert into #tbltmpHistoryMother      
  select 0,h_HistoryId,0,3,h_ExaminationId,h_OrgId,h_ParticipantSourceId,h_AreaId,'Past History',h_ParticipantAreaId,Item,h_Surgery      
  from @tbltmpHistory cross apply dbo.fSplitStr(h_Mother,',') where Item <> ''      
         
  IF OBJECT_ID('tempdb..#tbltmpHistoryFather') IS NOT NULL      
  DROP TABLE #tbltmpHistoryFather      
  create table #tbltmpHistoryFather      
  (      
   tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,HistoryDetailId bigint,RelationId int,      
   ExaminationId bigint,f_OrgId int,PatientId bigint,AreaId int,AreaName varchar(200),ParticipantAreaId bigint,Name varchar(200),      
   h_Surgery varchar(1000)      
  )      
  insert into #tbltmpHistoryFather      
  select 0,h_HistoryId,0,2,h_ExaminationId,h_OrgId,h_ParticipantSourceId,h_AreaId,'Past History',h_ParticipantAreaId,Item,h_Surgery      
  from @tbltmpHistory cross apply dbo.fSplitStr(h_Father,',') where Item <> ''      
        
  IF OBJECT_ID('tempdb..#tbltmpHistoryBrother') IS NOT NULL      
  DROP TABLE #tbltmpHistoryBrother      
  create table #tbltmpHistoryBrother      
  (      
   tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,HistoryDetailId bigint,RelationId int,      
   ExaminationId bigint,f_OrgId int,PatientId bigint,AreaId int,AreaName varchar(200),ParticipantAreaId bigint,Name varchar(200),      
   h_Surgery varchar(1000)      
  )      
  insert into #tbltmpHistoryBrother      
  select 0,h_HistoryId,0,2,h_ExaminationId,h_OrgId,h_ParticipantSourceId,h_AreaId,'Past History',h_ParticipantAreaId,Item,h_Surgery      
  from @tbltmpHistory cross apply dbo.fSplitStr(h_Brother,',') where Item <> ''      
        
  IF OBJECT_ID('tempdb..#tbltmpHistorySister') IS NOT NULL      
  DROP TABLE #tbltmpHistorySister      
  create table #tbltmpHistorySister      
  (      
   tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,HistoryDetailId bigint,RelationId int,      
   ExaminationId bigint,f_OrgId int,PatientId bigint,AreaId int,AreaName varchar(200),ParticipantAreaId bigint,Name varchar(200),      
   h_Surgery varchar(1000)      
  )      
  insert into #tbltmpHistorySister      
  select 0,h_HistoryId,0,2,h_ExaminationId,h_OrgId,h_ParticipantSourceId,h_AreaId,'Past History',h_ParticipantAreaId,Item,h_Surgery      
  from @tbltmpHistory cross apply dbo.fSplitStr(h_Sister,',') where Item <> ''      
         
  update #tbltmpHistorySelf set h_DiseaseId = Id from sExamination.tDiseaseMaster where Name = Title COLLATE SQL_Latin1_General_CP1_CI_AS and s_OrgId = OrgId      
  update #tbltmpHistoryMother set h_DiseaseId = Id from sExamination.tDiseaseMaster where Name = Title COLLATE SQL_Latin1_General_CP1_CI_AS and m_OrgId = OrgId      
  update #tbltmpHistoryFather set h_DiseaseId = Id from sExamination.tDiseaseMaster where Name = Title COLLATE SQL_Latin1_General_CP1_CI_AS and f_OrgId = OrgId      
  update #tbltmpHistoryBrother set h_DiseaseId = Id from sExamination.tDiseaseMaster where Name = Title COLLATE SQL_Latin1_General_CP1_CI_AS and f_OrgId = OrgId      
  update #tbltmpHistorySister set h_DiseaseId = Id from sExamination.tDiseaseMaster where Name = Title COLLATE SQL_Latin1_General_CP1_CI_AS and f_OrgId = OrgId      
        
  update #tbltmpHistorySelf set HistoryDetailId = Id from sExamination.tHistoryDetail      
  where HistoryId = h_HistoryId and s_OrgId = OrgId and DiseaseId = h_DiseaseId and RelationshipId=1      
        
  update #tbltmpHistoryMother set HistoryDetailId = Id from sExamination.tHistoryDetail      
  where HistoryId = h_HistoryId and m_OrgId = OrgId and DiseaseId = h_DiseaseId and RelationshipId=2      
        
  update #tbltmpHistoryFather set HistoryDetailId = Id from sExamination.tHistoryDetail      
  where HistoryId = h_HistoryId and f_OrgId = OrgId and DiseaseId = h_DiseaseId and RelationshipId=3      
        
  update #tbltmpHistoryBrother set HistoryDetailId = Id from sExamination.tHistoryDetail      
  where HistoryId = h_HistoryId and f_OrgId = OrgId and DiseaseId = h_DiseaseId and RelationshipId=4      
        
  update #tbltmpHistoryBrother set HistoryDetailId = Id from sExamination.tHistoryDetail      
  where HistoryId = h_HistoryId and f_OrgId = OrgId and DiseaseId = h_DiseaseId and RelationshipId=5      
         
  set @cnt = 0      
  select @cnt = count(*) from #tbltmpHistorySelf      
        
   --mentis issue no:0014229 MS - 2020-02-02       
  if @cnt > 0      
  begin      
   --select * from #tbltmpHistorySelf      
   delete from #tbltmpHistorySelf where isnull(HistoryDetailId,0)>0      
   --DELETE HD      
   --FROM sExamination.tHistoryDetail HD      
   --INNER JOIN sExamination.tHistory H ON HD.HistoryId = H.Id      
   --INNER JOIN #tbltmpHistorySelf S on S.PatientId = H.ParticipantSourceId      
   --where RelationshipId = 1      
  end      
        
  set @cnt = 0      
  select @cnt = count(*) from #tbltmpHistoryMother      
        
  if @cnt > 0      
  begin      
   DELETE HD      
   FROM sExamination.tHistoryDetail HD      
   INNER JOIN sExamination.tHistory H ON HD.HistoryId = H.Id      
   INNER JOIN #tbltmpHistoryMother S on S.PatientId = H.ParticipantSourceId      
   where RelationshipId = 3      
  end      
        
  set @cnt = 0      
  select @cnt = count(*) from #tbltmpHistoryFather      
        
  if @cnt > 0      
  begin      
   DELETE HD      
   FROM sExamination.tHistoryDetail HD      
   INNER JOIN sExamination.tHistory H ON HD.HistoryId = H.Id      
   INNER JOIN #tbltmpHistoryFather S on S.PatientId = H.ParticipantSourceId      
   where RelationshipId = 2      
  end      
        
  set @cnt = 0      
  select @cnt = count(*) from #tbltmpHistoryBrother      
        
  if @cnt > 0      
  begin      
   DELETE HD      
   FROM sExamination.tHistoryDetail HD      
   INNER JOIN sExamination.tHistory H ON HD.HistoryId = H.Id      
   INNER JOIN #tbltmpHistoryBrother S on S.PatientId = H.ParticipantSourceId      
   where RelationshipId = 7      
  end      
        
  set @cnt = 0      
  select @cnt = count(*) from #tbltmpHistorySister      
        
  if @cnt > 0      
  begin      
   DELETE HD      
   FROM sExamination.tHistoryDetail HD      
   INNER JOIN sExamination.tHistory H ON HD.HistoryId = H.Id      
   INNER JOIN #tbltmpHistorySister S on S.PatientId = H.ParticipantSourceId      
   where RelationshipId = 8      
  end      
        
  IF OBJECT_ID('tempdb..#tbltmpHistorySelfN') IS NOT NULL      
  DROP TABLE #tbltmpHistorySelfN          
  create table #tbltmpHistorySelfN(tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,s_OrgId int)      
  insert into #tbltmpHistorySelfN      
  select distinct h_DiseaseId,h_HistoryId,s_OrgId from #tbltmpHistorySelf where h_DiseaseId is not null and h_DiseaseId > 0 and h_HistoryId is not null      
        
  IF OBJECT_ID('tempdb..#tbltmpHistoryMotherN') IS NOT NULL      
  DROP TABLE #tbltmpHistoryMotherN      
  create table #tbltmpHistoryMotherN(tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,s_OrgId int)      
  insert into #tbltmpHistoryMotherN      
  select distinct h_DiseaseId,h_HistoryId,m_OrgId from #tbltmpHistoryMother where h_DiseaseId is not null and h_DiseaseId > 0 and h_HistoryId is not null      
        
  IF OBJECT_ID('tempdb..#tbltmpHistoryFatherN') IS NOT NULL      
  DROP TABLE #tbltmpHistoryFatherN      
  create table #tbltmpHistoryFatherN(tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,s_OrgId int)      
  insert into #tbltmpHistoryFatherN      
  select distinct h_DiseaseId,h_HistoryId,f_OrgId from #tbltmpHistoryFather where h_DiseaseId is not null and h_DiseaseId > 0 and h_HistoryId is not null      
        
  IF OBJECT_ID('tempdb..#tbltmpHistoryBrotherN') IS NOT NULL      
  DROP TABLE #tbltmpHistoryBrotherN      
  create table #tbltmpHistoryBrotherN(tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,s_OrgId int)      
  insert into #tbltmpHistoryBrotherN      
  select distinct h_DiseaseId,h_HistoryId,f_OrgId from #tbltmpHistoryBrother where h_DiseaseId is not null and h_DiseaseId > 0 and h_HistoryId is not null      
        
  IF OBJECT_ID('tempdb..#tbltmpHistorySisterN') IS NOT NULL      
  DROP TABLE #tbltmpHistorySisterN      
  create table #tbltmpHistorySisterN(tid int identity(1,1),h_DiseaseId int,h_HistoryId bigint,s_OrgId int)      
  insert into #tbltmpHistorySisterN      
  select distinct h_DiseaseId,h_HistoryId,f_OrgId from #tbltmpHistorySister where h_DiseaseId is not null and h_DiseaseId > 0 and h_HistoryId is not null      
        
  insert into sExamination.tHistoryDetail(HistoryId,RelationshipId,DiseaseId,OrgId,IsObsolete)      
  select h_HistoryId,1,h_DiseaseId,s_OrgId,0 from #tbltmpHistorySelfN      
        
  insert into sExamination.tHistoryDetail(HistoryId,RelationshipId,DiseaseId,OrgId,IsObsolete)      
  select h_HistoryId,3,h_DiseaseId,s_OrgId,0 from #tbltmpHistoryMotherN      
        
  insert into sExamination.tHistoryDetail(HistoryId,RelationshipId,DiseaseId,OrgId,IsObsolete)      
  select h_HistoryId,2,h_DiseaseId,s_OrgId,0 from #tbltmpHistoryFatherN      
        
  insert into sExamination.tHistoryDetail(HistoryId,RelationshipId,DiseaseId,OrgId,IsObsolete)      
  select h_HistoryId,7,h_DiseaseId,s_OrgId,0 from #tbltmpHistoryBrotherN      
        
  insert into sExamination.tHistoryDetail(HistoryId,RelationshipId,DiseaseId,OrgId,IsObsolete)      
  select h_HistoryId,8,h_DiseaseId,s_OrgId,0 from #tbltmpHistorySisterN      
      
  -- mentis issue no:0014229 MS - 2020-02-02 for duplicate records delete      
  delete       
  from sExamination.tHistoryDetail      
  where id not in(      
  select MAx(ID) as Id       
  from sExamination.tHistoryDetail      
  Group by HistoryId,RelationshipId,DiseaseId,OrgId        
  )      
      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrHistoryXML,6,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>      
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tbltmpTests') IS NOT NULL      
  DROP TABLE #tbltmpTests      
      
  create table #tbltmpTests       
  (      
   tid int identity(1,1),t_ParticipantSourceId bigint,t_TestDetailId int,t_Result varchar(300),t_Remark varchar(500),      
   t_ExaminationId bigint,t_OrgId int,t_TestId int,t_TestRequestId bigint,t_TestRequestDetailId bigint,      
   t_ParticipantAreaId bigint,t_ParamId int,t_TestDetailIdMain int      
  )      
  insert into #tbltmpTests      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@TestDetailId','int') as TestDetailId,      
  T.c.value('@Result','varchar(300)') as Result,      
  left(T.c.value('@Remark','varchar(700)'),200) as Remark,      
  null,null,null,null,null,null,null,null      
  from @loXMLTest.nodes('/Tests/Test')T(c)      
        
  IF EXISTS (SELECT 1 FROM sys.indexes WHERE NAME = N'IX_tTestRequestDetail')      
  DROP INDEX IX_tTestRequestDetail ON sExamination.tTestRequestDetail      
  CREATE INDEX IX_tTestRequestDetail ON sExamination.tTestRequestDetail (Id,TestRequestId,TestDetailId)      
          
  update #tbltmpTests set t_ExaminationId = e_examinationid,t_OrgId = e_OrgId from #tbltmpExamination where e_ParticipantSourceId = t_ParticipantSourceId      
  update #tbltmpTests set t_TestDetailIdMain = sCommon.fGetIntIdForOrg(t_TestDetailId,t_OrgId) WHERE t_TestDetailId<1000 -- FOR STATIC TEST BY MS 2022-07-21    
  update #tbltmpTests set t_TestDetailIdMain = t_TestDetailId  WHERE t_TestDetailId>1000 -- FOR Manualy Added TEST BY MS 2022-07-21    
  update #tbltmpTests set t_TestId = TestId,t_ParamId = TestParameterId from sOrderEntry.tTestDetail where Id = t_TestDetailIdMain       
  update #tbltmpTests set t_TestRequestId = Id from sExamination.tTestRequest where t_TestId = TestId and SourceId = t_ExaminationId and OrgId = t_OrgId      
  update #tbltmpTests set t_TestRequestDetailId = Id from sExamination.tTestRequestDetail      
  where t_TestRequestId = TestRequestId and t_TestDetailIdMain = TestDetailId      
  OPTION(RECOMPILE)      
        
  declare @tbl table(tid int identity(1,1),t_TestId int,ExId bigint,t_PartId bigint)      
  insert into @tbl      
  select distinct t_TestId,t_ExaminationId,t_ParticipantAreaId from #tbltmpTests where t_TestId is not null      
          
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequest', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
         
  MERGE sExamination.tTestRequest AS Target USING       
  (      
   SELECT Id,TestId as AreaId,SourceId,ExId,TT.t_TestId,tid      
   FROM @tbl TT LEFT JOIN sExamination.tTestRequest T ON TT.ExId = T.SourceId AND TestId = t_TestId      
  ) AS Source ON Target.SourceId = Source.ExId AND Target.TestId = Source.t_TestId      
  WHEN MATCHED THEN      
   UPDATE SET IsObsolete = 0      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    OrgId,Id,SourceTypeId,SourceId,IsObsolete,TestId      
   )      
   VALUES     (      
    @lOrgId,@lFromNextNumber + tid,1002,ExId,0,t_TestId      
   );      
         
  select @lCount = COUNT(1) FROM @tbl      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tTestRequest', @rCurrentNumber = @lNextNumber      
        
  update #tbltmpTests set t_TestRequestId = Id from sExamination.tTestRequest where SourceId = t_ExaminationId      
  and TestId = t_TestId and OrgId = t_OrgId      
        
  --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output       
  --SET @lFromNextNumber = @lNextNumber - 1      
         
  IF OBJECT_ID('tempdb..#tbltmpTestsN') IS NOT NULL      
  DROP TABLE #tbltmpTestsN      
  create table #tbltmpTestsN       
  (      
   tid int identity(1,1),t_ParticipantSourceId bigint,t_TestDetailId int,t_Result varchar(300),t_Remark varchar(500),      
   t_ExaminationId bigint,t_OrgId int,t_TestId int,t_TestRequestId bigint,t_TestRequestDetailId bigint,      
   t_ParticipantAreaId bigint,t_ParamId int,t_TestDetailIdMain int      
  )      
  insert into #tbltmpTestsN       
  (      
   t_ParticipantSourceId,t_TestDetailId,t_Result,t_Remark,      
   t_ExaminationId,t_OrgId,t_TestId,t_TestRequestId,t_TestRequestDetailId,      
   t_ParticipantAreaId,t_ParamId,t_TestDetailIdMain      
 )      
  select t_ParticipantSourceId,t_TestDetailId,t_Result,left(t_Remark,200),t_ExaminationId,t_OrgId,t_TestId,t_TestRequestId,t_TestRequestDetailId,      
  t_ParticipantAreaId,t_ParamId,t_TestDetailIdMain from #tbltmpTests where t_ParamId is not null and t_TestId is not null and t_TestRequestId is not null      
          
  MERGE sExamination.tTestRequestDetail AS Target USING       
  (      
   SELECT tid,Id,TestRequestId,TestDetailId,t_TestDetailId,t_TestRequestId,t_Result,t_ParamId,t_Remark,t_TestDetailIdMain      
   FROM #tbltmpTestsN TT LEFT JOIN sExamination.tTestRequestDetail T ON TT.t_TestRequestId = TestRequestId and TestDetailId = t_TestDetailIdMain      
  ) AS Source ON Target.TestRequestId = Source.t_TestRequestId AND Target.TestDetailId = Source.t_TestDetailIdMain      
  WHEN MATCHED THEN      
   UPDATE SET ServiceValue = [sSetup].[fPortalXMLTagsReplaceReverse](t_Result),      
   Remark = [sSetup].[fPortalXMLTagsReplaceReverse](t_Remark)      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    OrgId,TestRequestId,TestDetailId,ServiceValue,Remark      
   )      
   VALUES      
   (      
    @lOrgId,t_TestRequestId,t_TestDetailIdMain,      
    [sSetup].[fPortalXMLTagsReplaceReverse](t_Result),[sSetup].[fPortalXMLTagsReplaceReverse](t_Remark)      
   );      
         
  --select @lCount = COUNT(1) FROM #tbltmpTestsN       
  --SET @lNextNumber  = @lCount + @lFromNextNumber       
  --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tTestRequestDetail', @rCurrentNumber = @lNextNumber        
        
  update #tbltmpTests set t_TestRequestDetailId = Id from sExamination.tTestRequestDetail      
  where t_TestRequestId = TestRequestId and t_TestDetailIdMain = TestDetailId      
        
  update w set w.IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](w.Id,w.ServiceValue),
  w.Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](w.Id,w.ServiceValue) = 0 THEN '' ELSE w.Diagnosis END
  from sExamination.tTestRequestDetail w inner join #tbltmpTests t on t.t_TestRequestDetailId = w.Id      
        
  IF OBJECT_ID('tempdb..#tbltmpRatio') IS NOT NULL      
  DROP TABLE #tbltmpRatio      
  create table #tbltmpRatio(tid int identity(1,1),r_TestRequestDetailId bigint,r_TestDetailId int,      
  r_ParameterId int,r_Res varchar(200),r_ExaminationId bigint,r_TestRequestId bigint,r_TestId int)      
  insert into #tbltmpRatio      
  select t_TestRequestDetailId,t_TestDetailIdMain,t_ParamId,t_Result,t_ExaminationId,t_TestRequestId,t_TestId from #tbltmpTests      
  where t_ParamId in (sCommon.fGetIntIdForOrg(34,@lOrgId),sCommon.fGetIntIdForOrg(33,@lOrgId),sCommon.fGetIntIdForOrg(31,@lOrgId)      
  ,sCommon.fGetIntIdForOrg(32,@lOrgId))        
        
  IF OBJECT_ID('tempdb..#tbltmpRatioN') IS NOT NULL      
  DROP TABLE #tbltmpRatioN      
  create table #tbltmpRatioN(tid int identity(1,1),n_ExaminationId bigint,n_StoreLocationId int)      
  insert into #tbltmpRatioN      
  select distinct r_ExaminationId,null from #tbltmpRatio      
        
  update w set w.n_StoreLocationId = e.e_StoreLocationId from #tbltmpRatioN w inner join #tbltmpExamination e on w.n_ExaminationId = e.e_examinationid      
        
  declare @lRatioCnt int,@lRationIncr int,@lConfValueAuto int      
  select @lRationIncr = 1,@lRatioCnt = count(*) from #tbltmpRatioN      
        
  --select * from #tbltmpRatio      
        
      
  while @lRationIncr <= @lRatioCnt      
  begin      
   declare @lExaminationId bigint,@lTestId int,@lTestRequestId bigint,@lTestDetail1Id int,@lTestDetail2Id int      
   declare @lTestDetail3Id int,@lTestDetail4Id int,@lStoreLocationId int,@lLocationId int,@lUserId bigint      
   declare @lLDLVal varchar(300),@lHDLVal varchar(300),@lCHOLEVal varchar(300),@lTryVal varchar(300)     
   declare @lVLDL varchar(300)='',@lLDL varchar(300)=''      
         
   select @lExaminationId = n_ExaminationId,@lStoreLocationId = n_StoreLocationId from #tbltmpRatioN where tid = @lRationIncr      
   select @lLocationId = LocationId from sIp.tStoreLocationMaster where Id = @lStoreLocationId      
   select @lUserId = CreatedUserId from sExamination.tExamination where Id = @lExaminationId      
         
   select @lConfValueAuto = case when      
   sConfig.fConfigurationValueGet('Examination.IsLipidParameterAutoCalculate',@lOrgId,@lStoreLocationId,@lLocationId,@lUserId) = 'True' then 1 else 0 end      
         
   select @lLDLVal = r_Res,@lTestRequestId = r_TestRequestId,@lTestId = r_TestId from #tbltmpRatio      
   where r_ExaminationId = @lExaminationId and r_ParameterId = sCommon.fGetIntIdForOrg(34,@lOrgId)      
         
   select @lHDLVal = r_Res,@lTestRequestId = r_TestRequestId,@lTestId = r_TestId from #tbltmpRatio      
   where r_ExaminationId = @lExaminationId and r_ParameterId = sCommon.fGetIntIdForOrg(33,@lOrgId)      
         
   select @lCHOLEVal = r_Res,@lTestRequestId = r_TestRequestId,@lTestId = r_TestId from #tbltmpRatio      
   where r_ExaminationId = @lExaminationId and r_ParameterId = sCommon.fGetIntIdForOrg(31,@lOrgId)      
         
   select @lTryVal = r_Res,@lTestRequestId = r_TestRequestId,@lTestId = r_TestId from #tbltmpRatio      
   where r_ExaminationId = @lExaminationId and r_ParameterId = sCommon.fGetIntIdForOrg(32,@lOrgId)      
         
   if @lTryVal <> '' and @lHDLVal <> '' and @lCHOLEVal <> ''      
   begin      
    select @lVLDL = convert(float,@lTryVal) / 5      
    select @lLDL = convert(float,@lCHOLEVal) - convert(float,@lHDLVal) - convert(float,@lVLDL)      
    select @lLDLVal = @lLDL      
   end      
         
   select @lTestDetail1Id = Id from sOrderEntry.tTestDetail where TestParameterId = sCommon.fGetIntIdForOrg(36,@lOrgId)      
   select @lTestDetail2Id = Id from sOrderEntry.tTestDetail where TestParameterId = sCommon.fGetIntIdForOrg(37,@lOrgId)      
   select @lTestDetail3Id = Id from sOrderEntry.tTestDetail where TestParameterId = sCommon.fGetIntIdForOrg(35,@lOrgId)      
   select @lTestDetail4Id = Id from sOrderEntry.tTestDetail where TestParameterId = sCommon.fGetIntIdForOrg(34,@lOrgId)      
         
   if exists (select 1 from sExamination.tTestRequestDetail where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail1Id)      
   begin      
    update sExamination.tTestRequestDetail set       
    ServiceValue = case when @lLDLVal <> '' and @lHDLVal <> '' and @lLDLVal <> '0' and @lHDLVal <> '0' then      
    convert(varchar,convert(decimal(12,2),convert(float,@lLDLVal) / convert(float,@lHDLVal))) else '' end      
    where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail1Id      
          
    update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
    where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail1Id      
   end      
   else      
   begin      
    --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output      
          
    insert into sExamination.tTestRequestDetail      
    (      
     TestRequestId,TestDetailId,ServiceValue,OrgId      
    )      
    select @lTestRequestId,@lTestDetail1Id,      
    case when @lLDLVal <> '' and @lHDLVal <> '' and @lLDLVal <> '0' and @lHDLVal <> '0' then      
    convert(varchar,convert(decimal(12,2),convert(float,@lLDLVal) / convert(float,@lHDLVal))) else '' end,@lOrgId      
          
    update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
    where Id = SCOPE_IDENTITY()      
   end      
         
   if exists (select 1 from sExamination.tTestRequestDetail where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail2Id)      
   begin      
    update sExamination.tTestRequestDetail set      
    ServiceValue = case when @lHDLVal <> '' and @lCHOLEVal <> '' and @lHDLVal <> '0' and @lCHOLEVal <> '0' then      
    convert(varchar,convert(decimal(12,2),convert(float,@lCHOLEVal) / convert(float,@lHDLVal))) else '' end      
    where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail2Id      
          
    update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
    where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail2Id      
   end      
   else      
   begin      
    --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output      
          
    insert into sExamination.tTestRequestDetail      
    (      
     TestRequestId,TestDetailId,ServiceValue,OrgId      
    )      
    select @lTestRequestId,@lTestDetail2Id,      
    case when @lHDLVal <> '' and @lCHOLEVal <> '' and @lHDLVal <> '0' and @lCHOLEVal <> '0' then      
    convert(varchar,convert(decimal(12,2),convert(float,@lCHOLEVal) / convert(float,@lHDLVal))) else '' end,@lOrgId      
          
    update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
    where Id = SCOPE_IDENTITY()      
   end      
   print @lVLDL      
   Print @lLDL      
   if @lConfValueAuto = 1      
   begin      
    if exists (select 1 from sExamination.tTestRequestDetail where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail3Id)      
    begin      
     update sExamination.tTestRequestDetail set ServiceValue = @lVLDL      
     where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail3Id      
           
     update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	 Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
     where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail3Id      
    end      
    else      
    begin      
     --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output      
           
     insert into sExamination.tTestRequestDetail      
     (      
      TestRequestId,TestDetailId,ServiceValue,OrgId      
     )      
     select @lTestRequestId,@lTestDetail3Id,@lVLDL,@lOrgId      
           
     update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	 Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
     where Id = SCOPE_IDENTITY()      
    end      
          
    if exists (select 1 from sExamination.tTestRequestDetail where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail4Id)      
    begin      
     update sExamination.tTestRequestDetail set ServiceValue = @lLDL      
     where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail4Id      
           
     update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	 Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
     where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail4Id      
    end      
    else      
    begin      
     --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output      
           
     insert into sExamination.tTestRequestDetail      
     (      
      TestRequestId,TestDetailId,ServiceValue,OrgId      
     )      
     select @lTestRequestId,@lTestDetail4Id,@lLDL,@lOrgId      
           
     update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
	 Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
     where Id = SCOPE_IDENTITY()      
    end      
   end      
         
   select @lRationIncr = @lRationIncr + 1      
  end      
        
  --added by ms- for getting correct abnormal flag update for first time insert records      
  update #tbltmpRatio set r_TestRequestDetailId = Id from sExamination.tTestRequestDetail where TestRequestId = r_TestRequestId      
  and TestDetailId = r_TestDetailId      
  -- finish      
      
  update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue),
  Diagnosis = CASE WHEN [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue) = 0 THEN '' ELSE Diagnosis END
  from sExamination.tTestRequestDetail inner join #tbltmpRatio on r_TestRequestDetailId = Id      
   
 --select @rConfigBloodGroup  
  IF(@rConfigBloodGroup = 1)  
  BEGIN  
  --select * from #tbltmpTests  
  UPDATE EPD  
   SET BloodGroupId = (SELECT Id FROM sCommon.tBloodGroupMaster WHERE Title = TMPT.t_Result)  
   FROM sHrm.tEmployeePersonalDetail EPD  
   INNER JOIN sExamination.tExamination E ON E.ParticipantSourceId = EPD.EmployeeId  
   INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.Id  
   INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id  
   INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = TRD.TestDetailId  
   INNER JOIN #tbltmpTests TMPT ON TMPT.t_TestDetailIdMain = TD.Id  
   INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId  
   WHERE TPM.StaticTestParameterId = 1;  
  END  
  
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrTestXML,7,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>      
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tblGeneral') IS NOT NULL      
  DROP TABLE #tblGeneral      
      
  create table #tblGeneral      
  (      
   tid int identity(1,1),g_EmpId bigint,g_ParamId int,g_Res varchar(1000),g_Rem varchar(1500),      
   g_ExamId bigint,g_TestId int,g_OrgId int,g_GeneralDetId bigint,g_GenId bigint      
  )      
  insert into #tblGeneral      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@ParameterId','int') as ParameterId,      
  T.c.value('@Result','varchar(1000)') as Result,      
  T.c.value('@Remark','varchar(1500)') as Remark,null,null,null,null,null      
  from @loXMLGeneral.nodes('/General/Clinic')T(c) where T.c.value('@Result','varchar(1000)') <> ''      
        
  update #tblGeneral set g_ExamId = e_examinationid,g_OrgId = e_OrgId from #tbltmpExamination where e_ParticipantSourceId = g_EmpId      
  update #tblGeneral set g_ParamId = Id,g_TestId = GeneralTemplateId from sExamination.tGeneralTemplateParameter      
  where StaticGeneralTemplateParameterId = g_ParamId and OrgId = g_OrgId     
    
  update #tblGeneral set g_ParamId = Id,g_TestId = GeneralTemplateId from sExamination.tGeneralTemplateParameter      
  where StaticGeneralTemplateParameterId IS NuLL and Id = g_ParamId and OrgId = g_OrgId   -- if staticgeneralparamterid is null ; Nidhi Pandey DT - 22/04/2024;mantis - 0032971  
     
    
  IF OBJECT_ID('tempdb..#tblGeneralN') IS NOT NULL      
  DROP TABLE #tblGeneralN      
      
  create table #tblGeneralN(tid int identity(1,1),n_TestId int,n_Exid bigint,n_OrgId int,n_PartAreaId bigint,n_GeneralId bigint)      
  insert into #tblGeneralN      
  select distinct g_TestId,g_ExamId,g_OrgId,null,null from #tblGeneral      
         
  update #tblGeneralN set n_GeneralId = Id from sExamination.tGeneralTemplateExamination where GeneralTemplateId = n_TestId      
  and SourceId = n_Exid      
       
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tGeneralTemplateExamination', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tGeneralTemplateExamination AS Target USING       
  (      
   SELECT Id,n_TestId,n_Exid,n_OrgId,n_GeneralId,tid      
   FROM #tblGeneralN TT LEFT JOIN sExamination.tGeneralTemplateExamination T ON TT.n_GeneralId = T.Id        
  ) AS Source ON Target.Id = Source.n_GeneralId       
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],SourceId,SourceTypeId,GeneralTemplateId,OrgId      
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,n_Exid,1002,n_TestId,n_OrgId      
   );      
         
  select @lCount = COUNT(1) FROM #tblGeneralN      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tGeneralTemplateExamination', @rCurrentNumber = @lNextNumber      
        
  update #tblGeneralN set n_GeneralId = Id from sExamination.tGeneralTemplateExamination where GeneralTemplateId = n_TestId      
  and SourceId = n_Exid      
        
  update #tblGeneral set g_GenId = n_GeneralId from #tblGeneralN where g_TestId = n_TestId and g_ExamId = n_Exid      
  update #tblGeneral set g_GeneralDetId = Id from sExamination.tGeneralTemplateExaminationDetail      
  where GeneralTemplateExaminationId = g_GenId and GeneralTemplateParameterId = g_ParamId      
  OPTION(RECOMPILE)      
        
  --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tGeneralTemplateExaminationDetail', 0, 1, 1,@outNextNumber = @lNextNumber output       
  --SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tGeneralTemplateExaminationDetail AS Target USING       
  (      
   SELECT Id,g_ParamId,g_GeneralDetId,g_Res,g_Rem,g_GenId,tid      
   FROM #tblGeneral TT LEFT JOIN sExamination.tGeneralTemplateExaminationDetail T ON TT.g_GeneralDetId = T.Id        
  ) AS Source ON Target.Id = Source.g_GeneralDetId      
  WHEN MATCHED THEN      
   UPDATE SET ParameterValue = [sSetup].[fPortalXMLTagsReplaceReverse](g_Res),Remark = [sSetup].[fPortalXMLTagsReplaceReverse](g_Rem)      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    GeneralTemplateExaminationId,GeneralTemplateParameterId,ParameterValue,Remark      
   )      
   VALUES      
   (      
    g_GenId,g_ParamId,[sSetup].[fPortalXMLTagsReplaceReverse](g_Res),[sSetup].[fPortalXMLTagsReplaceReverse](g_Rem)      
   );      
         
  --select @lCount = COUNT(1) FROM #tblGeneral      
  --SET @lNextNumber  = @lCount + @lFromNextNumber       
  --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tGeneralTemplateExaminationDetail', @rCurrentNumber = @lNextNumber      
        
  update #tblGeneral set g_GeneralDetId = Id from sExamination.tGeneralTemplateExaminationDetail      
  where GeneralTemplateExaminationId = g_GenId and GeneralTemplateParameterId = g_ParamId      
        
  update sExamination.tGeneralTemplateExaminationDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForGeneralN](TRD.Id,TRD.ParameterValue)      
  from sExamination.tGeneralTemplateExaminationDetail TRD inner join #tblGeneral tt on TRD.Id = tt.g_GeneralDetId      
  OPTION(RECOMPILE)      
        
  IF OBJECT_ID('tempdb..#tblExaminationGeneral') IS NOT NULL      
  begin    
 DROP TABLE #tblExaminationGeneral      
  end    
    
  create table #tblExaminationGeneral      
  (      
   tid int identity(1,1),g_ParticipantSourceId bigint,g_SetupId int,g_OrgId int,g_ExaminationId bigint      
  )      
  insert into #tblExaminationGeneral      
  select e_ParticipantSourceId,e_SetupId,e_OrgId,e_examinationid from #tbltmpExamination      
      
  select top 1 @lOrgId = g_OrgId from #tblExaminationGeneral      
   --select * from #tblExaminationGeneral     
  IF OBJECT_ID('tempdb..#tblGeneralTests') IS NOT NULL      
  DROP TABLE #tblGeneralTests      
  create table #tblGeneralTests      
  (      
   tid int identity(1,1),g_ExaminationId bigint,g_TestId int,g_ParticipantAreaId bigint,g_GeneralTemplateExaminationId bigint,      
   g_StaticId int      
  )      
  insert into #tblGeneralTests      
  select g_ExaminationId,Id,null,null,Id from #tblExaminationGeneral cross apply sExamination.tStaticGeneralTemplateMaster       
        
  update #tblGeneralTests set g_TestId = sCommon.fGetIntIdForOrg(g_TestId,@lOrgId)      
        
  update #tblGeneralTests set g_GeneralTemplateExaminationId = Id from sExamination.tGeneralTemplateExamination      
  where g_ExaminationId = SourceId and g_TestId = GeneralTemplateId      
         
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tGeneralTemplateExamination', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tGeneralTemplateExamination AS Target USING       
  (      
   SELECT Id,g_TestId,g_GeneralTemplateExaminationId,g_ExaminationId,tid as rno,      
   (      
    SELECT MAX(T.Id) FROM sExamination.tGeneralTemplateExamination t      
   ) as maxid      
   FROM #tblGeneralTests TT LEFT JOIN sExamination.tGeneralTemplateExamination T ON TT.g_GeneralTemplateExaminationId = T.Id        
  ) AS Source ON Target.Id = Source.g_GeneralTemplateExaminationId       
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],SourceId,SourceTypeId,GeneralTemplateId,OrgId      
   )      
   VALUES      
   (      
    @lFromNextNumber + rno,g_ExaminationId,1002,g_TestId,@lOrgId      
   );      
        
  select @lCount = COUNT(1) FROM #tblGeneralTests      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tGeneralTemplateExamination', @rCurrentNumber = @lNextNumber      
          
  update #tblGeneralTests set g_GeneralTemplateExaminationId = Id from sExamination.tGeneralTemplateExamination      
  where g_ExaminationId = SourceId and g_TestId = GeneralTemplateId      
        IF OBJECT_ID('tempdb..#tblGeneralParameters') IS NOT NULL      
  DROP TABLE #tblGeneralParameters       
  create table #tblGeneralParameters      
  (      
   tid int identity(1,1),p_GeneralTemplateExaminationId bigint,p_GeneralTemplateExaminationDetailId bigint,      
   p_ParameterId int,p_Result varchar(max),p_IsDefault bit      
  )      
  insert into #tblGeneralParameters      
  select distinct g_GeneralTemplateExaminationId,null,SP.Id,null,isnull(GP.IsNotDefault,0) from #tblGeneralTests cross apply #tblExaminationGeneral      
  cross apply sExamination.tStaticGeneralTemplateParameter SP inner join sExamination.tGeneralTemplateParameter GP      
  on SP.Id = GP.StaticGeneralTemplateParameterId      
  where g_StaticId = StaticGeneralTemplateId and GP.OrgId = @lOrgId and isnull(ImportCode,'') = '' --and isnull(GP.IsNotDefault,0) = 0      
          
  update #tblGeneralParameters set p_Result = Title from sExamination.tStaticGeneralTemplateParameterList      
  where p_ParameterId = StaticGeneralTemplateParameterId and IsNormal = 1      
        
  update #tblGeneralParameters set p_ParameterId = sCommon.fGetIntIdForOrg(p_ParameterId,@lOrgId)      
        
  update #tblGeneralParameters set p_GeneralTemplateExaminationDetailId = Id from sExamination.tGeneralTemplateExaminationDetail      
  where p_GeneralTemplateExaminationId = GeneralTemplateExaminationId and p_ParameterId = GeneralTemplateParameterId      
  OPTION(RECOMPILE)      
         
  --exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tGeneralTemplateExaminationDetail', 0, 1, 1,@outNextNumber = @lNextNumber output       
  --SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tGeneralTemplateExaminationDetail AS Target USING       
  (      
   SELECT Id,p_GeneralTemplateExaminationId,p_GeneralTemplateExaminationDetailId,p_Result,p_ParameterId,p_IsDefault,tid as rno,      
   (      
    SELECT MAX(T.Id) FROM sExamination.tGeneralTemplateExaminationDetail t      
   ) as maxid      
   FROM #tblGeneralParameters TT LEFT JOIN sExamination.tGeneralTemplateExaminationDetail T ON TT.p_GeneralTemplateExaminationDetailId = T.Id        
  ) AS Source ON Target.Id = Source.p_GeneralTemplateExaminationDetailId       
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    GeneralTemplateExaminationId,GeneralTemplateParameterId,ParameterValue      
   )      
   VALUES      
   (      
    p_GeneralTemplateExaminationId,p_ParameterId,      
    case when isnull(p_IsDefault,0) = 1 then '' else isnull(p_Result,'Normal') end      
   );      
        
  --select @lCount = COUNT(1) FROM #tblGeneralParameters      
  --SET @lNextNumber  = @lCount + @lFromNextNumber       
  --exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tGeneralTemplateExaminationDetail', @rCurrentNumber = @lNextNumber      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrGeneralXML,8,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>      
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tblPulmonary') IS NOT NULL      
  DROP TABLE #tblPulmonary      
      
  create table #tblPulmonary      
  (      
   tid int identity(1,1),pl_ParticipantId bigint,pl_Fvc varchar(100),pl_Fev1 varchar(100),      
   pl_PEFR varchar(100),pl_FVCP varchar(100),pl_FEV1P varchar(100),pl_FEV3P varchar(100),pl_PEFP varchar(100),      
   pl_FEF2575P varchar(100),pl_FEF212P varchar(100),pl_FEF25P varchar(100),pl_FEF50P varchar(100),pl_FEF75P varchar(100),   
   pl_Fev6 varchar(100), pl_FEV6P varchar(100),  
   pl_SVCP varchar(100),pl_ExaminationId bigint,pl_OrgId int,pl_FVCPer float,pl_FEV1Per float,pl_FVCbFEV1per float,      
   pl_PEFRper float,pl_Id bigint,pl_PartId bigint,pl_store int,pl_FEV5Ob float,pl_FEV1ByFEV5 float,pl_MVV float,pl_MVVP varchar(100),      
   pl_FEV1ByFVCObserved float,pl_MVVPer float, pl_FEV6Per float, pl_FEV6bFEV1per float, pl_FEV1ByFEV6Observed float,
   pl_PulmonaryRemark nvarchar(2000), p1_IntensityId nvarchar(100), p1_IntensityResultId nvarchar(100), p1_IsDoneManually bit
  )      
  insert into #tblPulmonary      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@FVC','varchar(100)') as FVC,      
  T.c.value('@FEV1','varchar(100)') as FEV1,      
  T.c.value('@PEFR','varchar(100)') as PEFR,      
  T.c.value('@FVCP','varchar(100)') as FVCP,      
  T.c.value('@FEV1P','varchar(100)') as FEV1P,      
  T.c.value('@FEV3P','varchar(100)') as FEV3P,      
  T.c.value('@PEFP','varchar(100)') as PEFP,      
  T.c.value('@FEF2575P','varchar(100)') as FEF2575P,      
  T.c.value('@FEF212P','varchar(100)') as FEF212P,      
  T.c.value('@FEF25P','varchar(100)') as FEF25P,      
  T.c.value('@FEF50P','varchar(100)') as FEF50P,      
  T.c.value('@FEF75P','varchar(100)') as FEF75P,      
  T.c.value('@FEV6','varchar(100)') as FEV6,  
  T.c.value('@FEV6P','varchar(100)') as FEV6P,  
  T.c.value('@SVCP','varchar(100)') as SVCP,      
  null,null,null,null,null,null,null,null,null,null,null,null,  
  T.c.value('@MVVP','varchar(100)') as MVVP,null,null,null,null,null,
  T.c.value('@PulmonaryRemark','varchar(100)') as PulmonaryRemark,
  T.c.value('@IntensityId','varchar(100)') as IntensityId,
  T.c.value('@IntensityResultId','varchar(100)') as IntensityResultId,0
  from @loXMLPulmonary.nodes('/Pulmonarys/Pulmonary')T(c)      
        
  Delete From #tblPulmonary where Isnull(pl_Fvc,'')='' and Isnull(pl_Fev1,'')='' and Isnull(pl_PEFR,'')='' and       
  Isnull(pl_FVCP,'')='' and Isnull(pl_FEV1P,'')='' and Isnull(pl_FEV3P,'')='' and Isnull(pl_PEFP,'')='' and      
  Isnull(pl_FEF2575P,'')='' and Isnull(pl_FEF212P,'')='' and Isnull(pl_FEF25P,'')='' And Isnull(pl_FEF50P,'')='' And      
  Isnull(pl_FEF75P,'')='' And Isnull(pl_SVCP,'')='' And Isnull(pl_MVVP,'')='' and Isnull(pl_Fev6,'')='' and Isnull(pl_FEV6P,'')=''
  AND Isnull(pl_PulmonaryRemark,'')='' AND Isnull(p1_IntensityId,'')='' AND Isnull(p1_IntensityResultId,'')=''
              
  update #tblPulmonary set pl_ExaminationId = e_examinationid,pl_OrgId = e_OrgId,pl_store = e_StoreLocationId      
  from #tbltmpExamination where e_ParticipantSourceId = pl_ParticipantId      
        
  update #tblPulmonary set pl_Id = Id from sExamination.tPulmonary where SourceId = pl_ExaminationId       

  update #tblPulmonary set p1_IsDoneManually = 1 from sExamination.tPulmonary where Isnull(p1_IntensityResultId,'') <> ''
        
  update #tblPulmonary set pl_FVCPer = case when isnull(pl_Fvc,'') <> '' and isnull(pl_FVCP,'') <> ''      
  and isnull(pl_Fvc,'') <> '0' and isnull(pl_FVCP,'') <> '0' then ((convert(float,pl_Fvc) * 100) / convert(float,pl_FVCP)) else null end      
        
  update #tblPulmonary set pl_FEV1Per = case when isnull(pl_Fev1,'') <> '' and isnull(pl_FEV1P,'') <> ''      
  and isnull(pl_Fev1,'') <> '0' and isnull(pl_FEV1P,'') <> '0' then ((convert(float,pl_Fev1) * 100) / convert(float,pl_FEV1P)) else null end      
        
  update #tblPulmonary set pl_FVCbFEV1per = case when isnull(pl_FEV1P,'') <> '' and isnull(pl_FVCP,'') <> ''      
  and isnull(pl_Fev1,'') <> '' and isnull(pl_Fvc,'') <> '' and isnull(pl_FEV1P,'') <> '0' and isnull(pl_FVCP,'') <> '0'      
  and isnull(pl_Fev1,'') <> '0' and isnull(pl_Fvc,'') <> '0' then      
  (((convert(float,pl_Fev1) * 100) / convert(float,pl_Fvc)) * 100 / (((convert(float,pl_FEV1P) * 100) / convert(float,pl_FVCP))))      
  else null end      
          
  update #tblPulmonary set pl_PEFRPer = case when isnull(pl_PEFR,'') <> '' and isnull(pl_PEFP,'') <> ''      
  and isnull(pl_PEFR,'') <> '0' and isnull(pl_PEFP,'') <> '0' then ((convert(float,pl_PEFR) * 100) / convert(float,pl_PEFP)) else null end      
        
  update #tblPulmonary set pl_FEV5Ob = case when isnull(pl_Fev1,'') <> '' and isnull(pl_Fev1,'') <> '0' then Convert(float,pl_Fev1) / 1.8 else null end      
      
  update #tblPulmonary set pl_FEV1ByFEV5 = case when isnull(pl_Fev1,'') <> '0' and isnull(pl_Fev1,'') <> ''      
  and isnull(pl_FEV5Ob,'') <> '0' and isnull(pl_FEV5Ob,'') <> '' then pl_Fev1 / pl_FEV5Ob else null end      
        
  update #tblPulmonary set pl_MVV = case when isnull(pl_Fev1,'') <> '0.00' and isnull(pl_Fev1,'') <> '' then (convert(float,pl_Fev1) * 35) else null end      
        
  update #tblPulmonary set pl_MVVPer = case when isnull(pl_MVV,'') <> '0.00' and isnull(pl_MVV,'') <> ''      
  and isnull(pl_MVVP,'') <> '0.00' and isnull(pl_MVVP,'') <> '' then (convert(float,pl_MVV) * 100 / convert(float,pl_MVVP)) else null end      
        
  update #tblPulmonary set pl_FEV1ByFVCObserved = case when isnull(pl_Fev1,'') <> '0.00' and isnull(pl_Fev1,'') <> ''      
  and isnull(pl_Fvc,'') <> '0.00' and isnull(pl_Fvc,'') <> '' then (convert(float,pl_Fev1) / convert(float,pl_Fvc)) else null end      
  
  update #tblPulmonary set pl_FEV6Per = case when isnull(pl_Fev6,'') <> '' and isnull(pl_FEV6P,'') <> ''      
  and isnull(pl_Fev6,'') <> '0' and isnull(pl_FEV6P,'') <> '0' then ((convert(float,pl_Fev6) * 100) / convert(float,pl_FEV6P)) else null end  
  
  update #tblPulmonary set pl_FEV6bFEV1per = case when isnull(pl_FEV1P,'') <> '' and isnull(pl_FEV6P,'') <> ''      
  and isnull(pl_Fev1,'') <> '' and isnull(pl_FEV6,'') <> '' and isnull(pl_FEV1P,'') <> '0' and isnull(pl_FEV6P,'') <> '0'      
  and isnull(pl_Fev1,'') <> '0' and isnull(pl_FEV6,'') <> '0' then      
  (((convert(float,pl_Fev1) * 100) / convert(float,pl_FEV6)) * 100 / (((convert(float,pl_FEV1P) * 100) / convert(float,pl_FEV6P))))      
  else null end  
  
  update #tblPulmonary set pl_FEV1ByFEV6Observed = case when isnull(pl_Fev1,'') <> '0.00' and isnull(pl_Fev1,'') <> ''      
  and isnull(pl_FEV6,'') <> '0.00' and isnull(pl_FEV6,'') <> '' then (convert(float,pl_Fev1) / convert(float,pl_FEV6)) else null end  
         
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tPulmonary', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
        
  MERGE sExamination.tPulmonary AS Target USING       
  (      
   SELECT Id,pl_Fvc,pl_Fev1,pl_FVCP,pl_FEV1P,pl_FEV3P,pl_PEFP,pl_FEF2575P,pl_FEF212P,pl_FEF25P,pl_FEF50P,      
   pl_FEF75P,pl_SVCP,pl_ExaminationId,pl_OrgId,pl_FVCPer,pl_FEV1Per,pl_FVCbFEV1per,pl_Id,pl_store,pl_PEFR,pl_PEFRPer,      
   pl_FEV5Ob,pl_FEV1ByFEV5,pl_MVV,pl_MVVP,pl_FEV1ByFVCObserved,tid,  
   pl_Fev6,pl_FEV6P,pl_FEV6Per,pl_FEV1ByFEV6Observed,pl_FEV6bFEV1per,pl_PulmonaryRemark, 
   p1_IntensityId, p1_IntensityResultId, p1_IsDoneManually  
   FROM #tblPulmonary TT LEFT JOIN sExamination.tPulmonary T ON TT.pl_Id = T.Id        
  ) AS Source ON Target.Id = Source.pl_Id      
  WHEN MATCHED THEN      
   UPDATE SET [FVCPredicted] = case when isnull(pl_FVCP,'') = '' then null else pl_FVCP end,      
   [FVCObserved] = case when isnull(pl_Fvc,'') = '' then null else pl_Fvc end,      
   [PerOfPredictedFVC] = pl_FVCPer,[FEV1Predicted] = case when isnull(pl_FEV1P,'') = '' then null else pl_FEV1P end,      
   [FEV1Observed] = case when isnull(pl_Fev1,'') = '' then null else pl_Fev1 end,      
   [PerOfFEV1] = pl_FEV1Per,[FEV3Predicted] = case when isnull(pl_FEV3P,'') = '' then null else pl_FEV3P end,      
   [PEFRPredicted] = case when isnull(pl_PEFP,'') = '' then null else pl_PEFP end,      
   [PerPEFR] = case when isnull(pl_PEFRPer,'') = '' then null else pl_PEFRPer end,      
   [PEFRObserved] = case when isnull(pl_PEFR,'') = '' then null else pl_PEFR end,      
   [FEF2575Predicted] = case when isnull(pl_FEF2575P,'') = '' then null else pl_FEF2575P end,      
   [FEF212Predicted] = case when isnull(pl_FEF212P,'') = '' then null else pl_FEF212P end,      
   [FEF25Predicted] = case when isnull(pl_FEF25P,'') = '' then null else pl_FEF25P end,      
   [FEF50Predicted] = case when isnull(pl_FEF50P,'') = '' then null else pl_FEF50P end,      
   [FEF75Predicted] = case when isnull(pl_FEF75P,'') = '' then null else pl_FEF75P end,      
   [PerOfFEV1ByFVC] = pl_FVCbFEV1per,SVCPredicted = case when isnull(pl_SVCP,'') = '' then null else pl_SVCP end,      
   IsDone =case when isnull(pl_Fvc,'') <> '' and isnull(pl_Fev1,'') <> '' then 1 else 0 end,      
   StoreLocationId = pl_store,FEV5Observed = pl_FEV5Ob,PerOfFEV1ByFEV5 = pl_FEV1ByFEV5,MVVObserved = pl_MVV,      
   MVVPredicted = case when isnull(pl_MVVP,'') = '' then null else pl_MVVP end,      
   Fev1ByFVCObserved = case when isnull(pl_FEV1ByFVCObserved,'') = '' then null else pl_FEV1ByFVCObserved end,  
   FEV6Observed = case when isnull(pl_Fev6,'') = '' then null else pl_Fev6 end,  
   FEV6Predicted = case when isnull(pl_FEV6P,'') = '' then null else pl_FEV6P end,  
   PerOfFEV6 = case when isnull(pl_FEV6Per,'') = '' then null else pl_FEV6Per end,  
   FEV1FEV6Observed = case when isnull(pl_FEV1ByFEV6Observed,'') = '' then null else pl_FEV1ByFEV6Observed end,  
   PerOfFEV1FEV6 = case when isnull(pl_FEV6bFEV1per,'') = '' then null else pl_FEV6bFEV1per end,
   PulmonaryRemark = case when isnull(pl_PulmonaryRemark,'') = '' then null else pl_PulmonaryRemark end,
   PulmonaryResulIntensity = case when isnull(p1_IntensityId,'') = '' then null else p1_IntensityId end,
   PulmonaryResult = case when isnull(p1_IntensityResultId,'') = '' then null else p1_IntensityResultId end,
   IsDoneManually = case when isnull(p1_IsDoneManually,0) = 0 then 0 else p1_IsDoneManually end
  WHEN NOT MATCHED THEN  
   INSERT      
   (      
    [Id],[SourceTypeId],[SourceId],[FVCPredicted],[FVCObserved],[PerOfPredictedFVC],[FEV1Predicted],[FEV1Observed],[PerOfFEV1],      
    [FEV3Predicted],[PEFRPredicted],[FEF2575Predicted],[FEF212Predicted],[FEF25Predicted],[FEF50Predicted],      
    [FEF75Predicted],[PerOfFEV1ByFVC],SVCPredicted,IsDone,StoreLocationId,PerPEFR,PEFRObserved,FEV5Observed,      
    PerOfFEV1ByFEV5,MVVObserved,MVVPredicted,Fev1ByFVCObserved,FEV6Observed,FEV6Predicted,PerOfFEV6,FEV1FEV6Observed,PerOfFEV1FEV6,
	PulmonaryRemark, PulmonaryResulIntensity, PulmonaryResult, IsDoneManually
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,1002,pl_ExaminationId,case when isnull(pl_FVCP,'') = '' then null else pl_FVCP end,      
    case when isnull(pl_Fvc,'') = '' then null else pl_Fvc end,pl_FVCPer,      
    case when isnull(pl_FEV1P,'') = '' then null else pl_FEV1P end,      
    case when isnull(pl_Fev1,'') = '' then null else pl_Fev1 end,pl_FEV1Per,      
    case when isnull(pl_FEV3P,'') = '' then null else pl_FEV3P end,      
    case when isnull(pl_PEFP,'') = '' then null else pl_PEFP end,      
    case when isnull(pl_FEF2575P,'') = '' then null else pl_FEF2575P end,      
    case when isnull(pl_FEF212P,'') = '' then null else pl_FEF212P end,      
    case when isnull(pl_FEF25P,'') = '' then null else pl_FEF25P end,      
    case when isnull(pl_FEF50P,'') = '' then null else pl_FEF50P end,      
    case when isnull(pl_FEF75P,'') = '' then null else pl_FEF75P end,pl_FVCbFEV1per,      
    case when isnull(pl_SVCP,'') = '' then null else pl_SVCP end,      
    case when isnull(pl_Fvc,'') <> '' and isnull(pl_Fev1,'') <> '' then 1 else 0 end,pl_store,      
    case when isnull(pl_PEFRPer,'') = '' then null else pl_PEFRPer end,      
    case when isnull(pl_PEFR,'') = '' then null else pl_PEFR end,      
    case when isnull(pl_FEV5Ob,'') = '' then null else pl_FEV5Ob end,      
    pl_FEV1ByFEV5,pl_MVV,case when isnull(pl_MVVP,'') = '' then null else pl_MVVP end,      
    case when isnull(pl_FEV1ByFVCObserved,'') = '' then null else pl_FEV1ByFVCObserved end,  
	case when isnull(pl_Fev6,'') = '' then null else pl_Fev6 end,  
	case when isnull(pl_FEV6P,'') = '' then null else pl_FEV6P end,  
	case when isnull(pl_FEV6Per,'') = '' then null else pl_FEV6Per end,  
	case when isnull(pl_FEV1ByFEV6Observed,'') = '' then null else pl_FEV1ByFEV6Observed end,  
	case when isnull(pl_FEV6bFEV1per,'') = '' then null else pl_FEV6bFEV1per end,
	case when isnull(pl_PulmonaryRemark,'') = '' then null else pl_PulmonaryRemark end,
	case when isnull(p1_IntensityId,'') = '' then null else p1_IntensityId end,
	case when isnull(p1_IntensityResultId,'') = '' then null else p1_IntensityResultId end,
	case when isnull(p1_IsDoneManually,0) = 0 then 0 else p1_IsDoneManually end
   );  
        
   --update w set PulmonaryResult = item1,PulmonaryResulIntensity = item2 from sExamination.tPulmonary w      
   --inner join #tblPulmonary p on p.pl_ExaminationId = w.SourceId cross apply [sExamination].[fGetPulmonaryResults_NEW](w.SourceId)      
         
   -- update by MS On 26-03-2019 For Diffranciate Adani and Click2Health      
   update w set PulmonaryResult = item1,PulmonaryResulIntensity = item2 from sExamination.tPulmonary w      
        inner join #tblPulmonary p on p.pl_ExaminationId = w.SourceId cross apply [sExamination].[fGetPulmonaryResult](w.SourceId)      
      where (isnull(p.p1_IntensityId,'') = '' and isnull(p.p1_IntensityResultId,'') = '')

  select @lCount = max(tid) FROM #tblPulmonary      
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tPulmonary', @rCurrentNumber = @lNextNumber      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrPulmonary,9,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>      
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
       
 BEGIN TRY      
  IF OBJECT_ID('tempdb..#tbltmpAudiometry') IS NOT NULL      
  DROP TABLE #tbltmpAudiometry      
      
  create table #tbltmpAudiometry      
  (      
   tid int identity(1,1),a_ParticipantSourceId bigint,a_LocationId int,a_SetupId int,      
   a_LeftAcRemarkId int,a_RightAcRemarkId int,a_By_Rule int,a_AudioLeftACIds varchar(max),a_AudioRightACIds varchar(max),      
   a_AudioLeftBCIds varchar(max),a_AudioRightBCIds varchar(max),a_ExaminationId bigint,a_ParticipantAreaId bigint,      
   a_AudiometryId bigint,a_OrgId int,a_SetupGroupId int,a_LeftManualRemark nvarchar(2000),a_RightManualRemark nvarchar(2000),
   a_LeftAcResultId int, a_LeftBcResultId int, a_RightAcResultId int, a_RightBcResultId int
  )
         
  insert into #tbltmpAudiometry      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@LocationId','int') as LocationId,      
  T.c.value('@SetupId','int') as SetupId,      
  T.c.value('@LeftAcRemarkId','int') as LeftAcRemarkId,      
  T.c.value('@RightAcRemarkId','int') as RightAcRemarkId,      
  case when T.c.value('@By_Rule','varchar(10)') = 'y' or T.c.value('@By_Rule','varchar(10)') = 'yes' or T.c.value('@By_Rule','varchar(10)') = '1' then 1 else 0 end as By_Rule,      
  T.c.value('@AudioLeftACIds','varchar(max)') as e_AudioLeftACIds,      
  T.c.value('@AudioRightACIds','varchar(max)') as AudioRightACIds,      
  T.c.value('@AudioLeftBCIds','varchar(max)') as AudioLeftBCIds,      
  T.c.value('@AudioRightBCIds','varchar(max)') as AudioRightBCIds,      
  null,null,null,null,null,
  T.c.value('@LeftManualRemark','varchar(2000)') as LeftManualRemark,
  T.c.value('@RightManualRemark','varchar(2000)') as RightManualRemark,
  T.c.value('@LeftAcResultId','int') as LeftAcResultId,
  T.c.value('@LeftBcResultId','int') as LeftBcResultId,
  T.c.value('@RightAcResultId','int') as RightAcResultId,
  T.c.value('@RightBcResultId','int') as RightBcResultId
  from @loXMLAudiometry.nodes('/Examinations/Examination')T(c)      
        
  Delete From #tbltmpAudiometry Where Isnull(a_LeftAcRemarkId,'')='' and Isnull(a_RightAcRemarkId,'')='' and Isnull(a_By_Rule,'')='' and      
  Isnull(a_AudioLeftACIds,'')='' and Isnull(a_AudioRightACIds,'')='' and Isnull(a_AudioLeftBCIds,'')='' and Isnull(a_AudioRightBCIds,'')=''
  and Isnull(a_LeftManualRemark,'')='' and Isnull(a_RightManualRemark,'')='' and Isnull(a_LeftAcResultId,'0')='0' and Isnull(a_LeftBcResultId,'0')='0'
  and Isnull(a_RightAcResultId,'0')='0' and Isnull(a_RightBcResultId,'0')='0'

  update #tbltmpAudiometry set a_ExaminationId = e_examinationid,a_OrgId = e_OrgId      
  from #tbltmpExamination where e_ParticipantSourceId = a_ParticipantSourceId      
        
  declare @lAudioAreaId int,@lConfValue int,@i int      
  select top 1 @lOrgId = e_OrgId from #tbltmpExamination    select @lAudioAreaId = Id from [sExamination].[tAreaMaster] where Title = 'Audiometry' and OrgId = @lOrgId      
  select @lAudioAreaId = isnull(@lAudioAreaId,0)       
        
  if @lAudioAreaId = 0      
  begin      
   insert into [sExamination].[tAreaMaster]      
   (      
    Id,Title,Remark,AreaTypeId,AreaGroupId,IsObsolete,PagePath,OrderIndex,ImagePath,OrgId      
   )      
   select sCommon.fGetIntIdForOrg(23,@lOrgId),'Audiometry','p',2,4,0,      
   '~/Pages/Examination/Audiometry.aspx',23,'~/Images/Icon 16x16/icon_outpatient.gif',@lOrgId      
  end      
  IF OBJECT_ID('tempdb..#tbltmpExaminationN') IS NOT NULL      
  DROP TABLE #tbltmpExaminationN      
  create table #tbltmpExaminationN      
  (      
   tid int identity(1,1),e_ParticipantSourceId bigint,e_LocationId int,e_SetupId int,      
   e_LeftAcRemarkId int,e_RightAcRemarkId int,e_By_Rule int,e_AudioLeftACIds varchar(max),e_AudioRightACIds varchar(max),      
   e_AudioLeftBCIds varchar(max),e_AudioRightBCIds varchar(max),e_ExaminationId bigint,e_ParticipantAreaId bigint,      
   e_AudiometryId bigint,e_OrgId int,e_LeftManualRemark nvarchar(2000),e_RightManualRemark nvarchar(2000),
   e_LeftAcResultId int, e_LeftBcResultId int, e_RightAcResultId int, e_RightBcResultId int      
  )      
        
  insert into #tbltmpExaminationN      
  select a_ParticipantSourceId ,a_LocationId ,a_SetupId ,      
  a_LeftAcRemarkId ,a_RightAcRemarkId ,a_By_Rule ,a_AudioLeftACIds ,a_AudioRightACIds ,      
  a_AudioLeftBCIds ,a_AudioRightBCIds ,a_ExaminationId ,a_ParticipantAreaId ,      
  a_AudiometryId ,a_OrgId, a_LeftManualRemark,a_RightManualRemark,
   a_LeftAcResultId, a_LeftBcResultId, a_RightAcResultId, a_RightBcResultId from #tbltmpAudiometry where a_ExaminationId is not null      
          
  update #tbltmpExaminationN set e_AudiometryId = Id from sExamination.tAudiometry where SourceId = e_ExaminationId      
        
         
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tAudiometry', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
          
  MERGE sExamination.tAudiometry AS Target USING       
  (      
   SELECT tid,Id,e_AudiometryId,e_ExaminationId,e_OrgId,e_LeftAcRemarkId,e_RightAcRemarkId,e_By_Rule      
   FROM #tbltmpExaminationN TT LEFT JOIN sExamination.tAudiometry T ON TT.e_AudiometryId = T.Id and e_ExaminationId is not null      
  ) AS Source ON Target.Id = Source.e_AudiometryId      
  WHEN MATCHED THEN      
   UPDATE SET IsByRuleLeft = e_By_Rule,AudiometryResultRemarkLeftId = e_LeftAcRemarkId,      
   IsByRuleRight = e_By_Rule,AudiometryResultRemarkRightId = e_RightAcRemarkId,IsDoneLeft = e_By_Rule,IsDoneRight = e_By_Rule      
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    [Id],SourceId,IsByRuleLeft,AudiometryResultRemarkLeftId,IsByRuleRight,AudiometryResultRemarkRightId,IsDoneLeft,      
    IsDoneRight,SourceTypeId,IsByExaminationLeft,IsByExaminationRight,OrgId      
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,e_ExaminationId,e_By_Rule,e_LeftAcRemarkId,e_By_Rule,e_RightAcRemarkId,e_By_Rule,e_By_Rule,1002,0,0,e_OrgId      
   );      
         
  select @lCount = max(tid) FROM #tbltmpExaminationN       
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tAudiometry', @rCurrentNumber = @lNextNumber      
        
  update #tbltmpExaminationN set e_AudiometryId = Id from sExamination.tAudiometry where SourceId = e_ExaminationId      
        
  IF OBJECT_ID('tempdb..#tbltmpAudiometryN') IS NOT NULL      
  DROP TABLE #tbltmpAudiometryN              
  create table #tbltmpAudiometryN(tid int identity(1,1),a_AudiometryId bigint,a_FreqId int,LeftAcValue varchar(100),      
  RightAcValue varchar(100),LeftBcValue varchar(100),RightBcValue varchar(100),AudiometryDetailId bigint)      
  insert into #tbltmpAudiometryN      
  select e_AudiometryId,val1,val2,null,null,null,null      
 from #tbltmpExaminationN cross apply dbo.fnc_SplitWord(e_AudioLeftACIds,'MAPSTATEPARAMKEYTWO')      
  cross apply dbo.fnc_BifurcateString(ISNULL(word,''),'MAPSTATEPARAMKEYONE') WHERE word <> '' and e_AudiometryId is not null      
          
  update #tbltmpAudiometryN set RightAcValue = val2 from #tbltmpExaminationN cross apply dbo.fnc_SplitWord(e_AudioRightACIds,'MAPSTATEPARAMKEYTWO')      
  cross apply dbo.fnc_BifurcateString(ISNULL(word,''),'MAPSTATEPARAMKEYONE')      
  where a_FreqId = val1 and word <> '' and e_AudiometryId is not null and e_AudiometryId=a_AudiometryId      
        
  update #tbltmpAudiometryN set LeftBcValue = val2 from #tbltmpExaminationN cross apply dbo.fnc_SplitWord(e_AudioLeftBCIds,'MAPSTATEPARAMKEYTWO')      
  cross apply dbo.fnc_BifurcateString(ISNULL(word,''),'MAPSTATEPARAMKEYONE')      
  where a_FreqId = val1 and word <> '' and e_AudiometryId is not null and e_AudiometryId=a_AudiometryId      
        
  update #tbltmpAudiometryN set RightBcValue = val2 from #tbltmpExaminationN cross apply dbo.fnc_SplitWord(e_AudioRightBCIds,'MAPSTATEPARAMKEYTWO')      
  cross apply dbo.fnc_BifurcateString(ISNULL(word,''),'MAPSTATEPARAMKEYONE')      
  where a_FreqId = val1 and word <> '' and e_AudiometryId is not null and e_AudiometryId=a_AudiometryId      
         
  update #tbltmpAudiometryN set AudiometryDetailId = Id from sExamination.tAudiometryDetail      
  where a_AudiometryId = AudiomentryId and a_FreqId = FrequencyId      
        
  update #tbltmpAudiometryN set LeftAcValue = null where isnull(LeftAcValue,'') = ''      
  update #tbltmpAudiometryN set RightAcValue = null where isnull(RightAcValue,'') = ''      
  update #tbltmpAudiometryN set LeftBcValue = null where isnull(LeftBcValue,'') = ''      
  update #tbltmpAudiometryN set RightBcValue = null where isnull(RightBcValue,'') = ''      
        
        
  declare @MaxAudio bigint,@lCurrentN bigint      
  select @MaxAudio = max(Id) from sExamination.tAudiometryDetail      
  select @lCurrentN = CurrentNumber from sCommon.tTableRowId where TableTitle = 'sExamination.tAudiometryDetail' and OrgId = @lOrgId      
  if @MaxAudio > @lCurrentN      
  begin      
   update sCommon.tTableRowId set CurrentNumber = @MaxAudio where TableTitle = 'sExamination.tAudiometryDetail' and OrgId = @lOrgId      
  end      
  
  Declare @lConfValueDynamic varchar(10);  
    
  select @lConfValueDynamic = Isnull(CS.ItemValue,CM.ItemValue)  
  from sConfig.tConfigurationMaster CM  
  LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id   
  where CM.ItemKey = 'Examination.AudiometryFrequency'  
         
  exec sCommon.pTableRowIdGet @lOrgId, 'sExamination.tAudiometryDetail', 0, 1, 1,@outNextNumber = @lNextNumber output       
  SET @lFromNextNumber = @lNextNumber - 1      
         
  MERGE sExamination.tAudiometryDetail AS Target USING       
  (      
   SELECT tid,Id,AudiometryDetailId,a_FreqId,LeftAcValue,RightAcValue,LeftBcValue,RightBcValue,a_AudiometryId      
   FROM #tbltmpAudiometryN TT LEFT JOIN sExamination.tAudiometryDetail T ON TT.AudiometryDetailId = T.Id      
  ) AS Source ON Target.Id = Source.AudiometryDetailId  
  WHEN MATCHED THEN  
   UPDATE SET   
    AcValueLeft = CASE WHEN @lConfValueDynamic = 'Dynamic' AND ISNULL(Source.LeftAcValue, '') = '' THEN Target.AcValueLeft ELSE Source.LeftAcValue END,  
    AcValueRight = CASE WHEN @lConfValueDynamic = 'Dynamic' AND ISNULL(Source.RightAcValue, '') = '' THEN Target.AcValueRight ELSE Source.RightAcValue END,      
    BcValueLeft = CASE WHEN @lConfValueDynamic = 'Dynamic' AND ISNULL(Source.LeftBcValue, '') = '' THEN Target.BcValueLeft ELSE Source.LeftBcValue END,  
    BcValueRight = CASE WHEN @lConfValueDynamic = 'Dynamic' AND ISNULL(Source.RightBcValue, '') = '' THEN Target.BcValueRight ELSE Source.RightBcValue END  
  WHEN NOT MATCHED THEN      
   INSERT      
   (  
    [Id],AudiomentryId,FrequencyId,AcValueLeft,BcValueLeft,AcValueRight,BcValueRight,OrgId      
   )      
   VALUES      
   (      
    @lFromNextNumber + tid,a_AudiometryId,a_FreqId,LeftAcValue,LeftBcValue,RightAcValue,RightBcValue,@lOrgId      
   );  
         
  select @lCount = max(tid) FROM #tbltmpAudiometryN       
  SET @lNextNumber  = @lCount + @lFromNextNumber       
  exec sCommon.pTableRowIdModify @lOrgId, @rTableTitle = 'sExamination.tAudiometryDetail', @rCurrentNumber = @lNextNumber      
          
  select @lConfValue = Isnull(CS.ItemValue,CM.ItemValue)       
  from sConfig.tConfigurationMaster CM      
  LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id       
  where CM.ItemKey = 'Examination.AudiometryFrequencyCount'  

  Declare @lAudiometryResultRemarkManualConf nvarchar(10);

  select @lAudiometryResultRemarkManualConf = Isnull(CS.ItemValue,CM.ItemValue)       
  from sConfig.tConfigurationMaster CM
  LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id
  where CM.ItemKey = 'Examination.IsAudiometryResultRemarkManualUpdate'
        
  select @lCount = count(1),@i = 1 from #tbltmpExaminationN      
  while @i <= @lCount      
  begin      
   declare @lAudiomentryId bigint,@lSumAcLeft int,@lSumBcLeft int,@lSumAcRight int,@lSumBcRight int      
   declare @lSumAcLeftDivide decimal(12,2),@lSumBcLeftDivide decimal(12,2),@lSumAcRightDivide decimal(12,2),@lSumBcRightDivide decimal(12,2);  
   declare @lCountAcLeft int, @lCountBcLeft int, @lCountAcRight int, @lCountBcRight int;  
  
   select @lAudiomentryId = e_AudiometryId from #tbltmpExaminationN where tid = @i;  
  
 IF @lConfValueDynamic = 'Dynamic'  
 BEGIN  
   select @lSumAcLeft = ISNULL(sum(convert(int,AcValueLeft)), 0) from sExamination.tAudiometryDetail where AudiomentryId = @lAudiomentryId and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
   select @lSumBcLeft = ISNULL(sum(convert(int,BcValueLeft)), 0) from sExamination.tAudiometryDetail where AudiomentryId = @lAudiomentryId and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
   select @lSumAcRight = ISNULL(sum(convert(int,AcValueRight)), 0) from sExamination.tAudiometryDetail where AudiomentryId = @lAudiomentryId and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
   select @lSumBcRight = ISNULL(sum(convert(int,BcValueRight)), 0) from sExamination.tAudiometryDetail where AudiomentryId = @lAudiomentryId and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
  
   select @lCountAcLeft = Count(AcValueLeft) from sExamination.tAudiometryDetail   
         where AudiomentryId = @lAudiomentryId   
         and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)   
         and (AcValueLeft != 0 and AcValueLeft is not null)  
  
   select @lCountBcLeft = Count(BcValueLeft) from sExamination.tAudiometryDetail   
         where AudiomentryId = @lAudiomentryId   
         and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
         and (BcValueLeft != 0 and BcValueLeft is not null)  
  
   select @lCountAcRight = Count(AcValueRight) from sExamination.tAudiometryDetail   
         where AudiomentryId = @lAudiomentryId   
         and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
         and (AcValueRight != 0 and AcValueRight is not null)  
  
   select @lCountBcRight = Count(BcValueRight) from sExamination.tAudiometryDetail   
         where AudiomentryId = @lAudiomentryId   
         and FrequencyId in (250,500,1000,2000,3000,4000,6000,8000)  
         and (BcValueRight != 0 and BcValueRight is not null)  
  
   select @lSumAcLeftDivide = convert(decimal(12,2),@lSumAcLeft) / convert(decimal(12,2), (Case @lCountAcLeft When 0 then 1 ELSE @lCountAcLeft END))  
   select @lSumBcLeftDivide = convert(decimal(12,2),@lSumBcLeft) / convert(decimal(12,2), (Case @lCountBcLeft When 0 then 1 ELSE @lCountBcLeft END))  
   select @lSumAcRightDivide = convert(decimal(12,2),@lSumAcRight) / convert(decimal(12,2), (Case @lCountAcRight When 0 then 1 ELSE @lCountAcRight END))  
   select @lSumBcRightDivide = convert(decimal(12,2),@lSumBcRight) / convert(decimal(12,2), (Case @lCountBcRight When 0 then 1 ELSE @lCountBcRight END))  
 END  
 ELSE  
 BEGIN  
    if @lConfValue = 3      
    begin      
  select @lSumAcLeft = sum(convert(int,LeftAcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (500,1000,2000)      
  select @lSumBcLeft = sum(convert(int,LeftBcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (500,1000,2000)      
  select @lSumAcRight = sum(convert(int,RightAcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (500,1000,2000)      
  select @lSumBcRight = sum(convert(int,RightBcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (500,1000,2000)      
    end  
    else if @lConfValue = 5  
    begin      
  select @lSumAcLeft = sum(convert(int,LeftAcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (250,500,1000,2000,4000)      
  select @lSumBcLeft = sum(convert(int,LeftBcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (250,500,1000,2000,4000)      
  select @lSumAcRight = sum(convert(int,RightAcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (250,500,1000,2000,4000)      
  select @lSumBcRight = sum(convert(int,RightBcValue)) from #tbltmpAudiometryN where a_AudiometryId = @lAudiomentryId and a_FreqId in (250,500,1000,2000,4000)      
    end      
  
    select @lSumAcLeftDivide = convert(decimal(12,2),@lSumAcLeft) / convert(decimal(12,2),@lConfValue)      
    select @lSumBcLeftDivide = convert(decimal(12,2),@lSumBcLeft) / convert(decimal(12,2),@lConfValue)      
    select @lSumAcRightDivide = convert(decimal(12,2),@lSumAcRight) / convert(decimal(12,2),@lConfValue)      
    select @lSumBcRightDivide = convert(decimal(12,2),@lSumBcRight) / convert(decimal(12,2),@lConfValue)   
    END  
     
   update sExamination.tAudiometry set AudiometryAcResultLeftId = case when @lSumAcLeftDivide = 0 then 0      
   when @lSumAcLeftDivide <= 25 then 1      
   when @lSumAcLeftDivide > 26 and @lSumAcLeftDivide <= 40 then 3      
   when @lSumAcLeftDivide > 41 and @lSumAcLeftDivide <= 55 then 4      
   when @lSumAcLeftDivide > 56 and @lSumAcLeftDivide <= 70 then 5      
   when @lSumAcLeftDivide > 71 and @lSumAcLeftDivide <= 90 then 6      
   when @lSumAcLeftDivide > 90 then 7      
   else 0 end,AudiometryBcResultLeftId = case when @lSumBcLeftDivide = 0 then 0      
   when @lSumBcLeftDivide <= 25 then 1      
   when @lSumBcLeftDivide > 26 and @lSumBcLeftDivide <= 40 then 3      
   when @lSumBcLeftDivide > 41 and @lSumBcLeftDivide <= 55 then 4      
   when @lSumBcLeftDivide > 56 and @lSumBcLeftDivide <= 70 then 5      
   when @lSumBcLeftDivide > 71 and @lSumBcLeftDivide <= 90 then 6      
   when @lSumBcLeftDivide > 90 then 7      
   else 0 end,AudiometryAcResultRightId = case when @lSumAcRightDivide = 0 then 0      
   when @lSumAcRightDivide <= 25 then 1      
   when @lSumAcRightDivide > 26 and @lSumAcRightDivide <= 40 then 3      
   when @lSumAcRightDivide > 41 and @lSumAcRightDivide <= 55 then 4      
   when @lSumAcRightDivide > 56 and @lSumAcRightDivide <= 70 then 5      
   when @lSumAcRightDivide > 71 and @lSumAcRightDivide <= 90 then 6      
   when @lSumAcRightDivide > 90 then 7      
   else 0 end,AudiometryBcResultRightId = case when @lSumBcRightDivide = 0 then 0      
   when @lSumBcRightDivide <= 25 then 1      
   when @lSumBcRightDivide > 26 and @lSumBcRightDivide <= 40 then 3      
   when @lSumBcRightDivide > 41 and @lSumBcRightDivide <= 55 then 4      
   when @lSumBcRightDivide > 56 and @lSumBcRightDivide <= 70 then 5      
   when @lSumBcRightDivide > 71 and @lSumBcRightDivide <= 90 then 6      
   when @lSumBcRightDivide > 90 then 7      
   else 0 end,AcRightDb = @lSumAcRightDivide,AcLeftDB = @lSumAcLeftDivide where Id = @lAudiomentryId      
         
   update sExamination.tAudiometry set IsDoneLeft=case when (AudiometryAcResultLeftId>0 or AudiometryBcResultLeftId>0) then 1 else 0 end       
   where Id = @lAudiomentryId      
      
   update sExamination.tAudiometry set IsDoneRight=case when (AudiometryAcResultRightId>0 or AudiometryBcResultRightId>0) then 1 else 0 end       
   where Id = @lAudiomentryId      

   IF(@lAudiometryResultRemarkManualConf = 'True')
   BEGIN
	   update AUD set AudiometryAcResultLeftId = tmp.e_LeftAcResultId, AudiometryBcResultLeftId= tmp.e_LeftBcResultId, 
	   AudiometryAcResultRightId = tmp.e_RightAcResultId, AudiometryBcResultRightId = tmp.e_RightBcResultId, 
	   LeftManualRemark = tmp.e_LeftManualRemark, RightManualRemark = tmp.e_RightManualRemark
	   FROM sExamination.tAudiometry AUD
	   INNER JOIN #tbltmpExaminationN tmp on tmp.e_AudiometryId = AUD.Id
	   where AUD.Id = @lAudiomentryId
   END

   select @i = @i + 1      
  end      
 END TRY      
 BEGIN CATCH      
  insert into tbl_ImportExaminationErrorLog      
  select @rstrAudiometry,10,'Error ' + ERROR_MESSAGE(),getdate(),@rUserId      
      
  set @exceptiondetail='<Table style="border:2px solid #ddd;margin:10px" cellpadding="0" cellspacing="0" >      
  <tr><td colspan="2" style="text-align: center;font-weight: bold;font-size:20px;padding:4px;background-color:#dadada"> :: Exception :: </td> </tr>      
  <tr><td style="width: 15%;padding:4px;font-weight: bold;border-bottom: 1px solid #ddd;border-right: 1px solid #dadada">Error Message : </td>      
  <td style="width: 85%;padding:4px;border-bottom: 1px solid #ddd">'+ ERROR_MESSAGE() +'</td></tr>      
  </Table>'      
      
  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime,CreatedUserId)      
  Select @orgid,'DBError',5000,@exceptiondetail,getdate(),@rUserId      
 END CATCH      
 select distinct e_type, case       
    when e_type=0 then 'Error In XML Generation'      
    when e_type=1 then 'Error In Importing Examination Data'      
    when e_type=2 then 'Error In Importing Vital Data'      
    when e_type=3 then 'Error In Importing Diagnosis Data'      
    when e_type=4 then 'Error In Importing Habit Data'      
    when e_type=5 then 'Error In Importing Disease Data'      
    when e_type=6 then 'Error In Importing History Data'      
    when e_type=7 then 'Error In Importing Test Data'      
    when e_type=8 then 'Error In Importing General Data'      
    when e_type=9 then 'Error In Importing Pulmonary Data'      
    when e_type=10 then 'Error In Importing Audiometry Data'      
    else 'Error In Importing Data'      
    end as e_Message      
  from tbl_ImportExaminationErrorLog where e_UserId =@rUserId and (DATEDIFF(minute,e_CreatedDate,getdate())<=5)      
      
IF OBJECT_ID('tempdb..#tbltmpExamination') IS NOT NULL DROP TABLE #tbltmpExamination;  
IF OBJECT_ID('tempdb..#tbltmpExaminationNull') IS NOT NULL DROP TABLE #tbltmpExaminationNull;  
IF OBJECT_ID('tempdb..#tbltmpVitals') IS NOT NULL DROP TABLE #tbltmpVitals;  
IF OBJECT_ID('tempdb..#tbltmpDiagnosis') IS NOT NULL DROP TABLE #tbltmpDiagnosis;  
IF OBJECT_ID('tempdb..#tbltmpHabitsNull') IS NOT NULL DROP TABLE #tbltmpHabitsNull;  
IF OBJECT_ID('tempdb..#tbltmpHabitss') IS NOT NULL DROP TABLE #tbltmpHabitss;  
IF OBJECT_ID('tempdb..#tbltmpDisease') IS NOT NULL DROP TABLE #tbltmpDisease;  
IF OBJECT_ID('tempdb..#tbltmpDiseaseNull') IS NOT NULL DROP TABLE #tbltmpDiseaseNull;  
IF OBJECT_ID('tempdb..#tbltmpDiseaseDetailsNull') IS NOT NULL DROP TABLE #tbltmpDiseaseDetailsNull;  
IF OBJECT_ID('tempdb..#tbltmpTests') IS NOT NULL DROP TABLE #tbltmpTests;  
IF OBJECT_ID('tempdb..#tblGeneral') IS NOT NULL DROP TABLE #tblGeneral;  
IF OBJECT_ID('tempdb..#tblGeneralN') IS NOT NULL DROP TABLE #tblGeneralN;  
IF OBJECT_ID('tempdb..#tblExaminationGeneral') IS NOT NULL DROP TABLE #tblExaminationGeneral;  
IF OBJECT_ID('tempdb..#tblGeneralTests') IS NOT NULL DROP TABLE #tblGeneralTests;  
IF OBJECT_ID('tempdb..#tblPulmonary') IS NOT NULL DROP TABLE #tblPulmonary;  
IF OBJECT_ID('tempdb..#tbltmpAudiometry') IS NOT NULL DROP TABLE #tbltmpAudiometry;  
IF OBJECT_ID('tempdb..#tbltmpExaminationN') IS NOT NULL DROP TABLE #tbltmpExaminationN;  
IF OBJECT_ID('tempdb..#tbltmpAudiometryN') IS NOT NULL DROP TABLE #tbltmpAudiometryN;  
IF OBJECT_ID('tempdb..#tbltmpHabitDetailsNull') IS NOT NULL DROP TABLE #tbltmpHabitDetailsNull;  
IF OBJECT_ID('tempdb..#tbltmpDiseaseN') IS NOT NULL DROP TABLE #tbltmpDiseaseN;  
IF OBJECT_ID('tempdb..#tbltmpHistorySelf') IS NOT NULL DROP TABLE #tbltmpHistorySelf;  
IF OBJECT_ID('tempdb..#tbltmpHistoryMother') IS NOT NULL DROP TABLE #tbltmpHistoryMother;  
IF OBJECT_ID('tempdb..#tbltmpHistoryFather') IS NOT NULL DROP TABLE #tbltmpHistoryFather;  
IF OBJECT_ID('tempdb..#tbltmpHistoryBrother') IS NOT NULL DROP TABLE #tbltmpHistoryBrother;  
IF OBJECT_ID('tempdb..#tbltmpHistorySister') IS NOT NULL DROP TABLE #tbltmpHistorySister;  
IF OBJECT_ID('tempdb..#tbltmpHistorySelfN') IS NOT NULL DROP TABLE #tbltmpHistorySelfN;  
IF OBJECT_ID('tempdb..#tbltmpHistoryMotherN') IS NOT NULL DROP TABLE #tbltmpHistoryMotherN;  
IF OBJECT_ID('tempdb..#tbltmpHistoryFatherN') IS NOT NULL DROP TABLE #tbltmpHistoryFatherN;  
IF OBJECT_ID('tempdb..#tbltmpHistoryBrotherN') IS NOT NULL DROP TABLE #tbltmpHistoryBrotherN;  
IF OBJECT_ID('tempdb..#tbltmpHistorySisterN') IS NOT NULL DROP TABLE #tbltmpHistorySisterN;  
  
--Drop Table #tbltmpExamination  
--Drop Table #tbltmpExaminationNull      
--Drop Table #tbltmpVitals      
--Drop Table #tbltmpDiagnosis      
--Drop Table #tbltmpHabitsNull      
--Drop Table #tbltmpHabitss      
--Drop Table #tbltmpDisease      
--Drop Table #tbltmpDiseaseNull      
--Drop Table #tbltmpDiseaseDetailsNull      
--Drop Table #tbltmpTests      
----Drop table #tbltmpTestsN      
----Drop table #tbltmpRatioN      
----Drop table #tbltmpRatio      
--Drop table #tblGeneral      
--Drop table #tblGeneralN      
--Drop table #tblExaminationGeneral      
--Drop table #tblGeneralTests      
----Drop table #tblGeneralParameters      
--Drop table #tblPulmonary      
--Drop table #tbltmpAudiometry      
--Drop table #tbltmpExaminationN      
--Drop table #tbltmpAudiometryN      
--Drop table #tbltmpHabitDetailsNull      
--Drop table #tbltmpDiseaseN      
--Drop table #tbltmpHistorySelf      
--Drop table #tbltmpHistoryMother      
--Drop table #tbltmpHistoryFather      
--Drop table #tbltmpHistoryBrother      
--Drop table #tbltmpHistorySister      
--Drop table #tbltmpHistorySelfN      
--Drop table #tbltmpHistoryMotherN      
--Drop table #tbltmpHistoryFatherN      
--Drop table #tbltmpHistoryBrotherN      
--Drop table #tbltmpHistorySisterN      
end
GO
PRINT N'Altering Procedure [sExamination].[pMISExaminationDashboardDiagnosisTrackerReport]...';


GO

ALTER PROC [sExamination].[pMISExaminationDashboardDiagnosisTrackerReport]
@rStoreLocationId int = 0,  
@rParticipantTypeId int = 0,  
@rCaseCauseId int = 0,  
@rLocationId int = 0,  
@rFunctionId int = 0,  
@rDepartmentGroupId int = 0,  
@rDepartmentId int = 0,  
@rGradeId int = 0,  
@rDesignationId int = 0,  
@rJobTitleId int = 0,  
@rCompanyId int = 0,  
@rContractorId int = 0,  
@rGenderId smallint = 0,  
@rStatusId smallint = 0,  
@rAgeFrom int = 0,  
@rAgeTo int = 100,  
@rFromDate date = NULL,  
@rToDate date = NULL,  
@rOrgId int,  
@rEmployeeCode nvarchar(50) = '',  
@rUserId bigint,  
@rSectorId bigint = 0,  
@rVerticalId bigint = 0,  
@rCompnayGroupId bigint = 0,  
@rRoundGroupId bigint,
@rRoundId bigint = 0,  
@rEmployeeTypeGoupId bigint = 0,  
@rEmployeeTypeId bigint = 0,  
@rEmployeeSubTypeId bigint = 0,  
@rTargetGroupId int = 0  
AS  
BEGIN  

	DECLARE @lExcludeExistingOrNewRecordsFromTracker varchar(5);
      
	select @lExcludeExistingOrNewRecordsFromTracker = sConfig.fConfigurationValueGet('Diagnosis.ExcludeExistingOrNewRecordsFromTracker',@rOrgId,0,0,0)

    SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)  
  
    DECLARE @TableOne TABLE (  
        tId int IDENTITY (1, 1),  
        GroupId int,  
        GroupName varchar(50)  
    )  
    DECLARE @TableHeader TABLE (  
        tId int IDENTITY (1, 1),  
        HeaderId int,  
        HeaderName varchar(50)  
    )  
    DECLARE @tExamination TABLE (  
        tId int IDENTITY (1, 1),  
        Id bigint,  
        StoreLocationId int,  
  EmployeeID bigint  
    )  
  
    INSERT INTO @tExamination (Id, StoreLocationId,EmployeeID)  
  
    SELECT EXM.Id, EXM.StoreLocationId,EMP.ID  
    FROM sExamination.tExamination AS EXM  
    INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID = EXM.SetupId  
    INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId  
    INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID = EXM.ParticipantSourceId  
    INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId = EMP.ID  
    INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id = EXM.EmployeeCompanyId  
    INNER JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id = ECM.CompanyGroupId  
    INNER JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID = CGM.VerticalId  
    INNER JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id = VTM.SectorId  
    INNER JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID = SCT.OrgId  
    INNER JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id = EXM.StoreLocationId  
    INNER JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id = SLM.LocationId  
    INNER JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id = EXM.OrganizationDepartmentId  
    INNER JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id = DPT.DepartmentGroupId  
    INNER JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id = DPG.FunctionId  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EMP.Id = EPD.EmployeeId  
    INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id  
	INNER JOIN sHrm.tEmployeeTypeMaster ETM on ETM.Id=EJD.EmployeeTypeId  
    WHERE EXM.ParticipantSourceTypeId = 95 and SLM.IsActiveHealth =1
    AND EXM.OrgId = @rOrgId  
    AND SSM.MainTypeId in (1, 2)  
    AND UL.UserId=@rUserId  
    AND ((STM.SetupGroupId = @rRoundGroupId) OR (@rRoundGroupId = 0))  
    AND ((EXM.SetupId = @rRoundId) OR (@rRoundId = 0))  
    AND ((VTM.SectorId = @rSectorId) OR (@rSectorId = 0))  
    AND ((CGM.VerticalId = @rVerticalId) OR (@rVerticalId = 0))  
    AND ((ECM.CompanyGroupId = @rCompnayGroupId) OR (@rCompnayGroupId = 0))  
    AND ((EJD.EmployeeCompanyId = @rCompanyId) OR (@rCompanyId = 0))  
    --AND ((SLM.LocationId = @rLocationId) OR (@rLocationId = 0))  
    AND ((EXM.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))  
    AND ((DPG.FunctionId = @rFunctionId) OR (@rFunctionId = 0))  
    AND ((DPT.DepartmentGroupId = @rDepartmentGroupId) OR (@rDepartmentGroupId = 0))  
    AND ((EXM.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
    AND ((EMP.Code LIKE @rEmployeeCode) OR (@rEmployeeCode = ''))  
    AND ((EXM.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate, '') = ''))  
    AND ((EXM.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate, '') = ''))  
    AND ((EPD.GenderId = @rGenderId) OR (@rGenderId = 0))  
    AND ((EXM.GradeId = @rGradeId) OR (@rGradeId = 0))  
    AND ((EXM.TargetGroupId = @rTargetGroupId) OR (@rTargetGroupId = 0))  
    AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR @rEmployeeTypeId = 0)  
    --AND ((EJD.EmployeeGroupId = @rEmployeeTypeGoupId) OR (@rEmployeeTypeGoupId = 0))  
    AND ((ETM.EmployeeTypeGroupId = @rEmployeeTypeGoupId) OR (@rEmployeeTypeGoupId = 0))  
    AND ((EJD.EmployeeSubTypeId = @rEmployeeSubTypeId) OR (@rEmployeeSubTypeId = 0))  
    order by SLM.Title  
  
    INSERT INTO @TableOne (GroupId, GroupName)  
    SELECT SLM.Id, SLM.Title  
    FROM sIp.tStoreLocationMaster AS SLM  
    WHERE SLM.id IN (SELECT StoreLocationId FROM @tExamination GROUP BY StoreLocationId)  
 ORDER BY SLM.Title  
  
  
 DECLARE @TotalExaminationCount bigint = 0  
 SELECT @TotalExaminationCount = COUNT(DISTINCT Id) FROM @tExamination  

	IF OBJECT_ID('tempdb..##tmpDiagnosis') IS NOT NULL  
	BEGIN  
	  DROP TABLE ##tmpDiagnosis  
	END
    IF OBJECT_ID('tempdb..##tempTable') IS NOT NULL  
    BEGIN  
	  DROP TABLE ##tempTable  
	END
	IF OBJECT_ID('tempdb..##tempTable1') IS NOT NULL
	BEGIN
		DROP TABLE ##tempTable1;
	END
	IF OBJECT_ID('tempdb..##tempTable2') IS NOT NULL
	BEGIN
		DROP TABLE ##tempTable2;
	END

	DECLARE @DiagnosisHeader NVARCHAR(MAX)='';

	SELECT @DiagnosisHeader =
		STUFF((
			SELECT ',' + QUOTENAME(Title)
			FROM sExamination.tDiagnosisTrackerMaster M
			INNER JOIN sExamination.tDiagnosisTrackerOrg T
				ON M.Id = T.DiagnosisTrackerId
			   AND T.OrgId = @rOrgId
			WHERE M.IsObsolete = 0
			  AND M.Id NOT IN (49,50,51)
			FOR XML PATH(''), TYPE
		).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
   
    CREATE TABLE ##tmpDiagnosis
 (  
  tId int IDENTITY (1, 1),  
  GroupId int,  
  GroupName varchar(50),
  [Tobacco] smallint,
  [Smoker] smallint,
  [Alcohol] smallint,
  [UnderWeight] smallint,  
  [OverWeight] smallint,  
  [Obese] smallint,  
  [TB] smallint,  
  [COPD] smallint,
  [NewPreHypertension] smallint, 
  [PreHypertension] smallint, 
  [NewHypertension] smallint,
  [Hypertension] smallint,
  [NewPreDiabetic] smallint,
  [Pre Diabetic] smallint,  
  [NewDiabetic] smallint,
  [Diabetic] smallint,  
  [IHD] smallint,
  [NIHLMild] smallint,  
  [NIHLModerate] smallint,  
  [NIHLSevere] smallint,  
  [XrayILO] smallint,  
  [Low Hb] smallint,  
  [Hypercholesterolemia] smallint,  
  [Borderline Cholesterol] smallint,  
  [Hypertriglyceridemia] smallint,  
  [Borderline Triglyceride] smallint,  
  [Elevated LDL] smallint,  
  [Borderline LDL] smallint,  
  [Low HDL] smallint,  
  [Elevated SGPT] smallint,  
  [High Serum Creatinine] smallint,  
  [Abnormal ECG] smallint,  
  [Abnormal TMT] smallint,  
  [Abnormal ECHO] smallint,  
  [Abnormal Sonography] smallint,  
  [ObstructivePFT] smallint,  
  [RestructivePFT] smallint,  
  [MixPFT] smallint,  
  [Mentzer Index] smallint,  
  [Abnormal XRay] smallint,  
  [Diabetic Existing] smallint,  
  [Hypertension Existing] smallint  
 )  
  
  
    INSERT INTO ##tmpDiagnosis
        SELECT t.GroupId, t.GroupName, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.Tobacco = 1)  
        Tobacco, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.Smoker = 1)  
        Smoker, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.Alcohol = 1)  
        Alcohol, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.BMI = 'Underweight')  
        UnderWeight, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.BMI = 'Overweight')  
        OverWeight, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.BMI = 'Obese')  
        Obese, (SELECT  
          COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
 WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.TB = 1)  
        TB, (SELECT  
            COUNT(0)
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.COPD = 1)  
        COPD, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.IsNewHypertensionStatus = 1)
        NewPreHypertension, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.BloodPressure = 'PreHypertension'
		AND ((@lExcludeExistingOrNewRecordsFromTracker = 'False') 
		    OR (@lExcludeExistingOrNewRecordsFromTracker = 'True' 
			AND (DTE.HypertensionExisting <> 'Hypertension Existing' OR DTE.HypertensionExisting IS NULL) AND ISNULL(DTE.IsNewHypertensionStatus,0) <> 1)))
        PreHypertension, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.IsNewHypertensionStatus = 2)
        NewHypertension, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId
        AND DTE.BloodPressure = 'Hypertension'
        AND ((@lExcludeExistingOrNewRecordsFromTracker = 'False') 
		    OR (@lExcludeExistingOrNewRecordsFromTracker = 'True' 
			AND (DTE.HypertensionExisting <> 'Hypertension Existing' OR DTE.HypertensionExisting IS NULL) AND ISNULL(DTE.IsNewHypertensionStatus,0) <> 2)))
        Hypertension, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId
        AND DTE.IsNewDiabeticStatus = 1)
        NewPreDiabetic, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId
        AND DTE.FBS = 'Pre Diabetic'
		AND ((@lExcludeExistingOrNewRecordsFromTracker = 'False') 
		    OR (@lExcludeExistingOrNewRecordsFromTracker = 'True' 
			AND (DTE.DiabeticExisting <> 'Diabetic Existing' OR DTE.DiabeticExisting IS NULL) AND ISNULL(DTE.IsNewDiabeticStatus,0) <> 1)))
        PreDiabatic, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId
        AND DTE.IsNewDiabeticStatus = 2)
        NewDiabetic, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.FBS = 'Diabetic'
		AND ((@lExcludeExistingOrNewRecordsFromTracker = 'False') 
		    OR (@lExcludeExistingOrNewRecordsFromTracker = 'True' 
			AND (DTE.DiabeticExisting <> 'Diabetic Existing' OR DTE.DiabeticExisting IS NULL) AND ISNULL(DTE.IsNewDiabeticStatus,0) <> 2)))
        Diabatic, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.IHD = 1)  
        IHD, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.AudiometryACRight = 'Mild hearing loss')  
        NIHLMild, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.AudiometryACRight = 'Moderate hearing loss')  
        NIHLModerate, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.AudiometryACRight = 'Severe hearing loss')  
        NIHLSevere,  
        (0) XrayILO,  
        (  
  SELECT COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.HB = 'Low Hb') [Low Hb], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.Cholesterol = 'Hypercholesterolemia')  
        [Cholesterol High], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.Cholesterol = 'Borderline Cholesterol')  
        [Cholesterol Borderline], (SELECT  
      COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.Triglyceride = 'Hypertriglyceridemia')  
        [Triglyceride High], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
   INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.Triglyceride = 'Borderline Triglyceride')  
        [Triglyceride Borderline], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.LDL = 'Elevated  LDL')  
        [LDL High], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.LDL = 'Borderline LDL')  
        [LDL Borderline], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.HDL = 'Low HDL')  
        [HDL Low], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.SGPT = 'Elevated SGPT')  
        [SGPT High], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.SerumCreatinine = 'High Serum Creatinine')  
        [High Serum Creatinine], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.ECG = 'ECG Abnormal')  
        [Abnormal ECG], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.TMT = 'TMT Abnormal')  
        [Abnormal TMT], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.ECHO = 'ECHO Abnormal')  
        [Abnormal ECHO], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.Sonography = 'Sonography Abnormal')  
        [Abnormal Sonography], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        --AND DTE.PFT = 'Obstructive Lung Disease' Mentis issue no:8825  
  AND DTE.PFT like '%Obstructive Pattern%')  
        [ObstructivePFT], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        --AND DTE.PFT = 'Restrictive Lung Disease' Mentis issue no:8825  
  AND DTE.PFT like '%Restrictive Pattern%')  
        [RestructivePFT], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        --AND DTE.PFT = 'Mix Lung Disease' Mentis issue no:8825  
  AND DTE.PFT like '%Mix Pattern%')  
        [MixPFT], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.MenzerIndex = 'Mentzer < 13')  
        [Mentzer Index], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
         ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.AbnormalXRay = '1')  
        [Abnormal XRay], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.DiabeticExisting = 'Diabetic Existing')  
        [Diabetic Existing], (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND DTE.HypertensionExisting = 'Hypertension Existing')  
        [Hypertension Existing]  
  
        FROM @TableOne t  
        ORDER BY 1  

	DECLARE @FinalDiagnosisHeader NVARCHAR(MAX);

	;WITH HeaderCTE AS
	(
		SELECT
			LTRIM(RTRIM(T.C.value('.', 'SYSNAME'))) AS ColumnName,
			REPLACE(LTRIM(RTRIM(T.C.value('.', 'SYSNAME'))), ' ', '') AS NormalizedName
		FROM (
			SELECT CAST(
				'<x>' + REPLACE(
							REPLACE(
								REPLACE(@DiagnosisHeader, '[', ''),
								']', ''
							),
							',', '</x><x>'
					   ) + '</x>' AS XML
			) AS XmlCol
		) A
		CROSS APPLY XmlCol.nodes('/x') T(C)
	)
	SELECT @FinalDiagnosisHeader =
	STUFF((
		SELECT ',' + QUOTENAME(c.name)
		FROM tempdb.sys.columns c
		INNER JOIN tempdb.sys.objects o
			ON c.object_id = o.object_id
		INNER JOIN HeaderCTE h
			ON REPLACE(c.name, ' ', '') = h.NormalizedName
		WHERE o.name LIKE '##tmpDiagnosis%'
		FOR XML PATH(''), TYPE
	).value('.', 'NVARCHAR(MAX)'), 1, 1, '');

	DECLARE @CreateSQL NVARCHAR(MAX);

	SET @CreateSQL = N'
	IF OBJECT_ID(''tempdb..##tempTable1'') IS NOT NULL
		DROP TABLE ##tempTable1;

	CREATE TABLE ##tempTable1
	(
		GroupId INT,' + REPLACE(@FinalDiagnosisHeader, ',', ' SMALLINT,') + ' SMALLINT
	);
	';

	EXEC sp_executesql @CreateSQL;

	DECLARE @DiagnosisSQL NVARCHAR(MAX);

	SET @DiagnosisSQL = N'
	INSERT INTO ##tempTable1 (GroupId, ' + @FinalDiagnosisHeader + ')
	SELECT GroupId, ' + @FinalDiagnosisHeader + '
	FROM ##tmpDiagnosis;
	';

	EXEC sp_executesql @DiagnosisSQL;
  
	 CREATE TABLE ##tempTable2   
	 (  
	  tId int IDENTITY (1, 1),  
	  GroupId int,  
	  GroupName varchar(50),
	  [Non-Tobacco] smallint,
	  [Non-Smoker] smallint,
	  [Non-Alcohol] smallint,
	  [NormalBMI] smallint,  
	  [NormalBP] smallint,
	  [NormalBloodSugar] smallint
	 )

	INSERT INTO ##tempTable2
        SELECT t.GroupId, t.GroupName, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND ISNULL(DTE.Tobacco, 0) = 0)  
        'Non-Tobacco', (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND ISNULL(DTE.Smoker,0) = 0)  
        'Non-Smoker', (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId  
        AND ISNULL(DTE.Alcohol,0) = 0)  
        'Non-Alcohol', (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE  
            ON DTE.ExaminationId = EXM.Id  
		INNER JOIN sExamination.tVital VIT ON VIT.SourceId = EXM.Id
        WHERE EXM.StoreLocationId = t.GroupId AND ISNULL(VIT.BMI, '0.00') <> '0.00'
        AND DTE.BMI = 'Normal')
        NormalBMI, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
            ON DTE.ExaminationId = EXM.Id  
		INNER JOIN sExamination.tVital VIT ON VIT.SourceId = EXM.Id
        WHERE EXM.StoreLocationId = t.GroupId AND ISNULL(VIT.BloodPressureSystolic, '') <> '' AND ISNULL(VIT.BloodPressureDiastolic, '') <> ''
        AND DTE.BloodPressure = '')
        NormalBP, (SELECT  
            COUNT(0)  
        FROM @tExamination AS EXM  
        INNER JOIN sExamination.tDiagnosisTrackerEmployee AS DTE
            ON DTE.ExaminationId = EXM.Id  
        WHERE EXM.StoreLocationId = t.GroupId
        AND DTE.FBS = 'Normal')
		NormalBloodSugar
  
        FROM @TableOne t  
        ORDER BY 1

		DECLARE @T1Columns NVARCHAR(MAX);

		SELECT @T1Columns =
		STUFF((
			SELECT ', t1.' + QUOTENAME(c.name)
			FROM tempdb.sys.columns c
			JOIN tempdb.sys.objects o
				ON c.object_id = o.object_id
			WHERE o.name LIKE '##tempTable1%'
			  AND c.column_id > 1      -- removes FIRST column (GroupId)
			ORDER BY c.column_id
			FOR XML PATH(''), TYPE
		).value('.', 'NVARCHAR(MAX)'), 1, 2, '');

		DECLARE @SQL NVARCHAR(MAX);

		SET @SQL = N'
		SELECT
			t2.GroupId,
			t2.[Non-Alcohol],
			t2.[Non-Smoker],
			t2.[Non-Tobacco],
			t2.NormalBMI,
			t2.NormalBP,
			t2.NormalBloodSugar,
			' + @T1Columns + '
		INTO ##tempTable
		FROM ##tempTable1 t1
		JOIN ##tempTable2 t2
			ON t1.GroupId = t2.GroupId;
		';

		EXEC sp_executesql @SQL;
  
    DECLARE @columns nvarchar(max) = ''  
    DECLARE @Header nvarchar(max) = ''  
  
  
    DECLARE @sqlStatement nvarchar(max) = ''  
  
    IF OBJECT_ID('tempdb..#tblTmp') IS NOT NULL  
        DROP TABLE #tblTmp  
  
    CREATE TABLE #tblTmp (  
        tid int IDENTITY (1, 1),  
        id int,  
        title varchar(200),  
        TotalCount int,  
  OriginalName NVARCHAR(MAX)  
    )  
  
 INSERT INTO #tblTmp  
 SELECT column_id,'['+ name+']', 0,name  
 FROM   tempdb.sys.columns  
 WHERE  object_id = Object_id('tempdb..##tempTable') AND column_id NOT IN (1)  
    
  
  --SELECT * FROM #tblTmp  
  --SELECT * FROM ##tempTable  
   
  
 DECLARE @colscnt int  
    SELECT @colscnt = COUNT(0) FROM #tblTmp  
  
 DECLARE @ColIncr int = 1  
    IF (@colscnt > 0)  
    BEGIN  
        WHILE @ColIncr <= @colscnt  
        BEGIN  
            DECLARE @ColName2 varchar(200) = '', @quer1 varchar(max)  
  
            SELECT @ColName2 = title  
            FROM #tblTmp  
            WHERE tid = @ColIncr  
  
            SELECT @quer1 = 'update #tblTmp set TotalCount = (select isnull(sum(' + @ColName2 + '),0) from ##tempTable) where title = ''' + @ColName2 + ''''  
   print @quer1  
            EXEC (@quer1)  
  
            SELECT @ColIncr = @ColIncr + 1  
        END  
    END  
 IF OBJECT_ID('tempdb..#temp_GroupingWithPercentage') IS NOT NULL  
    BEGIN  
  DROP TABLE #temp_GroupingWithPercentage  
 END  
 IF OBJECT_ID('tempdb..#temp_EmployeeDetails') IS NOT NULL  
    BEGIN  
  DROP TABLE #temp_EmployeeDetails  
 END  
  
 IF OBJECT_ID('tempdb..#temp_EmployeeDemographicsDetails') IS NOT NULL  
    BEGIN  
  DROP TABLE #temp_EmployeeDemographicsDetails  
 END  
  
 IF OBJECT_ID('tempdb..#temp_EmployeeAgeGrouping') IS NOT NULL  
    BEGIN  
  DROP TABLE #temp_EmployeeAgeGrouping  
 END  
    
 CREATE TABLE #temp_EmployeeDemographicsDetails  
 (  
  Lable NVARCHAR(MAX),  
  Percentage decimal(18,2),  
  GroupingWise NVARCHAR(MAX)  
 )
  
 SELECT id,  
     CASE WHEN OriginalName IN ('Hypercholesterolemia','Borderline Cholesterol','Hypertriglyceridemia','Borderline Triglyceride','Elevated LDL','Borderline LDL','Low HDL') THEN 'Lipid'  
    WHEN OriginalName IN ('Non-Tobacco','Tobacco','Non-Smoker','Smoker','Non-Alcohol','Alcohol') THEN 'Habit'  
    WHEN OriginalName IN ('NormalBMI','UnderWeight','OverWeight','Obese') THEN 'BMI'  
    WHEN OriginalName IN ('IHD','XrayILO','Elevated SGPT','High Serum Creatinine','Abnormal Sonography','Mentzer Index','Abnormal XRay') THEN 'Other Diagnosis'  
    WHEN OriginalName IN ('NormalBP','NewPreHypertension','PreHypertension','NewHypertension','Hypertension','Hypertension Existing') THEN 'Blood Pressure'  
    WHEN OriginalName IN ('NormalBloodSugar', 'NewPreDiabetic', 'Pre Diabetic', 'NewDiabetic', 'Diabetic','Diabetic Existing') THEN 'Blood Sugar'  
    WHEN OriginalName IN ('ObstructivePFT','RestructivePFT','MixPFT') THEN 'Pulmonary'
    WHEN OriginalName IN ('Abnormal ECG','Abnormal TMT','Abnormal ECHO') THEN 'ECG/TMT/ECHO'  
    WHEN OriginalName IN ('NIHLMild','NIHLModerate','NIHLSevere') THEN 'Audiometry'  
    WHEN OriginalName IN ('Low Hb') THEN 'CBC'  
    WHEN OriginalName IN ('TB','COPD') THEN 'Life Style Disease' END 'MainTitle',
     CASE 
        WHEN OriginalName LIKE 'Normal%' THEN 'Normal'
        ELSE OriginalName
    END AS OriginalName,  
     TotalCount,  
     CAST(CASE WHEN @TotalExaminationCount = 0 THEN 0.00 -- Ensure a decimal value for division by zero  
        ELSE (CAST(TotalCount AS decimal(18, 2)) * 100 / @TotalExaminationCount)  
    END AS decimal(18, 2)  
) AS 'Percentage'  
     INTO #temp_GroupingWithPercentage  
    FROM #tblTmp  
  
  
 ------------ START Table 1 Return -------------  
 SELECT * FROM #temp_GroupingWithPercentage  

 ------------ END Table 1 Return -------------  
------------ START Table 2 Return -------------
SELECT 
    'Main_' + CAST(Row_Number() OVER (ORDER BY (SELECT 1)) AS nvarchar(max)) AS ID, 
    MainTitle,
    CAST(CASE WHEN MainTitle IN ('BMI', 'Blood Pressure', 'Blood Sugar') THEN SUM(Percentage) 
	     ELSE AVG(Percentage) END AS decimal(18, 2)
    ) AS Percentage, @TotalExaminationCount as ExaminationCount
FROM 
    #temp_GroupingWithPercentage   
Where OriginalName NOT IN ('Normal')
AND OriginalName Not Like 'NON-%'
GROUP BY 
    MainTitle
------------ END Table 2 Return -------------

  
  
 ------------ START Table 3 Return -------------  
 CREATE TABLE #temp_EmployeeAgeGrouping   
 (  
  Lable NVARCHAR(MAX),  
  FromValue int,  
  ToValue int  
 )  
  
 INSERT INTO #temp_EmployeeAgeGrouping   
 SELECT Title,AgeFrom,AgeTo FROM  sCommon.tAgeGroupMaster WHERE OrgId = @rOrgId  
  
  
 SELECT  
  DISTINCT  
  EM.Id 'EmployeeID',   
  EPD.GenderId,  
  GM.Title 'GenderTitle',  
  EPD.DateOfBirth,  
  CONVERT(int,ROUND(DATEDIFF(hour,EPD.DateOfBirth,GETDATE())/8766.0,0)) 'EmployeeAge',  
  NM.Id 'NationalityID',  
  NM.Title 'NationalityLabel'  
  INTO #temp_EmployeeDetails  
 FROM sHrm.tEmployeeMaster EM   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId   
 INNER JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId  
 LEFT JOIN sHrm.tNationalityMaster NM ON NM.Id = EPD.NationalityId AND ISNULL(NM.IsObsolete,0) = 0  
 WHERE EM.OrgId = @rOrgId AND EM.Id IN (SELECT DISTINCT EmployeeID FROM @tExamination)  
  
   
 INSERT INTO #temp_EmployeeDemographicsDetails  
 SELECT GenderTitle,  
    CAST(CAST(COUNT(EmployeeID) as DECIMAL(18,2)) * 100/ SUM(CAST(COUNT(GenderTitle) as decimal(18,2))) OVER() as decimal(18,2)) 'Percentage',  
    'GenderWise'  
 FROM #temp_EmployeeDetails   
 GROUP BY GenderTitle,GenderId  
 ORDER BY GenderId  
  
 INSERT INTO #temp_EmployeeDemographicsDetails  
 SELECT   
  EAG.Lable,  
  CAST(CAST(COUNT(ED.EmployeeID) as DECIMAL(18,2)) * 100/ SUM(CAST(COUNT(EAG.Lable) as decimal(18,2))) OVER() as decimal(18,2)) 'Percentage',  
  'AgeWise'  
 FROM #temp_EmployeeDetails ED  
 INNER JOIN  #temp_EmployeeAgeGrouping EAG ON ED.EmployeeAge BETWEEN EAG.FromValue AND EAG.ToValue  
 GROUP BY EAG.Lable  
  
  
 INSERT INTO #temp_EmployeeDemographicsDetails  
 SELECT   
  ED.NationalityLabel,  
  CAST(CAST(COUNT(ED.EmployeeID) as DECIMAL(18,2)) * 100/ SUM(CAST(COUNT(ED.NationalityLabel) as decimal(18,2))) OVER() as decimal(18,2)) 'Percentage',  
  'NationalityWise'  
 FROM #temp_EmployeeDetails ED   
 WHERE ISNULL(ED.NationalityID,0) != 0  
 GROUP BY ED.NationalityLabel  
  
 SELECT * FROM #temp_EmployeeDemographicsDetails  
 ------------ END Table 3 Return -------------  

IF OBJECT_ID('tempdb..##tmpDiagnosis') IS NOT NULL  
BEGIN  
  DROP TABLE ##tmpDiagnosis  
END
IF OBJECT_ID('tempdb..##tempTable') IS NOT NULL  
BEGIN  
  DROP TABLE ##tempTable  
END
IF OBJECT_ID('tempdb..##tempTable1') IS NOT NULL  
BEGIN  
  DROP TABLE ##tempTable1  
END
IF OBJECT_ID('tempdb..##tempTable2') IS NOT NULL  
BEGIN  
  DROP TABLE ##tempTable2 
END
 
 IF OBJECT_ID('tempdb..#temp_GroupingWithPercentage') IS NOT NULL  
BEGIN  
  DROP TABLE #temp_GroupingWithPercentage  
 END  
  
 IF OBJECT_ID('tempdb..#temp_EmployeeDetails') IS NOT NULL  
BEGIN  
  DROP TABLE #temp_EmployeeDetails  
END  
  
 IF OBJECT_ID('tempdb..#temp_EmployeeDemographicsDetails') IS NOT NULL  
BEGIN  
  DROP TABLE #temp_EmployeeDemographicsDetails  
END  
  
 IF OBJECT_ID('tempdb..#temp_EmployeeAgeGrouping') IS NOT NULL  
BEGIN  
  DROP TABLE #temp_EmployeeAgeGrouping  
END  
  
  
END
GO
PRINT N'Altering Procedure [sExamination].[prc_GetHealthAnalysisEmployeeExportWithMail]...';


GO

ALTER  PROC [sExamination].[prc_GetHealthAnalysisEmployeeExportWithMail]      
  @rMaINTypeId INT,      
  @rOrgId INT,      
  @rSetupGroupId INT,      
  @rSetupId INT,      
  @rSectorId INT,      
  @rVerticalId INT,      
  @rCompanyGroupId INT,      
  @rEmployeeCompanyId INT,      
  @rLocationMainGroupId INT,      
  @rLocationSubGroupId INT,      
  @rLocationId INT,      
  @rStoreLocationId INT,      
  @rFunctionId INT,      
  @rDepartmentGroupId INT,      
  @rDepartmentId INT,      
  @PageIndex INT,      
  @rEmployeeCode VARCHAR(100),      
  @rEmployeeFname VARCHAR(100),      
  @rEmployeeLname VARCHAR(100),      
  @rFromPercentage DEcimal(10,2),      
  @rToPercentage DEcimal(10,2),      
  @rHealthIndexParameterId NVARCHAR(MAX),      
  @rUserId bigint,      
  @rFromDate varchar(100) = '',      
  @rToDate varchar(100) = '',      
  @rGenderId int = 0,      
  @rGradeId int = 0,      
  @rEmployeeTypeGoupId int = 0,      
  @rEmployeeTypeId int = 0,      
  @rEmployeeSubTypeId int = 0,      
      
      
  @SortColumnName NVARCHAR(MAX)= '',      
  @IsAscendingOrder bit= 0,      
  @PageNumber int = 1,      
 
  @GlobalSearch NVARCHAR(MAX)= ''      
AS      
BEGIN      
      
 IF(@rToDate='')      
 BEGIN      
  SET @rToDate='01/06/2050'      
 END      
      
    DECLARE @GeneralCols varchar(max) = '', @GeneralCols1 varchar(max) = '', @lQueryExisting varchar(max), @GeneralCols2 varchar(max)      
    SELECT @GeneralCols = STUFF((SELECT      
        ',' + QUOTENAME(sCommon.fGetIntIdForOrg(Id, @rOrgId))      
    FROM sExamination.tStaticHealthIndexParameterMaster      
    WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 22, 23, 24, 25, 26)      
    ORDER BY Id      
    FOR xml PATH (''), TYPE)      
    .value('.', 'NVARCHAR(MAX)'), 1, 1, '')      
      
      
 print '1'      
      
    SELECT @GeneralCols1 = STUFF((SELECT      
        ',' + QUOTENAME(Code) + ' varchar(300)'      
    FROM sExamination.tStaticHealthIndexParameterMaster      
    WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 22, 23, 24, 25, 26)      
    ORDER BY Id      
    FOR xml PATH (''), TYPE)      
    .value('.', 'NVARCHAR(MAX)'), 1, 1, '')      
      
      
 print '1'      
      
    SELECT @GeneralCols2 = STUFF((SELECT      
        ',' + QUOTENAME(Code)      
    FROM sExamination.tStaticHealthIndexParameterMaster      
    WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 22, 23, 24, 25, 26)      
    ORDER BY Id      
    FOR xml PATH (''), TYPE)      
    .value('.', 'NVARCHAR(MAX)'), 1, 1, '')      
      
       
     DECLARE @Header nvarchar(max) = 'Code{#####}Name{#####}Grade'    
    DECLARE @rHealthIndexGroupId NVARCHAR(20) = N'2'--Health Index Group -Non Executive   
    --SELECT @Header = @Header + '{#####}' + code      
    --FROM sExamination.tStaticHealthIndexParameterMaster      
    --WHERE Id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 22, 23, 24, 25, 26)      
    --ORDER BY Id    
  
       SELECT @Header = @Header + '{#####}' + hpm.Code  
       FROM sExamination.tStaticHealthIndexParameterMaster AS hpm  
       JOIN sExamination.tHealthIndexGroupParameter AS hig  
           ON hig.HealthIndexParameterId = hpm.Id  
           AND ISNULL(hig.RoundGroupId, 0) = @rSetupGroupId  
           AND hig.HealthIndexGroupId = @rHealthIndexGroupId  
       WHERE hpm.Id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 22, 23, 24, 25, 26)  
       ORDER BY hpm.Id;  
  
           
      
    IF OBJECT_ID('tempdb..#tblExamination') IS NOT NULL      
        DROP TABLE #tblExamination      
      
      
    CREATE TABLE #tblExamination (tid int IDENTITY (1, 1),ExaminationId bigint,EarnedPoints int,HealthIndexParameterId int,Code varchar(100))      
      
    INSERT INTO #tblExamination      
        SELECT H.ExaminationId, EarnedPoints, HealthIndexParameterId, HM.Code      
        FROM sExamination.tHealthIndexPartial H      
        INNER JOIN sExamination.tHealthIndexParameterMaster HM ON H.HealthIndexParameterId = HM.Id      
        INNER JOIN sExamination.tStaticHealthIndexParameterMaster AS s ON s.Id = hm.StaticHealthIndexParameterId      
        INNER JOIN sExamination.tExamination AS EXM ON H.ExaminationId = EXM.Id      
        INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID = EXM.SetupId      
        INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id = STM.SetupGroupId      
        INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId      
        INNER JOIN sExamination.tDiagnosisPartial AS DIA ON EXM.Id = DIA.ExaminationId      
        INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId      
 INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID      
 INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD on EMP.Id = EPD.EmployeeId       
 LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=EXM.EmployeeCompanyId      
 LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId      
 LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId      
 LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId      
 LEFT JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId      
 LEFT JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId      
 LEFT JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId      
 LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId      
 LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId      
 LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId      
 LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId      
 LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId      
 LEFT JOIN sHrm.tGradeMaster GRD on EJD.GradeId = GRD.Id      
 INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId      
       
        WHERE EXM.ParticipantSourceTypeId=95 AND EXM.OrgId=@rOrgId      
 AND SSM.MaINTypeId=@rMaINTypeId       
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))      
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))      
 AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))      
 AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))      
       
 AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))      
 AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))      
 AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))      
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))      
 AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))      
 AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))      
 AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))      
 AND ((EMP.Code LIKE @rEmployeeCode) OR (@rEmployeeCode  = ''))      
 AND ((EMP.FirstName LIKE @rEmployeeFname)  OR  (@rEmployeeFname = ''))      
 AND ((EMP.LastName  LIKE @rEmployeeLname)  OR  (@rEmployeeLname = ''))      
       
 AND ((LSG.Id=@rLocationSubGroupId ) OR (@rLocationSubGroupId  = 0 ))      
 AND ((LMG.Id=@rLocationMainGroupId) OR (@rLocationMainGroupId = 0 ))      
 AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)  -- Nidhi Pandey; Mantis id = 22911, DT - 16/01/2023      
 AND UL.UserId = @rUserId       
        AND s.Id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 22, 23, 24, 25, 26)      
      
      
    IF OBJECT_ID('tempdb..##tblMainTable_New') IS NOT NULL      
        DROP TABLE ##tblMainTable_New      
      
    SELECT @lQueryExisting = 'create table ##tblMainTable_New(tid int identity(1,1),d_ExamId bigint,' + @GeneralCols1 + ')'      
    EXEC (@lQueryExisting)      
      
    SELECT @lQueryExisting = '      
    insert into ##tblMainTable_New       
 select ExaminationId,' + @GeneralCols2 + '      
 from      
 (      
  select ExaminationId,EarnedPoints,Code from #tblExamination      
 ) src       
 pivot      
 (      
   max(EarnedPoints) for Code in (' + @GeneralCols2 + ')      
 ) piv;'      
      
     
    EXEC (@lQueryExisting)      
      
	   IF OBJECT_ID('tempdb..#tblMainData') IS NOT NULL      
        DROP TABLE #tblMainData

 CREATE TABLE #tblMainData(
    Code NVARCHAR(100),
    Name NVARCHAR(200),
    Grade NVARCHAR(100),    
    BMI NVARCHAR(100),
    [FBS] NVARCHAR(100),
    [CHOLESTEROL] NVARCHAR(100),
    [TRIGLYCERIDE] NVARCHAR(100),
    [LDL] NVARCHAR(100),
    [HDL] NVARCHAR(100),
    [SGPT] NVARCHAR(100),
    [SERUM CREATININE] NVARCHAR(100),
    [PSA] NVARCHAR(100),
    [URIC ACID] NVARCHAR(100),
    [SONOGRAPHY] NVARCHAR(100),
    [ECHO] NVARCHAR(100),
    [ECG] NVARCHAR(100),
    [TMT] NVARCHAR(100),
    [Habit] NVARCHAR(100),
    [Existing Disease] NVARCHAR(100),
    [Blood Pressure Diastolic] NVARCHAR(100),
    [Blood Pressure Systolic] NVARCHAR(100),
    [Waist Circumference] NVARCHAR(100),
    [HB] NVARCHAR(100),
    [Audiometry] NVARCHAR(100),
    [Pulmonary] NVARCHAR(100)
);

DECLARE @FinalSelectColumns NVARCHAR(MAX);

SELECT @FinalSelectColumns = 
    STUFF((
        SELECT ',' +
            'ISNULL(' 
            + QUOTENAME(LTRIM(RTRIM(CASE WHEN item = 'F B S' THEN 'FBS' ELSE item END))) 
            + ', '''') AS ' 
            + QUOTENAME(LTRIM(RTRIM(CASE WHEN item = 'F B S' THEN 'FBS' ELSE item END)))
        FROM [sCommon].[fnSplit](@Header, '{#####}')
        WHERE LTRIM(RTRIM(item)) <> ''
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 1, '');   

    
	INSERT INTO #tblMainData (
    Code, Name, Grade,
    BMI,[FBS],[CHOLESTEROL],[TRIGLYCERIDE],[LDL],[HDL],[SGPT],[SERUM CREATININE],
    [PSA],[URIC ACID],[SONOGRAPHY],[ECHO],[ECG],[TMT],[Habit],[Existing Disease],
    [Blood Pressure Diastolic],[Blood Pressure Systolic],[Waist Circumference],
    [HB],[Audiometry],[Pulmonary]
)   
	SELECT      
  UPPER(ISNULL(EMP.Code, '')) COLLATE Latin1_General_CI_AI 'Code' ,      
  ISNULL(EMP.FirstName, '') + ' ' + ISNULL(EMP.LastName, '') 'Name',      
  ISNULL(GRD.Title,'') 'Grade',      
  ISNULL(m.[BMI], '') 'BMI',      
  ISNULL(m.[F B S], '') 'FBS',      
  ISNULL(m.[CHOLESTEROL], '') 'Cholesterol',      
  ISNULL(m.[TRIGLYCERIDE], '') 'Triglyceride',      
  ISNULL(m.[LDL], '') 'LDL',      
  ISNULL(m.[HDL], '') 'HDL',      
  ISNULL(m.[SGPT], '') 'SGPT',      
  ISNULL(m.[SERUM CREATININE], '') 'SerumCreatinine',  
  ISNULL(m.[PSA], '') 'PSA',  
  ISNULL(m.[URIC ACID], '') 'UricAcid',      
  ISNULL(m.[SONOGRAPHY], '') 'Sonography',      
  ISNULL(m.[ECHO], '') 'ECHO',      
  ISNULL(m.[ECG], '') 'ECG',      
  ISNULL(m.[TMT], '') 'TMT',      
  ISNULL(m.[Habit], '') 'Habit',  
  ISNULL(m.[Existing Disease], '') 'ExistingDisease',      
  ISNULL(m.[Blood Pressure Diastolic], '') 'BloodPressureDiastolic',      
  ISNULL(m.[Blood Pressure Systolic], '') 'BloodPressureSystolic',      
  ISNULL(m.[Waist Circumference], '') 'WaistCircumference',  
  ISNULL(m.[HB], '') 'HB',  
  ISNULL(m.[Audiometry], '') 'Audiometry',  
  ISNULL(m.[Pulmonary], '') 'Pulmonary'
      
    FROM ##tblMainTable_New AS m      
    INNER JOIN sExamination.tExamination AS EXM ON m.d_ExamId = EXM.Id      
    INNER JOIN [sExamination].[tSetupMaster] AS STM ON STM.ID = EXM.SetupId      
    INNER JOIN [sExamination].[tSetupGroupMaster] AS SGM ON SGM.Id = STM.SetupGroupId      
    INNER JOIN [sExamination].[tSubTypeMaster] AS SSM ON SSM.Id = STM.SubTypeId      
    INNER JOIN [sExamination].[tDiagnosisPartial] AS DIA ON EXM.Id = DIA.ExaminationId      
    INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId      
 INNER JOIN [sHrm].[tEmployeeJobDetail] AS EJD ON EJD.EmployeeId=EMP.ID      
 INNER JOIN [sHrm].[tEmployeePersonalDetail] AS EPD on EMP.Id = EPD.EmployeeId       
 LEFT JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=EXM.EmployeeCompanyId      
 LEFT JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId      
 LEFT JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId      
 LEFT JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId      
 LEFT JOIN [sCommon].[tCompanyInformation] AS CMP ON CMP.ID=SCT.OrgId      
 LEFT JOIN [sIp].[tStoreLocationMaster] AS SLM ON SLM.Id=EXM.StoreLocationId      
 LEFT JOIN [sCommon].[tLocationMaster] AS LMN ON LMN.Id=SLM.LocationId      
 LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id=EXM.OrganizationDepartmentId      
 LEFT JOIN [sCommon].[tDepartmentGroupMaster] AS DPG ON DPG.id=DPT.DepartmentGroupId      
 LEFT JOIN [sCommon].[tFunctionMaster] AS FCN ON FCN.Id=DPG.FunctionId      
 LEFT JOIN [sCommon].[tLocationSubGroupMaster] AS LSG ON LSG.Id=LMN.LocationSubGroupId      
 LEFT JOIN [sCommon].[tLocationMainGroupMaster] AS LMG ON LMG.Id=LSG.LocationMainGroupId       
 LEFT JOIN sHrm.tGradeMaster GRD on EJD.GradeId = GRD.Id      
 INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId      
 LEFT JOIN [sExamination].[tHealthIndicatorMaster] AS HIM ON HIM.Id = DIA.HealthIndicatorId      
    WHERE EXM.ParticipantSourceTypeId = 95      
    AND SSM.MaINTypeId=@rMaINTypeId       
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))      
 AND ((EXM.SetupId=@rSetupId) OR (@rSetupId=0))      
 AND ((VTM.SectorId=@rSectorId) OR (@rSectorId=0))      
 AND ((CGM.VerticalId=@rVerticalId) OR (@rVerticalId=0))      
       
 AND ((ECM.CompanyGroupId=@rCompanyGroupId) OR (@rCompanyGroupId=0))      
 AND ((EJD.EmployeeCompanyId=@rEmployeeCompanyId) OR (@rEmployeeCompanyId=0))      
 AND ((SLM.LocationId=@rLocationId) OR (@rLocationId=0))      
 AND ((EXM.StoreLocationId=@rStoreLocationId) OR (@rStoreLocationId=0))      
 AND ((DPG.FunctionId=@rFunctionId) OR (@rFunctionId=0))      
 AND ((DPT.DepartmentGroupId=@rDepartmentGroupId) OR (@rDepartmentGroupId=0))      
 AND ((EXM.OrganizationDepartmentId=@rDepartmentId) OR (@rDepartmentId=0))      
 AND ((EMP.Code LIKE @rEmployeeCode) OR (@rEmployeeCode  = ''))      
 AND ((EMP.FirstName LIKE @rEmployeeFname)  OR  (@rEmployeeFname = ''))      
 AND ((EMP.LastName  LIKE @rEmployeeLname)  OR  (@rEmployeeLname = ''))      
       
 AND ((LSG.Id=@rLocationSubGroupId ) OR (@rLocationSubGroupId  = 0 ))      
 AND ((LMG.Id=@rLocationMainGroupId) OR (@rLocationMainGroupId = 0 ))      
 AND UL.UserId = @rUserId       
 AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0) -- Nidhi Pandey; Mantis id = 22911, DT - 16/01/2023      
      
 AND (ISNULL(@GlobalSearch,'') = '' OR UPPER(ISNULL(EMP.Code, '')) LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(EMP.FirstName, '') + ' ' + ISNULL(EMP.LastName, '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(GRD.Title,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR CONVERT(varchar, isnull(DIA.TotalHealthPoints,0)) LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR CONVERT(varchar, isnull(DIA.EarnedHealthPoints,0)) LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR CONVERT(varchar, isnull(DIA.HealthIndex,0)) LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(HIM.title,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[BMI], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[F B S], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[CHOLESTEROL], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[TRIGLYCERIDE], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[LDL], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[HDL], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[SGPT], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[SERUM CREATININE], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'  
   OR ISNULL(m.[PSA], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'  
            OR ISNULL(m.[URIC ACID], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[SONOGRAPHY], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[ECHO], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[ECG], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[TMT], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'     
   OR ISNULL(m.[Habit], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'  
            OR ISNULL(m.[Existing Disease], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[Blood Pressure Diastolic], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[Blood Pressure Systolic], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
            OR ISNULL(m.[Waist Circumference], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
   OR ISNULL(m.[HB], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'   
   OR ISNULL(m.[Audiometry], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'  
   OR ISNULL(m.[Pulmonary], '') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'   
            )  

			DECLARE @SQL NVARCHAR(MAX) = 'select ' + @FinalSelectColumns + ' from #tblMainData';
			EXEC(@SQL)
 
 IF OBJECT_ID('tempdb..#tblMainData') IS NOT NULL      
        DROP TABLE #tblMainData  

  IF OBJECT_ID('tempdb..#tblExamination') IS NOT NULL      
        DROP TABLE #tblExamination      
      
 IF OBJECT_ID('tempdb..##tblMainTable_New') IS NOT NULL      
        DROP TABLE ##tblMainTable_New      
END
GO
PRINT N'Altering Procedure [sExamination].[pTipsViewEmployeeFields]...';


GO
ALTER PROC [sExamination].[pTipsViewEmployeeFields]      
    @rId INT,       
    @rUserId BIGINT      
AS      
BEGIN      
    DECLARE @rMaINTypeId INT = 1,     
            @rSetupGroupId BIGINT = 0,     
            @rSetupId BIGINT = 0,     
            @rStoreLocationId BIGINT = 0,     
            @rOrgId INT = 0,       
            @rSqlCondition NVARCHAR(MAX) = '',     
            @rManualCondition NVARCHAR(100) = '';      
    
    -- Retrieve values from the table and set local variables    
    SELECT     
        @rMaINTypeId = ExaminationTypeId,     
        @rSetupGroupId = SetupGroupId,     
        @rSetupId = SetupId,     
        @rStoreLocationId = StoreLocationId,      
        @rSqlCondition = SqlCondition,     
        @rManualCondition = ManualCondition,     
        @rOrgId = OrgId     
    FROM [sExamination].[tAutoScheduleTipsDetail]     
    WHERE Id = @rId;      
    
    -- Replace specific conditions dynamically to simplify the values
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'BMI=''Underweight''', 'Underweight');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'BMI=''Overweight''', 'Overweight');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'BMI=''Obese''', 'Obese');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'BloodPressure=''PreHypertension''', 'PreHypertension');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'BloodPressure=''Hypertension''', 'Hypertension');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'FBS=''Pre Diabetic''', 'Pre Diabetic');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'FBS=''Diabetic''', 'Diabetic');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'Cholesterol=''Hypercholesterolemia''', 'Hypercholesterolemia');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'Cholesterol=''Borderline Cholesterol''', 'Borderline Cholesterol');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'Triglyceride=''Hypertriglyceridemia''', 'Hypertriglyceridemia');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'Triglyceride=''Borderline Triglyceride''', 'Borderline Triglyceride');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'LDL=''Elevated  LDL''', 'Elevated LDL');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'LDL=''Borderline LDL''', 'Borderline LDL');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'HDL=''Low HDL''', 'Low HDL');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'ECG=''Abnormal ECG''', 'Abnormal ECG');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'TMT=''Abnormal TMT''', 'Abnormal TMT');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'ECHO=''Abnormal ECHO''', 'Abnormal ECHO');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'Sonography=''Abnormal Sonography''', 'Abnormal Sonography');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'PFT=''RestructivePFT''', 'RestructivePFT');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'PFT=''MixPFT''', 'MixPFT');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'Diabetic Existing=''Diabetic Existing''', 'Diabetic Existing');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'Hypertension Existing=''Hypertension Existing''', 'Hypertension Existing');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'Menzer index=''Menzer index''', 'Menzer index');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'Abnormal XRay=''Abnormal XRay''', 'Abnormal XRay');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'IsNewDiabeticStatus=1', 'New Diabetic Status 1');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'IsNewDiabeticStatus=2', 'New Diabetic Status 2');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'IsNewHypertensionStatus=1', 'New Hypertension Status 1');
    SET @rSqlCondition = REPLACE(@rSqlCondition, 'IsNewHypertensionStatus=2', 'New Hypertension Status 2');
    
    ---- Construct the JSON response
    --SELECT 
    --    ( 
    --        SELECT 
    --            @rManualCondition AS ManualCondition,         
    --            @rSqlCondition AS result         
    --        FOR JSON PATH       
    --    ) AS [JSON_F52E2B61-18A1-11d1-B105-00805F49916B];   
	SELECT 
	(
		'[{' +
		'"ManualCondition":"' + 
			REPLACE(ISNULL(@rManualCondition, ''), '"', '\"') + '",' +
		'"result":"' + 
			REPLACE(ISNULL(@rSqlCondition, ''), '"', '\"') + '"' +
		'}]'
	) AS [JSON_F52E2B61-18A1-11d1-B105-00805F49916B];
END;
GO
PRINT N'Altering Procedure [sHrm].[pGetEmployeeListGeneralSearch]...';


GO
-- exec [sHrm].[pGetEmployeeListGeneralSearch] 1,9999,'','','',''  
-- drop proc [sHrm].[pGetEmployeeListGeneralSearch]  
ALTER proc [sHrm].[pGetEmployeeListGeneralSearch]  
@rPageIndex int,  
@rOrgId int,  
@rCode varchar(200),  
@rFirstName varchar(200),  
@rLastName varchar(200),  
@rMobileNo varchar(12),  
@rReferenceCode varchar(200) = '',  
@rUID varchar(200) = ''  
as  
begin  
  
 --declare @a int =1000000 while (@a <>0) begin set @a=@a-1 end  
  
 declare @lTotalRecords int,@lPageSize int = 15  
 declare @lPaging varchar(max)=''  
 declare @tbltmp table(tid int identity(1,1),t_EmpId bigint)  
 insert into @tbltmp  
 select EM.EmployeeId from sHrm.vEmployeeCommonDetail EM   
 left join [sHrm].[tEmployeeMaster] tEM ON EM.EmployeeId = tEM.Id  
 left join [sHrm].[tEmployeePersonalDetail] EPD on EPD.EmployeeId = EM.EmployeeId  
 where EM.OrgID = @rOrgId  
 and (EM.FirstName like @rFirstName + '%' or @rFirstName = '')  
 and (EM.LastName like @rLastName + '%' or @rLastName = '')  
 and (EM.Code like @rCode + '%' or @rCode = '')  
 and (EM.MobileNumber like @rMobileNo + '%' or @rMobileNo = '')  
 and (tEM.ReferenceCode like @rReferenceCode + '%' or @rReferenceCode = '') 
 and (EPD.UIDNumber like @rUID + '%' or @rUID = '')  
 
   
 select @lTotalRecords = count(1) from @tbltmp  
 select @lPaging = @lpaging + dbo.fnc_SearchPagingFormat(@rPageindex,@lTotalRecords,@lPageSize)  
 select @lpaging = replace(@lpaging,'ChangePage','ChangeGeneralSearchEmpPage')  
   
 select result = '<tr><td align="left">' + isnull(EM.Code,'') + '</td>  
 <td align="left">' + isnull(EmployeeName,'') + '</td><td align="left">' + isnull(ELM.Title,'') + '</td>  
 <td align="left">' + isnull(OD.Title,'') + '</td><td align="left">' + isnull(ECM.Title,'') + '</td>  
 <td align="left">' + isnull(SM.Title,'') + '</td><td align="left">' +ISNULL(tEM.ReferenceCode,'')+'</td><td align="left">' +ISNULL(EM.MobileNumber,'')+'</td></tr>',@lpaging as paging   
 from sHrm.vEmployeeCommonDetail EM  
 inner join sCommon.tLocationMaster ELM ON ELM.Id = EM.EmployeeLocationId  
 inner join sCommon.tOrganizationDepartmentMaster OD on EM.OrganizationDepartmentId = OD.Id  
 inner join sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4  
 left join sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = EM.EmployeeCompanyId  
 left join [sHrm].[tEmployeeMaster] tEM ON EM.EmployeeId = tEM.Id  
   
 ,@tbltmp where t_EmpId = EM.EmployeeId  
 and tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)  
 order by tid  
end
GO
PRINT N'Altering Procedure [sHrm].[pGetEmployeeListGeneralSearchData]...';


GO
-- exec [sHrm].[pGetEmployeeListGeneralSearchData] 1,9999,'','','',''
-- drop proc [sHrm].[pGetEmployeeListGeneralSearchData]
ALTER proc [sHrm].[pGetEmployeeListGeneralSearchData]
@rPageIndex int,
@rOrgId int,
@rCode varchar(200),
@rFirstName varchar(200),
@rLastName varchar(200),
@rMobileNo varchar(12),
@rReferenceCode varchar(200) = '',
@rUID varchar(200) = '' --Date:-17/02/2022,Devloper:-Ayush
as
begin


	declare @lTotalRecords int,@lPageSize int = 15
	declare @lPaging varchar(max)=''
	declare @tbltmp table(tid int identity(1,1),t_EmpId bigint)
	insert into @tbltmp
	select EM.EmployeeId from sHrm.vEmployeeCommonDetail EM 
	left join [sHrm].[tEmployeeMaster] tEM ON EM.EmployeeId = tEM.Id
	left join [sHrm].[tEmployeePersonalDetail] EPD on EPD.EmployeeId = EM.EmployeeId  --Date:-17/02/2022,Devloper:-Ayush
	where EM.OrgID = @rOrgId
	and (EM.FirstName like @rFirstName + '%' or @rFirstName = '')
	and (EM.LastName like @rLastName + '%' or @rLastName = '')
	and (EM.Code like @rCode + '%' or @rCode = '')
	and (EM.MobileNumber like @rMobileNo + '%' or @rMobileNo = '')
	and (tEM.ReferenceCode like @rReferenceCode + '%' or @rReferenceCode = '')
	and (EPD.UIDNumber like @rUID + '%' or @rUID = '')  --Date:-17/02/2022,Devloper:-Ayush
	
	select @lTotalRecords = count(1) from @tbltmp
	
	select isnull(EM.Code,'') as Code , isnull(EmployeeName,'') as EmployeeName , isnull(ELM.Title,'') as [Location]
	, isnull(OD.Title,'') ODTitle, isnull(ECM.Title,'') as ECMTitle,
	isnull(SM.Title,'') as [Status] ,ISNULL(tEM.ReferenceCode,'') as ReferenceCode,ISNULL(EM.MobileNumber,'') as MobileNumber
	from sHrm.vEmployeeCommonDetail EM
	inner join sCommon.tLocationMaster ELM ON ELM.Id = EM.EmployeeLocationId
	inner join sCommon.tOrganizationDepartmentMaster OD on EM.OrganizationDepartmentId = OD.Id
	inner join sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
	left join sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = EM.EmployeeCompanyId
	left join [sHrm].[tEmployeeMaster] tEM ON EM.EmployeeId = tEM.Id
	,@tbltmp where t_EmpId = EM.EmployeeId
	and tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)
	order by tid

	select @lTotalRecords as Total
end
GO
PRINT N'Altering Procedure [sHrm].[pMobEmployeeMasterListingGet]...';


GO
ALTER proc [sHrm].[pMobEmployeeMasterListingGet]

(

	@rOrgId INT,

	@rSetupGroupId INT,

	@rCode VARCHAR(20) = '',

	@rName VARCHAR(200) = '',	

	@rSurName VARCHAR(200) = '',

	@rEmployeeId BIGINT = 0,

	@rHealthIndicatorId INT=0,

	@rCodeLike VARCHAR(200) = ''

)

AS
 
	IF(@rSurName IS NULL)	

		SET @rSurName = ''

	IF(@rCode IS NULL)	

		SET @rCode = ''	

	IF(@rName IS NULL)	

		SET @rName = ''	

	SET NOCOUNT ON

	BEGIN

	SET @rName = sCommon.fSearchStringGet(@rName)

	SET @rSurName = sCommon.fSearchStringGet(@rSurName)

	DECLARE @lCondition1 VARCHAR(MAX)='',

			@lCondition2 VARCHAR(MAX)='',

			@lCondition3 VARCHAR(MAX)='',

			@lCondition4 VARCHAR(MAX)=''

	DECLARE @lCondition VARCHAR(MAX) = '',

			@lQuery VARCHAR(MAX)=''

	SELECT @lCondition1 = @lCondition1 + CASE WHEN EntitySourceTypeId = 2012 THEN

	CASE WHEN @lCondition1 = '' THEN ' and SCT.Id = ' + convert(VARCHAR,EntitySourceId)	

	ELSE ' or SCT.Id = ' + convert(VARCHAR,EntitySourceId) END

	ELSE '' END	FROM sHrm.tEntityHead WHERE HeadEmployeeId = @rEmployeeId AND EntitySourceTypeId = 2012

	SELECT @lCondition2 = @lCondition2 + CASE EntitySourceTypeId WHEN 2013 THEN

	CASE WHEN @lCondition2 = '' THEN ' and VTM.Id = ' + CONVERT(VARCHAR,EntitySourceId)

	ELSE ' or VTM.Id = ' + convert(VARCHAR,EntitySourceId) END

	ELSE '' END	FROM sHrm.tEntityHead WHERE HeadEmployeeId = @rEmployeeId and EntitySourceTypeId = 2013

	SELECT @lCondition3 = @lCondition3 + case EntitySourceTypeId WHEN 1014 THEN

	CASE WHEN @lCondition3 = '' THEN ' and E.StoreLocationId = ' + CONVERT(VARCHAR,EntitySourceId)

	ELSE ' or E.StoreLocationId = ' + convert(varchar,EntitySourceId) END

	ELSE '' END	FROM sHrm.tEntityHead WHERE HeadEmployeeId = @rEmployeeId AND EntitySourceTypeId = 1014

	SELECT @lCondition4 = @lCondition4 + case EntitySourceTypeId WHEN 2016 THEN

	CASE WHEN @lCondition4 = '' THEN ' and DGM.FunctionId = ' + CONVERT(VARCHAR,EntitySourceId)

	ELSE ' or DGM.FunctionId = ' + CONVERT(VARCHAR,EntitySourceId) END

	ELSE '' END	FROM sHrm.tEntityHead where HeadEmployeeId = @rEmployeeId and EntitySourceTypeId = 2016

	IF CHARINDEX(' or ',@lCondition1) > 0

	BEGIN

		SELECT @lCondition1 = REPLACE(@lCondition1,'and','and (')

		SELECT @lCondition1 = @lCondition1 + ') '

	END	

	IF CHARINDEX(' or ',@lCondition2) > 0

	BEGIN	

		SELECT @lCondition2 = REPLACE(@lCondition2,'and','and (')

		SELECT @lCondition2 = @lCondition2 + ') '

	END	

	IF CHARINDEX(' or ',@lCondition3) > 0

	BEGIN

		SELECT @lCondition3 = REPLACE(@lCondition3,'and','and (')

		SELECT @lCondition3 = @lCondition3 + ') '

	end

	IF CHARINDEX(' or ',@lCondition4) > 0

	BEGIN

		SELECT @lCondition4 = REPLACE(@lCondition4,'and','and (')

		SELECT @lCondition4 = @lCondition4 + ') '

	END

	SELECT @lCondition =  CASE WHEN isnull(@lCondition1,'') = '' THEN '' ELSE @lCondition1 END

	+ CASE WHEN isnull(@lCondition2,'') = '' THEN '' ELSE @lCondition2 END

	+ CASE WHEN isnull(@lCondition3,'') = '' THEN '' ELSE @lCondition3 END

	+ CASE WHEN isnull(@lCondition4,'') = '' THEN '' ELSE @lCondition4 END

	--select @lCondition

	SELECT @lQuery = 'SELECT EM.Id AS EmployeeId,S.Id as SetupId,S.Title as SetupName,E.StoreLocationId,SLM.Title as StoreLocationName,

	CASE WHEN EM.IsTemporary = 0 THEN EM.Code ELSE EM.TemporaryCode END AS Code,

	ISNULL(EM.FirstName, '''') + '' '' + ISNULL(EM.LastName, '''') AS EmployeeName,SCT.Id as SectorId, MTM.Id AS MainTypeId, S.SubTypeId AS SubTypeId

	FROM sHrm.tEmployeeMaster EM

	inner join sExamination.tExamination E on EM.Id=ParticipantSourceId and ParticipantSourceTypeId=95 and isnull(E.IsPublish,0) = 1   

	inner join sIp.tStoreLocationMaster SLM on SLM.Id=E.StoreLocationId

	inner join sExamination.tsetupMaster S on E.SetupId = S.Id	

	inner join sExamination.tMainTypeMaster MTM ON MTM.Id = s.SubTypeId

	left JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=E.EmployeeCompanyId

	left JOIN [sHrm].[tCompanyGroupMaster] AS CGM ON CGM.Id=ECM.CompanyGroupId

	left JOIN [sHrm].[tVerticalMaster] AS VTM ON VTM.ID=CGM.VerticalId

	left JOIN [sHrm].[tSectorMaster] AS SCT ON SCT.Id=VTM.SectorId	

	left join sCommon.tOrganizationDepartmentMaster ODM on ODM.Id=E.OrganizationDepartmentId

	left join sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id

	left JOIN sExamination.tDiagnosis AS DIA ON    E.Id=DIA.SourceId

	left join [sExamination].[tHealthIndicatorMaster] HIM on HIM.Id=DIA.HealthIndicatorId

	WHERE EM.OrgId = ' + CONVERT(VARCHAR,@rOrgId) + '	

	AND (EM.Code = ''' + @rCode + ''' OR ''' + @rCode + ''' = '''')

	AND (EM.FirstName like ''' + @rName + '%'' OR ''' + @rName + ''' = '''')

	AND (EM.LastName like ''' + @rSurName + '%'' OR ''' + @rSurName + ''' = '''')

	AND (S.SetupGroupId = ' + CONVERT(VARCHAR,@rSetupGroupId) + ' OR ' + CONVERT(VARCHAR,@rSetupGroupId) + ' = 0)

	AND (DIA.HealthIndicatorId = ' + CONVERT(VARCHAR,@rHealthIndicatorId) + ' or ' + CONVERT(VARCHAR,ISNULL(@rHealthIndicatorId,0)) + ' = 0) 

	AND E.StatusId = 4 '

	+ @lCondition + 

	CASE WHEN LEN(@rCodeLike) > 0 THEN ' AND EXISTS (SELECT 1 FROM sCommon.fnSplit(''' + @rCodeLike + ''', '','') AS SPLIT WHERE SPLIT.item = EM.Code) ' ELSE '' 

	END

	+  'Order By EM.Code'

	EXEC (@lQuery)

END
GO
PRINT N'Altering Procedure [sIp].[pGroupItemWiseReportGet]...';


GO
CREATE OR ALTER PROCEDURE [sIp].[pGroupItemWiseReportGet](
	
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rFilterId int,
	@rStoreLocationId int,
	@rMainGroupId int,
	@rSubGroupId int,
	@rId int=0,
	@rItemCode nvarchar(500)='',	
	@rOrgId int,
	@rFromDate datetime=NULL,
	@rToDate datetime=NULL,
	@rItemName nvarchar(500) = '',
	@rTagIds varchar(max)=''
)
AS
BEGIN
    SET NOCOUNT ON;

    ---------------------------------------------------------
    -- 1️⃣ First Result: Tray Summary (SQL 2008 Compatible)
    ---------------------------------------------------------
    SELECT 
        SM.Title AS [Tray Name],
        CONVERT(VARCHAR(10), SM.CreatedDateTime, 103) AS [Date of Use],

        COUNT(DISTINCT EM.ParticipantSourceId) AS [Total Patients Prescribed],

        CAST(COUNT(SM2.Title) AS VARCHAR(10)) + ' items (' + 
        STUFF((
            SELECT ', ' + SM3.Title
            FROM sProcurement.tGroupItemIssue GI2
            INNER JOIN sIp.tStockItemMaster SM3 
                ON SM3.Id = GI2.StockItemId
            WHERE GI2.GroupItemId = SM.Id
            FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') 
        + ')' AS [Total Quantity Used (All Items)],

        (SELECT TOP 1 DisplayTitle 
         FROM sSecurity.tUser U 
         WHERE U.Id = GI.CreatedUserId) AS [Issued By (Store)],

        (SELECT TOP 1 DisplayTitle 
         FROM sSecurity.tUser U 
         WHERE U.Id = EM.DoctorEmployeeId) AS [Doctor(s) Involved]

    FROM sIp.tStockItemMaster SM
    INNER JOIN sProcurement.tGroupItemIssue GI 
        ON GI.GroupItemId = SM.Id
    INNER JOIN sIp.tStockItemMaster SM2 
        ON SM2.Id = GI.StockItemId 
        AND SM.IsGroupItem = 1
    INNER JOIN sExamination.tPrescriptionDetail PD 
        ON PD.StockItemId = SM2.Id
    INNER JOIN sExamination.tPrescription PS 
        ON PS.Id = PD.PrescriptionId
    INNER JOIN sExamination.tExamination EM 
        ON EM.Id = PS.SourceId

    GROUP BY 
        SM.Title, 
        CONVERT(VARCHAR(10), SM.CreatedDateTime, 103),
        EM.DoctorEmployeeId, 
        GI.CreatedUserId,
        SM.Id

    ORDER BY [Date of Use];

    ---------------------------------------------------------
    -- 2️⃣ Second Result: Tray Detail (No change required)
    ---------------------------------------------------------
    SELECT 
        SM.Title AS [Tray Name],
        CONVERT(VARCHAR(10), SM.CreatedDateTime, 103) AS [Date of Use],  
        SM2.Title AS [Component Item],
        GI.DefaultUOM AS [UOM],
        EMS.Code AS [Prescribed To (Employee Code)],
        EMS.FirstName + ' ' + EMS.LastName AS [Patient Name],

        (SELECT TOP 1 DisplayTitle 
         FROM sSecurity.tUser U 
         WHERE U.Id = EM.DoctorEmployeeId) AS [Doctor Name]

    FROM sIp.tStockItemMaster SM
    INNER JOIN sProcurement.tGroupItemIssue GI 
        ON GI.GroupItemId = SM.Id
    INNER JOIN sIp.tStockItemMaster SM2 
        ON SM2.Id = GI.StockItemId 
        AND SM.IsGroupItem = 1
    INNER JOIN sExamination.tPrescriptionDetail PD 
        ON PD.StockItemId = SM2.Id
    INNER JOIN sExamination.tPrescription PS 
        ON PS.Id = PD.PrescriptionId
    INNER JOIN sExamination.tExamination EM 
        ON EM.Id = PS.SourceId
    INNER JOIN sHrm.tEmployeeMaster EMS 
        ON EMS.Id = EM.ParticipantSourceId

    ORDER BY [Date of Use];

END
GO
PRINT N'Altering Procedure [sProcurement].[pFirstAidInspectionDetailGet]...';


GO

CREATE OR ALTER PROCEDURE [sProcurement].[pFirstAidInspectionDetailGet]
	@rFAIId bigint,
	@rStoreLocationId int,
	@rOrgId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN

	  SELECT 
		FAM.Code AS FirstAidCode,
		FAM.Title AS FirstAidTitle,
		FAM.Id AS FirstAidId,
		ISNULL(FAID.Id,'')AS FAIDId,
		ISNULL(FAID.FirstAidInspectionId,'')AS FAIId,
		ISNULL(FAID.IsWellMaintained,0)AS IsWellMaintained,
		ISNULL(FAID.Remark,'')AS Remark,
		EM.FirstName +' '+EM.LastName as CustodianName,
		CASE WHEN FAID.Id > 0 and FAM.IsObsolete = 1 then 1
			 WHEN ISNULL(FAID.Id, 0) = 0 and FAM.IsObsolete = 1 then 2
		     else 0 end as FirstAidInActive
	  
	  FROM 
			sCommon.tFirstAidMaster FAM
			LEFT JOIN sProcurement.tFirstAidInspectionDetail FAID ON FAM.Id=FAID.FirstAidId	AND FAID.FirstAidInspectionId=@rFAIId
			Left join sHrm.tEmployeeMaster EM on EM.Id=FAM.CustodianEmployeeId
				
	  WHERE
			((FAM.IsObsolete=0 AND @rFAIId = 0) OR @rFAIId > 0)
			AND (FAM.StoreLocationId=@rStoreLocationId)
			AND (FAM.OrgId=@rOrgId)
	 ORDER BY FAM.Title ASC

END
GO
PRINT N'Altering Procedure [sSecurity].[pAutoInActiveUser]...';


GO
ALTER   PROCEDURE [sSecurity].[pAutoInActiveUser]
(
    @InactiveDays INT,
    @OrgId INT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @Today DATETIME = GETDATE();
    DECLARE @SysUser1 BIGINT,
            @SysUser2 BIGINT,
            @SysUser3 BIGINT;

    SELECT 
        @SysUser1 = [sCommon].[fGetBigIntIdForOrg](1, @OrgId),
        @SysUser2 = [sCommon].[fGetBigIntIdForOrg](2, @OrgId),
        @SysUser3 = [sCommon].[fGetBigIntIdForOrg](3, @OrgId);

    --Users who NEVER logged in
    UPDATE U
    SET 
        U.IsObsolete = 1,
        U.UpdatedDateTime = @Today
    OUTPUT
        inserted.Id,
        @OrgId,
        'NEVER_LOGGED_IN',
        inserted.CreatedDateTime,
        @InactiveDays,
        @Today
    INTO sSecurity.tInActiveUserLog
    (
        UserId,
        OrgId,
        InactiveReason,
        ReferenceDateTime,
        InactiveDays,
        CreatedDateTime
    )
    FROM sSecurity.tUser U
    LEFT JOIN sSecurity.tUserLog UL
    ON UL.UserId = U.Id
WHERE
    U.IsObsolete = 0
    AND U.OrgId = @OrgId
    AND DATEDIFF(DAY, U.CreatedDateTime, @Today) >= @InactiveDays
    AND UL.UserId IS NULL
    AND U.Id NOT IN (@SysUser1, @SysUser2, @SysUser3);


    --Users logged in before BUT NOT currently
     UPDATE U
    SET 
        U.IsObsolete = 1,
        U.UpdatedDateTime = @Today
    OUTPUT
        inserted.Id,
        @OrgId,
        'INACTIVE_AFTER_LOGOUT',
        L.LastLogoutDate,
        @InactiveDays,
        @Today
    INTO sSecurity.tInActiveUserLog
    (
        UserId,
        OrgId,
        InactiveReason,
        ReferenceDateTime,
        InactiveDays,
        CreatedDateTime
    )
    FROM sSecurity.tUser U
    CROSS APPLY
    (
        SELECT MAX(UL.LoggedOutDateTime) AS LastLogoutDate
        FROM sSecurity.tUserLog UL
        WHERE UL.UserId = U.Id
    ) L
    WHERE 
        U.IsObsolete = 0 AND U.OrgId = @OrgId
        AND U.Id NOT IN (@SysUser1, @SysUser2, @SysUser3)
        AND L.LastLogoutDate IS NOT NULL
        AND NOT EXISTS (
            SELECT 1
            FROM sSecurity.tUserLog UL
            WHERE UL.UserId = U.Id
              AND UL.LoggedOutDateTime IS NULL
        )
        AND DATEDIFF(DAY, L.LastLogoutDate, @Today) >= @InactiveDays;
END
GO
PRINT N'Altering Procedure [sSecurity].[pLoggedInUserGet]...';


GO


CREATE OR ALTER PROCEDURE [sSecurity].[pLoggedInUserGet]  
 @rOrgId [smallint],  
 @rUserId [bigint],  
 @rStoreLocationId [int]  
   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
  
DECLARE @lLocationId int=null  
DECLARE @lStoreLocationId int=null  
DECLARE @lLocationName nvarchar(100)=null  
DECLARE @lStoreLocationName nvarchar(100)=null  

--Developer: Deval, Date: 03/08/2023, To Check Given User is Employee or not
Declare @RoleId int, @rIsEmployeePortal bit;
set @RoleId = (select [sCommon].[fGetIntIdForOrg] (10, @rOrgId))

IF EXISTS(select 1 from sSecurity.tUserRole where RoleId=@RoleId and UserId=@rUserId)
BEGIN
	set @rIsEmployeePortal = 1
END
ELSE
BEGIN
	set @rIsEmployeePortal = 0
END
--Developer: Deval, Date: 03/08/2023
  
SELECT top 1  @lLocationId = LocationId, @lLocationName = LocationName,@lStoreLocationId = StoreLocationId,
@lStoreLocationName = StoreName FROM sSecurity.vExtUserLocation  
WHERE StoreLocationId = @rStoreLocationId AND UserId = @rUserId   

		if(Isnull(@lLocationId,0)<=0 or Isnull(@lStoreLocationId,0)<=0)
		begin
			Select top 1 @lLocationId=Isnull(LM.Id,0),@lLocationName=Isnull(LM.Title,''),@lStoreLocationId=Isnull(SLM.Id,0),@lStoreLocationName=Isnull(SLM.Title,'')
			FROM sSecurity.tUser UserTbl
			Inner JOIN sCommon.vEmployeeMaster EM  
			ON EM.Id = UserTbl.SourceId AND UserTbl.OrgId = EM.OrgId AND UserTbl.SourceTypeId = 95
			Inner JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId=EM.Id       
			Inner join sCommon.tLocationMaster LM ON EJ.EmployeeLocationId = LM.Id
			Inner JOin sIp.tStoreLocationMaster SLM ON SLM.LocationId=LM.Id
			WHERE (SLM.IsActiveHealth = 1) AND (LM.IsActiveHealth = 1) AND
			UserTbl.Id = @rUserId AND
			UserTbl.OrgId = @rOrgId
				
		end
  
 SELECT   
  UserTbl.OrgId,  
  UserTbl.Id AS UserId,     
  UserTbl.LoginTitle AS LoginTitle,  
  UserTbl.DisplayTitle  AS DisplayTitle,     
  --UserTbl.EmployeeId AS EmployeeId,   
  UserTbl.SourceId AS UserSourceId,  
  UserTbl.SourceTypeId AS UserSourceTypeId,  
    (EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + EM.LastName)  AS EmployeeFullName,   
    (EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + EM.LastName)  AS UserFullName,  
  EM.EmployeeJobTitleId,  
  ScreenTbl.Page AS HomePageUrl,  
  MenuTbl.Id AS MenuId,  
  UserPrefTbl.FavoriteScreenID AS ScreenID,  
  UserTbl.SessionId AS SessionId,  
  @lLocationId AS LocationId,  
  @lLocationName AS LocationName,  
  UR.RoleId,
  EI.EmployeePhoto as UserPhoto,  
     @lStoreLocationName as  StoreLocationName,
	@lStoreLocationId as    StoreLocationId,
	EC.MobileNumber,EC.PersonalEmail,EP.GenderId,	
	(select Title from sCommon.tGenderMaster where Id=EP.GenderId) as Gender,
	EP.DateOfBirth,EP.BloodGroupId,
	(select Title from sCommon.tBloodGroupMaster where Id=EP.BloodGroupId) as BloodGroup,
	EP.MaritalStatusId,
	(select Title from sCommon.tMaritalStatusMaster where Id=EP.MaritalStatusId) as MaritalStatus,
	EC.EmergencyContactNo,
	EJ.EmployeeDesignationId as DesignationId,
	(select Title from sHrm.tEmployeeDesignationMaster where id=EJ.EmployeeDesignationId) as Designation,
	EJ.OrganizationDepartMentId as DepartmentId,
	(select DepartmentName from sCommon.tOrganizationDepartmentMaster where Id=EJ.OrganizationDepartMentId) as DepartmentName,
	EJ.DateOfJoining,
	@rIsEmployeePortal as IsEmployeePortal, --Developer: Deval, Date: 03/08/2023, To Check Given User is Employee or not
	R.AccessTypeId,  --Nidhi Pandey; To add AccessTypeId in session; DT - 14/10/2022
	EC.CompanyEmail,  --Yoges Banwe; Add for Employee profile; DT - 11-01-2023 
	ELP.LanguagePreferenceId, --Nidhi Pandey; mantis id: 29981 ; DT - 16/01/2024
	ISNULL(LP.Title,'English') as LanguagePreference, --Nidhi Pandey; mantis id: 29981 ; DT - 16/01/2024,
	EM.Code as EmployeeCode,  --Nidhi Pandey; suggested by Manthan Sir ; DT - 26/02/2024,
	(Case when exists(Select 1 from [sSecurity].[tPermissionUser] PU where PU.UserId = UserTbl.Id) Then 'Y' else 'N' END) as UserPermission,
	CGM.Id as SafetyDepartmentId, CGM.Title as SafetyDepartmentName,
	CASE WHEN LOWER(LTRIM(RTRIM(VM.Title))) = 'central safety' AND EM.UserId = @rUserId THEN 1 ELSE 0 END AS IsCentralSafety
	 FROM sSecurity.tUser UserTbl  
  INNER JOIN sSecurity.tUserRole UR  
   ON UR.UserId=UserTbl.Id AND UR.IsObsolete=0 AND UR.IsPrimary=1 AND UR.UserId=@rUserId  
  LEFT JOIN sCommon.vEmployeeMaster EM  
   ON EM.Id = UserTbl.SourceId AND UserTbl.OrgId = EM.OrgId AND UserTbl.SourceTypeId = 95      
  LEFT OUTER JOIN sSecurity.tUserPreference UserPrefTbl  
   ON UserTbl.Id = UserPrefTbl.UserId AND  UserTbl.OrgId = UserPrefTbl.OrgId  
  LEFT OUTER JOIN sSecurity.tScreen ScreenTbl  
   ON UserPrefTbl.FavoriteScreenId = ScreenTbl.Id     
  LEFT OUTER JOIN sSecurity.tMenu MenuTbl  
   ON MenuTbl.ScreenId =  ScreenTbl.Id   
  LEFT JOIN sHrm.tEmployeeImages EI  
   ON EI.EmployeeId=EM.Id
   LEFT JOIN sHrm.tEmployeePersonalDetail EP  
   ON EP.EmployeeId=EM.Id
   LEFT JOIN sHrm.tEmployeeCommunications EC  
   ON EC.EmployeeId=EM.Id
   LEFT JOIN sHrm.tEmployeeJobDetail EJ 
   ON EJ.EmployeeId=EM.Id
   LEFT JOIN sHrm.tEmployeeCompanyMaster ECM on ECM.Id = EJ.EmployeeCompanyId
   LEFT JOIN sHrm.tCompanyGroupMaster CGM on CGM.Id = ECM.CompanyGroupId
   LEFT JOIN sSecurity.tRole R   --Nidhi Pandey; To add AccessTypeId in session; DT - 14/10/2022
   ON R.Id = UR.RoleId  
   LEFT JOIN sHrm.tEmployeeLanguagePreference ELP ON ELP.EmployeeId = EM.Id --Nidhi Pandey; mantis id: 29981 ; DT - 16/01/2024
   LEFT JOIN sHrm.tLanguagePreference LP ON LP.Id = ELP.LanguagePreferenceId  --Nidhi Pandey; mantis id: 29981 ; DT - 16/01/2024
   LEFT JOIN [sHrm].[tVerticalMaster] VM ON VM.Id = CGM.VerticalId
 WHERE   
  UserTbl.Id = @rUserId AND  
  UserTbl.OrgId = @rOrgId   
  
END
GO
PRINT N'Altering Procedure [sSecurity].[pMenuGet]...';


GO
CREATE OR ALTER PROCEDURE [sSecurity].[pMenuGet]        
 @rUserId [bigint],        
 @rMenuId int = 0,        
 @rResourceTypeId int= 0,        
 @rOrgId int,        
 @rflg bit = 0         
         
WITH EXECUTE AS CALLER        
AS        
SET NOCOUNT ON        
        
BEGIN        
declare @result varchar(15)='False'        
Select @result = [dbo].[fPHIPermissionUserwise](@rUserId,@rOrgId)        
        
if(@rflg=0)        
         
 begin        
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)        
  BEGIN        
   SELECT        
   MenuID,        
   ModuleId,        
   ParentMenuID,        
   MenuTitle,          
   ScreenTitle,           
   case when MenuID = 3314  then '~/Pages/Common/CommonMaster/CommonNavigationMaster.aspx' else         
   case when Menuid=1115 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   case when Menuid=3510 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   PageURL end end end PageURL,        
   ScreenId,        
   Permission,        
   OrderNumber,          
   TaskId,          
    PageURL  AS PagePath,        
    MenuIsObsolete          
  FROM        
    (SELECT Menu.Id AS MenuID,         
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
   Menu.Title AS MenuTitle,           
   ISNULL(Screen.Title, '') AS ScreenTitle,            
   ISNULL(Screen.Page, '') AS PageURL,        
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
   ISNULL(Menu.ScreenId, 0) AS ScreenId,        
   ISNULL(PermissionValue, 0) AS Permission,        
   ISNULL(OrderNumber, 0) AS OrderNumber,        
   ISNULL(Screen.TaskId,0) AS TaskId,        
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
   ISNULL(T.ModuleId,0) AS ModuleId,        
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete            
            
  FROM sSecurity.tMenu Menu         
  LEFT OUTER JOIN sSecurity.tScreen Screen        
   ON Menu.ScreenId = Screen.Id            
           
  LEFT OUTER JOIN (         
      SELECT         
       P.TaskId,         
       SUM(OT.AvailablePermission & 2) PermissionValue              
      FROM         
       sSecurity.tPermissionUser P        
       INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
       INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
       INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
       INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
      where p.userid= @rUserId 
	  AND T.Id not in (20834,20853)            
      GROUP BY         
       P.TaskId) TBL2        
      ON         
       Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId               
      WHERE         
      (Menu.IsObsolete = 0)         
      AND ISNULL(Screen.IsObsolete, 0) = 0 AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368))         
      MenuTable          
              
  WHERE         
   MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
   AND         
   ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
   AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
   AND MenuIsObsolete = 0        
  ORDER BY         
   ParentMenuID          
  END        
         
 ELSE         
  BEGIN        
   SELECT        
   MenuID,        
   ModuleId,        
   ParentMenuID,        
   MenuTitle,          
   ScreenTitle,           
   case when MenuID = 3314  then '~/Pages/Common/CommonMaster/CommonNavigationMaster.aspx' else        
   case when Menuid=1115 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
 case when Menuid=3510 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   PageURL end end end PageURL,       
   ScreenId,        
   Permission,        
   OrderNumber,          
   TaskId,          
    PageURL  AS PagePath,        
    MenuIsObsolete          
  FROM        
    (SELECT Menu.Id AS MenuID,         
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
   Menu.Title AS MenuTitle,           
   ISNULL(Screen.Title, '') AS ScreenTitle,            
   ISNULL(Screen.Page, '') AS PageURL,        
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
   ISNULL(Menu.ScreenId, 0) AS ScreenId,        
   ISNULL(PermissionValue, 0) AS Permission,        
   ISNULL(OrderNumber, 0) AS OrderNumber,        
   ISNULL(Screen.TaskId,0) AS TaskId,        
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
   ISNULL(T.ModuleId,0) AS ModuleId,        
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete        
            
            
  FROM sSecurity.tMenu Menu         
  LEFT OUTER JOIN sSecurity.tScreen Screen        
   ON Menu.ScreenId = Screen.Id            
           
  LEFT OUTER JOIN (         
      SELECT         
       P.TaskId,         
       SUM(OT.AvailablePermission & 2) PermissionValue              
      FROM         
       sSecurity.tPermission P        
       INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
       INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
       INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
       INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
       INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId         
      --WHERE         
      -- RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) 
	  WHERE T.Id not in (20834,20853)        
      GROUP BY         
       P.TaskId) TBL2        
      ON         
       Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
               
      WHERE         
      (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
      AND ISNULL(Screen.IsObsolete, 0) = 0 AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368))         
      MenuTable          
      --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
  WHERE         
   MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
   AND         
   ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
   AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
   AND MenuIsObsolete = 0        
           
           
             
  ORDER BY         
   ParentMenuID        
        
   --SELECT DISTINCT Menu.Id AS MenuID,         
  --  ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
  --  Menu.Title AS MenuTitle,         
  --  Menu.TitleResourceKeyId AS MenuResourceKey,         
  --  Screen.Title AS ScreenTitle,        
  --  Screen.TitleResourceKeyId AS ScreenResourceKey,        
  --  Screen.Page AS PageURL        
  --FROM sSecurity.tMenu Menu        
  --LEFT OUTER JOIN sSecurity.tScreen Screen        
  -- ON Menu.ScreenId = Screen.Id        
  --LEFT OUTER JOIN sSecurity.tPermission Permission        
  -- ON Screen.TaskId = Permission.TaskId        
  --WHERE Menu.IsObsolete = 0 AND        
  --  Screen.IsObsolete = 0 AND        
  --  Permission.RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId) AND        
  --  (Permission.Permission & 2) = 2        
  --ORDER BY ParentMenuID        
  END        
 end        
else        
 begin        
  IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)        
   begin        
    SELECT        
        MenuID,        
        ModuleId,        
        ParentMenuID,        
        MenuTitle,          
        ScreenTitle,           
        case when Menuid=1510 then '~/Pages/MaterialManagement/Procurement/ReportCriteria/Report' else  PageURL end PageURL,       
        ScreenId,        
        Permission,        
        OrderNumber,          
        TaskId,          
        PageURL  AS PagePath,        
        MenuIsObsolete,        
        Icon          
          FROM        
           (        
           SELECT Menu.Id AS MenuID,         
		  ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
          Menu.Title AS MenuTitle,           
          ISNULL(Screen.Title, '') AS ScreenTitle,            
          --case when Menu.Id=3023 then '' else ISNULL(Screen.Page, '') end AS PageURL,        
          ISNULL(Screen.Page, '') AS PageURL,        
          ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
          ISNULL(Menu.ScreenId, 0) AS ScreenId,        
          ISNULL(PermissionValue, 0) AS Permission,        
          ISNULL(OrderNumber, 0) AS OrderNumber,        
          ISNULL(Screen.TaskId,0) AS TaskId,        
          ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
          ISNULL(T.ModuleId,0) AS ModuleId,        
          ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
          case when Menu.Id=18 then 'fa fa-wrench'         
         when Menu.Id=35 then 'fa fa-support'         
         when Menu.Id=15 then 'fa fa-tasks'         
         when Menu.Id=22 then 'fa fa-user'         
         when Menu.Id=34 then 'fa fa-bar-chart'        
         when Menu.Id=31 then 'icon-hourglass'        
         when Menu.Id=33 then 'fa fa-exclamation-triangle'        
         when Menu.Id=11 then 'fa fa-medkit'        
         when Menu.Id=12 then 'fa fa-hospital-o'        
         when Menu.Id=10 then 'fa fa-building-o'        
         when Menu.Id=30 then 'fa fa-book'        
         when Menu.Id=56 then 'fa fa-list'        
         when Menu.Id=3023 then 'fa fa-stethoscope'
		 when Menu.Id=191810371 then 'fa fa-heart'
         else ISNULL(Screen.IconPath,'') end AS Icon        
            
         FROM sSecurity.tMenu Menu         
         LEFT OUTER JOIN sSecurity.tScreen Screen        
          ON Menu.ScreenId = Screen.Id            
           
         LEFT OUTER JOIN (         
          SELECT         
           P.TaskId,         
           SUM(OT.AvailablePermission & 2) PermissionValue              
          FROM         
           sSecurity.tPermissionUser P        
           INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
           INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
           INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
           INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          WHERE p.userid= @rUserId
		  AND T.Id not in (20834,20853)         
          GROUP BY         
           P.TaskId) TBL2        
          ON         
           Screen.TaskId = TBL2.TaskId         
            LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
               
          WHERE         
          (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
          AND ISNULL(Screen.IsObsolete, 0) = 0        
          --AND (Menu.Id in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023) Or ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
          AND (Menu.Id in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371) Or ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371))        
          AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)         
          AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
         union        
           
          SELECT case when Menu.Id = 3023 then 1 else Menu.Id end AS MenuID,         
          ISNULL(Menu.Id, 0) AS ParentMenuID,         
          Screen1.Title AS MenuTitle,           
          ISNULL(Screen1.Title, '') AS ScreenTitle,            
          ISNULL(Screen1.Page, '')  AS PageURL,        
          ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,        
          ISNULL(Menu.ScreenId, 0) AS ScreenId,        
          ISNULL(PermissionValue, 0) AS Permission,        
          ISNULL(Screen1.OrderIndex, Screen.OrderIndex) AS OrderNumber,        
          ISNULL(Screen1.TaskId,0) AS TaskId,        
          ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
          ISNULL(T.ModuleId,0) AS ModuleId,        
          ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
          ISNULL(Screen1.IconPath,'') AS Icon        
            
         FROM sSecurity.tMenu Menu         
         LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id            
         LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId         
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId --AND ResourceTypeId = 0        
         LEFT OUTER JOIN (         
          SELECT         
         P.TaskId,         
           SUM(OT.AvailablePermission & 2) PermissionValue              
          FROM         
           sSecurity.tPermissionUser P        
           INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
           INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
           INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
           INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          WHERE p.userid= @rUserId
		  AND T.Id not in (20834,20853)         
          GROUP BY         
           P.TaskId        
          ) TBL2        
          ON Screen1.TaskId = TBL2.TaskId         
         WHERE         
         (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
         AND ISNULL(Screen1.IsObsolete, 0) = 0        
         --AND (Menu.ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
         AND (Menu.ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371) or Menu.Id in (3023))        
         AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)        
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen1.PHIAccessLevel,0)<>1))        
         )         
          MenuTable          
          --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
         WHERE         
       MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
          AND         
          ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
          AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
          AND MenuIsObsolete = 0        
          AND (1=(case when @rResourceTypeId=0 then 0 else 1 end) or (MenuTable.ResourceTypeId !=1))      
             
         ORDER BY         
          ParentMenuID        
   end        
  else        
   begin        
    SELECT        
         MenuID,        
         ModuleId,        
         ParentMenuID,        
         MenuTitle,          
         ScreenTitle,           
         case when Menuid=1510 then '~/Pages/MaterialManagement/Procurement/ReportCriteria/Report' else PageURL end PageURL,        
         ScreenId,        
         Permission,        
         OrderNumber,          
         TaskId,          
       PageURL  AS PagePath,        
       MenuIsObsolete,        
       Icon          
        FROM        
       (        
       SELECT Menu.Id AS MenuID,         
         ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
         Menu.Title AS MenuTitle,           
         ISNULL(Screen.Title, '') AS ScreenTitle,            
         --case when Menu.Id=3023 then '' else ISNULL(Screen.Page, '') end AS PageURL,        
         ISNULL(Screen.Page, '') AS PageURL,        
         ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
         ISNULL(Menu.ScreenId, 0) AS ScreenId,        
         ISNULL(PermissionValue, 0) AS Permission,        
         ISNULL(OrderNumber, 0) AS OrderNumber,        
         ISNULL(Screen.TaskId,0) AS TaskId,        
         ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
         ISNULL(T.ModuleId,0) AS ModuleId,        
         ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
         case when Menu.Id=18 then 'fa fa-wrench'         
        when Menu.Id=35 then 'fa fa-support'         
        when Menu.Id=15 then 'fa fa-tasks'         
        when Menu.Id=22 then 'fa fa-user'         
        when Menu.Id=34 then 'fa fa-bar-chart'        
        when Menu.Id=31 then 'icon-hourglass'        
        when Menu.Id=33 then 'fa fa-exclamation-triangle'        
        when Menu.Id=11 then 'fa fa-medkit'        
        when Menu.Id=12 then 'fa fa-hospital-o'        
        when Menu.Id=10 then 'fa fa-building-o'        
        when Menu.Id=30 then 'fa fa-book'        
        when Menu.Id=56 then 'fa fa-list'        
        when Menu.Id=3023 then 'fa fa-stethoscope'
		when Menu.Id=191810371 then 'fa fa-heart'
        else ISNULL(Screen.IconPath,'') end AS Icon        
            
        FROM sSecurity.tMenu Menu         
        LEFT OUTER JOIN sSecurity.tScreen Screen        
         ON Menu.ScreenId = Screen.Id            
           
        LEFT OUTER JOIN (         
         SELECT         
          P.TaskId,         
          SUM(OT.AvailablePermission & 2) PermissionValue              
         FROM         
          sSecurity.tPermission P        
          INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
          INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
          INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
          INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId         
         --WHERE         
         -- RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) 
		 Where T.Id not in (20834,20853)        
         GROUP BY         
          P.TaskId) TBL2        
         ON         
          Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
         
         WHERE         
         (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
         AND ISNULL(Screen.IsObsolete, 0) = 0        
         --AND (Menu.Id in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023) Or ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
         AND (Menu.Id in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371) Or ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371))        
         AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,
		 191810363,191810364,191810365,191810366,191810367,191810368)       
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
              
        union        
           
         SELECT case when Menu.Id = 3023 then 1 else Menu.Id end AS MenuID,         
         ISNULL(Menu.Id, 0) AS ParentMenuID,         
         Screen1.Title AS MenuTitle,           
         ISNULL(Screen1.Title, '') AS ScreenTitle,            
         ISNULL(Screen1.Page, '')  AS PageURL,        
         ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,        
         ISNULL(Menu.ScreenId, 0) AS ScreenId,        
         ISNULL(PermissionValue, 0) AS Permission,        
         ISNULL(Screen1.OrderIndex, Screen.OrderIndex) AS OrderNumber,        
         ISNULL(Screen1.TaskId,0) AS TaskId,        
         ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
         ISNULL(T.ModuleId,0) AS ModuleId,        
         ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
         ISNULL(Screen1.IconPath,'') AS Icon        
            
        FROM sSecurity.tMenu Menu         
        LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id            
        LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId --AND ResourceTypeId = 0        
        LEFT OUTER JOIN (         
         SELECT         
          P.TaskId,         
          SUM(OT.AvailablePermission & 2) PermissionValue              
         FROM         
       sSecurity.tPermission P        
          INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
          INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
          INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
          INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId               
         where T.Id not in (20834,20853) 
		 GROUP BY         
          P.TaskId        
         ) TBL2        
         ON Screen1.TaskId = TBL2.TaskId         
        WHERE         
        (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
        AND ISNULL(Screen1.IsObsolete, 0) = 0        
        --AND (Menu.ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
        AND (Menu.ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371) or Menu.Id in (3023))        
        AND Menu.Id not in (40,191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)         
        AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
        AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen1.PHIAccessLevel,0)<>1))        
        )         
         MenuTable          
         --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
        WHERE         
         MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
         AND         
         ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
         AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
         AND MenuIsObsolete = 0        
         AND (1=(case when @rResourceTypeId=0 then 0 else 1 end) or (MenuTable.ResourceTypeId !=1))      
             
        ORDER BY         
         ParentMenuID        
   end        
        
 end        
END
GO
PRINT N'Altering Procedure [sSecurity].[pMenuGetRoleWise]...';


GO
CREATE OR ALTER PROCEDURE [sSecurity].[pMenuGetRoleWise]        
 @rUserId [bigint],        
 @rMenuId int = 0,        
 @rResourceTypeId int= 0,        
 @rOrgId int,        
 @rflg bit = 0,   
 @rRoleId int
         
WITH EXECUTE AS CALLER        
AS        
SET NOCOUNT ON        
        
BEGIN        
declare @result varchar(15)='False'        
Select @result = [dbo].[fPHIPermissionUserwise](@rUserId,@rOrgId)        
        
if(@rflg=0)        
         
 begin        
 IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)        
  BEGIN   
   SELECT        
   MenuID,        
   ModuleId,        
   ParentMenuID,        
   MenuTitle,          
   ScreenTitle,           
   case when MenuID = 3314  then '~/Pages/Common/CommonMaster/CommonNavigationMaster.aspx' else         
   case when Menuid=1115 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   case when Menuid=3510 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   PageURL end end end PageURL,        
   ScreenId,        
   Permission,        
   OrderNumber,          
   TaskId,          
    PageURL  AS PagePath,        
    MenuIsObsolete          
  FROM        
    (SELECT Menu.Id AS MenuID,         
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
   Menu.Title AS MenuTitle,           
   ISNULL(Screen.Title, '') AS ScreenTitle,            
   ISNULL(Screen.Page, '') AS PageURL,        
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
   ISNULL(Menu.ScreenId, 0) AS ScreenId,        
   ISNULL(PermissionValue, 0) AS Permission,        
   ISNULL(OrderNumber, 0) AS OrderNumber,        
   ISNULL(Screen.TaskId,0) AS TaskId,        
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
   ISNULL(T.ModuleId,0) AS ModuleId,        
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete            
            
  FROM sSecurity.tMenu Menu         
  LEFT OUTER JOIN sSecurity.tScreen Screen        
   ON Menu.ScreenId = Screen.Id            
           
  LEFT OUTER JOIN (         
      SELECT         
       P.TaskId,         
       SUM(OT.AvailablePermission & 2) PermissionValue              
      FROM         
       sSecurity.tPermissionUser P        
       INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
       INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
       INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
       INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
      where p.userid= @rUserId 
	  AND T.Id not in (20834,20853)            
      GROUP BY         
       P.TaskId) TBL2        
      ON         
       Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId               
      WHERE         
      (Menu.IsObsolete = 0)         
      AND ISNULL(Screen.IsObsolete, 0) = 0 AND Menu.Id not in (191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368))         
      MenuTable          
              
  WHERE         
   MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
   AND         
   ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
   AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
   AND MenuIsObsolete = 0        
  ORDER BY         
   ParentMenuID          
  END        
         
 ELSE         
  BEGIN    
   SELECT        
   MenuID,        
   ModuleId,        
   ParentMenuID,        
   MenuTitle,          
   ScreenTitle,           
   case when MenuID = 3314  then '~/Pages/Common/CommonMaster/CommonNavigationMaster.aspx' else        
   case when Menuid=1115 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
 case when Menuid=3510 then '~/Pages/Common/CommonMaster/GeneralNavigationMaster.aspx' else       
   PageURL end end end PageURL,       
   ScreenId,        
   Permission,        
   OrderNumber,          
   TaskId,          
    PageURL  AS PagePath,        
    MenuIsObsolete          
  FROM        
    (SELECT Menu.Id AS MenuID,         
   ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
   Menu.Title AS MenuTitle,           
   ISNULL(Screen.Title, '') AS ScreenTitle,            
   ISNULL(Screen.Page, '') AS PageURL,        
   ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
   ISNULL(Menu.ScreenId, 0) AS ScreenId,        
   ISNULL(PermissionValue, 0) AS Permission,        
   ISNULL(OrderNumber, 0) AS OrderNumber,        
   ISNULL(Screen.TaskId,0) AS TaskId,        
   ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
   ISNULL(T.ModuleId,0) AS ModuleId,        
   ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete        
            
            
  FROM sSecurity.tMenu Menu         
  LEFT OUTER JOIN sSecurity.tScreen Screen        
   ON Menu.ScreenId = Screen.Id            
           
  LEFT OUTER JOIN (         
      SELECT         
       P.TaskId,         
       SUM(OT.AvailablePermission & 2) PermissionValue              
      FROM         
       sSecurity.tPermission P        
       INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
       INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
       INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
       INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
       INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  RoleId = @rRoleId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId         
      --WHERE         
      -- RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) 
	  WHERE T.Id not in (20834,20853)        
      GROUP BY         
       P.TaskId) TBL2        
      ON         
       Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
               
      WHERE         
      (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
      AND ISNULL(Screen.IsObsolete, 0) = 0 AND Menu.Id not in (191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368) )         
      MenuTable          
      --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
  WHERE         
   MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
   AND         
   ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
   AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
   AND MenuIsObsolete = 0        
           
           
             
  ORDER BY         
   ParentMenuID        
        
   --SELECT DISTINCT Menu.Id AS MenuID,         
  --  ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
  --  Menu.Title AS MenuTitle,         
  --  Menu.TitleResourceKeyId AS MenuResourceKey,         
  --  Screen.Title AS ScreenTitle,        
  --  Screen.TitleResourceKeyId AS ScreenResourceKey,        
  --  Screen.Page AS PageURL        
  --FROM sSecurity.tMenu Menu        
  --LEFT OUTER JOIN sSecurity.tScreen Screen        
  -- ON Menu.ScreenId = Screen.Id        
  --LEFT OUTER JOIN sSecurity.tPermission Permission        
  -- ON Screen.TaskId = Permission.TaskId        
  --WHERE Menu.IsObsolete = 0 AND        
  --  Screen.IsObsolete = 0 AND        
  --  Permission.RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE UserId = @rUserId) AND        
  --  (Permission.Permission & 2) = 2        
  --ORDER BY ParentMenuID        
  END        
 end        
else        
 begin   
 
  IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)        
   begin 
   
    SELECT        
        MenuID,        
        ModuleId,        
        ParentMenuID,        
        MenuTitle,          
        ScreenTitle,           
        case when Menuid=1510 then '~/Pages/MaterialManagement/Procurement/ReportCriteria/Report' else  PageURL end PageURL,       
        ScreenId,        
        Permission,        
        OrderNumber,          
        TaskId,          
        PageURL  AS PagePath,        
        MenuIsObsolete,        
        Icon          
          FROM        
           (        
           SELECT Menu.Id AS MenuID,         
		  ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
          Menu.Title AS MenuTitle,           
          ISNULL(Screen.Title, '') AS ScreenTitle,            
          --case when Menu.Id=3023 then '' else ISNULL(Screen.Page, '') end AS PageURL,        
          ISNULL(Screen.Page, '') AS PageURL,        
          ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
          ISNULL(Menu.ScreenId, 0) AS ScreenId,        
          ISNULL(PermissionValue, 0) AS Permission,        
          ISNULL(OrderNumber, 0) AS OrderNumber,        
          ISNULL(Screen.TaskId,0) AS TaskId,        
          ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
          ISNULL(T.ModuleId,0) AS ModuleId,        
          ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
          case when Menu.Id=18 then 'fa fa-wrench'         
         when Menu.Id=35 then 'fa fa-support'         
         when Menu.Id=15 then 'fa fa-tasks'         
         when Menu.Id=22 then 'fa fa-user'         
         when Menu.Id=34 then 'fa fa-bar-chart'        
         when Menu.Id=31 then 'icon-hourglass'        
         when Menu.Id=33 then 'fa fa-exclamation-triangle'        
         when Menu.Id=11 then 'fa fa-medkit'        
         when Menu.Id=12 then 'fa fa-hospital-o'        
         when Menu.Id=10 then 'fa fa-building-o'        
         when Menu.Id=30 then 'fa fa-book'        
         when Menu.Id=56 then 'fa fa-list'        
         when Menu.Id=3023 then 'fa fa-stethoscope'
		 when Menu.Id=191810371 then 'fa fa-heart'
         else ISNULL(Screen.IconPath,'') end AS Icon        
            
         FROM sSecurity.tMenu Menu         
         LEFT OUTER JOIN sSecurity.tScreen Screen        
          ON Menu.ScreenId = Screen.Id            
           
         LEFT OUTER JOIN (         
          SELECT         
           P.TaskId,         
           SUM(OT.AvailablePermission & 2) PermissionValue              
          FROM         
           sSecurity.tPermissionUser P        
           INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
           INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
           INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
           INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          WHERE p.userid= @rUserId
		  AND T.Id not in (20834,20853)         
          GROUP BY         
           P.TaskId) TBL2        
          ON         
           Screen.TaskId = TBL2.TaskId         
            LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
               
          WHERE         
          (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
          AND ISNULL(Screen.IsObsolete, 0) = 0        
          --AND (Menu.Id in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023) Or ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
          AND (Menu.Id in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371) Or ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371))        
          AND Menu.Id not in (191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)         
          AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
         union        
           
          SELECT case when Menu.Id = 3023 then 1 else Menu.Id end AS MenuID,         
          ISNULL(Menu.Id, 0) AS ParentMenuID,         
          Screen1.Title AS MenuTitle,           
          ISNULL(Screen1.Title, '') AS ScreenTitle,            
          ISNULL(Screen1.Page, '')  AS PageURL,        
          ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,        
          ISNULL(Menu.ScreenId, 0) AS ScreenId,        
          ISNULL(PermissionValue, 0) AS Permission,        
          ISNULL(Screen1.OrderIndex, Screen.OrderIndex) AS OrderNumber,        
          ISNULL(Screen1.TaskId,0) AS TaskId,        
          ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
          ISNULL(T.ModuleId,0) AS ModuleId,        
          ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
          ISNULL(Screen1.IconPath,'') AS Icon        
            
         FROM sSecurity.tMenu Menu         
         LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id            
         LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId         
         LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId --AND ResourceTypeId = 0        
         LEFT OUTER JOIN (         
          SELECT         
         P.TaskId,         
           SUM(OT.AvailablePermission & 2) PermissionValue              
          FROM         
           sSecurity.tPermissionUser P        
           INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
           INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
           INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
           INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          WHERE p.userid= @rUserId
		  AND T.Id not in (20834,20853)         
          GROUP BY         
           P.TaskId        
          ) TBL2        
          ON Screen1.TaskId = TBL2.TaskId         
         WHERE         
         (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
         AND ISNULL(Screen1.IsObsolete, 0) = 0        
         --AND (Menu.ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
         AND (Menu.ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371) or Menu.Id in (3023))        
         AND Menu.Id not in (191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)         
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen1.PHIAccessLevel,0)<>1))        
         )         
          MenuTable          
          --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
         WHERE         
       MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
          AND         
          ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
          AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
          AND MenuIsObsolete = 0        
          AND (1=(case when @rResourceTypeId=0 then 0 else 1 end) or (MenuTable.ResourceTypeId !=1))      
             
         ORDER BY         
          ParentMenuID        
   end        
  else        
   begin  
  
    SELECT        
         MenuID,        
         ModuleId,        
         ParentMenuID,        
         MenuTitle,          
         ScreenTitle,           
         case when Menuid=1510 then '~/Pages/MaterialManagement/Procurement/ReportCriteria/Report' else PageURL end PageURL,        
         ScreenId,        
         Permission,        
         OrderNumber,          
         TaskId,          
       PageURL  AS PagePath,        
       MenuIsObsolete,        
       Icon          
        FROM        
       (        
       SELECT Menu.Id AS MenuID,         
         ISNULL(Menu.ParentMenuID, 0) AS ParentMenuID,         
         Menu.Title AS MenuTitle,           
         ISNULL(Screen.Title, '') AS ScreenTitle,            
         --case when Menu.Id=3023 then '' else ISNULL(Screen.Page, '') end AS PageURL,        
         ISNULL(Screen.Page, '') AS PageURL,        
         ISNULL(Screen.ScreenGroupId,0) AS ScreenGroupId,        
         ISNULL(Menu.ScreenId, 0) AS ScreenId,        
         ISNULL(PermissionValue, 0) AS Permission,        
         ISNULL(OrderNumber, 0) AS OrderNumber,        
         ISNULL(Screen.TaskId,0) AS TaskId,        
         ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
         ISNULL(T.ModuleId,0) AS ModuleId,        
         ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
         case when Menu.Id=18 then 'fa fa-wrench'         
        when Menu.Id=35 then 'fa fa-support'         
        when Menu.Id=15 then 'fa fa-tasks'         
        when Menu.Id=22 then 'fa fa-user'         
        when Menu.Id=34 then 'fa fa-bar-chart'        
        when Menu.Id=31 then 'icon-hourglass'        
        when Menu.Id=33 then 'fa fa-exclamation-triangle'        
        when Menu.Id=11 then 'fa fa-medkit'        
        when Menu.Id=12 then 'fa fa-hospital-o'        
        when Menu.Id=10 then 'fa fa-building-o'        
        when Menu.Id=30 then 'fa fa-book'        
        when Menu.Id=56 then 'fa fa-list'        
        when Menu.Id=3023 then 'fa fa-stethoscope'  
		when Menu.Id=191810371 then 'fa fa-heart'
        else ISNULL(Screen.IconPath,'') end AS Icon        
            
        FROM sSecurity.tMenu Menu         
        LEFT OUTER JOIN sSecurity.tScreen Screen        
         ON Menu.ScreenId = Screen.Id            
           
        LEFT OUTER JOIN (         
         SELECT         
          P.TaskId,         
          SUM(OT.AvailablePermission & 2) PermissionValue              
         FROM         
          sSecurity.tPermission P        
          INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
          INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
          INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
          INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE  RoleId = @rRoleId and UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId         
         --WHERE         
         -- RoleId  IN (SELECT RoleId FROM sSecurity.tUserRole WHERE  UserId = @rUserId AND IsObsolete = 0) 
		 Where T.Id not in (20834,20853)        
         GROUP BY         
          P.TaskId) TBL2        
         ON         
          Screen.TaskId = TBL2.TaskId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen.TaskId AND ResourceTypeId = @rResourceTypeId        
         
         WHERE         
         (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
         AND ISNULL(Screen.IsObsolete, 0) = 0        
         --AND (Menu.Id in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023) Or ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
         AND (Menu.Id in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371) Or ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371))        
         AND Menu.Id not in (191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)        
         AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
              
        union        
           
         SELECT case when Menu.Id = 3023 then 1 else Menu.Id end AS MenuID,         
         ISNULL(Menu.Id, 0) AS ParentMenuID,         
         Screen1.Title AS MenuTitle,           
         ISNULL(Screen1.Title, '') AS ScreenTitle,            
         ISNULL(Screen1.Page, '')  AS PageURL,        
         ISNULL(Screen1.ScreenGroupId,0) AS ScreenGroupId,        
         ISNULL(Menu.ScreenId, 0) AS ScreenId,        
         ISNULL(PermissionValue, 0) AS Permission,        
         ISNULL(Screen1.OrderIndex, Screen.OrderIndex) AS OrderNumber,        
         ISNULL(Screen1.TaskId,0) AS TaskId,        
         ISNULL(T.ResourceTypeId,0) AS ResourceTypeId,        
         ISNULL(T.ModuleId,0) AS ModuleId,        
         ISNULL(Menu.IsObsolete,1) AS MenuIsObsolete,        
         ISNULL(Screen1.IconPath,'') AS Icon        
            
        FROM sSecurity.tMenu Menu         
        LEFT OUTER JOIN sSecurity.tScreen Screen ON Menu.ScreenId = Screen.Id            
        LEFT OUTER JOIN sSecurity.tScreen Screen1 ON Screen1.ScreenGroupId = Screen.ScreenGroupId         
        LEFT OUTER JOIN sSecurity.tTask  T ON T.Id =  Screen1.TaskId --AND ResourceTypeId = 0        
        LEFT OUTER JOIN (         
         SELECT         
          P.TaskId,         
          SUM(OT.AvailablePermission & 2) PermissionValue              
         FROM         
       sSecurity.tPermission P        
          INNER JOIN sSecurity.tTask T ON T.Id = P.TaskId        
          INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId = T.ModuleId AND MP.OrgId = P.OrgId        
          INNER JOIN sCommon.tModuleMaster MM ON MP.ModuleId = MM.Id And  MM.IsObsolete = 0        
          INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgId = @rOrgId        
          INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE RoleId = @rRoleId and UserId = @rUserId AND IsObsolete = 0) UR ON UR.RoleId = P.RoleId               
         where T.Id not in (20834,20853) 
		 GROUP BY         
          P.TaskId        
         ) TBL2        
         ON Screen1.TaskId = TBL2.TaskId         
        WHERE         
        (Menu.IsObsolete = 0)  --For ScreenGroupId Master Page        
        AND ISNULL(Screen1.IsObsolete, 0) = 0        
        --AND (Menu.ParentMenuID in (10,11,12,15,18,22,56,31,32,33,34,35,36,3023))        
        AND (Menu.ParentMenuID in (10,11,12,15,18,22,30,31,33,34,35,56,3023,191810340,191810371) or Menu.Id in (3023))        
        AND Menu.Id not in (191810352,191810353,191810354,191810355,191810356,191810357,191810358,191810359,191810360,191810362,191810363,191810364,191810365,191810366,191810367,191810368)        
        AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen.PHIAccessLevel,0)<>1))        
        AND (1 = (Case when UPPER(@result) = 'TRUE' then 0 else 1 end) or (Isnull(Screen1.PHIAccessLevel,0)<>1))        
        )         
         MenuTable          
         --INNER JOIN sSecurity.tTask  T ON T.Id =  MenuTable.TaskId         
        WHERE         
         MenuTable.ScreenId = 0 OR MenuTable.Permission >= 2         
         AND         
         ((MenuTable.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))        
         AND ((MenuTable.MenuID = @rMenuID)OR(@rMenuID = 0))        
         AND MenuIsObsolete = 0        
         AND (1=(case when @rResourceTypeId=0 then 0 else 1 end) or (MenuTable.ResourceTypeId !=1))      
             
        ORDER BY         
         ParentMenuID        
   end        
        
 end        
END
GO
PRINT N'Altering Procedure [sSecurity].[pMobilePermissionGet]...';


GO

CREATE OR ALTER PROCEDURE [sSecurity].[pMobilePermissionGet]
	@rOrgId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF EXISTS(SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId = @rUserId)
	BEGIN
		SELECT B.*
			FROM
			(
			SELECT		TP.TaskId AS TaskID,
						CAST(MAX(TP.C) AS BIT) AS [Create],
						CAST(MAX(TP.R) AS BIT) AS [Read],
						CAST(MAX(TP.U) AS BIT) AS [Update],
						CAST(MAX(TP.D) AS BIT) AS [Delete],
						CAST(MAX(TP.S) AS BIT) AS [Search],
						CAST(MAX(TP.P) AS BIT) AS [Print],
						CAST(MAX(TP.X) AS BIT) AS [Execute],
						TP.O AS [OrderIndex]
				FROM
				(
					SELECT 	
						TaskId					AS	TaskID,
						(Permission & 1) 		AS	C, --[Create],
						(Permission & 2)/2		AS	R, --[Read],
						(Permission & 4)/4		AS	U, --[Update],
						(Permission & 8)/8		AS	D, --[Delete],
						(Permission & 16)/16 	AS	S, --[Search],
						(Permission & 32)/32 	AS	P, --[Print],
						(Permission & 64)/64 	AS	X, --[Execute],
						(isnull(T1.OrderIndex,0)) AS O
					FROM sSecurity.tPermissionUser P
					INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
					WHERE
					--P.OrgId = @rOrgId AND T1.ModuleId = 227 
					P.OrgId = @rOrgId AND (T1.ModuleId = 215 OR T1.ModuleId = 217 OR T1.ModuleId = 255 OR T1.ModuleId = 250 OR T1.Id = 20626)
					
					 AND P.UserId = @rUserId
					--AND	P.UserId IN (SELECT UserId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId )
				
				) TP 
				GROUP BY TP.TaskId,TP.O
				) B INNER JOIN sSecurity.tTask C ON B.TaskId = C.Id
				Order By C.OrderIndex
	END
	ELSE
	BEGIN	
		SELECT B.*
		FROM
		(
		SELECT		TP.TaskId AS TaskID,
					CAST(MAX(TP.C) AS BIT) AS [Create],
					CAST(MAX(TP.R) AS BIT) AS [Read],
					CAST(MAX(TP.U) AS BIT) AS [Update],
					CAST(MAX(TP.D) AS BIT) AS [Delete],
					CAST(MAX(TP.S) AS BIT) AS [Search],
					CAST(MAX(TP.P) AS BIT) AS [Print],
					CAST(MAX(TP.X) AS BIT) AS [Execute],
						TP.O AS [OrderIndex]
			FROM
			(
				SELECT 	
					TaskId					AS	TaskID,
					(Permission & 1) 		AS	C, --[Create],
					(Permission & 2)/2		AS	R, --[Read],
					(Permission & 4)/4		AS	U, --[Update],
					(Permission & 8)/8		AS	D, --[Delete],
					(Permission & 16)/16 	AS	S, --[Search],
					(Permission & 32)/32 	AS	P, --[Print],
					(Permission & 64)/64 	AS	X, --[Execute],
						(isnull(T1.OrderIndex,0)) AS O
				FROM sSecurity.tPermission P
				INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
				WHERE
				--P.OrgId = @rOrgId AND T1.ModuleId = 227 AND
				P.OrgId = @rOrgId AND (T1.ModuleId = 215 OR T1.ModuleId = 217 OR T1.ModuleId = 255 OR T1.ModuleId = 250 OR T1.Id = 20626) AND
			P.RoleId IN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId )
			
			) TP 
			GROUP BY TP.TaskId , TP.O
			) B INNER JOIN sSecurity.tTask C ON B.TaskId = C.Id
			Order By C.OrderIndex
	 
	END
	 
END
GO
PRINT N'Altering Procedure [sSupport].[pAHCCounsellingReferDoctor]...';


GO

ALTER proc [sSupport].[pAHCCounsellingReferDoctor]
@rDoctorId bigint,
@rHealthIndicatorId int,
@rStatusId int, 
@rstrXML nvarchar(max),
@rCreatedUserId bigint,
@rOrgId int
as  
Begin
	BEGIN TRY
		 BEGIN TRANSACTION	
		 declare @lostrXML  xml
		 declare @empId bigint, @rDoctorName nvarchar(200) = '';

		 declare @lAssignDesignationConfigVal varchar(5);
            
		 select @lAssignDesignationConfigVal = sConfig.fConfigurationValueGet('Provider.AssignDesignationFreezeWiseOrEntityWise',@rOrgId,0,0,0)

		 Set @empId = (select SourceId  from sSecurity.tUser Where id = @rCreatedUserId And SourceTypeId = 95);

		IF (@rDoctorId > 0)
		BEGIN
			set @rDoctorName = (select ISNULL(FirstName, '') + ' ' + ISNULL(LastName, '') from sHrm.tEmployeeMaster where Id = @rDoctorId)
		END

		 set @lostrXML = cast(@rstrXML as xml)

			IF OBJECT_ID('tempdb..#tbltmpAHCTeam') IS NOT NULL 
			BEGIN 
				DROP TABLE #tbltmpAHCTeam
			END

			Create table #tbltmpAHCTeam
			(
				tid int identity(1,1),
				ProviderAppointmentId bigint,
				CSVNonPathoParameters nvarchar(max),
				HealthIndicatorCurrentStatus int
			)
			insert into #tbltmpAHCTeam
			select T.c.value('@ProviderAppointmentId','int') as ProviderAppointmentId,
			T.c.value('@CSVNonPathoParameters','nvarchar(max)') as CSVNonPathoParameters, 0
			from @lostrXML.nodes('/StatusChange/StatusData')T(c)

			update tmp set tmp.HealthIndicatorCurrentStatus = PA.HealthIndicatorId from #tbltmpAHCTeam tmp 
			INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = tmp.ProviderAppointmentId

			MERGE sSupport.tProviderAppointment AS TARGET
USING (SELECT * FROM #tbltmpAHCTeam) AS SOURCE
ON TARGET.Id = SOURCE.ProviderAppointmentId AND TARGET.OrgId = @rOrgId
WHEN MATCHED THEN
    UPDATE SET  
        HealthIndicatorId = @rHealthIndicatorId,
        AssignToDoctorId = @rDoctorId,
        UpdatedUserId = @rCreatedUserId,
        UpdatedDateTime = sCommon.fGetDate(),
		NonPathoParameters = CSVNonPathoParameters,
		AssignByDoctorId = @empId,
		AssignDate = sCommon.fGetDate(),
        StatusId = CASE 
                      WHEN @rHealthIndicatorId = 608 OR @rHealthIndicatorId = 611 OR @rHealthIndicatorId = 612 THEN @rStatusId 
					  WHEN @rHealthIndicatorId = 606 OR @rHealthIndicatorId = 607 THEN 609
                      ELSE TARGET.StatusId 
                   END;

			Insert into sSupport.tProviderAppointmentlog
			select AHCT.ProviderAppointmentId, CASE 
                      WHEN @rHealthIndicatorId = 608 OR @rHealthIndicatorId = 611 OR @rHealthIndicatorId = 612 THEN @rStatusId 
					  WHEN @rHealthIndicatorId = 606 OR @rHealthIndicatorId = 607 THEN 609
                      ELSE PA.StatusId END, 
					  @rCreatedUserId, sCommon.fGetDate(),'Refer to Doctor ' + @rDoctorName
			from #tbltmpAHCTeam AHCT
			INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId

			--Health Indicator Log
			Insert into sSupport.tProviderAppointmentHealthIndicatorLog
			select AHCT.ProviderAppointmentId, @rHealthIndicatorId, @rCreatedUserId, sCommon.fGetDate(),'Refer to Doctor ' + @rDoctorName
			from #tbltmpAHCTeam AHCT
			INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId

			if (@lAssignDesignationConfigVal = 'True' AND @rHealthIndicatorId = 606)
			BEGIN
				UPDATE tpa SET tpa.HealthIndicatorId = (CASE WHEN CAST(DetailsVital.BMI AS Float) >= 30 AND CAST(DetailsVital.BMI AS Float) <= 35 THEN 612
													WHEN CAST(DetailsVital.BloodPressureSystolic AS Float) >= 150 AND CAST(DetailsVital.BloodPressureSystolic AS Float) <= 160 THEN 612
													WHEN CAST(DetailsVital.BloodPressureDiastolic AS Float) >= 100 AND CAST(DetailsVital.BloodPressureDiastolic AS Float) <= 110 THEN 612
													WHEN CAST(Details.HB AS Float) >= 8 and CAST(Details.HB AS Float) < 10 THEN 612
													WHEN CAST(Details.HBA1C AS Float) >= 8 and CAST(Details.HBA1C AS Float) <= 10 THEN 612
													WHEN CAST(Details.[SERUM CREATININE] AS Float) >= 1.5 AND CAST(Details.[SERUM CREATININE] AS Float) <= 2 THEN 612
													WHEN CAST(Details.[SERUM URIC ACID] AS Float) >= 7.7 AND CAST(Details.[SERUM URIC ACID] AS Float) <= 9.4 THEN 612
													WHEN CAST(Details.[TRIGLYCERIDE] AS Float) >= 200 AND CAST(Details.[TRIGLYCERIDE] AS Float) <= 500 THEN 612
													WHEN CAST(Details.[LDL] AS Float) >= 150 AND CAST(Details.[LDL] AS Float) <= 200 THEN 612
													WHEN CAST(Details.[TSH] AS Float) >= 11 AND CAST(Details.[TSH] AS Float) <= 50 THEN 612
													WHEN CAST(Details.[PSA] AS Float) > 5 THEN 612
													--Mild
													WHEN CAST(DetailsVital.BMI AS Float) >= 26 AND CAST(DetailsVital.BMI AS Float) < 30 THEN 611
													WHEN CAST(DetailsVital.BloodPressureSystolic AS Float) >= 140 AND CAST(DetailsVital.BloodPressureSystolic AS Float) < 150 THEN 611
													WHEN CAST(DetailsVital.BloodPressureDiastolic AS Float) >= 90 AND CAST(DetailsVital.BloodPressureDiastolic AS Float) < 100 THEN 611
													WHEN CAST(Details.HB AS Float) >= 10 and CAST(Details.HB AS Float) < 12 THEN 611
													WHEN CAST(Details.HBA1C AS Float) >= 6.5 and CAST(Details.HBA1C AS Float) < 8 THEN 611
													WHEN CAST(Details.[SERUM CREATININE] AS Float) >= 1.3 AND CAST(Details.[SERUM CREATININE] AS Float) < 1.5 THEN 611
													WHEN CAST(Details.[SERUM URIC ACID] AS Float) >= 6.5 AND CAST(Details.[SERUM URIC ACID] AS Float) < 7.7 THEN 611
													WHEN CAST(Details.[TRIGLYCERIDE] AS Float) >= 150 AND CAST(Details.[TRIGLYCERIDE] AS Float) < 200 THEN 611
													WHEN CAST(Details.[LDL] AS Float) >= 101 AND CAST(Details.[LDL] AS Float) < 150 THEN 611
													WHEN CAST(Details.[TSH] AS Float) >= 5.6 AND CAST(Details.[TSH] AS Float) < 11 THEN 611
													Else 606 END),
							tpa.UpdatedDateTime = sCommon.fGetDate()
						FROM sSupport.tProviderAppointment AS tpa
						INNER JOIN #tbltmpAHCTeam AS ot ON ot.ProviderAppointmentId = tpa.Id
						INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId = tpa.PatientSourceId AND EXM.SetupId = tpa.SetupId
						INNER JOIN sExamination.tSetupMaster AS STM ON STM.ID = EXM.SetupId
						INNER JOIN sExamination.tSubTypeMaster AS SSM ON SSM.Id = STM.SubTypeId
						INNER JOIN sIp.tStoreLocationMaster AS SLM ON SLM.Id = EXM.StoreLocationId
						LEFT JOIN  
						(
							SELECT ExaminationId, Details.[R.B.C. COUNT], Details.[MCV], Details.[F B S], Details.[CHOLESTEROL],  
								   Details.[TRIGLYCERIDE], Details.[LDL], Details.[HDL], Details.[SGPT],  
								   Details.[ECG], Details.[SONOGRAPHY], Details.[TMT], Details.[ECHO],  
								   Details.[HB], Details.[SERUM CREATININE], Details.[SERUM URIC ACID], [HBA1C], [R B S], [P P B S], 
								   Details.[Waist Circumference], Details.[TSH], Details.[PSA], Details.[XRAY]
							FROM sExamination.tExamination AS EXM
							LEFT JOIN
							(
								SELECT ExaminationId, [R.B.C. COUNT], [MCV], [F B S], [CHOLESTEROL], [TRIGLYCERIDE], [LDL], [HDL],  
									   [SGPT], [ECG], [SONOGRAPHY], [TMT], [ECHO], [HB], [SERUM CREATININE], [SERUM URIC ACID], [HBA1C], [R B S], [P P B S], 
									   [Waist Circumference], [TSH], [PSA], [XRAY]
								FROM  
								(
									SELECT SPM.Title, TR.SourceId [ExaminationId], TRD.ServiceValue  
									FROM sOrderEntry.tStaticTestParameterMaster AS SPM  
									INNER JOIN sOrderEntry.tTestParameterMaster AS TPM ON TPM.StaticTestParameterId = SPM.Id  
									INNER JOIN sOrderEntry.tTestDetail AS TTD ON TTD.TestParameterId = TPM.Id  
									INNER JOIN sExamination.tTestRequestDetail AS TRD ON TRD.TestDetailId = TTD.Id  
									INNER JOIN sExamination.tTestRequest AS TR ON TR.Id = TRD.TestRequestId  
									WHERE SPM.Id in (3, 5, 19, 20, 21, 25, 31, 32, 33, 34, 38, 107, 104, 105, 109, 108, 2, 27, 49, 166, 54, 58)
								)
								d PIVOT
								(
									MIN(ServiceValue) FOR Title IN  
									(
										[R.B.C. COUNT], [MCV], [F B S], [CHOLESTEROL], [TRIGLYCERIDE], [LDL], [HDL], [SGPT],  
										[ECG], [SONOGRAPHY], [TMT], [ECHO], [HB], [SERUM CREATININE], [SERUM URIC ACID], [HBA1C], [R B S], [P P B S], 
										[Waist Circumference], [TSH], [PSA], [XRAY]
									)
								) piv
							) AS Details ON Details.ExaminationId = EXM.Id
						) AS Details ON Details.ExaminationId = EXM.Id
						LEFT JOIN 
						(
							SELECT TR.SourceId AS ExaminationId, TRD.Remark
							FROM sExamination.tTestRequestDetail TRD
							INNER JOIN sOrderEntry.tTestDetail TTD ON TTD.Id = TRD.TestDetailId
							INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TTD.TestParameterId
							INNER JOIN sOrderEntry.tStaticTestParameterMaster SPM ON SPM.Id = TPM.StaticTestParameterId
							INNER JOIN sExamination.tTestRequest TR ON TR.Id = TRD.TestRequestId
							WHERE SPM.Id = 108
						) AS ECHO_REMARKS ON ECHO_REMARKS.ExaminationId = EXM.Id
						LEFT JOIN 
						(
							SELECT TR.SourceId AS ExaminationId, TRD.Remark
							FROM sExamination.tTestRequestDetail TRD
							INNER JOIN sOrderEntry.tTestDetail TTD ON TTD.Id = TRD.TestDetailId
							INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TTD.TestParameterId
							INNER JOIN sOrderEntry.tStaticTestParameterMaster SPM ON SPM.Id = TPM.StaticTestParameterId
							INNER JOIN sExamination.tTestRequest TR ON TR.Id = TRD.TestRequestId
							WHERE SPM.Id = 107
						) AS ECG_REMARKS ON ECG_REMARKS.ExaminationId = EXM.Id
						LEFT JOIN
						 (
						  SELECT EXM.ID [ExaminationId],DetailsVital.[BMI],DetailsVital.[BloodPressureSystolic], DetailsVital.[BloodPressureDiastolic]
						  FROM sExamination.tExamination AS EXM  
						  LEFT JOIN
						  (
						   SELECT VTL.SourceId [ExaminationId],
						   ISNULL(BMI, 0) as BMI, 
						   ISNULL(BloodPressureSystolic, 0) as BloodPressureSystolic,
						   ISNULL(BloodPressureDiastolic, 0) as BloodPressureDiastolic
						   FROM sExamination.tVital AS VTL
						  ) AS DetailsVital ON DetailsVital.ExaminationId = EXM.Id
						 ) AS DetailsVital ON DetailsVital.ExaminationId = EXM.Id
						WHERE EXM.ParticipantSourceTypeId = 95 AND ot.HealthIndicatorCurrentStatus = 607
						AND EXM.OrgId = @rOrgId;

						UPDATE PA SET PA.AssignToDoctorId = SE.SiteDoctorId,
							   PA.HealthIndicatorId = (CASE WHEN SE.SiteDoctorId IS NULL THEN 606 ELSE PA.HealthIndicatorId END),
							   PA.AssignDate = sCommon.fGetDate()
						FROM sSupport.tProviderAppointment AS PA
						INNER JOIN #tbltmpAHCTeam AS ot ON ot.ProviderAppointmentId = PA.Id
						INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId = PA.PatientSourceId AND EXM.SetupId = PA.SetupId
						INNER JOIN sExamination.tSetupEmployee AS SE ON SE.SetupId = EXM.SetupId AND SE.EmployeeId = EXM.ParticipantSourceId
						INNER JOIN sExamination.tSetupMaster AS STM ON STM.ID = EXM.SetupId
						INNER JOIN sExamination.tSubTypeMaster AS SSM ON SSM.Id = STM.SubTypeId
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EXM.ParticipantSourceId
						WHERE EXM.ParticipantSourceTypeId = 95
						AND EXM.OrgId = @rOrgId AND ot.HealthIndicatorCurrentStatus = 607
						AND (PA.HealthIndicatorId = 611 OR PA.HealthIndicatorId = 612);

						UPDATE tpa SET tpa.StatusId=CASE WHEN HealthIndicatorId = 611 OR HealthIndicatorId = 612 THEN @rStatusId 
                                                         WHEN HealthIndicatorId = 606 THEN 609 ELSE TPA.StatusId END,
							tpa.UpdatedDateTime = sCommon.fGetDate()
						FROM sSupport.tProviderAppointment AS tpa
						INNER JOIN #tbltmpAHCTeam AS ot ON ot.ProviderAppointmentId = tpa.Id
						INNER JOIN sExamination.tExamination AS EXM ON EXM.ParticipantSourceId = tpa.PatientSourceId AND EXM.SetupId = tpa.SetupId
						WHERE EXM.ParticipantSourceTypeId = 95 AND ot.HealthIndicatorCurrentStatus = 607
						AND EXM.OrgId = @rOrgId;

						Insert into sSupport.tProviderAppointmentlog
						select AHCT.ProviderAppointmentId, PA.StatusId, @rCreatedUserId, sCommon.fGetDate(),
							   'Refer to Doctor ' + ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '')
						from #tbltmpAHCTeam AHCT
						INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId
						LEFT JOIN sHRM.tEmployeeMaster EM ON EM.Id = PA.AssignToDoctorId
						WHERE AHCT.HealthIndicatorCurrentStatus = 607

						--Health Indicator Log
						Insert into sSupport.tProviderAppointmentHealthIndicatorLog
						select AHCT.ProviderAppointmentId, PA.HealthIndicatorId, @rCreatedUserId, sCommon.fGetDate(),
							   'Refer to Doctor ' + ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '')
						from #tbltmpAHCTeam AHCT
						INNER JOIN sSupport.tProviderAppointment PA ON PA.Id = AHCT.ProviderAppointmentId
						LEFT JOIN sHRM.tEmployeeMaster EM ON EM.Id = PA.AssignToDoctorId
						WHERE AHCT.HealthIndicatorCurrentStatus = 607
			END

		
		COMMIT TRANSACTION
		SELECT 1 AS Result
	END TRY
	
	BEGIN CATCH 
		IF @@TRANCOUNT > 0
        ROLLBACK
		--SELECT -1 AS Result
		select ERROR_MESSAGE() 
	END CATCH	

end

GO
PRINT N'Altering Procedure [sSupport].[pDocumentListGet]...';


GO

ALTER proc [sSupport].[pDocumentListGet]

@readpermission bit = null,
@deletepermission bit = null,
@orgid int,
@rConfVal int,
@rDocumentTypeId int = 0,
@rVersionTypeId int = 0,
@rRole int = 0,
@rUserId bigint = 0
as
begin
	
	declare @res varchar(max)='',@delmessage varchar(100)='''Are you sure to delete this item?'''
	if(@rConfVal=1)
	begin
		select @res = @res + '<tr><td>' + LI.Title + '</td><td>' + DTM.Title + '</td><td>' + VTM.Title + '</td><td>' + HD.DocumentName + '</td>
		<td>' + case when @readpermission = 1 then + '<a target="_blank" class="clsview" href="../../..'+replace(HD.DocumentPath,'~','')+' ">View</a>' else '' end + '</td>
		<td>' + case when @readpermission = 1 then + '<a attrcode="' + convert(varchar, isnull(HD.DocumentUploadId,HD.CreatedUserId)) + '" onclick="downloadthis(this,' + convert(varchar,@orgid) + ',''' + (select convert(varchar,Id) from [sSupport].[tDataUpdateLog] 
		where Id = HD.DataLogId) + ''',''' +HD.DocumentName + ''');" style="cursor:pointer;">Download</a>' else '' end + '</td></tr>'
		from [sSupport].[tDocumentMangementDetail] HD
		inner join [sSupport].[tDataUpdateLog] LI on HD.DataLogId = LI.Id
		LEFT JOIN [sSupport].[tDocumentTypeMaster] DTM ON DTM.Id = LI.DocumentTypeId			
			LEFT JOIN [sSupport].[tVersionTypeMaster] VTM ON VTM.Id = LI.VersionTypeId	
		where  HD.Type=1 
		and ((LI.DocumentTypeId=@rDocumentTypeId) OR (@rDocumentTypeId= 0)) 
			and ((LI.VersionTypeId=@rVersionTypeId) OR (@rVersionTypeId= 0)) 
 AND HD.DocumentUploadId IN (@rRole, @rUserId);
	end
	else if (@rConfVal=2)
	begin
		select @res = @res + '<tr><td>' + LI.Title + '</td><td>' + DTM.Title + '</td><td>' + VTM.Title + '</td><td>' + HD.DocumentName + '</td>	<td>' + case when @readpermission = 1 then + '<a attrMTitle="' + convert(varchar,isnull(HD.DocumentUploadId,HD.CreatedUserId)) + '"	attrCode="' + convert(varchar,LI.Id) + '"	attrTitle="' + HD.DocumentName + '"	attrExt="' + SUBSTRING(HD.DocumentName,CHARINDEX('.',HD.DocumentName)+1,LEN(HD.DocumentName)) + '"	onclick="Viewthis(this);" style="cursor:pointer;">View</a>' else '' end + '</td>
	<td>' + case when @readpermission = 1 then + '<a attrcode="' + convert(varchar, isnull(HD.DocumentUploadId,HD.CreatedUserId)) + '" onclick="downloadthis(this,' + convert(varchar,@orgid) + ',''' + (select convert(varchar,Id) from [sSupport].[tDataUpdateLog] where Id = HD.DataLogId) + ''',''' + HD.DocumentName + ''');" style="cursor:pointer;">Download</a>' else '' end + '</td></tr>'
	from [sSupport].[tDocumentMangementDetail] HD inner join [sSupport].[tDataUpdateLog] LI on HD.DataLogId = LI.Id	
			LEFT JOIN [sSupport].[tDocumentTypeMaster] DTM ON DTM.Id = LI.DocumentTypeId			
			LEFT JOIN [sSupport].[tVersionTypeMaster] VTM ON VTM.Id = LI.VersionTypeId	
		where  HD.Type=2 
		and ((LI.DocumentTypeId=@rDocumentTypeId) OR (@rDocumentTypeId= 0)) 
			and ((LI.VersionTypeId=@rVersionTypeId) OR (@rVersionTypeId= 0)) 
 AND HD.DocumentUploadId IN (@rRole, @rUserId);
	end
	else if(@rConfVal=3)

	begin
		select @res = @res + '<tr><td>' + LI.Title + '</td><td>' + DTM.Title + '</td><td>' + VTM.Title + '</td><td>' + HD.DocumentName + '</td>
	<td>' + case when @readpermission = 1 then + '<a attrOrgId="' + convert(varchar,@orgid) + '"
	attrTitle="' + convert(varchar,isnull(HD.DocumentUploadId,HD.CreatedUserId)) + '"
	attrCode="' + convert(varchar,LI.Id) + '"
	attrName="' + HD.DocumentName + '" style="cursor:pointer" onclick="ViewAzure(this);">View</a>' else '' end + '</td>
	<td>' + case when @readpermission = 1 then + '<a attrOrgId="' + convert(varchar,@orgid) + '"
	attrTitle="' + convert(varchar,isnull(HD.DocumentUploadId,HD.CreatedUserId)) + '"
	attrCode="' + convert(varchar,LI.Id) + '"
	attrName="' + HD.DocumentName  + '" style="cursor:pointer" onclick="DownloadAzure(this);">Download</a>' else '' end + '</td></tr>'
	from [sSupport].[tDocumentMangementDetail] HD
	inner join [sSupport].[tDataUpdateLog] LI on HD.DataLogId = LI.Id
			LEFT JOIN [sSupport].[tDocumentTypeMaster] DTM ON DTM.Id = LI.DocumentTypeId			
			LEFT JOIN [sSupport].[tVersionTypeMaster] VTM ON VTM.Id = LI.VersionTypeId	
		where HD.Type=3 
		and ((LI.DocumentTypeId=@rDocumentTypeId) OR (@rDocumentTypeId= 0)) 
			and ((LI.VersionTypeId=@rVersionTypeId) OR (@rVersionTypeId= 0))
 AND HD.DocumentUploadId IN (@rRole, @rUserId);
	end

	select @res as res

end
GO
PRINT N'Altering Procedure [sSupport].[pSetUpLocationGet]...';


GO
  
ALTER proc [sSupport].[pSetUpLocationGet]
@rOrgId int,  
@rEmployeeId bigint,
@rSetUpGroupId int
as    
begin  
 Declare @rSetUpId bigint, @rStoreLocationId bigint;
IF(@rSetUpGroupId = 0)
BEGIN
    select @rSetUpGroupId = (select Top 1 Id from [sExamination].[tSetupGroupMaster] where MainTypeId = 1 and OrgId = @rOrgId and Isnull(IsProviderHealthCheckup,0)=1)  
END

 Select SM.Id as SetUpId, SM.StoreLocationId, @rSetUpGroupId as SetUpGroupId,  
 MIN(SM.FromDate) as FromDate,  
 MAX(SM.ToDate) as ToDate  
 FROM  sExamination.tSetupEmployee SE  
 Inner join [sExamination].[tSetupMaster] SM On SM.Id=SE.SetupId  
 Where SM.SetUpGroupId = @rSetUpGroupId and SE.EmployeeId=@rEmployeeId  
 Group BY SM.Id, SM.StoreLocationId  
end
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramMasterDocumentsDatas]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramMasterDocumentsDatas]
(
	@ReqId BIGINT,
	@readpermission BIT = NULL,
	@deletepermission BIT = NULL,
	@orgid INT,
	@rConfVal INT
)
AS
BEGIN
	DECLARE @res VARCHAR(MAX)='',@delmessage VARCHAR(100)='''Are you sure to delete this item?'''
	IF(@rConfVal=1)
	BEGIN
		SELECT
			@res = @res + '<tr><td>' + FileName + '</td>
			<td>' + CASE WHEN @readpermission = 1 THEN + '<a target="_blank" class="clsview" href="../../../Content/' + CONVERT(VARCHAR,@orgid) + '/ProgramMaster/' +  CONVERT(VARCHAR,PM.Id) + '/' + FileName + '">View</a>' ELSE '' END + '</td>
			<td>' + CASE WHEN @readpermission = 1 THEN + '<a attrcode="' + CONVERT(VARCHAR,PM.Id) + '" onclick="downloadthis(this,' + CONVERT(VARCHAR,@orgid) + ',''' +  CONVERT(VARCHAR,PM.Id)+ ''',''' + FileName + ''');" style="cursor:pointer;">Download</a>' ELSE '' END + '</td>		<td>' + CASE WHEN @deletepermission = 1 THEN + '<a href="javascript:;" onclick="if (!confirm('+@delmessage+')) { false } else { deletethis(' + CONVERT(VARCHAR,PM.Id) + ',this) }">Delete</a>' ELSE '' END + '</td></tr>'
		FROM 
			[sSupport].[tProgram] PM
		WHERE
			PM.Id = @ReqId 
		AND 
			PM.ConfigurationTypeId=1
	END
	SELECT @res AS res
END
GO
PRINT N'Creating Procedure [sWellness].[pMobWellnessAppointmentListGet]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pMobWellnessAppointmentListGet] 
 @rEmployeeId Bigint,     
 @rOrgId int,    
 @rVisitPurposeId int=0,     
 @rStatusId int=0,    
 @rEmpCode nvarchar(50),    
 @rStoreLocationId int=0    
    
WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
    
BEGIN    
SELECT    
 A.Id,A.AppointmentNumber,A.MainType,Setup as RoundType,    
 A.PatientName as EmployeeName,replace(A.Relation,'Ohter','Other') as Relation,    
 A.DoctorName,A.AppointmentDate,case when A.Timeslot is null then '' else A.Timeslot end as TimeSlot,    
 A.StatusId,A.Status,A.AppointmentType,case when A.MeetingId is null then '' else A.MeetingId end as MeetingId,
 case when A.MeetingPassword is null then '' else A.MeetingPassword end as MeetingPassword,A.IsCompleted,  
 A.IsMeetingStarted,IsMeetingCreated,OMA.MeetingProviderId,OMA.APIKey,OMA.APISecret,    
 OMA.WebAPIKey,OMA.WebAPISecret,A.FollowupRemark as Complaints, (select Count(*) from [sWellness].[tWellnessAppointmentDocuments] Where AppointmentId = A.Id) as DocumentCount ,
 A.StoreLocation,CM.Title as VisitPurpose , A.CompliantRemark as AppointmentComplaints
FROM [sWellness].[vMobExtPatientWellnessAppointmentDetail] A
 LEFT OUTER JOIN sCommon.tOnlineMeetingAccount OMA on A.DoctorEmployeeId=OMA.EmployeeId
 LEFT JOIN sExamination.tExamination E ON A.ReferSourceId = E.Id
 LEFT JOIN sExamination.tCauseMaster CM on CM.Id = A.CauseId
WHERE (A.OrgId = @rOrgId)
 AND A.EmployeeCode=(select code from sHrm.tEmployeeMaster where Id=@rEmployeeId)
 AND IsNULL(E.IsCancel,0) = 0
 AND (A.StatusId=@rStatusId or ISNULL(@rStatusId,0)=0)
 AND (A.CauseId=@rVisitPurposeId or isnull(@rVisitPurposeId,0)=0)
 AND (A.EmployeeCode = @rEmpCode OR ISNULL(@rEmpCode, '') = '')
 AND (A.StoreLocationId = @rStoreLocationId or isnull(@rStoreLocationId,0)=0)
ORDER BY A.AppointmentNumber DESC
END
GO
PRINT N'Creating Procedure [sWellness].[pAddORUpdateProgramCustomField]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAddORUpdateProgramCustomField]
(
    @rProgramId INT,
    @rUserId bigint,
    @rProgramCustomFields [sWellness].[udt_ProgramCustomFieldTableType] READONLY,
    @rResult INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ModifiedRows INT = 0;

    DELETE PCF
    FROM [sWellness].[tProgramCustomField] PCF
    WHERE PCF.ProgramId = @rProgramId
      AND NOT EXISTS (
            SELECT 1
            FROM @rProgramCustomFields S
            WHERE S.Id = PCF.Id
        );

    UPDATE T
    SET		  
        FieldTitle = s.FieldTitle, 
		FieldRemark = s.FieldRemark,
		FieldTypeId = s.FieldTypeId, 
        FieldList = s.FieldList,
        IsMandatory = s.IsMandatory,
        FieldOrderIndex = s.FieldOrderIndex,
		UpdatedUserId = @rUserId,
		UpdatedDateTime = sCommon.fGetDate()
    FROM [sWellness].[tProgramCustomField] T
    INNER JOIN @rProgramCustomFields S
        ON T.Id = S.Id
    WHERE S.Id > 0;

    SET @ModifiedRows = @ModifiedRows + @@ROWCOUNT;

    INSERT INTO [sWellness].[tProgramCustomField]
    (
         ProgramId
		,FieldTitle
		,FieldRemark
		,FieldTypeId
		,FieldList
		,IsMandatory
		,FieldOrderIndex
		,CreatedUserId
		,CreatedDatetime
    )
    SELECT 
        @rProgramId,
        PCF.FieldTitle,
		PCF.FieldRemark,
		PCF.FieldTypeId,
		PCF.FieldList,
		PCF.IsMandatory,
		PCF.FieldOrderIndex,
		@rUserId,
		sCommon.fGetDate()

    FROM @rProgramCustomFields PCF
    WHERE Id = 0;

    SET @ModifiedRows = @ModifiedRows + @@ROWCOUNT;

    SET @rResult = @ModifiedRows;
END
GO
PRINT N'Creating Procedure [sWellness].[pAddProgramCustomFieldResponse]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAddProgramCustomFieldResponse]
(   
    @rUserId bigint,
    @rProgramCustomFieldResponse [sWellness].[ProgramCustomFieldResponseTableType] READONLY,
    @ResultCount INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @RowsAffected INT = 0;

        INSERT INTO [sWellness].[tProgramCustomFieldResponse]
        (
            ProgramParticipantId,
            ProgramCustomFieldId,
            ProgramCustomFieldValue,
            CreatedUserId,
            CreatedDatetime
        )
        SELECT			
            ProgramParticipantId,
            ProgramCustomFieldId,
            ProgramCustomFieldValue,
			@rUserId,
			sCommon.fGetDate()
        FROM @rProgramCustomFieldResponse;

        SET @RowsAffected = @@ROWCOUNT;


    SET @ResultCount = @RowsAffected;
END
GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdateProgramTypeMaster]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramTypeMaster]
(				
	@rId INT = 0,
	@rTitle NVARCHAR(100),
	@rCode NVARCHAR(100),
	@rIsObsolete BIT,
	@rOrgId SMALLINT,
	@rCreatedUserId BIGINT,
	@rUpdatedUserId BIGINT
)	
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lNextNumber BIGINT
		IF(@rId = 0)	
		BEGIN
			IF  EXISTS(SELECT Id FROM  [sWellness].[tProgramTypeMaster] WHERE Title=@rTitle AND Id <> @rId)
			BEGIN
				SELECT -102 AS Result -- Title Already Exists
				RETURN
			END

			IF  EXISTS(SELECT Id FROM [sWellness].[tProgramTypeMaster] WHERE Code=@rCode AND Id <> @rId)
			BEGIN
				SELECT -103 AS Result -- Code Already Exists
				RETURN
			END

			INSERT INTO [sWellness].[tProgramTypeMaster] (Title,Code,IsObsolete,OrgId, CreatedUserId,CreatedDateTime)
			Values (@rTitle,@rCode,@rIsObsolete,@rOrgId,@rCreatedUserId,sCommon.fGetDate())
			SET @lNextNumber = SCOPE_IDENTITY();
			SELECT @lNextNumber AS Result
			RETURN				
		END	 
		ELSE
		BEGIN	 

			IF  EXISTS(SELECT Id FROM [sWellness].[tProgramTypeMaster] WHERE Title=@rTitle AND Id <> @rId)
			BEGIN
				SELECT -102 AS Result -- Title Already Exists
				RETURN
			END

			IF  EXISTS(SELECT Id FROM [sWellness].[tProgramTypeMaster] WHERE Code=@rCode AND Id <> @rId)
			BEGIN
				SELECT -103 AS Result -- Code Already Exists
				RETURN
			END

			UPDATE 
				[sWellness].[tProgramTypeMaster]
			SET			
				Title=@rTitle,
				Code=@rCode,			
				IsObsolete=@rIsObsolete,	
				UpdatedUserId=@rUpdatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
			WHERE 
				Id = @rId

			SELECT @rId AS Result
			RETURN @rId
		 END     
	END TRY
	BEGIN CATCH 
	  SELECT -101 AS Result
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pListProgramTypeMaster]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pListProgramTypeMaster]
(
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

	BEGIN TRY
		SELECT 
			PTM.Id,
			PTM.Code,
			PTM.Title,
			PTM.IsObsolete			
		FROM
			[sWellness].[tProgramTypeMaster] PTM
		WHERE
			PTM.IsObsolete = 0
		AND
			PTM.OrgId = @rOrgId
		ORDER BY
			PTM.Id DESC
	END TRY
	BEGIN CATCH 
	  SELECT -101 AS Result
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramTypeMaster]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramTypeMaster]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

	BEGIN TRY
		SELECT 
			PTM.Id,
			PTM.Code,
			PTM.Title,
			PTM.IsObsolete			
		FROM
			[sWellness].[tProgramTypeMaster] PTM
		WHERE
			PTM.OrgId = @rOrgId
		AND
			PTM.Id = @rId
	END TRY
	BEGIN CATCH 
	  SELECT -101 AS Result
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pDeleteProgramTypeMaster]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pDeleteProgramTypeMaster]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

    BEGIN TRY    
		DELETE FROM [sWellness].[tProgramTypeMaster] WHERE OrgId = @rOrgId AND Id = @rId ;

        IF @@ROWCOUNT > 0
            SELECT 1 AS Result;  -- Return 1 if deletion is successful
        ELSE
            SELECT 0 AS Result;  -- Return 0 if no record was found

    END TRY
    BEGIN CATCH 
        SELECT -101 AS Result;  -- Return -101 in case of an error
    END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pInsertProgramParticipants]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pInsertProgramParticipants]
(
@rProgramId INT,
@rRegisterTypeId SMALLINT,
@rParticipantSourceTypeId INT,
@rParticipantSourceId BIGINT,
@rParticipantCode NVARCHAR(200),
@rParticipantName NVARCHAR(200),
@rParticipantEmail NVARCHAR(200),
@rParticipantMobileNo NVARCHAR(20),
@rParticipantBirthDate DATE,
@rParticipantGender INT,
@rParticipantLocationId BIGINT,
@rParticipantDepartmentId BIGINT,
@rCreatedUserId BIGINT
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Result INT = 0,
		@ParticipantAge SMALLINT = 0;
	
	INSERT INTO [sWellness].[tProgramParticipant]
           ([ProgramId]
           ,[RegisterTypeId]
           ,[ParticipantSourceTypeId]
           ,[ParticipantSourceId]
           ,[RegisterDateTime]
           ,[ParticipantCode]
           ,[ParticipantName]
           ,[ParticipantEmail]
           ,[ParticipantMobileNo]
           ,[ParticipantBirthDate]
           ,[ParticipantAge]
           ,[ParticipantGender]
           ,[ParticipantLocationId]
           ,[ParticipantDepartmentId]
           ,[CreatedUserId]
           ,[CreatedDateTime])
     VALUES
           (@rProgramId
           ,@rRegisterTypeId
           ,@rParticipantSourceTypeId
           ,@rParticipantSourceId
           ,sCommon.fGetDate()
           ,@rParticipantCode
           ,@rParticipantName
           ,@rParticipantEmail
           ,@rParticipantMobileNo
           ,@rParticipantBirthDate
           ,@ParticipantAge
           ,@rParticipantGender
           ,@rParticipantLocationId
           ,@rParticipantDepartmentId
           ,@rCreatedUserId
           ,sCommon.fGetDate())
		
	SET @Result = SCOPE_IDENTITY();
	SELECT @Result AS Id
END;
GO
PRINT N'Creating Procedure [sWellness].[pIsProgramTypeMasterUsed]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pIsProgramTypeMasterUsed]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

    BEGIN TRY    
		SELECT 
			COUNT(*)
		FROM 
			[sWellness].[tProgramSubTypeMaster] 
		WHERE 
			OrgId = @rOrgId
		AND
			ProgramTypeMasterId = @rId
    END TRY
    BEGIN CATCH 
        SELECT -101 AS Result;  -- Return -101 in case of an error
    END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pListProgramSubTypeMaster]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pListProgramSubTypeMaster]
(
	@rProgramTypeMasterId INT = 0,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

	BEGIN TRY
		SELECT 
			PSTM.Id,
			PSTM.ProgramTypeMasterId,
			PTM.Title AS ProgramTypeMasterTitle,
			PTM.Code AS ProgramTypeMasterCode,
			PSTM.Code,
			PSTM.Title,
			PSTM.IsObsolete			
		FROM
			[sWellness].[tProgramSubTypeMaster] PSTM
		INNER JOIN
			[sWellness].[tProgramTypeMaster] PTM
		ON
			PTM.Id = PSTM.ProgramTypeMasterId
		WHERE
			PSTM.IsObsolete = 0
		AND
			PSTM.OrgId = @rOrgId
		AND
			((@rProgramTypeMasterId = 0) OR (PSTM.ProgramTypeMasterId = @rProgramTypeMasterId))
		ORDER BY
			PSTM.Id DESC
	END TRY
	BEGIN CATCH 
	  SELECT -101 AS Result
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramSubTypeMaster]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramSubTypeMaster]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

	BEGIN TRY
		SELECT 
			PSTM.Id,
			PSTM.ProgramTypeMasterId,
			PSTM.Code,
			PSTM.Title,
			PSTM.IsObsolete			
		FROM
			[sWellness].[tProgramSubTypeMaster] PSTM
		WHERE
			PSTM.OrgId = @rOrgId
		AND
			PSTM.Id = @rId
	END TRY
	BEGIN CATCH 
	  SELECT -101 AS Result
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pDeleteProgramCustomField]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pDeleteProgramCustomField]
(
    @rId INT
)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @Result INT;
	IF EXISTS 
	(
        SELECT 1 FROM [sWellness].[tProgramCustomFieldResponse] WHERE ProgramCustomFieldId = @rId
    )
    BEGIN
         SET @Result = -101;
		  SELECT @Result AS Result;
        RETURN;
    END
    
    DELETE FROM [sWellness].[tProgramCustomField]
    WHERE Id = @rId;
	 SET @Result=@rId;
	 SELECT @Result AS Result;
     RETURN;
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessAppointmentDocumentsGet]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pWellnessAppointmentDocumentsGet]
	@rAppointmentId bigint,@rReadPermission bit = null, @rDeletePermission bit = null, @rOrgId int, @rConfVal int 
AS
BEGIN
	SET NOCOUNT ON;

	
	declare @res varchar(max)='',@delmessage varchar(100)='''Are you sure to delete this item?'''
	select AD.Id,AD.AppointmentId,AD.FileName,AD.ConfigurationTypeId,'../../../Content/' + convert(varchar,@rOrgId) + '/WellnessAppointmentDocuments/'   
			+ convert(varchar,AD.AppointmentId) + '/' + FileName as FilePath  
			from sWellness.tWellnessAppointmentDocuments AD
			where AD.AppointmentId = @rAppointmentId and AD.ConfigurationTypeId=@rConfVal
END
GO
PRINT N'Creating Procedure [sWellness].[pDeleteProgramSubTypeMaster]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pDeleteProgramSubTypeMaster]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

    BEGIN TRY    
		DELETE FROM [sWellness].[tProgramSubTypeMaster] WHERE OrgId = @rOrgId AND Id = @rId ;

        IF @@ROWCOUNT > 0
            SELECT 1 AS Result;  -- Return 1 if deletion is successful
        ELSE
            SELECT 0 AS Result;  -- Return 0 if no record was found

    END TRY
    BEGIN CATCH 
        SELECT -101 AS Result;  -- Return -101 in case of an error
    END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pIsProgramSubTypeMasterUsed]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pIsProgramSubTypeMasterUsed]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

    BEGIN TRY    
		SELECT 
			COUNT(*)
		FROM 
			[sWellness].[tProgram] 
		WHERE 
			OrgId = @rOrgId
		AND
			ProgramSubTypeMasterId = @rId
    END TRY
    BEGIN CATCH 
        SELECT -101 AS Result;  -- Return -101 in case of an error
    END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdateProgramSubTypeMaster]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramSubTypeMaster]
(				
	@rId INT = 0,
	@rProgramTypeMasterId INT,
	@rTitle NVARCHAR(100),
	@rCode NVARCHAR(100),
	@rIsObsolete BIT,
	@rOrgId SMALLINT,
	@rCreatedUserId BIGINT,
	@rUpdatedUserId BIGINT
)	
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	DECLARE @lNextNumber BIGINT
		IF(@rId = 0)	
		BEGIN
			IF  EXISTS(SELECT Id FROM  [sWellness].[tProgramSubTypeMaster] WHERE Title=@rTitle AND ProgramTypeMasterId = @rProgramTypeMasterId AND Id <> @rId)
			BEGIN
				SELECT -102 AS Result -- Title Already Exists
				RETURN
			END

			IF  EXISTS(SELECT Id FROM [sWellness].[tProgramSubTypeMaster] WHERE Code=@rCode AND ProgramTypeMasterId = @rProgramTypeMasterId AND Id <> @rId)
			BEGIN
				SELECT -103 AS Result -- Code Already Exists
				RETURN
			END

			INSERT INTO [sWellness].[tProgramSubTypeMaster] (ProgramTypeMasterId, Title, Code, IsObsolete, OrgId, CreatedUserId,CreatedDateTime)
			Values (@rProgramTypeMasterId, @rTitle,@rCode,@rIsObsolete,@rOrgId,@rCreatedUserId,sCommon.fGetDate())
			SET @lNextNumber = SCOPE_IDENTITY();
			SELECT @lNextNumber AS Result
			RETURN				
		END	 
		ELSE
		BEGIN	 

			IF  EXISTS(SELECT Id FROM [sWellness].[tProgramSubTypeMaster] WHERE Title=@rTitle AND ProgramTypeMasterId = @rProgramTypeMasterId AND Id <> @rId)
			BEGIN
				SELECT -102 AS Result -- Title Already Exists
				RETURN
			END

			IF  EXISTS(SELECT Id FROM [sWellness].[tProgramSubTypeMaster] WHERE Code=@rCode AND ProgramTypeMasterId = @rProgramTypeMasterId AND Id <> @rId)
			BEGIN
				SELECT -103 AS Result -- Code Already Exists
				RETURN
			END

			UPDATE 
				[sWellness].[tProgramSubTypeMaster]
			SET	
				ProgramTypeMasterId = @rProgramTypeMasterId,
				Title=@rTitle,
				Code=@rCode,			
				IsObsolete=@rIsObsolete,	
				UpdatedUserId=@rUpdatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
			WHERE 
				Id = @rId

			SELECT @rId AS Result
			RETURN @rId
		 END     
	END TRY
	BEGIN CATCH 
	  SELECT -101 AS Result
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pMobWellnessAppointmentListByDoctorId]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pMobWellnessAppointmentListByDoctorId]
	@rDoctorEmployeeId Bigint,
	@rVisitPurposeId int=0,	
	@rOrgId Bigint,	
	@rFromDate Date,
	@rToDate Date,
	@rStatusId int=0,
	@rEmpCode nvarchar(50),
	@rStoreLocationId int=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
if @rStatusId=0
	SELECT A.Id,A.AppointmentNumber,A.DoctorEmployeeId,A.EmployeeCode,A.PatientName as EmployeeName,
		A.AppointmentDate,case when A.Timeslot is null then '' else A.Timeslot end as TimeSlot,A.StatusId,A.Status,A.AppointmentType,case when A.FollowupRemark is null then '' else A.FollowupRemark end as Remark,
		OMA.MeetingProviderId,case when OMA.MeetingProviderID=30 then 'Zoom' when OMA.MeetingProviderID=31 then 'Meet' when OMA.MeetingProviderID=32 then 'Teams' else '' end as MeetingProviderTitle,OMA.AccountName,OMA.AccountEmailId,OMA.AccountPassword,OMA.APIKey,OMA.APISecret,
		OMA.WebAPIKey,OMA.WebAPISecret,OMA.JWTToken,
		A.MeetingId,A.MeetingPassword,(select Count(*) from [sWellness].[tWellnessAppointmentDocuments] Where AppointmentId = A.Id) as DocumentCount
		,ISNULL(MainType,'') as MainType,A.FollowupRemark as Complaints,
		A.StoreLocation,CM.Title as VisitPurpose, A.CompliantRemark as AppointmentComplaints
	FROM [sWellness].[vMobExtPatientWellnessAppointmentDetail] A	
		left outer join sCommon.tOnlineMeetingAccount OMA on A.DoctorEmployeeId=OMA.EmployeeId
		LEFT JOIN sExamination.tCauseMaster CM on CM.Id = A.CauseId
	WHERE (A.DoctorEmployeeId=@rDoctorEmployeeId or A.DoctorEmployeeId = 0) and A.AppointmentDate >=@rFromDate 
		and A.AppointmentDate<=@rToDate
		and (A.CauseId=@rVisitPurposeId or isnull(@rVisitPurposeId,0)=0)
		AND (A.EmployeeCode = @rEmpCode OR ISNULL(@rEmpCode, '') = '')
		AND (A.StoreLocationId = @rStoreLocationId or isnull(@rStoreLocationId,0)=0)
	ORDER BY A.AppointmentDate DESC
else
	SELECT A.Id,A.AppointmentNumber,A.DoctorEmployeeId,A.EmployeeCode,A.PatientName as EmployeeName,
		A.AppointmentDate,case when A.Timeslot is null then '' else A.Timeslot end as TimeSlot,A.StatusId,A.Status,A.AppointmentType,case when A.FollowupRemark is null then '' else A.FollowupRemark end as Remark,
		OMA.MeetingProviderId,case when OMA.MeetingProviderID=30 then 'Zoom' when OMA.MeetingProviderID=31 then 'Meet' when OMA.MeetingProviderID=32 then 'Teams' else '' end as MeetingProviderTitle,OMA.AccountName,OMA.AccountEmailId,OMA.AccountPassword,OMA.APIKey,OMA.APISecret,
		OMA.WebAPIKey,OMA.WebAPISecret,OMA.JWTToken,
		A.MeetingId,A.MeetingPassword,(select Count(*) from [sWellness].[tWellnessAppointmentDocuments] Where AppointmentId = A.Id) as DocumentCount
		,ISNULL(MainType,'') as MainType,A.FollowupRemark as Complaints,
		A.StoreLocation,CM.Title as VisitPurpose
	FROM [sWellness].[vMobExtPatientWellnessAppointmentDetail] A	
		left outer join sCommon.tOnlineMeetingAccount OMA on A.DoctorEmployeeId=OMA.EmployeeId
		LEFT JOIN sExamination.tCauseMaster CM on CM.Id = A.CauseId
	WHERE (A.DoctorEmployeeId=@rDoctorEmployeeId or A.DoctorEmployeeId = 0) and A.OrgId=@rOrgId and A.AppointmentDate >=@rFromDate 
		and A.AppointmentDate<=@rToDate and A.StatusId=@rStatusId
		and (A.CauseId=@rVisitPurposeId or isnull(@rVisitPurposeId,0)=0)
		AND (A.EmployeeCode = @rEmpCode OR ISNULL(@rEmpCode, '') = '')  
		AND (A.StoreLocationId = @rStoreLocationId or isnull(@rStoreLocationId,0)=0)
	ORDER BY A.AppointmentDate DESC
END
GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdateProgramLocations]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramLocations]
(
	@rProgramId INT,
    @rLocationList [sWellness].[udt_ProgramLocationTableType] READONLY,
    @Result INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ProgramId INT;
    DECLARE @ModifiedRows INT = 0;   

    DELETE T
    FROM [sWellness].[tProgramLocation] T
    WHERE T.ProgramId = @rProgramId
    AND T.LocationId NOT IN (SELECT LocationId FROM @rLocationList);

    UPDATE T
    SET T.LocationId = S.LocationId
    FROM [sWellness].[tProgramLocation] T
    INNER JOIN @rLocationList S
	ON
		T.ProgramId = @rProgramId
	AND
		T.LocationId = S.LocationId
        

    SET @ModifiedRows = @ModifiedRows + @@ROWCOUNT;

    INSERT INTO [sWellness].[tProgramLocation]
    (
        ProgramId,
        LocationId
    )
    SELECT 
		@rProgramId,
        L.LocationId
    FROM @rLocationList  L
    WHERE L.LocationId NOT IN (SELECT LocationId From [sWellness].[tProgramLocation] WHERE ProgramId = @rProgramId)

    SET @ModifiedRows = @ModifiedRows + @@ROWCOUNT;

    SET @Result = @ModifiedRows;
END
GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdateProgramCoach]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramCoach]
(
	@rProgramId INT,
    @rCoachList [sWellness].[udt_ProgramCoachTableType] READONLY,
    @Result INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ProgramId INT;
    DECLARE @ModifiedRows INT = 0;   

    DELETE T
    FROM [sWellness].[tProgramCoach] T
    WHERE T.ProgramId = @rProgramId
    AND T.DoctorEmployeeId NOT IN (SELECT DoctorEmployeeId FROM @rCoachList);

    UPDATE T
    SET T.DoctorEmployeeId = S.DoctorEmployeeId
    FROM [sWellness].[tProgramCoach] T
    INNER JOIN @rCoachList S
	ON
		T.ProgramId = @rProgramId
	AND
		T.DoctorEmployeeId = S.DoctorEmployeeId
        

    SET @ModifiedRows = @ModifiedRows + @@ROWCOUNT;

    INSERT INTO [sWellness].[tProgramCoach]
    (
        ProgramId,
        DoctorEmployeeId
    )
    SELECT 
		@rProgramId,
        L.DoctorEmployeeId
    FROM @rCoachList  L
    WHERE L.DoctorEmployeeId NOT IN (SELECT DoctorEmployeeId From [sWellness].[tProgramCoach] WHERE ProgramId = @rProgramId)

    SET @ModifiedRows = @ModifiedRows + @@ROWCOUNT;

    SET @Result = @ModifiedRows;
END
GO
PRINT N'Creating Procedure [sWellness].[pSaveProgramAttendance]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pSaveProgramAttendance]
(
    @rProgramId INT,
    @rAttendanceDate DATE,
    @rCreatedUserId BIGINT,
    @AttendanceList sWellness.ProgramAttendanceTableType READONLY,
	@Result BIT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    MERGE sWellness.tProgramAttendance AS TARGET
    USING 
    (
        SELECT 
            @rProgramId AS ProgramId,
            ProgramParticipantId,
            @rAttendanceDate AS AttendanceDate,
            IsPresent
        FROM @AttendanceList
    ) AS SOURCE
    ON  TARGET.ProgramId = SOURCE.ProgramId
    AND TARGET.ProgramParticipantId = SOURCE.ProgramParticipantId
    AND TARGET.AttendanceDate = SOURCE.AttendanceDate

    
    WHEN MATCHED THEN
        UPDATE SET
            TARGET.IsPresent = SOURCE.IsPresent

    WHEN NOT MATCHED THEN
        INSERT
        (
            ProgramId,
            ProgramParticipantId,
            AttendanceDate,
            IsPresent,
            CreatedUserId,
            CreatedDateTime
        )
        VALUES
        (
            SOURCE.ProgramId,
            SOURCE.ProgramParticipantId,
            SOURCE.AttendanceDate,
            SOURCE.IsPresent,
            @rCreatedUserId,
            GETUTCDATE()
        );

		SET @Result = 1;
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessAppointmentListGetScheduling]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pWellnessAppointmentListGetScheduling]      
    @rOrgId INT,
    @rId BIGINT = 0,      
    @rFromDate DATETIME,      
    @rToDate DATETIME,      
    @rEmployeeCode NVARCHAR(20) = '',      
    @rPatientName NVARCHAR(500) = '',      
    @rStoreLocationId INT = 0,      
    @rLocationId INT = 0,      
    @rSetupId INT = 0,      
    @rDoctorEmployeeId BIGINT = 0,      
    @rEmployeeStoreLocationId INT = 0,  
    @rAppointmentFlag NVARCHAR(500) = ''
AS      
BEGIN    
    SET @rEmployeeCode = CASE     
        WHEN CHARINDEX('*', @rEmployeeCode) > 0    
            THEN REPLACE(@rEmployeeCode, '*', '%')    
        ELSE '%' + @rEmployeeCode + '%'    
    END;    
    
    SELECT     
        A.Id,    
        A.AppointmentNumber,    
        A.PatientSourceTypeId,    
        A.PatientSourceId,    
        A.PatientName,    
        A.AppointmentDate,    
        ISNULL(A.FromTime, CONVERT(DATETIME, A.AppointmentDate)) AS FromTime,    
        ISNULL(A.ToTime, CONVERT(DATETIME, A.AppointmentDate)) AS ToTime,    
        ISNULL(A.DoctorEmployeeId, 0) AS DoctorEmployeeId,    
        A.EmployeeCode,    
        A.EmployeeId,    
        REPLACE(A.Relation, 'Ohter', 'Other') AS Relation,    
        A.Gender,    
        A.DoctorName,    
        A.OrgId,    
        A.IsRegister,    
        A.IsObsolete,    
        A.StatusName,    
        A.DepartmentName,    
        ISNULL(A.DepartmentId, 0) AS DepartmentId,    
        A.DependentId,    
        A.StoreLocationId,    
        A.SetupId,    
        A.ExaminationTypeId,    
        A.MainType,    
        A.Setup,    
        A.ReferSourceId,    
        A.LocationId,    
        ISNULL(A.CauseId, -1) AS CauseId,    
        A.StoreLocation,    
        ISNULL(A.OtherName, '') AS OtherName,    
        ISNULL(A.FollowupRemark, '') AS FollowupRemark,    
        A.Age,    
        A.Months,    
        A.GenderId,    
        A.ExaminationId,    
        A.Timeslot,
		ISNULL(A.CompliantRemark, '') AS CompliantRemark,
		A.AppointmentFlag
    FROM     
        [sWellness].[vExtPatientWellnessAppointmentDetail] A  
    LEFT JOIN 
        sExamination.tExamination E ON A.ExaminationId = E.Id    
        OR A.ReferSourceId = E.Id    
    WHERE     
        A.ApprovalStatusId = 548    
        AND A.AppointmentDate BETWEEN ISNULL(@rFromDate, sCommon.fGetDate()) AND ISNULL(@rToDate, sCommon.fGetDate())    
        AND (A.Id = @rId OR @rId = 0)    
        AND A.OrgId = @rOrgId    
        AND (A.PatientName LIKE @rPatientName + '%' OR A.OtherName LIKE @rPatientName + '%' OR ISNULL(@rPatientName, '') = '')    
        AND (A.EmployeeCode LIKE @rEmployeeCode OR ISNULL(@rEmployeeCode, '') = '')    
        AND (A.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)    
        AND (A.LocationId = @rLocationId OR @rLocationId = 0)    
        AND (A.SetupId = @rSetupId OR @rSetupId = 0)    
        AND (A.DoctorEmployeeId = @rDoctorEmployeeId OR @rDoctorEmployeeId = 0)    
        AND (A.AppointmentFlag = @rAppointmentFlag OR @rAppointmentFlag = '0')    
        AND ISNULL(A.ExaminationId, 0) = 0    
        AND ISNULL(E.IsCancel, 0) = 0  
		AND A.Id NOT IN (SELECT IsNull(AppointmentId,0) FROM [sWellness].[tWellnessRegistration] WHERE OrgId =@rOrgId);
END
GO
PRINT N'Creating Procedure [sWellness].[pGetAllDetailForProgramMaster]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetAllDetailForProgramMaster]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

	SELECT 
		 PM.Id
		,PM.OrgId
		,PM.Title
		,PM.ModeId
		,PM.Description
		,PM.FromDate
		,PM.ToDate
		,PM.FromTime
		,PM.ToTime
		,PM.IsSurveyRequired
		,PM.AssignSurveyId
		,PSTM.ProgramTypeMasterId AS ProgramTypeId
		,PM.ProgramSubTypeId
		,PM.IsRegistrationRequired
		,PM.RegisterUptoDatetime
		,PM.IsObsolete
	FROM
		[sWellness].[tProgramMaster] PM
	INNER JOIN
		[sWellness].[tProgramSubTypeMaster] PSTM
	ON
		PSTM.Id = PM.ProgramSubTypeId
	WHERE
		PM.OrgId = @rOrgId
	AND
		PM.Id = @rId


	SELECT
		LM.Title AS Text,
		LocationId AS Value
	FROM
		sWellness.tProgramLocation PL
	INNER JOIN
		sCommon.tLocationMaster LM
	ON
		LM.Id = PL.LocationId
	WHERE
		PL.ProgramId = @rId

	SELECT
		EM.FirstName + ' ' + EM.LastName AS Text,
		DoctorEmployeeId AS Value
	FROM
		sWellness.tProgramCoach PC
	INNER JOIN
		sCwb.tDoctorMaster DM
	ON
		DM.Id = PC.DoctorEmployeeId 
	INNER JOIN
		sHrm.tEmployeeMaster EM
	ON
		EM.Id = DM.EmployeeId
	WHERE
		PC.ProgramId = @rId

	SELECT
		Id,
		FieldTitle,
		FieldRemark,
		FieldTypeId,
		FieldList,
		IsMandatory,
		FieldOrderIndex
	FROM
		[sWellness].[tProgramCustomField] PCF
	WHERE
		PCF.ProgramId = @rId
END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramMasterEmployeeList]...';


GO
CREATE OR ALTER PROCEDURE[sWellness].[pGetProgramMasterEmployeeList]
(
    @rId BIGINT,
    @rProgramName NVARCHAR(10),
    @rFromDate DATETIME = null,
    @rToDate DATETIME = null,
	@rLocationId BIGINT = 0,
	@rIsRegistrationRequired BIT = 0,
	@rEmployeeId BIGINT = 0,
    @rOrgId INT
)
AS
SET NOCOUNT ON
BEGIN

    SELECT DISTINCT
		P.Id,
        Title,
		ModeId,
        Description AS ProgramDescription,
        FromDate AS FromDate,
		ToDate AS ToDate,
		RegisterUptoDatetime,
		IsRegistrationRequired,
		[sWellness].[fn_IsEmployeeRegistered](P.Id,@rEmployeeId) AS RegistrationStatus,
		FromTime,
		ToTime
    FROM 
		[sWellness].[tProgramMaster] P
	LEFT JOIN
		[sWellness].[tProgramLocation] PL
	ON	
		P.Id = PL.ProgramId
    WHERE 
		P.IsObsolete = 0
	AND
		(ISNULL(P.Id, 0) = @rId OR ISNULL(@rId, 0) = 0)
	AND
		(ISNULL(P.IsRegistrationRequired, 0) = @rIsRegistrationRequired OR ISNULL(@rIsRegistrationRequired, 0) = 0)
    AND 
		(ISNULL(PL.LocationId, 0) = @rLocationId OR ISNULL(@rLocationId, 0) = 0)
    AND 
		OrgId = @rOrgId
    AND 
		((Title LIKE (@rProgramName + '%')) OR ISNULL(@rProgramName, '') = '')
    AND 
		((FromDate >= @rFromDate) OR (ISNULL(@rFromDate, '') = ''))
    AND 
		((FromDate <= @rToDate) OR (ISNULL(@rToDate, '') = ''))
	ORDER BY 
		RegistrationStatus
END
GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdateProgramDocuments]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramDocuments]
(
    @rId INT,
    @rProgramId INT,
    @rTypeId INT,
    @rFileName NVARCHAR(500),
    @rFilePath NVARCHAR(MAX),
    @rConfigurationTypeId TINYINT,
    @rIsObselete BIT,
	@rUserId BIGINT
)
AS
SET NOCOUNT ON
BEGIN

    DECLARE @Result INT,@Now DATETIME = sCommon.fGetDate();

    BEGIN TRY
        BEGIN TRANSACTION


    IF (@rId = 0)
    BEGIN
         IF (@rTypeId = 1)
         BEGIN
              INSERT INTO [sWellness].[tProgramDocument]
              (
                ProgramId,
                FileName,
                FilePath,
                ConfigurationTypeId,
                IsObsolete,
                CreatedUserId,
                CreatedDateTime
              )
              VALUES
              (
                @rProgramId,
                @rFileName,
                @rFilePath,
                @rConfigurationTypeId,
                @rIsObselete,
                @rUserId,
                @Now
              );

        SET @Result = SCOPE_IDENTITY();
        END
        ELSE IF (@rTypeId = 2)
        BEGIN
             INSERT INTO [sWellness].[tProgramEvidence]
             (
               ProgramId,
               FileName,
               FilePath,
               ConfigurationTypeId,
               IsObsolete,
               CreatedUserId,
               CreatedDateTime
             )
             VALUES
             (
               @rProgramId,
               @rFileName,
               @rFilePath,
               @rConfigurationTypeId,
               @rIsObselete,
               @rUserId,
               @Now
              );

        SET @Result = SCOPE_IDENTITY();
        END
    END
    ELSE
    BEGIN
         IF (@rTypeId = 1)
         BEGIN
              UPDATE [sWellness].[tProgramDocument]
              SET
                 ProgramId = @rProgramId,
                 FileName = @rFileName,
                 FilePath = @rFilePath,
                 ConfigurationTypeId = @rConfigurationTypeId,
                 IsObsolete = @rIsObselete,
                 UpdatedUserId = @rUserId,
                 UpdateDateTime = @Now
              WHERE Id = @rId;
          END
          ELSE IF (@rTypeId = 2)
          BEGIN
               UPDATE [sWellness].[tProgramEvidence]
               SET
                  ProgramId = @rProgramId,
                  FileName = @rFileName,
                  FilePath = @rFilePath,
                  ConfigurationTypeId = @rConfigurationTypeId,
                  IsObsolete = @rIsObselete,
                  UpdatedUserId = @rUserId,
                  UpdateDateTime = @Now
               WHERE Id = @rId;
          END

          SET @Result = @rId;
     END


    COMMIT TRANSACTION

    SELECT CAST(@Result AS NVARCHAR(10)) AS Result
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION

        SELECT CAST(-1 AS NVARCHAR(10)) AS Result
        SELECT ERROR_MESSAGE()
    END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramMasterCoachList]...';


GO
CREATE OR ALTER PROCEDURE[sWellness].[pGetProgramMasterCoachList]
(
    @rId BIGINT,
    @rProgramName NVARCHAR(10),
    @rFromDate DATETIME = null,
    @rToDate DATETIME = null,
	@rLocationId BIGINT = 0,
	@rIsSurveyRequired BIT = 0,
	@rEmployeeId BIGINT = 0,
    @rOrgId INT
)
AS
SET NOCOUNT ON
BEGIN

    SELECT DISTINCT
		P.Id,
        Title,
		ModeId,
        Description AS ProgramDescription,
        FromDate AS FromDate,
		ToDate AS ToDate,
		RegisterUptoDatetime,
		IsSurveyRequired,
		FromTime,
		ToTime
    FROM 
		[sWellness].[tProgramMaster] P
	INNER JOIN
		[sWellness].[tProgramCoach] PC
	ON	
		P.Id = P.Id
	INNER JOIN
		[sCwb].[tDoctorMaster] DM
	ON
		DM.Id = PC.DoctorEmployeeId 
    WHERE 
		P.IsObsolete = 0
	AND
		(ISNULL(P.Id, 0) = @rId OR ISNULL(@rId, 0) = 0)
	AND
		(ISNULL(P.IsSurveyRequired, 0) = @rIsSurveyRequired OR ISNULL(@rIsSurveyRequired, 0) = 0)
  --AND 
		--(ISNULL(PL.LocationId, 0) = @rLocationId OR ISNULL(@rLocationId, 0) = 0)
	AND
		DM.EmployeeId = @rEmployeeId
    AND 
		P.OrgId = @rOrgId
    AND 
		((Title LIKE (@rProgramName + '%')) OR ISNULL(@rProgramName, '') = '')
    AND 
		((FromDate >= @rFromDate) OR (ISNULL(@rFromDate, '') = ''))
    AND 
		((FromDate <= @rToDate) OR (ISNULL(@rToDate, '') = ''))
	ORDER BY 
		Id
	DESC
END
GO
PRINT N'Creating Procedure [sWellness].[pDeleteProgramDocuments]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pDeleteProgramDocuments]
(
    @rId INT,
    @rTypeId INT
)
AS
SET NOCOUNT ON
BEGIN TRY

    IF (@rTypeId = 1)
    BEGIN
        DELETE FROM [sWellness].[tProgramDocument]
        WHERE Id = @rId;
    END
    ELSE IF (@rTypeId = 2)
    BEGIN
        DELETE FROM [sWellness].[tProgramEvidence]
        WHERE Id = @rId;
    END
    ELSE
    BEGIN
        RAISERROR ('Invalid TypeId', 16, 1);
        RETURN;
    END

    IF @@ROWCOUNT = 0
    BEGIN
        SELECT CAST(-1 AS NVARCHAR(10)) AS Result;  -- Not found
    END
    ELSE
    BEGIN
        SELECT CAST(@rId AS NVARCHAR(10)) AS Result; -- Success
    END

END TRY
BEGIN CATCH
    SELECT CAST(-1 AS NVARCHAR(10)) AS Result;
    SELECT ERROR_MESSAGE() AS ErrorMessage;
END CATCH
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramDocuments]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramDocuments]
(
    @rId INT,
    @rTypeId INT
)
AS
BEGIN 
    SET NOCOUNT ON

    IF (@rTypeId = 1)
    BEGIN
        SELECT 
		Id,
		ProgramId,
		FileName,
		FilePath,
		ConfigurationTypeId,
		IsObsolete 
		FROM 
		[sWellness].[tProgramDocument]
        WHERE 
		Id = @rId;
    END
    ELSE IF (@rTypeId = 2)
    BEGIN
        SELECT Id,
		ProgramId,
		FileName,
		FilePath,
		ConfigurationTypeId,
		IsObsolete
		FROM 
		[sWellness].[tProgramEvidence]
        WHERE
		Id = @rId;
    END
    ELSE
    BEGIN
        RAISERROR ('Invalid TypeId', 16, 1);
        RETURN;
    END
END
GO
PRINT N'Creating Procedure [sWellness].[pGetCoachProgramsList]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetCoachProgramsList]
(
    @rLocationId BIGINT,
	@rEmployeeId BIGINT = 0,
	@rProgramSubTypeMaster INT = 0,
    @rOrgId INT
)
AS
SET NOCOUNT ON
BEGIN

	SELECT DISTINCT
		P.Id,
        Title
    FROM 
		[sWellness].[tProgramMaster] P
	INNER JOIN
		[sWellness].[tProgramCoach] PC
	ON	
		P.Id = P.Id
	INNER JOIN
		[sCwb].[tDoctorMaster] DM
	ON
		DM.Id = PC.DoctorEmployeeId 
    WHERE 
		P.IsObsolete = 0
	AND
		DM.EmployeeId = @rEmployeeId
	AND
		P.ProgramSubTypeId = @rProgramSubTypeMaster
    AND 
		P.OrgId = @rOrgId
	ORDER BY 
		Id 
	DESC

END
GO
PRINT N'Creating Procedure [sWellness].[pAppointmentWellnessSchedulingModify]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pAppointmentWellnessSchedulingModify]  
@rId bigint  
,@rPatientSourceId bigint  
,@rPatientSourceTypeId smallint  
,@rAppointmentDate date  
,@rAppointmentNumber nvarchar(20)  
,@rDoctorEmployeeId bigint  
,@rFromTime time  
,@rToTime time  
,@rIsRegister bit  
,@rIsObsolete bit  
,@rStoreLocationId int  
,@rSetupid int,  
@rCauseId int,  
@rOtherName varchar(200)=null,  
@rFollowupRemark varchar(200)=null, 
@rComplaintRemark varchar(200)=null,
@rAge int=null,  
@rMonth tinyint = null,  
@rGenderId tinyint = null  
AS  
BEGIN  
 BEGIN TRY   
 BEGIN TRANSACTION  
  
  IF @rPatientSourceTypeId != 1009  
  BEGIN  
    Declare @lAge int;  
    select @lAge = Case When @rPatientSourceTypeId = 1001 Then (select case when ISNULL(DateOfBirth,'1900-01-01') = '1900-01-01' then 0 else datediff(yy,DateOfBirth,getdate()) end as Age from sHrm.tEmployeeFamilyDetails where Id = @rPatientSourceId)  
        ELSE (select case when ISNULL(DateOfBirth,'1900-01-01') = '1900-01-01' then 0 else datediff(yy,DateOfBirth,getdate()) end as Age from sHrm.tEmployeePersonalDetail where EmployeeId = @rPatientSourceId) END  
    IF @lAge != @rAge  
    BEGIN  
     SELECT -3 AS Result
     RETURN  
    END  
  END  
  
  UPDATE sWellness.tAppointment SET PatientSourceId = @rPatientSourceId,  
  PatientSourceTypeId = @rPatientSourceTypeId,AppointmentDate = @rAppointmentDate,  
  DoctorEmployeeId = @rDoctorEmployeeId,FromTime=@rFromTime,ToTime=@rToTime,  
  IsRegister = @rIsRegister,IsObsolete= @rIsObsolete,StoreLocationId = @rStoreLocationId,  
  SetupId = @rSetupid,CauseId = @rCauseId,OtherName = @rOtherName,  
  CompliantRemark = @rComplaintRemark, FollowupRemark = @rFollowupRemark,Age=@rAge,Months = @rMonth,GenderId = @rGenderId  
  WHERE Id=@rId AND AppointmentNumber=@rAppointmentNumber  
  SELECT 1 AS RESULT  
 COMMIT TRANSACTION  
  
 END TRY  
 BEGIN CATCH  
  ROLLBACK TRANSACTION  
  SELECT -1 AS RESULT  
 END CATCH  
END
GO
PRINT N'Creating Procedure [sWellness].[pGetCoachProgramTypeList]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetCoachProgramTypeList]
(
@rOrgId INT
)
AS 
BEGIN
	SELECT 
		Id,
		Code,
		Title,
		OrgId
	FROM 
		sWellness.tProgramTypeMaster
	WHERE 
		IsObsolete = 0
END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramsList]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramsList]
(
    @rLocationId BIGINT,
    @rOrgId INT
)
AS
SET NOCOUNT ON
BEGIN

    SELECT DISTINCT
		Id,
        Title
    FROM 
		[sWellness].[tProgramMaster] P
	INNER JOIN 
		[sWellness].[tProgramLocation] PL 
	ON 
		P.Id = PL.ProgramId
    WHERE 
		P.OrgId = @rOrgId
    AND 
		PL.LocationId = @rLocationId
	ORDER BY 
		Id 
	DESC
END
GO
PRINT N'Creating Procedure [sWellness].[pGetDoctorBasedOnLocation]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetDoctorBasedOnLocation]
(
	@rLocationIds NVARCHAR(MAX)
)
AS
BEGIN
	SET NOCOUNT ON;

	SELECT DISTINCT
		DM.Id AS Value,
		EM.FirstName + ' ' + EM.LastName AS Text
	FROM 
		[sCwb].[tDoctorMaster] DM
	INNER JOIN
		[sCwb].[tDoctorStoreLocation] DSL
	ON
		DSL.EmployeeId = DM.EmployeeId
	INNER JOIN
		[sIp].[tStoreLocationMaster] SLM
	ON
		SLM.Id = DSL.SubLocationId
	INNER JOIN
		[sHrm].[tEmployeeMaster] EM
	ON
		EM.Id = DM.EmployeeId
	WHERE 
		IsWellness = 1
	AND 
	   (ISNULL(SLM.LocationId,0) IN (SELECT CAST(item AS INT) FROM  sCommon.fnsplit(ISNULL(@rLocationIds,''),',')))     
END
GO
PRINT N'Creating Procedure [sWellness].[pGetCoachProgramSubTypeList]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetCoachProgramSubTypeList]
(
@rProgramTypeId INT,
@rOrgId INT
)
AS 
BEGIN
	SELECT 
		Id,
		ProgramTypeMasterId,
		Code,
		Title,
		OrgId
	FROM 
		sWellness.tProgramSubTypeMaster
	WHERE 
		ProgramTypeMasterId = @rProgramTypeId AND IsObsolete = 0
END
GO
PRINT N'Creating Procedure [sWellness].[pAssignedSurveryForWellnessList]...';


GO
CREATE OR ALTER PROCEDURE  [sWellness].[pAssignedSurveryForWellnessList]
(
	@rOrgId SMALLINT,
	@rSelectedLocation NVARCHAR(MAX)
)
AS
BEGIN
	SET NOCOUNT ON;

	SELECT TOP 10
		Id AS Value,
		Title AS Text
	FROM
	sSupport.tAssignSurveyMaster
	WHERE 
		SurveyTypeId = 2
	AND
		IsObsolete = 0
END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramDetails]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramDetails]
(@rOrgId INT,
@rProgramId INT)
AS
SET NOCOUNT ON
BEGIN

     SELECT 
	     PM.Id AS ProgramId,
		 PM.Title AS ProgramName ,
		 PM.Description,
		 PM.FromDate,
		 PM.ToDate ,
		 PL.LocationId ,
		 LM.Title AS LocationName 
     FROM 
	     [sWellness].[tProgramMaster] PM
     LEFT JOIN 
	     [sWellness].[tProgramLocation] PL ON PL.ProgramId=PM.Id
     LEFT JOIN 
	     sCommon.tLocationMaster LM ON LM.Id=PL.LocationId
     WHERE 
	      PM.OrgId= @rOrgId 
		  AND PM.Id = @rProgramId ;
END
GO
PRINT N'Creating Procedure [sWellness].[pAppointmentWellnessSchedulingAdd]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pAppointmentWellnessSchedulingAdd]
@rId bigint,      
@rOrgId int      
,@rPatientSourceId bigint      
,@rPatientSourceTypeId smallint      
,@rAppointmentDate datetime      
,@rDoctorEmployeeId bigint      
,@rFromTime time = null      
,@rToTime time = null      
,@rIsRegister bit      
,@rIsObsolete bit      
,@rCreatedUserId bigint      
,@rReferSourceId bigint      
,@rReferSourceTypeId int      
,@rStoreLocationId int      
,@rSetupId int,      
@rCauseId int,      
@rOtherName varchar(200)=null,  
@rFollowupRemark varchar(200)=null,
@rComplaintRemark varchar(200)=null,  
@rAge int = null,      
@rMonth tinyint = null,      
@rGenderId tinyint = null,      
@rTimeslotId int = null,      
@rAppointmentType tinyint = null,      
@rEntryType tinyint = 0,      
@rApprovalStatusId int = null
AS      
BEGIN        
 DECLARE @1SubTypeId int      
 SELECT @1SubTypeId = SubTypeId From sExamination.tSetupMaster where Id = @rSetupId      
 IF EXISTS(Select 1 FROM sWellness.tAppointment Where PatientSourceId = @rPatientSourceId AND PatientSourceTypeId = @rPatientSourceTypeId AND SetupId = @rSetupId) AND @1SubTypeId != 10 AND @rId = 0      
 BEGIN      
  SELECT -101 AS RESULT      
  RETURN      
 END    
    
  IF EXISTS(Select 1 FROM sWellness.tAppointment Where TimeSlotId = @rTimeSlotId AND PatientSourceTypeId = @rPatientSourceTypeId AND ApprovalStatusId = @rApprovalStatusId) AND @rId = 0 AND @rTimeSlotId != 0     
 BEGIN      
  SELECT -102 AS RESULT      
  RETURN      
 END    
 IF @rPatientSourceTypeId != 1009    
 BEGIN    
  Declare @lAge int;    
  select @lAge = Case When @rPatientSourceTypeId = 1001 Then (select case when ISNULL(DateOfBirth,'1900-01-01') = '1900-01-01' then 0 else datediff(yy,DateOfBirth,getdate()) end as Age from sHrm.tEmployeeFamilyDetails where Id = @rPatientSourceId)    
      ELSE (select case when ISNULL(DateOfBirth,'1900-01-01') = '1900-01-01' then 0 else datediff(yy,DateOfBirth,getdate()) end as Age from sHrm.tEmployeePersonalDetail where EmployeeId = @rPatientSourceId) END    
  IF @lAge != @rAge    
  BEGIN    
   SELECT -3 AS Result    
   RETURN    
  END    
 END    
      
 IF NOT EXISTS (Select 1 FROM sWellness.tAppointment Where PatientSourceId = @rPatientSourceId       
 AND PatientSourceTypeId = @rPatientSourceTypeId AND SetupId = @rSetupId  AND @1SubTypeId != 10) AND @rId = 0      
 BEGIN      
 BEGIN TRY      
 BEGIN TRANSACTION      
  DECLARE @lNextNumber BIGINT      
  EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sWellness.tAppointment', 0, 1, 1,@outNextNumber = @lNextNumber output      
      
  DECLARE @loNextNumber nVarchar(20)      
  Set @rApprovalStatusId = Isnull(@rApprovalStatusId,548)    
  EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1022,      
  @rStoreLocationId = @rStoreLocationId, @rNextNumber = @loNextNumber OUTPUT      
     SET @loNextNumber = ISNULL(@loNextNumber, '-300')    IF @loNextNumber = '-300'   BEGIN     SELECT -300 AS Result, '' AS Number, 0 AS Id     RETURN      
  END      
         
  INSERT INTO sWellness.tAppointment       
  (      
   Id,PatientSourceId,PatientSourceTypeId,AppointmentDate,      
   AppointmentNumber,DoctorEmployeeId,FromTime,ToTime,IsRegister,      
   IsObsolete,OrgId,StatusId,ReferSourceId,ReferSourceTypeId,      
   StoreLocationId,SetupId,CauseId,OtherName,FollowupRemark,CompliantRemark,Age,Months,GenderId,TimeSlotId,AppointmentType,EntryType,ApprovalStatusId,AppointmentFlag      
  )      
  VALUES      
  (      
   @lNextNumber,@rPatientSourceId,@rPatientSourceTypeId,@rAppointmentDate,      
   @loNextNumber,@rDoctorEmployeeId,@rFromTime,@rToTime,0,@rIsObsolete,@rOrgId,      
   1,@rReferSourceId,@rReferSourceTypeId,@rStoreLocationId,@rSetupId,@rCauseId,@rOtherName,      
   @rFollowupRemark,@rComplaintRemark,@rAge,@rMonth,@rGenderId,@rTimeslotId,@rAppointmentType,@rEntryType,@rApprovalStatusId,'New Appointment'     
  )      
  COMMIT TRANSACTION        
 END TRY      
 BEGIN CATCH       
  ROLLBACK TRANSACTION      
  SELECT -101 AS RESULT      
  RETURN      
 END CATCH      
 END      
 ELSE          
 BEGIN      
  SET @lNextNumber = @rId      
  UPDATE sWellness.tAppointment SET   
  DoctorEmployeeId = @rDoctorEmployeeId,      
  FromTime = @rFromTime,ToTime = @rToTime   
  WHERE Id = @rId       
 END        
 SELECT @lNextNumber AS RESULT          
END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramAttendance]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramAttendance]
(@rOrgId INT,
@rProgramId INT,
@rLocationId INT,
@rAttendanceDate DATE)
AS
SET NOCOUNT ON
BEGIN

     SELECT 
	     PP.Id AS ProgramParticipantId,
         PP.ParticipantCode,
         PP.ParticipantName,
         DM.Title AS DepartmentName,
         @rAttendanceDate AS AttendanceDate,
         ISNULL(PA.IsPresent, 0) AS IsPresent
     FROM 
         [sWellness].[tProgramParticipant] PP
     LEFT JOIN 
         sCommon.tOrganizationDepartmentMaster DM ON DM.Id = PP.ParticipantDepartmentId
     LEFT JOIN 
         [sWellness].[tProgramAttendance] PA  ON PA.ProgramParticipantId = PP.Id AND PA.ProgramId = @rProgramId AND CAST(PA.AttendanceDate AS DATE) = @rAttendanceDate
     WHERE 
         PP.ProgramId = @rProgramId
         AND (@rLocationId = 0 OR PP.ParticipantLocationId = @rLocationId)
         AND DM.OrgId = @rOrgId
     ORDER BY 
         PP.ParticipantName;
END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramParameters]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramParameters] 	
(
	@rOrgId INT,
	@rProgramId BIGINT
)
AS
BEGIN
	
	SET NOCOUNT ON;
	
    SELECT 
		GTP.Title AS ParameterName,
		pp.AutoID, 
		pp.OrgId,
		pp.ProgramId, 
		pp.ParameterTypeId, 'General' AS ParameterType,
		pp.ParameterSourceTypeId,
		pp.ParameterSourceId, 
		ISNULL(gtp.StaticGeneralTemplateParameterId,0) AS StaticParameterSourceId, 
		pp.OrderIndex, 
		pp.CreatedUserId, 
		pp.CreatedDateTime, 
		pp.UpdatedUserId, 
		pp.UpdatedDateTime 
	FROM 
		[sWellness].[tProgramParameter] PP
	INNER JOIN 
		[sExamination].[tGeneralTemplateParameter] GTP 
	ON 
		pp.ParameterSourceId = gtp.Id
	WHERE 
		pp.ParameterTypeId = 2 
	AND 
		pp.ProgramId = @rProgramId 
	AND 
		pp.OrgId = @rOrgId

	UNION

	SELECT 
		tpm.Title AS ParameterName,
		pp.AutoID, 
		pp.OrgId, 
		pp.ProgramId, 
		pp.ParameterTypeId,
		'Test' as ParameterType,
		pp.ParameterSourceTypeId,
		pp.ParameterSourceId,
		ISNULL(tpm.StaticTestParameterId,0) AS StaticParameterSourceId, 
		pp.OrderIndex, 
		pp.CreatedUserId, 
		pp.CreatedDateTime, 
		pp.UpdatedUserId, 
		pp.UpdatedDateTime 
	FROM 
		[sWellness].[tProgramParameter] pp
	INNER JOIN 
		sOrderEntry.tTestParameterMaster tpm ON pp.ParameterSourceId = tpm.Id
	WHERE 
		pp.ParameterTypeId = 3 
	AND 
		pp.ProgramId = @rProgramId 
	AND 
		pp.OrgId = @rOrgId
END
GO
PRINT N'Creating Procedure [sWellness].[pListProgram]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pListProgram]
(
    @rOrgId INT
)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
        Id AS Value,
        ProgramName AS Text
    FROM 
		sWellness.tProgram WITH (NOLOCK)
    WHERE 
		OrgId = @rOrgId
    ORDER BY 
		ProgramName 
END
GO
PRINT N'Creating Procedure [sWellness].[pProgramParameterAddUpdate]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pProgramParameterAddUpdate]
(
	@rProgramId BIGINT,
	@rProgramTypeId TINYINT,
	@rParameterSourceId BIGINT,
	@rCreatedUserId BIGINT,
	@rOrgId SMALLINT,
	@rOrderIndex INT
)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Id BIGINT, 
			@rParameterSourceTypeId NVARCHAR(100),
			@rStringParameterTable NVARCHAR(100),
			@Result INT;

	SET @rStringParameterTable = (CASE @rProgramTypeId WHEN 2 THEN 'sExamination_tGeneralTemplateParameter' WHEN 3 THEN 'sOrderEntry.tTestParameterMaster' END)
	SET @rParameterSourceTypeId = (SELECT Id FROM sSystem.tTable WHERE tableName = @rStringParameterTable)

	IF EXISTS (SELECT AutoId FROM [sWellness].[tProgramParameter] WHERE ProgramId=@rProgramId AND ParameterSourceTypeId = @rParameterSourceTypeId AND ParameterSourceId = @rParameterSourceId AND OrgId = @rOrgId)
	BEGIN
	  SET @Result = 0;
	  SELECT @Result;
	END
	ELSE
	BEGIN
		BEGIN
			INSERT INTO [sWellness].[tProgramParameter]
			(
				[ProgramId],[ParameterTypeId],[ParameterSourceTypeId],[ParameterSourceId],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],
				[UpdatedDateTime],OrgId,[OrderIndex]
			)
			VALUES
			(
				@rProgramId,@rProgramTypeId,@rParameterSourceTypeId,@rParameterSourceId,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,
				sCommon.fGetDate(),@rOrgId,@rOrderIndex
			)		
		END
		BEGIN
			SET @Id=(SELECT ISNULL(AutoId,0) AS Id FROM [sWellness].[tProgramParameter] WHERE ProgramId=@rProgramId AND ParameterSourceId = @rParameterSourceId AND OrgId = @rOrgId)
			IF @Id != 0 
			BEGIN
				set @Result = @Id;
			END
			ELSE
			BEGIN
				SET @Result = -1;
			END
			SELECT @Result;
		END
	END
END
GO
PRINT N'Creating Procedure [sWellness].[pUpdateProgramAttendance]...';


GO


CREATE OR ALTER PROCEDURE [sWellness].[pUpdateProgramAttendance]
(
    @lXML VARCHAR(MAX) = '',
    @rProgramId BIGINT = 0,
    @rCreatedBy BIGINT = 0,
	@rOrgId INT
)
AS
BEGIN
   BEGIN TRY
        BEGIN TRANSACTION
        DECLARE @loXML XML
        SET @loXML = CAST(@lXML AS XML)
        DECLARE @tblemp TABLE
        ( tid INT IDENTITY(1, 1), tmp_ecode VARCHAR(200), tmp_programid BIGINT, tmp_hasattended NVARCHAR(10), tmp_eid BIGINT)
		
        INSERT INTO @tblemp
        ( tmp_ecode, tmp_programid, tmp_hasattended )
        SELECT T.c.value('@Code', 'varchar(200)') AS EmployeeCode,
               T.c.value('@ProgramId', 'varchar(200)') AS ProgramId,
               T.c.value('@HasAttended', 'varchar(200)') AS HasAttended
        FROM @loXML.nodes('/Table/ParticipantAttendance')T(c)
		
        DECLARE @validate VARCHAR(MAX) = '', @orgid INT, @cnt INT, @i INT, @tablerowcnt INT = 0

        SELECT @cnt = count(*),  @i  = 1 FROM @tblemp
        WHILE @i <= @cnt
        BEGIN
            DECLARE @Code VARCHAR(200)
            SELECT @Code = tmp_ecode
            FROM @tblemp
            WHERE tid = @i
            IF EXISTS (SELECT 1 FROM sHrm.tEmployeeMaster WHERE Code = @Code)
            BEGIN
                update @tblemp
                SET tmp_eid = (SELECT Id FROM sHrm.tEmployeeMaster WHERE Code = @Code) WHERE tid = @i
            END
			ELSE 
			BEGIN
			PRINT @Code
			  SELECT -101 AS Result
			  RETURN
			END			
			SELECT @i = @i + 1;
        end
 
        MERGE [sWellness].[tProgramParticipants] AS Target
        USING
        (SELECT * FROM @tblemp) AS Source
        ON Target.ProgramId = Source.tmp_programid
           AND Target.EmployeeId = Source.tmp_eid
        WHEN MATCHED THEN
            UPDATE SET HasAttended = CASE WHEN tmp_hasattended = 'Y' THEN 1 ELSE 0 END
        WHEN NOT MATCHED THEN
            INSERT
            (ProgramId,EmployeeId,HasAttended,CreatedDate,CreatedBy )--Id,
            VALUES
            (   tmp_programid,tmp_eid, --@lNextNumber,
                CASE WHEN tmp_hasattended = 'Y' THEN 1 ELSE 0 END,
                GETDATE(),@rCreatedBy
            );
		
        INSERT INTO [sWellness].[tServiceFeedback]
        SELECT 3,tmp_programid,20396,tmp_eid,95,null,null,null,GETDATE(),@rCreatedBy from @tblemp where tmp_hasattended = 'Y'
        SELECT 1 as Result
        COMMIT
    END TRY
    BEGIN CATCH
         SELECT ERROR_NUMBER() AS Result, ERROR_MESSAGE() AS ResultMessage
        ROLLBACK TRANSACTION
    END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdatePrograms]...';


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdatePrograms]
(
    @rId BIGINT,
    @rOrgId SMALLINT,
    @rTitle NVARCHAR(100),
    @rModeId TINYINT,
    @rDescription NVARCHAR(500),
    @rFromDate DATETIME,
    @rToDate DATETIME,
    @rFromTime TIME(7),
    @rToTime TIME(7),
    @rIsSurveyRequired BIT,
    @rAssignedSurveyId INT,
    @rProgramSubTypeId INT,
    @rIsRegistrationRequired BIT,
    @rRegisterUptoDateTime DATETIME,
    @rIsObsolete BIT,
    @rUserId BIGINT
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @lNextNumber BIGINT = 0;

    -- 🔹 Check duplicate BEFORE transaction
    IF EXISTS
    (
        SELECT 1
        FROM [sWellness].[tProgramMaster]
        WHERE Id <> @rId
        AND Title = @rTitle
        AND FromDate = @rFromDate
        AND ToDate = @rToDate
        AND OrgId = @rOrgId
    )
    BEGIN
        SELECT CAST(-102 AS NVARCHAR(10)) AS Result
        RETURN
    END

    BEGIN TRY
        BEGIN TRANSACTION

        IF (@rId = 0)
        BEGIN
            EXEC sCommon.pTableRowIdGet 
                @rOrgId,
                'sWellness.tProgramMaster',
                0,1,1,
                @outNextNumber = @lNextNumber OUTPUT

            INSERT INTO [sWellness].[tProgramMaster]
            (
                Id, OrgId, Title, ModeId, Description, FromDate, ToDate,
                FromTime, ToTime, IsSurveyRequired, AssignSurveyId, ProgramSubTypeId,
                IsRegistrationRequired, RegisterUptoDatetime, IsObsolete,
                CreatedUserId, CreatedDatetime
            )
            VALUES
            (   
                @lNextNumber, @rOrgId, @rTitle, @rModeId, @rDescription,
                @rFromDate, @rToDate, @rFromTime, @rToTime,
                @rIsSurveyRequired, @rAssignedSurveyId, @rProgramSubTypeId,
                @rIsRegistrationRequired, @rRegisterUptoDateTime,
                @rIsObsolete, @rUserId, sCommon.fGetDate()
            )
        END
        ELSE
        BEGIN
            UPDATE [sWellness].[tProgramMaster]
            SET
                Title = @rTitle,
                ModeId = @rModeId,
                Description = @rDescription,
                FromDate = @rFromDate,
                ToDate = @rToDate,
                FromTime = @rFromTime,
                ToTime = @rToTime,
                IsSurveyRequired = @rIsSurveyRequired,
                AssignSurveyId = @rAssignedSurveyId,
                ProgramSubTypeId = @rProgramSubTypeId,
                IsRegistrationRequired = @rIsRegistrationRequired,
                RegisterUptoDatetime = @rRegisterUptoDateTime,
                IsObsolete = @rIsObsolete,
                UpdatedUserId = @rUserId,
                UpdatedDatetime = sCommon.fGetDate()
            WHERE Id = @rId
            AND OrgId = @rOrgId;

            SET @lNextNumber = @rId;
        END

        COMMIT TRANSACTION

        SELECT CAST(@lNextNumber AS NVARCHAR(10)) AS Result
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION

        SELECT CAST(-1 AS NVARCHAR(10)) AS Result
        SELECT ERROR_MESSAGE()
    END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pUpdateProgramAttendanceParameter]...';


GO


CREATE OR ALTER PROCEDURE [sWellness].[pUpdateProgramAttendanceParameter]
(
	@lXML varchar(max) = '',
    @rProgramId int = 0,
    @rCreatedBy bigint = 0,
	@rOrgId int
)
AS
BEGIN
	
	SET NOCOUNT ON;

    BEGIN TRY
        BEGIN TRANSACTION
		DECLARE @loXML XML, @ParticipantSourceTypeId INT = 95, @lNextNumber BIGINT--, @hDoc AS INT
        SET @loXML = CAST(@lXML AS XML)

		CREATE TABLE #ParticipantAttendance
		(
			Code NVARCHAR(20),
			ProgramId BIGINT,
			HasAttended INT,
			ParameterSourceTypeId SMALLINT,
			ParameterSourceId BIGINT,
			StaticParameterSourceId INT,
			OrderIndex INT,
			ParameterValue NVARCHAR(300),
			ParticipantSourceTypeId SMALLINT,
			ParticipantSourceId BIGINT
		)

		INSERT INTO #ParticipantAttendance(Code, ProgramId, HasAttended, ParameterSourceTypeId, ParameterSourceId, StaticParameterSourceId, OrderIndex, ParameterValue)
		SELECT T.c.value('@Code', 'varchar(200)') AS EmployeeCode,
               T.c.value('@ProgramId', 'varchar(200)') AS ProgramId,
               CASE LEFT(UPPER(ISNULL(T.c.value('@HasAttended', 'varchar(200)'),'Y')),1) WHEN 'Y' THEN 1 ELSE 0 END AS HasAttended,
			   T.c.value('@ParameterSourceTypeId', 'varchar(200)') AS ParameterSourceTypeId,
			   T.c.value('@ParameterSourceId', 'varchar(200)') AS ParameterSourceId,
			   T.c.value('@StaticParameterSourceId', 'varchar(200)') AS StaticParameterSourceId,
			   T.c.value('@OrderIndex', 'varchar(200)') AS OrderIndex,
			   T.c.value('@ParameterValue', 'varchar(200)') AS ParameterValue
        FROM @loXML.nodes('/Table/ParticipantAttendance')T(c)
				
		UPDATE pa
		SET pa.ParticipantSourceTypeId = @ParticipantSourceTypeId, pa.ParticipantSourceId = emp.Id
		FROM #ParticipantAttendance pa
		INNER JOIN sHrm.tEmployeeMaster emp ON ltrim(rtrim(pa.Code)) = ltrim(rtrim(emp.Code))
		AND @rOrgId = emp.OrgId
				
        EXECUTE sCommon.pTableRowIdGet 9999,
                                       'sSupport.tProgramParticipantParameter',
                                       0,
                                       1,
                                       1,
                                       @outNextNumber = @lNextNumber OUTPUT

		MERGE [sWellness].[tProgramParticipantParameter] AS Target
        USING
        (SELECT * FROM #ParticipantAttendance) AS Source
        ON Target.OrgId = @rOrgId
		   AND Target.ProgramId = Source.ProgramId
           AND Target.ParticipantSourceTypeId = @ParticipantSourceTypeId
		   AND Target.ParticipantSourceId = Source.ParticipantSourceId
		   AND Target.ParameterSourceTypeId = Source.ParameterSourceTypeId
		   AND Target.ParameterSourceId = Source.ParameterSourceId
        WHEN MATCHED THEN
            UPDATE SET ParameterValue = Source.ParameterValue,
			Target.UpdatedUserId = @rCreatedBy,
			Target.UpdatedDateTime = GETDATE()
        WHEN NOT MATCHED THEN
            Insert
            (
                OrgId,
				ProgramId,
				ParameterSourceTypeId,
				ParameterSourceId,
				StaticParameterSourceId,
				ParticipantSourceTypeId,
				ParticipantSourceId,
				ParameterValue,
				Remark,
				Diagnosis,
				Recommendation,
				IsAbnormal,
				CreatedDateTime,
				CreatedUserId				
            )
            VALUES
            (   
				@rOrgId,
                Source.ProgramId,
                Source.ParameterSourceTypeId,
				Source.ParameterSourceId,
				Source.StaticParameterSourceId,
				Source.ParticipantSourceTypeId,
				Source.ParticipantSourceId,
				Source.ParameterValue,
				'',
				'',
				'',
				0,
                GETDATE(),
                @rCreatedBy
            );
		 SELECT 1 AS Result
		COMMIT
	END TRY
    BEGIN CATCH		
        SELECT ERROR_NUMBER() as Result, ERROR_MESSAGE() as ResultMessage		 
        ROLLBACK TRANSACTION
    END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pMobWellnessAppointmentNotificationDetailGet]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pMobWellnessAppointmentNotificationDetailGet]	
	@rAppointmentId bigint,
	@rTypeId smallint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
declare @timeSlot nvarchar(500)=''
declare @doctorId bigint
declare @employeeId bigint
declare @appointDate nvarchar(12)

declare @tbltemp table(Id int identity(1,1),DoctorId bigint,DoctorName nvarchar(100),EmployeeId bigint,EmployeeName nvarchar(100))

	Select @doctorId=A.DoctorEmployeeId,@employeeId=A.PatientSourceId,@appointDate=A.AppointmentDate,@timeSlot=Convert(nvarchar(5),TSM.FromTime) FROM sWellness.tAppointment A
inner join sAppointment.tTimeSlotMaster TSM on A.TimeSlotId=TSM.Id
where A.Id=@rAppointmentId
	
	insert into @tbltemp 
	SELECT DM.EmployeeId AS DoctorId,vEDM.DoctorName AS DoctorName,0,''
	FROM sCwb.tDoctorMaster DM
	INNER JOIN sCwb.vExtDoctorMaster vEDM ON DM.EmployeeId = vEDM.EmployeeId where DM.EmployeeId=@doctorId			
	union 
	select 0,'',EmployeeId,FirstName +' '+ LastName as EmployeeName from sHrm.vEmployeeCustomSearch where EmployeeId=@employeeId
	
	--select * from @tbltemp
	declare @tbltemp2 table(Id int identity(1,1),DoctorId bigint,DoctorName nvarchar(100),EmployeeId bigint,EmployeeName nvarchar(100),Message nvarchar(500))
	insert into @tbltemp2(DoctorId,EmployeeId,DoctorName,EmployeeName,Message) select  case when T1.DoctorId>0 then T1.DoctorId else T2.DoctorId end as DoctorId,case when T1.EmployeeId>0 then T1.EmployeeId else T2.EmployeeId end as EmployeeId,
	case when T1.DoctorName is null or T1.DoctorName='' then T2.DoctorName else T1.DoctorName end as DoctorName,
	case when T1.EmployeeName is null or T1.EmployeeName='' then T2.EmployeeName else T1.EmployeeName end as EmployeeName,'' as Message  from @tbltemp T1 cross join
			@tbltemp T2 where T1.DoctorId!=T2.DoctorId or T2.EmployeeId!=T1.EmployeeId
			
	----- get notification details when appoinment is added
	if @rTypeId=1
	begin
			update @tbltemp2 set Message='Hi '+DoctorName+', you had an appointment on '+convert(nvarchar,sCommon.fGetDate(),103)+', at '+@timeSlot+' with the patient named '+EmployeeName+'.'
			where Id=1
			update @tbltemp2 set Message='Hi '+EmployeeName+', your appointment on ('+convert(nvarchar,sCommon.fGetDate(),103)+'), at'+ @timeSlot+' has been successfully  submitted to Dr.'+DoctorName+'.'
			 where Id=2
			select * from @tbltemp2 order by Id
	end			

	----- get notification details when appoinment is added with direct approved
	if @rTypeId=5
	begin
			update @tbltemp2 set Message='Hi '+DoctorName+', you had an appointment on '+convert(nvarchar,sCommon.fGetDate(),103)+', at '+@timeSlot+' with the patient named '+EmployeeName+'.'
			where Id=1
			update @tbltemp2 set Message='Hi '+EmployeeName+', your appointment on ('+convert(nvarchar,sCommon.fGetDate(),103)+'), at'+ @timeSlot+' has been successfully  submitted to Dr.'+DoctorName+'.'
			 where Id=2

			insert into @tbltemp2 (DoctorId,DoctorName,EmployeeId,EmployeeName,Message)			
			select DoctorId,DoctorName,EmployeeId,EmployeeName,'Hi '+EmployeeName+', your appointment has been approved by Dr.'+DoctorName+'.' from @tbltemp2 where Id=2

			select * from @tbltemp2 order by Id
	end	

	----- get notification details when appoinment is approved
	if @rTypeId=2
		begin
			update @tbltemp2 set Message='Hi '+EmployeeName+', your appointment has been approved by Dr.'+DoctorName+'.' where Id=1
			select * from @tbltemp2 order by Id
		end

	----- get notification details when appoinment is canceled
	if @rTypeId=3
		begin
		update @tbltemp2 set Message='Hi '+EmployeeName+', your appointment has been canceled by Dr.'+DoctorName+'.' where Id=1
			select * from @tbltemp2 order by Id
			
		end

	----- get notification details  when appoinment is missed
	if @rTypeId=4
		begin		
		
			update @tbltemp2 set Message='Hi '+DoctorName+', you had missed an appointment on '+convert(nvarchar,sCommon.fGetDate(),103)+', at '+@timeSlot+' with the patient named '+EmployeeName+'.'
			where Id=1
			update @tbltemp2 set Message='Hi '+EmployeeName+', your appointment on ('+convert(nvarchar,sCommon.fGetDate(),103)+'), at'+ @timeSlot+'  has been missed by Dr.'+DoctorName+' due to a busy schedule.'
			 where Id=2
			select * from @tbltemp2 order by Id
				
		end
END
GO
PRINT N'Creating Procedure [sWellness].[pProgramCustomFieldDataAddUpdate]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pProgramCustomFieldDataAddUpdate]
(
	@rProgramMasterId bigint,
	@rCustomFieldDataXml nvarchar(max) = '',
	@rCreatedUserId bigint
)	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loXML XML
SET @loXML = CAST(@rCustomFieldDataXml AS XML)

BEGIN
	BEGIN TRY
	BEGIN TRANSACTION
		CREATE TABLE #tbltmpCustomFieldData
		(
			tid int identity(1,1),
			lProgramCustomFieldId int,
			lFieldTitle nvarchar(500),
			lFieldData nvarchar(500),
			lOrderIndex int			
		)
		INSERT INTO #tbltmpCustomFieldData
		SELECT
			T.c.value('@Id','int') AS Id,
			T.c.value('@FieldTitle','nvarchar(500)') AS FieldTitle,
			T.c.value('@FieldData','nvarchar(500)') AS FieldData,
			T.c.value('@OrderIndex','int') AS OrderIndex
		FROM 
			 @loXML.nodes('/Table/CustomFieldData')T(c)
		MERGE [sWellness].[tProgramCustomField] AS Target USING 
		(
			SELECT * FROM #tbltmpCustomFieldData 
		) AS Source ON Target.Id = Source.lProgramCustomFieldId 
					AND Target.ProgramId = @rProgramMasterId
		WHEN MATCHED THEN 
			UPDATE 
			SET FieldTitle = lFieldTitle,
				FieldData = lFieldData,
				OrderIndex = lOrderIndex,
				UpdatedUserId = @rCreatedUserId,
				UpdatedDateTime = GETDATE()
		WHEN NOT MATCHED THEN
			INSERT
			(
				ProgramId,
				FieldTitle,
				FieldData,
				OrderIndex,
				CreatedUserId,
				CreatedDateTime
			)
			VALUES
			(
				@rProgramMasterId,
				lFieldTitle,
				lFieldData,
				lOrderIndex,
				@rCreatedUserId,
				GETDATE()
			);
		SELECT 1 AS Result
		COMMIT TRANSACTION	
	END TRY
	BEGIN CATCH 
		IF @@TRANCOUNT > 0
			ROLLBACK TRANSACTION	
		SELECT -1 AS Result
		SELECT Error_Message()
	END CATCH	
END
GO
PRINT N'Creating Procedure [sWellness].[pWellnessAppointmentDocumentAdd]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pWellnessAppointmentDocumentAdd]
	@rId int=0,
	@rAppointmentId bigint,
	@rFileName nvarchar(100),
	@rConfigurationTypeId int,
	@rIsObsolete bit=0,
	@rUserId bigint
AS
BEGIN
	SET NOCOUNT ON;
			
			INSERT INTO [sWellness].[tWellnessAppointmentDocuments]
			(
			AppointmentId,
			FileName,
			ConfigurationTypeId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime
			)
			VALUES
			(
			@rAppointmentId,
			@rFileName,
			@rConfigurationTypeId,
			@rIsObsolete,
			@rUserId,
			sCommon.fGetDate()
			)
END
GO
PRINT N'Creating Procedure [sWellness].[pGetPrograms]...';


GO
CREATE OR ALTER PROCEDURE[sWellness].[pGetPrograms]
(
    @rId BIGINT,
    @rProgramName NVARCHAR(10),
    @rFromDate DATETIME = null,
    @rToDate DATETIME = null,
	@rLocationId BIGINT = 0,
	@rIsRegistrationRequired BIT = 0,
	@rScreenFlagId SMALLINT = 0,
	@rEmployeeId BIGINT = 0,
    @rOrgId INT
)
AS
SET NOCOUNT ON
BEGIN

    SELECT DISTINCT
		P.Id,
        Title,
		ModeId,
        Description,
        FromDate AS FromDate,
		ToDate AS ToDate,
		RegisterUptoDatetime,
		IsRegistrationRequired,
		FromTime,
		ToTime
    FROM 
		[sWellness].[tProgramMaster] P
	LEFT JOIN
		[sWellness].[tProgramLocation] PL
	ON	
		P.Id = PL.ProgramId
    WHERE 
		P.IsObsolete = 0
	AND
		(ISNULL(P.Id, 0) = @rId OR ISNULL(@rId, 0) = 0)
	AND
		(ISNULL(P.IsRegistrationRequired, 0) = @rIsRegistrationRequired OR ISNULL(@rIsRegistrationRequired, 0) = 0)
  --  AND 
		--(ISNULL(PL.LocationId, 0) = @rLocationId OR ISNULL(@rLocationId, 0) = 0)
    AND 
		OrgId = @rOrgId
    AND 
		((Title LIKE (@rProgramName + '%')) OR ISNULL(@rProgramName, '') = '')
    AND 
		((FromDate >= @rFromDate) OR (ISNULL(@rFromDate, '') = ''))
    AND 
		((FromDate <= @rToDate) OR (ISNULL(@rToDate, '') = ''))
	ORDER BY 
		Id
	DESC
END
GO
PRINT N'Creating Procedure [sAudit].[pActivityLogMonthWiseMoveToArchive]...';


GO
CREATE OR ALTER PROCEDURE [sAudit].[pActivityLogMonthWiseMoveToArchive]
    @CurrentMonthDate DATETIME,
    @PreviousMonthDate DATETIME
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
    BEGIN TRY
        CREATE TABLE #TempActivityLog
        (
            OrganizationName NVARCHAR(200),
            UserName NVARCHAR(200),
            OSType NVARCHAR(50),
            ScreenName NVARCHAR(200),
            AuditDate DATETIME,
            Activity NVARCHAR(MAX),
            ScreenDetail NVARCHAR(MAX)
        );

        INSERT INTO #TempActivityLog
        (
            OrganizationName,
            UserName,
            OSType,
            ScreenName,
            AuditDate,
            Activity,
            ScreenDetail
        )
        SELECT OM.Title AS OrganizationName,
               U.DisplayTitle AS UserName,
               CASE
                   WHEN AL.OSType = 1 THEN
                       'Android'
                   WHEN AL.OSType = 2 THEN
                       'IOS'
                   ELSE
                       'Web'
               END AS OSType,
               CASE
                   WHEN ISNULL(AL.SourceTypeId, 2023) = 2024 THEN
                       R.Title
                   ELSE
                       S.Title
               END AS ScreenName,
               AL.AuditDate,
               AL.Activity,
               AL.ScreenDetail
        FROM sAudit.tActivityLog AL
         INNER JOIN sSecurity.tUser U ON U.Id = AL.UserId  
    INNER JOin sSecurity.tUserLocation UL on UL.Userid=U.id
    INNER JOIN sCommon.tCompanyInformation OM ON OM.Id = AL.OrgId  
    left JOIN sSecurity.tScreen S ON S.Id = AL.ScreenId  
       left JOIN sCommon.tReport R ON R.Id = AL.ScreenId
        WHERE AL.AuditDate >= @PreviousMonthDate
              AND AL.AuditDate < @CurrentMonthDate;

     INSERT INTO sAudit.tActivityLogArchive (OrgId, UserId, SessionId, ScreenId, AuditDate, Activity, RecordSourceId, RecordDetail, SourceTypeId)
		SELECT OrgId, UserId, SessionId, ScreenId, AuditDate, Activity, RecordSourceId, RecordDetail, SourceTypeId
		FROM sAudit.tActivityLog
        WHERE AuditDate >= @PreviousMonthDate
              AND AuditDate < @CurrentMonthDate;

        DELETE FROM sAudit.tActivityLog
        WHERE AuditDate >= @PreviousMonthDate
              AND AuditDate < @CurrentMonthDate;

        SELECT *
        FROM #TempActivityLog;
    END TRY
    BEGIN CATCH
        SELECT -101
    END CATCH

END
GO
PRINT N'Creating Procedure [sAudit].[pArchiveAuditLogHistoryDocumentListGet]...';


GO
CREATE OR ALTER PROCEDURE [sAudit].[pArchiveAuditLogHistoryDocumentListGet]
(
    @rDeletePermission BIT = 0,
    @rOrgId INT,
    @rConfVal INT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @res VARCHAR(MAX) = '',
            @delmessage VARCHAR(100) = '''Are you sure to delete this item?''';

    -- Local Drive / Different Drive
    IF (@rConfVal IN (1,2))
    BEGIN
       SELECT @res = @res +
'<tr>
    <td>' + FileName + '</td>
    <td>
        <a attrcode="0"
           onclick="downloadthis(this,' + CAST(OrgId AS VARCHAR) + ',''AuditLogHistory'',''' + FileName + ''');"
           style="cursor:pointer;">Download</a>
    </td>' +

    CASE 
        WHEN @rDeletePermission = 1 THEN
            '<td>
                <a href="javascript:;"
                   onclick="if (!confirm(' + @delmessage + '))
                   { false } else { deletethis(' + CAST(Id AS VARCHAR) + ',this) }">
                   Delete
                </a>
             </td>'
        ELSE
            ''
    END +

'</tr>'
FROM [sAudit].[tArchiveAuditLogHistoryDocuments]
WHERE OrgId = @rOrgId
  AND ConfigurationTypeId = @rConfVal;
  end
    -- Azure
    ELSE IF (@rConfVal = 3)
    BEGIN
        SELECT @res = @res +
'<tr>
    <td>' + FileName + '</td>
    <td>
        <a style="cursor:pointer"
           onclick="DownloadAzure(this);"
           attrOrgId="' + CAST(OrgId AS VARCHAR) + '"
           attrName="' + FileName + '">
            Download
        </a>
    </td>' +

    CASE 
        WHEN @rDeletePermission = 1 THEN
            '<td>
                <a href="javascript:;"
                   onclick="if (!confirm(' + @delmessage + '))
                   { false } else { deletethis(' + CAST(Id AS VARCHAR) + ',this) }">
                   Delete
                </a>
             </td>'
        ELSE
            ''   -- ❌ no empty <td>
    END +

'</tr>'
FROM [sAudit].[tArchiveAuditLogHistoryDocuments]
WHERE OrgId = @rOrgId
  AND ConfigurationTypeId = @rConfVal;
  end
    SELECT @res AS res;
END
GO
PRINT N'Creating Procedure [sAudit].[pArchiveAuditLogHistoryDocumentSave]...';


GO

CREATE OR ALTER PROCEDURE [sAudit].[pArchiveAuditLogHistoryDocumentSave]
@rFileName nvarchar(200), @rconfigurationTypeId int, @rOrgId int
AS
BEGIN
	SET NOCOUNT ON;

	INSERT INTO [sAudit].[tArchiveAuditLogHistoryDocuments]
           ([FileName]
           ,[ConfigurationTypeId]
           ,[CreatedDateTime],
		   [OrgId])
     VALUES
           (@rFileName, @rconfigurationTypeId,sCommon.fGetDate(),@rOrgId)
					
	SELECT scope_identity() AS Result		
END
GO
PRINT N'Creating Procedure [sCommon].[pWellnessDoctorByStoreLocationGet]...';


GO

CREATE OR ALTER PROCEDURE [sCommon].[pWellnessDoctorByStoreLocationGet]   
 @rOrgId [int],
 @rStoreLocationId [int]
AS
BEGIN
     SELECT  
	     d.EmployeeId AS Id,   
		 ISNULL(e.EmployeePrefix + ' ', ' ') + (e.FirstName + ISNULL(' ' + e.MiddleName, '') + ' ' + e.LastName) AS Title 
     FROM 
	     sCwb.tDoctorMaster d   
     INNER JOIN 
	     sHrm.tEmployeeMaster e on d.EmployeeId = e.Id   
     INNER JOIN 
	     sCwb.tDoctorStoreLocation S on d.EmployeeId = S.EmployeeId   
     WHERE 
          e.OrgId= @rOrgId  
          AND S.SubLocationId = @rStoreLocationId 
          AND e.StatusId = 7
		  AND isnull(d.IsWellness,0)=1
END
GO
PRINT N'Creating Procedure [sExamination].[pGetAnnualHealthCheckupTicketAssigned]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pGetAnnualHealthCheckupTicketAssigned]  
(  
    @rOrgId INT,  
    @rTemplate NVARCHAR(MAX),  
    @rMailSubject NVARCHAR(MAX),  
    @rProviderAppointmentIds NVARCHAR(MAX) = '',  
    @rEventId INT
)  
AS
BEGIN  
    SET NOCOUNT ON;

WITH LastAssign AS
(
    SELECT MAX(AssignDate) AS MaxAssignDate
    FROM sSupport.tProviderAppointment
    WHERE AssignDate >= CAST(GETDATE() AS DATE)
    AND AssignDate < DATEADD(DAY, 1, CAST(GETDATE() AS DATE))
)
SELECT  
	EM.Id,
    ISNull(EM.FirstName, '') + ' ' + ISNull(EM.LastName, '') as EmployeeName,
    EC.CompanyEmail AS ToDoctor,
    STUFF((
        SELECT DISTINCT ',' + EC2.CompanyEmail
        FROM sSupport.tProviderAppointment A2
        CROSS JOIN LastAssign L2
        INNER JOIN sHrm.tEmployeeCommunications EC_A2 
            ON EC_A2.EmployeeId = A2.AssignToDoctorId
        LEFT JOIN sExamination.tSetupEmployee SE2 
            ON SE2.SetupId = A2.SetupId 
            AND SE2.EmployeeId = A2.PatientSourceId 
            AND SE2.SiteDoctorId = A2.AssignToDoctorId
        LEFT JOIN sHrm.tEmployeeCommunications EC2 
            ON EC2.EmployeeId = SE2.CentralDoctorId
        WHERE EC_A2.CompanyEmail = EC.CompanyEmail
          AND SE2.EmployeeId IS NOT NULL
		  AND EC2.CompanyEmail IS NOT NULL
		  AND A2.AssignDate >= CAST(GETDATE() AS DATE)
          AND A2.AssignDate < DATEADD(DAY, 1, CAST(GETDATE() AS DATE))
          AND ABS(DATEDIFF(SECOND, A2.AssignDate, L2.MaxAssignDate)) <= 180
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS CCDoctor
INTO #DoctorAssignmentSummary
FROM sSupport.tProviderAppointment A
CROSS JOIN LastAssign L
INNER JOIN sHrm.tEmployeeMaster EM
    ON EM.Id = A.AssignToDoctorId
INNER JOIN sHrm.tEmployeeCommunications EC 
    ON EC.EmployeeId = A.AssignToDoctorId
WHERE A.StatusId <> 591
  AND A.AssignDate < DATEADD(DAY, 1, CAST(GETDATE() AS DATE))
  AND ABS(DATEDIFF(SECOND, A.AssignDate, L.MaxAssignDate)) <= 180
  AND ISNULL(A.AssignToDoctorId, 0) <> 0
  AND (ISNULL(A.Id,0) IN (SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rProviderAppointmentIds,''),',')) OR ISNULL(@rProviderAppointmentIds,'')='')
GROUP BY EM.Id, EM.FirstName, EM.LastName, EC.CompanyEmail
ORDER BY EC.CompanyEmail;

SELECT  
    D.Id,
    D.ToDoctor,
    D.CCDoctor,
	D.EmployeeName,
    -- New Assigned (last 48 hours)
    SUM(CASE 
            WHEN A.AssignDate >= DATEADD(HOUR, -48, GETDATE()) 
            THEN 1 
            ELSE 0 
        END) AS NewAssigned,

    -- Old Assigned (older than 48 hours)
    SUM(CASE 
            WHEN A.AssignDate < DATEADD(HOUR, -48, GETDATE()) 
            THEN 1 
            ELSE 0 
        END) AS LongOpen
INTO #CountDoctorAssign
FROM sSupport.tProviderAppointment A
INNER JOIN #DoctorAssignmentSummary D
    ON D.Id = A.AssignToDoctorId
WHERE A.StatusId <> 591
GROUP BY
    D.Id,
    D.ToDoctor,
    D.CCDoctor,
	D.EmployeeName
ORDER BY D.ToDoctor;

SELECT  
    C.Id,
    C.ToDoctor as EmailId,
    C.CCDoctor as strCC,
    C.NewAssigned,
    C.LongOpen,
    @rMailSubject AS Subject,

    REPLACE(
        REPLACE(
            REPLACE(@rTemplate,
                    '[AssignedDoctor]', C.EmployeeName),
            '[NewAssigned]', CAST(C.NewAssigned AS NVARCHAR(20))),
        '[LongOpen]', CAST(C.LongOpen AS NVARCHAR(20)))
    AS MsgText
FROM #CountDoctorAssign C;

IF OBJECT_ID('tempdb..#DoctorAssignmentSummary') IS NOT NULL      
 DROP TABLE #DoctorAssignmentSummary

IF OBJECT_ID('tempdb..#CountDoctorAssign') IS NOT NULL      
 DROP TABLE #CountDoctorAssign

END;
GO
PRINT N'Creating Procedure [sExamination].[pGetWellnessVisitPurposeDropdown]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pGetWellnessVisitPurposeDropdown]
@rOrgId int
AS
BEGIN
	select Id,Title,isnull(IsDefault,0) as IsDefault from sExamination.tCauseMaster 
	where IsObsolete = 0 and isnull(IsWellness,0)=1 and OrgId = @rOrgId order by isnull(IsDefault,0) desc
END
GO
PRINT N'Creating Procedure [sHospitalization].[pDashboardClosedDetailsGetAll]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pDashboardClosedDetailsGetAll]    
    @rFromDate NVARCHAR(50) = NULL,    
    @rToDate NVARCHAR(50) = NULL,    
    @rDoctorId NVARCHAR(50) = NULL,    
    @rStatus NVARCHAR(50) = NULL,    
 @rState NVARCHAR(50) = NULL,    
    @rOrgId BIGINT = NULL    
AS    
BEGIN            
    SET NOCOUNT ON;          
          
      
    IF @rFromDate = '' SET @rFromDate = NULL;          
    IF @rToDate = '' SET @rToDate = NULL;          
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;          
    IF @rStatus = '' OR @rStatus = '0' SET @rStatus = NULL;          
          
    DECLARE @FromDateConverted DATE = NULL;          
    DECLARE @ToDateConverted DATE = NULL;          
      
    IF @rFromDate IS NOT NULL          
        SET @FromDateConverted = CONVERT(DATE, LEFT(@rFromDate, 10), 103);  
          
    IF @rToDate IS NOT NULL          
        SET @ToDateConverted = CONVERT(DATE, LEFT(@rToDate, 10), 103);  
       
    IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL AND @FromDateConverted > @ToDateConverted)          
    BEGIN          
        DECLARE @tmp DATE;          
        SET @tmp = @FromDateConverted;          
        SET @FromDateConverted = @ToDateConverted;          
        SET @ToDateConverted = @tmp;          
    END          
          
      
    DECLARE @DoctorIdConverted BIGINT = NULL;          
    IF ISNUMERIC(@rDoctorId) = 1          
        SET @DoctorIdConverted = CAST(@rDoctorId AS BIGINT);          
          
      
    SELECT    
   ROW_NUMBER() OVER (ORDER BY PAL.TicketNumber) AS [Serial No],  
    PAL.EmpCode AS [Employee Code],  
     PAL.ProposerName AS [Employee Name],    
     HosB.Title as Business,  
	   LM.Title AS   [Hr Location],   
  PAL.BeneficiaryName as [Beneficiary Name],  
   PAL.Age,  
           PAL.NatureOfIllness as [Nature Of Illness]  , 
		     CUR.EmployeeName AS [Assigned Doctor],  
			   PAL.TicketStatus AS [Status],    
			   STUFF((  
    SELECT   
        CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103)   
        + ': ' + R.Remark  
    FROM sHospitalization.tIntimationRemark R  
    WHERE R.HospitalizationIntimationDetailId = pal.Id  
    ORDER BY R.CreatedDateTime DESC  
    FOR XML PATH(''), TYPE  
).value('.', 'nvarchar(max)'), 1, 1, '') AS Remarks ,
  Pal.HospitalName as [Hospital Name],  
    PAL.NetworkCity as [Network City],  
	     PAL.State as [State],    
  PAL.ClaimType as [Claim Type],  
      CASE   
          WHEN PAL.DateOfIntimation = DATEADD(DAY, DATEDIFF(DAY, 0, PAL.DateOfIntimation), 0)  
              THEN CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)  
          ELSE   
              CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)  
              + ' ' + CONVERT(VARCHAR(8), PAL.DateOfIntimation, 108)  
      END AS [Date Of Intimation]  
              
          
    FROM [sHospitalization].[tIntimationDetails] PAL       
 Inner Join sHospitalization.tIntimationAssignedDoctor ASID      
  On ASID.DoctorEmployeeId =PAL.AssignedDoctorId       
    LEFT JOIN [sHospitalization].[tIntimationAssignedDoctor] SM            
        ON SM.Id = PAL.IntimationAssignedDoctorId          
    LEFT JOIN [sSecurity].[tUser] UR            
        ON UR.Id = PAL.CreatedUserId            
        AND UR.IsObsolete = 0           
        AND UR.OrgId = PAL.OrgId          
    LEFT JOIN [shrm].[vEmployeeCommonDetail] CUR            
        ON CUR.EmployeeId = PAL.AssignedDoctorId            
          
    Left JOIN [sHrm].[tSectorMaster] HosB            
        ON HosB.Id = SM.AssignSubTypeId and  HosB.IsObsolete =SM.IsObsolete and HosB.OrgId = SM.OrgId          
          
    Left JOIN [sHrm].[tEmployeeMaster] EMD             
       ON EMD.Id = SM.DoctorEmployeeId            
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP             
            ON EMP.Id = PAL.ParticipantSourceId            
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD             
            ON ECD.EmployeeId = EMP.Id            
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD             
        ON EJD.EmployeeId = EMP.Id            
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM             
            ON ETM.Id = EJD.EmployeeTypeId            
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM             
            ON ECM.Id = EJD.EmployeeCompanyId            
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM             
            ON CGM.Id = ECM.CompanyGroupId            
        LEFT JOIN [sHrm].[tVerticalMaster] VTM             
            ON VTM.Id = CGM.VerticalId            
        LEFT JOIN [sHrm].[tSectorMaster] SCT             
            ON SCT.Id = VTM.SectorId            
        Left JOIN [sCommon].[tLocationMaster] LM             
            ON LM.Id = EJD.EmployeeLocationId            
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM             
            ON DGM.Id = EJD.OrganizationDepartmentId            
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM             
            ON ODM.Id = EJD.OrganizationDepartmentId            
            
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS             
            ON EMDS.Id = EJD.EmployeeDesignationId            
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS             
            ON VEMDS.EmployeeId = PAL.ParticipantSourceId            
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1             
            ON VEMDS1.EmployeeId = PAL.AssignedDoctorId            
     LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS2            
            ON VEMDS2.EmployeeId = PAL.UpdatedUserId            
        LEFT JOIN [sHrm].[tGradeMaster] GRD             
            ON GRD.Id = VEMDS.GradeId            
            
    WHERE           
        PAL.OrgId = @rOrgId          
        AND PAL.IsObsolete = 0      
  and    PAL.OrgId = ASID.OrgId and ASID.Id = PAL.IntimationAssignedDoctorId  
        AND (@FromDateConverted IS NULL OR PAL.DateOfIntimation >= @FromDateConverted)          
        AND (@ToDateConverted IS NULL OR PAL.DateOfIntimation < DATEADD(DAY, 1, @ToDateConverted))          
        AND (@DoctorIdConverted IS NULL OR PAL.AssignedDoctorId = @DoctorIdConverted)          
        AND (@rStatus IS NULL OR PAL.TicketStatus = @rStatus)    
		and PAL.TicketStatus ='Close'
   AND (          
       @rState IS NULL          
       OR @rState = ''          
       OR @rState = '0'          
       OR @rState = '- All -'          
       OR PAL.State = @rState          
    )          
          
    ORDER BY PAL.CreatedDateTime ASC;          
END
GO
PRINT N'Creating Procedure [sHospitalization].[pDashboardDetailsGetAllDoctors]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pDashboardDetailsGetAllDoctors]  
    @rFromDate NVARCHAR(50) = NULL,  
    @rToDate NVARCHAR(50) = NULL,  
    @rDoctorId NVARCHAR(50) = NULL,  
    @rStatus NVARCHAR(50) = NULL,  
 @rState NVARCHAR(50) = NULL,  
    @rOrgId BIGINT = NULL  
AS  
BEGIN    
    SET NOCOUNT ON;  
  
    -- Normalize empty inputs  
    IF @rFromDate = '' SET @rFromDate = NULL;  
    IF @rToDate = '' SET @rToDate = NULL;  
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;  
    IF @rStatus = '' OR @rStatus = '0' SET @rStatus = NULL;  
  
    DECLARE @FromDateConverted DATE = NULL;  
    DECLARE @ToDateConverted DATE = NULL;  
  
    -- Strip time and convert  
    IF @rFromDate IS NOT NULL  
        SET @FromDateConverted = CONVERT(DATE, LEFT(@rFromDate, 10), 103);  -- dd/MM/yyyy  
  
    IF @rToDate IS NOT NULL  
        SET @ToDateConverted = CONVERT(DATE, LEFT(@rToDate, 10), 103);  -- dd/MM/yyyy  
  
    -- Swap if From > To  
    IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL AND @FromDateConverted > @ToDateConverted)  
    BEGIN  
        DECLARE @tmp DATE;  
        SET @tmp = @FromDateConverted;  
        SET @FromDateConverted = @ToDateConverted;  
        SET @ToDateConverted = @tmp;  
    END  
  
    -- DoctorID conversion  
    DECLARE @DoctorIdConverted BIGINT = NULL;  
    IF ISNUMERIC(@rDoctorId) = 1  
        SET @DoctorIdConverted = CAST(@rDoctorId AS BIGINT);  
  
    -- DEBUG prints  
    PRINT 'DEBUG: FromDateConverted = ' + ISNULL(CONVERT(VARCHAR(10), @FromDateConverted, 120), 'NULL');  
    PRINT 'DEBUG: ToDateConverted   = ' + ISNULL(CONVERT(VARCHAR(10), @ToDateConverted, 120), 'NULL');  
  
    SELECT    
                   -- PAL.TicketNumber,    
 --  'TKT-' + RIGHT(PAL.TicketNumber, 5) AS TicketNumber,  
   ROW_NUMBER() OVER (ORDER BY PAL.TicketNumber) AS [Serial No],  
     PAL.ProposerName AS EmployeeName,    
  PAL.EmpCode AS EmployeeCode,    
        PAL.Mobile1 AS EmployeeMobile,    
  PAL.BeneficiaryName,  
  PAL.ClaimType,  
  Pal.HospitalName,  
  PAL.NetworkCity,    
     PAL.State,    
  CUR.EmployeeName AS [AssignedDoctor],  
  HosB.Title as Business,  
  PAL.TicketStatus AS [Status],    
      CASE   
          WHEN PAL.DateOfIntimation = DATEADD(DAY, DATEDIFF(DAY, 0, PAL.DateOfIntimation), 0)  
              THEN CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)  
          ELSE   
              CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)  
              + ' ' + CONVERT(VARCHAR(8), PAL.DateOfIntimation, 108)  
      END AS DateOfIntimation,  
        PAL.Age,  
        PAL.NatureOfIllness  ,  
         LM.Title AS   HrLocation,  
     
STUFF((  
    SELECT   
        CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103)   
        + ': ' + R.Remark  
    FROM sHospitalization.tIntimationRemark R  
    WHERE R.HospitalizationIntimationDetailId = pal.Id  
    ORDER BY R.CreatedDateTime DESC  
    FOR XML PATH(''), TYPE  
).value('.', 'nvarchar(max)'), 1, 1, '') AS Remarks  
  
    FROM [sHospitalization].[tIntimationDetails] PAL    
    left JOIN [sHospitalization].[tIntimationAssignedDoctor] SM    
        ON SM.DoctorEmployeeId = PAL.IntimationAssignedDoctorId  
    LEFT JOIN [sSecurity].[tUser] UR    
        ON UR.Id = PAL.CreatedUserId    
        AND UR.IsObsolete = 0   
        AND UR.OrgId = PAL.OrgId  
    LEFT JOIN [shrm].[vEmployeeCommonDetail] CUR    
        ON CUR.EmployeeId = PAL.AssignedDoctorId    
  
    Left JOIN [sHrm].[tSectorMaster] HosB    
        ON HosB.Id = SM.AssignSubTypeId and  HosB.IsObsolete =SM.IsObsolete and HosB.OrgId = SM.OrgId  
  
    Left JOIN [sHrm].[tEmployeeMaster] EMD     
            ON EMD.Id = SM.DoctorEmployeeId    
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP     
            ON EMP.Id = PAL.ParticipantSourceId    
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD     
            ON ECD.EmployeeId = EMP.Id    
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD     
            ON EJD.EmployeeId = EMP.Id    
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM     
            ON ETM.Id = EJD.EmployeeTypeId    
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM     
            ON ECM.Id = EJD.EmployeeCompanyId    
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM     
            ON CGM.Id = ECM.CompanyGroupId    
        LEFT JOIN [sHrm].[tVerticalMaster] VTM     
            ON VTM.Id = CGM.VerticalId    
        LEFT JOIN [sHrm].[tSectorMaster] SCT     
            ON SCT.Id = VTM.SectorId    
        Left JOIN [sCommon].[tLocationMaster] LM     
            ON LM.Id = EJD.EmployeeLocationId    
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM     
            ON DGM.Id = EJD.OrganizationDepartmentId    
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM     
            ON ODM.Id = EJD.OrganizationDepartmentId    
    
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS     
            ON EMDS.Id = EJD.EmployeeDesignationId    
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS     
            ON VEMDS.EmployeeId = PAL.ParticipantSourceId    
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1     
            ON VEMDS1.EmployeeId = PAL.AssignedDoctorId    
     LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS2    
            ON VEMDS2.EmployeeId = PAL.UpdatedUserId    
        LEFT JOIN [sHrm].[tGradeMaster] GRD     
            ON GRD.Id = VEMDS.GradeId    
    
    WHERE   
        PAL.OrgId = @rOrgId  
        AND PAL.IsObsolete = 0  
        AND (@FromDateConverted IS NULL OR PAL.DateOfIntimation >= @FromDateConverted)  
        AND (@ToDateConverted IS NULL OR PAL.DateOfIntimation < DATEADD(DAY, 1, @ToDateConverted))  
        AND (@DoctorIdConverted IS NULL OR PAL.AssignedDoctorId = @DoctorIdConverted)  
        AND (@rStatus IS NULL OR PAL.TicketStatus = @rStatus)  
   AND (  
       @rState IS NULL  
       OR @rState = ''  
       OR @rState = '0'  
       OR @rState = '- All -'  
       OR PAL.State = @rState  
    )  
  
    ORDER BY PAL.CreatedDateTime ASC;  
END
GO
PRINT N'Creating Procedure [sHospitalization].[pDashboardDoctorDetailsGetAll]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pDashboardDoctorDetailsGetAll]          
    @rFromDate NVARCHAR(50) = NULL,          
    @rToDate NVARCHAR(50) = NULL,          
    @rDoctorId NVARCHAR(50) = NULL,          
    @rStatus NVARCHAR(50) = NULL,          
 @rState NVARCHAR(50) = NULL,          
    @rOrgId BIGINT = NULL          
AS          
BEGIN            
    SET NOCOUNT ON;          
          
      
    IF @rFromDate = '' SET @rFromDate = NULL;          
    IF @rToDate = '' SET @rToDate = NULL;          
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;          
    IF @rStatus = '' OR @rStatus = '0' SET @rStatus = NULL;          
          
    DECLARE @FromDateConverted DATE = NULL;          
    DECLARE @ToDateConverted DATE = NULL;          
      
    IF @rFromDate IS NOT NULL          
        SET @FromDateConverted = CONVERT(DATE, LEFT(@rFromDate, 10), 103);  
          
    IF @rToDate IS NOT NULL          
        SET @ToDateConverted = CONVERT(DATE, LEFT(@rToDate, 10), 103);  
       
    IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL AND @FromDateConverted > @ToDateConverted)          
    BEGIN          
        DECLARE @tmp DATE;          
        SET @tmp = @FromDateConverted;          
        SET @FromDateConverted = @ToDateConverted;          
        SET @ToDateConverted = @tmp;          
    END          
          
      
    DECLARE @DoctorIdConverted BIGINT = NULL;          
    IF ISNUMERIC(@rDoctorId) = 1          
        SET @DoctorIdConverted = CAST(@rDoctorId AS BIGINT);          
          
      
    SELECT    
   ROW_NUMBER() OVER (ORDER BY PAL.TicketNumber) AS [Serial No],  
    PAL.EmpCode AS [Employee Code],  
     PAL.ProposerName AS [Employee Name],    
     HosB.Title as Business,  
	   LM.Title AS   [Hr Location],   
  PAL.BeneficiaryName as [Beneficiary Name],  
   PAL.Age,  
           PAL.NatureOfIllness as [Nature Of Illness]  , 
		     CUR.EmployeeName AS [Assigned Doctor],  
			   PAL.TicketStatus AS [Status],    
			   STUFF((  
    SELECT   
        CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103)   
        + ': ' + R.Remark  
    FROM sHospitalization.tIntimationRemark R  
    WHERE R.HospitalizationIntimationDetailId = pal.Id  
    ORDER BY R.CreatedDateTime DESC  
    FOR XML PATH(''), TYPE  
).value('.', 'nvarchar(max)'), 1, 1, '') AS Remarks ,
  Pal.HospitalName as [Hospital Name],  
    PAL.NetworkCity as [Network City],  
	     PAL.State as [State],    
  PAL.ClaimType as [Claim Type],  
      CASE   
          WHEN PAL.DateOfIntimation = DATEADD(DAY, DATEDIFF(DAY, 0, PAL.DateOfIntimation), 0)  
              THEN CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)  
          ELSE   
              CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)  
              + ' ' + CONVERT(VARCHAR(8), PAL.DateOfIntimation, 108)  
      END AS [Date Of Intimation]     
          
    FROM [sHospitalization].[tIntimationDetails] PAL       
 Inner Join sHospitalization.tIntimationAssignedDoctor ASID      
  On ASID.DoctorEmployeeId =PAL.AssignedDoctorId       
    LEFT JOIN [sHospitalization].[tIntimationAssignedDoctor] SM            
        ON SM.Id = PAL.IntimationAssignedDoctorId          
    LEFT JOIN [sSecurity].[tUser] UR            
        ON UR.Id = PAL.CreatedUserId            
        AND UR.IsObsolete = 0           
        AND UR.OrgId = PAL.OrgId          
    LEFT JOIN [shrm].[vEmployeeCommonDetail] CUR            
        ON CUR.EmployeeId = PAL.AssignedDoctorId            
          
    Left JOIN [sHrm].[tSectorMaster] HosB            
        ON HosB.Id = SM.AssignSubTypeId and  HosB.IsObsolete =SM.IsObsolete and HosB.OrgId = SM.OrgId          
          
    Left JOIN [sHrm].[tEmployeeMaster] EMD             
       ON EMD.Id = SM.DoctorEmployeeId            
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP             
            ON EMP.Id = PAL.ParticipantSourceId            
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD             
            ON ECD.EmployeeId = EMP.Id            
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD             
        ON EJD.EmployeeId = EMP.Id            
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM             
            ON ETM.Id = EJD.EmployeeTypeId            
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM             
            ON ECM.Id = EJD.EmployeeCompanyId            
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM             
            ON CGM.Id = ECM.CompanyGroupId            
        LEFT JOIN [sHrm].[tVerticalMaster] VTM             
            ON VTM.Id = CGM.VerticalId            
        LEFT JOIN [sHrm].[tSectorMaster] SCT             
            ON SCT.Id = VTM.SectorId            
        Left JOIN [sCommon].[tLocationMaster] LM             
            ON LM.Id = EJD.EmployeeLocationId            
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM             
            ON DGM.Id = EJD.OrganizationDepartmentId            
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM             
            ON ODM.Id = EJD.OrganizationDepartmentId            
            
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS             
            ON EMDS.Id = EJD.EmployeeDesignationId            
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS             
            ON VEMDS.EmployeeId = PAL.ParticipantSourceId            
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1             
            ON VEMDS1.EmployeeId = PAL.AssignedDoctorId            
     LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS2            
            ON VEMDS2.EmployeeId = PAL.UpdatedUserId            
        LEFT JOIN [sHrm].[tGradeMaster] GRD             
            ON GRD.Id = VEMDS.GradeId            
            
    WHERE           
        PAL.OrgId = @rOrgId          
        AND PAL.IsObsolete = 0    
		AND PAL.OrgId = ASID.OrgId and ASID.Id = PAL.IntimationAssignedDoctorId   
  and    PAL.OrgId = ASID.OrgId and ASID.Id = PAL.IntimationAssignedDoctorId  
        AND (@FromDateConverted IS NULL OR PAL.DateOfIntimation >= @FromDateConverted)          
        AND (@ToDateConverted IS NULL OR PAL.DateOfIntimation < DATEADD(DAY, 1, @ToDateConverted))          
        AND (@DoctorIdConverted IS NULL OR PAL.AssignedDoctorId = @DoctorIdConverted)          
        AND (@rStatus IS NULL OR PAL.TicketStatus = @rStatus)          
   AND (          
       @rState IS NULL          
       OR @rState = ''          
       OR @rState = '0'          
       OR @rState = '- All -'          
       OR PAL.State = @rState          
    )          
          
    ORDER BY PAL.CreatedDateTime ASC;          
END
GO
PRINT N'Creating Procedure [sHospitalization].[pDashboardNewticketDetailsGetAll]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pDashboardNewticketDetailsGetAll]      
    @rFromDate NVARCHAR(50) = NULL,      
    @rToDate NVARCHAR(50) = NULL,      
    @rDoctorId NVARCHAR(50) = NULL,      
    @rStatus NVARCHAR(50) = NULL,      
 @rState NVARCHAR(50) = NULL,      
    @rOrgId BIGINT = NULL      
AS      
BEGIN            
    SET NOCOUNT ON;          
          
      
    IF @rFromDate = '' SET @rFromDate = NULL;          
    IF @rToDate = '' SET @rToDate = NULL;          
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;          
    IF @rStatus = '' OR @rStatus = '0' SET @rStatus = NULL;          
          
    DECLARE @FromDateConverted DATE = NULL;          
    DECLARE @ToDateConverted DATE = NULL;          
      
    IF @rFromDate IS NOT NULL          
        SET @FromDateConverted = CONVERT(DATE, LEFT(@rFromDate, 10), 103);  
          
    IF @rToDate IS NOT NULL          
        SET @ToDateConverted = CONVERT(DATE, LEFT(@rToDate, 10), 103);  
       
    IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL AND @FromDateConverted > @ToDateConverted)          
    BEGIN          
        DECLARE @tmp DATE;          
        SET @tmp = @FromDateConverted;          
        SET @FromDateConverted = @ToDateConverted;          
        SET @ToDateConverted = @tmp;          
    END          
          
      
    DECLARE @DoctorIdConverted BIGINT = NULL;          
    IF ISNUMERIC(@rDoctorId) = 1          
        SET @DoctorIdConverted = CAST(@rDoctorId AS BIGINT);          
          
      
       SELECT    
   ROW_NUMBER() OVER (ORDER BY PAL.TicketNumber) AS [Serial No],  
    PAL.EmpCode AS [Employee Code],  
     PAL.ProposerName AS [Employee Name],    
     HosB.Title as Business,  
	   LM.Title AS   [Hr Location],   
  PAL.BeneficiaryName as [Beneficiary Name],  
  PAL.Relation ,  
  PAL.TreatingDoctor,  
   PAL.Age,  
           PAL.NatureOfIllness as [Nature Of Illness]  , 
		     CUR.EmployeeName AS [Assigned Doctor],  
			   PAL.TicketStatus AS [Status],    
			   STUFF((  
    SELECT   
        CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103)   
        + ': ' + R.Remark  
    FROM sHospitalization.tIntimationRemark R  
    WHERE R.HospitalizationIntimationDetailId = pal.Id  
    ORDER BY R.CreatedDateTime DESC  
    FOR XML PATH(''), TYPE  
).value('.', 'nvarchar(max)'), 1, 1, '') AS Remarks ,
  Pal.HospitalName as [Hospital Name],  
    PAL.NetworkCity as [Network City],  
	     PAL.State as [State],    
  PAL.ClaimType as [Claim Type],  
      CASE   
          WHEN PAL.DateOfIntimation = DATEADD(DAY, DATEDIFF(DAY, 0, PAL.DateOfIntimation), 0)  
              THEN CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)  
          ELSE   
              CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)  
              + ' ' + CONVERT(VARCHAR(8), PAL.DateOfIntimation, 108)  
      END AS [Date Of Intimation]  
            
          
    FROM [sHospitalization].[tIntimationDetails] PAL       
 Inner Join sHospitalization.tIntimationAssignedDoctor ASID      
  On ASID.DoctorEmployeeId =PAL.AssignedDoctorId       
    LEFT JOIN [sHospitalization].[tIntimationAssignedDoctor] SM            
        ON SM.Id = PAL.IntimationAssignedDoctorId          
    LEFT JOIN [sSecurity].[tUser] UR            
        ON UR.Id = PAL.CreatedUserId            
        AND UR.IsObsolete = 0           
        AND UR.OrgId = PAL.OrgId          
    LEFT JOIN [shrm].[vEmployeeCommonDetail] CUR            
        ON CUR.EmployeeId = PAL.AssignedDoctorId            
          
    Left JOIN [sHrm].[tSectorMaster] HosB            
        ON HosB.Id = SM.AssignSubTypeId and  HosB.IsObsolete =SM.IsObsolete and HosB.OrgId = SM.OrgId          
          
    Left JOIN [sHrm].[tEmployeeMaster] EMD             
       ON EMD.Id = SM.DoctorEmployeeId            
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP             
            ON EMP.Id = PAL.ParticipantSourceId            
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD             
            ON ECD.EmployeeId = EMP.Id            
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD             
        ON EJD.EmployeeId = EMP.Id            
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM             
            ON ETM.Id = EJD.EmployeeTypeId            
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM             
            ON ECM.Id = EJD.EmployeeCompanyId            
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM             
            ON CGM.Id = ECM.CompanyGroupId            
        LEFT JOIN [sHrm].[tVerticalMaster] VTM             
            ON VTM.Id = CGM.VerticalId            
        LEFT JOIN [sHrm].[tSectorMaster] SCT             
            ON SCT.Id = VTM.SectorId            
        Left JOIN [sCommon].[tLocationMaster] LM             
            ON LM.Id = EJD.EmployeeLocationId            
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM             
            ON DGM.Id = EJD.OrganizationDepartmentId            
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM             
            ON ODM.Id = EJD.OrganizationDepartmentId            
            
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS             
            ON EMDS.Id = EJD.EmployeeDesignationId            
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS             
            ON VEMDS.EmployeeId = PAL.ParticipantSourceId            
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1             
            ON VEMDS1.EmployeeId = PAL.AssignedDoctorId            
     LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS2            
            ON VEMDS2.EmployeeId = PAL.UpdatedUserId            
        LEFT JOIN [sHrm].[tGradeMaster] GRD             
            ON GRD.Id = VEMDS.GradeId            
            
    WHERE           
        PAL.OrgId = @rOrgId          
        AND PAL.IsObsolete = 0      
  and    PAL.OrgId = ASID.OrgId and ASID.Id = PAL.IntimationAssignedDoctorId  
        AND (@FromDateConverted IS NULL OR PAL.DateOfIntimation >= @FromDateConverted)          
        AND (@ToDateConverted IS NULL OR PAL.DateOfIntimation < DATEADD(DAY, 1, @ToDateConverted))          
        AND (@DoctorIdConverted IS NULL OR PAL.AssignedDoctorId = @DoctorIdConverted)          
        AND (@rStatus IS NULL OR PAL.TicketStatus = @rStatus)  
		and PAL.TicketStatus ='New'
   AND (          
       @rState IS NULL          
       OR @rState = ''          
       OR @rState = '0'          
       OR @rState = '- All -'          
       OR PAL.State = @rState          
    )          
          
    ORDER BY PAL.CreatedDateTime ASC;          
END
GO
PRINT N'Creating Procedure [sHospitalization].[pDashboardOpenAndNewDetailsGetAll]...';


GO
CREATE OR ALTER PROCEDURE [sHospitalization].[pDashboardOpenAndNewDetailsGetAll]      
    @rFromDate NVARCHAR(50) = NULL,      
    @rToDate NVARCHAR(50) = NULL,      
    @rDoctorId NVARCHAR(50) = NULL,      
    @rStatus NVARCHAR(50) = NULL,      
 @rState NVARCHAR(50) = NULL,      
    @rOrgId BIGINT = NULL      
AS      
BEGIN            
    SET NOCOUNT ON;          
          
      
    IF @rFromDate = '' SET @rFromDate = NULL;          
    IF @rToDate = '' SET @rToDate = NULL;          
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;          
    IF @rStatus = '' OR @rStatus = '0' SET @rStatus = NULL;          
          
    DECLARE @FromDateConverted DATE = NULL;          
    DECLARE @ToDateConverted DATE = NULL;          
      
    IF @rFromDate IS NOT NULL          
        SET @FromDateConverted = CONVERT(DATE, LEFT(@rFromDate, 10), 103);  
          
    IF @rToDate IS NOT NULL          
        SET @ToDateConverted = CONVERT(DATE, LEFT(@rToDate, 10), 103);  
       
    IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL AND @FromDateConverted > @ToDateConverted)          
    BEGIN          
        DECLARE @tmp DATE;          
        SET @tmp = @FromDateConverted;          
        SET @FromDateConverted = @ToDateConverted;          
        SET @ToDateConverted = @tmp;          
    END          
          
      
    DECLARE @DoctorIdConverted BIGINT = NULL;          
    IF ISNUMERIC(@rDoctorId) = 1          
        SET @DoctorIdConverted = CAST(@rDoctorId AS BIGINT);          
          
      
       SELECT    
   ROW_NUMBER() OVER (ORDER BY PAL.TicketNumber) AS [Serial No],  
    PAL.EmpCode AS [Employee Code],  
     PAL.ProposerName AS [Employee Name],    
     HosB.Title as Business,  
	   LM.Title AS   [Hr Location],   
  PAL.BeneficiaryName as [Beneficiary Name],
  PAL.Relation,
  PAL.TreatingDoctor,
   PAL.Age,  
           PAL.NatureOfIllness as [Nature Of Illness]  , 
		     CUR.EmployeeName AS [Assigned Doctor],  
			   PAL.TicketStatus AS [Status],    
			   STUFF((  
    SELECT   
        CHAR(10) + CONVERT(varchar(10), R.CreatedDateTime, 103)   
        + ': ' + R.Remark  
    FROM sHospitalization.tIntimationRemark R  
    WHERE R.HospitalizationIntimationDetailId = pal.Id  
    ORDER BY R.CreatedDateTime DESC  
    FOR XML PATH(''), TYPE  
).value('.', 'nvarchar(max)'), 1, 1, '') AS Remarks ,
  Pal.HospitalName as [Hospital Name],  
    PAL.NetworkCity as [Network City],  
	     PAL.State as [State],    
  PAL.ClaimType as [Claim Type],  
      CASE   
          WHEN PAL.DateOfIntimation = DATEADD(DAY, DATEDIFF(DAY, 0, PAL.DateOfIntimation), 0)  
              THEN CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)  
          ELSE   
              CONVERT(VARCHAR(10), PAL.DateOfIntimation, 103)  
              + ' ' + CONVERT(VARCHAR(8), PAL.DateOfIntimation, 108)  
      END AS [Date Of Intimation]  
            
          
    FROM [sHospitalization].[tIntimationDetails] PAL       
 Inner Join sHospitalization.tIntimationAssignedDoctor ASID      
  On ASID.DoctorEmployeeId =PAL.AssignedDoctorId       
    LEFT JOIN [sHospitalization].[tIntimationAssignedDoctor] SM            
        ON SM.Id = PAL.IntimationAssignedDoctorId          
    LEFT JOIN [sSecurity].[tUser] UR            
        ON UR.Id = PAL.CreatedUserId            
        AND UR.IsObsolete = 0           
        AND UR.OrgId = PAL.OrgId          
    LEFT JOIN [shrm].[vEmployeeCommonDetail] CUR            
        ON CUR.EmployeeId = PAL.AssignedDoctorId            
          
    Left JOIN [sHrm].[tSectorMaster] HosB            
        ON HosB.Id = SM.AssignSubTypeId and  HosB.IsObsolete =SM.IsObsolete and HosB.OrgId = SM.OrgId          
          
    Left JOIN [sHrm].[tEmployeeMaster] EMD             
       ON EMD.Id = SM.DoctorEmployeeId            
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP             
            ON EMP.Id = PAL.ParticipantSourceId            
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD             
            ON ECD.EmployeeId = EMP.Id            
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD             
        ON EJD.EmployeeId = EMP.Id            
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM             
            ON ETM.Id = EJD.EmployeeTypeId            
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM             
            ON ECM.Id = EJD.EmployeeCompanyId            
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM             
            ON CGM.Id = ECM.CompanyGroupId            
        LEFT JOIN [sHrm].[tVerticalMaster] VTM             
            ON VTM.Id = CGM.VerticalId            
        LEFT JOIN [sHrm].[tSectorMaster] SCT             
            ON SCT.Id = VTM.SectorId            
        Left JOIN [sCommon].[tLocationMaster] LM             
            ON LM.Id = EJD.EmployeeLocationId            
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM             
            ON DGM.Id = EJD.OrganizationDepartmentId            
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM             
            ON ODM.Id = EJD.OrganizationDepartmentId            
            
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS             
            ON EMDS.Id = EJD.EmployeeDesignationId            
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS             
            ON VEMDS.EmployeeId = PAL.ParticipantSourceId            
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1             
            ON VEMDS1.EmployeeId = PAL.AssignedDoctorId            
     LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS2            
            ON VEMDS2.EmployeeId = PAL.UpdatedUserId            
        LEFT JOIN [sHrm].[tGradeMaster] GRD             
            ON GRD.Id = VEMDS.GradeId            
            
    WHERE           
        PAL.OrgId = @rOrgId          
        AND PAL.IsObsolete = 0      
  and    PAL.OrgId = ASID.OrgId and ASID.Id = PAL.IntimationAssignedDoctorId  
        AND (@FromDateConverted IS NULL OR PAL.DateOfIntimation >= @FromDateConverted)          
        AND (@ToDateConverted IS NULL OR PAL.DateOfIntimation < DATEADD(DAY, 1, @ToDateConverted))          
        AND (@DoctorIdConverted IS NULL OR PAL.AssignedDoctorId = @DoctorIdConverted)          
        AND (@rStatus IS NULL OR PAL.TicketStatus = @rStatus)  
		and PAL.TicketStatus ='Open'
   AND (          
       @rState IS NULL          
       OR @rState = ''          
       OR @rState = '0'          
       OR @rState = '- All -'          
       OR PAL.State = @rState          
    )          
          
    ORDER BY PAL.CreatedDateTime ASC;          
END
GO
PRINT N'Creating Procedure [sSecurity].[pAutoInActiveUser_Test]...';


GO
CREATE OR ALTER PROCEDURE [sSecurity].[pAutoInActiveUser_Test]
(
    @InactiveDays INT,
    @OrgId INT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @Today DATETIME = GETDATE();
    DECLARE @SysUser1 BIGINT,
            @SysUser2 BIGINT,
            @SysUser3 BIGINT;

    SELECT 
        @SysUser1 = [sCommon].[fGetBigIntIdForOrg](1, @OrgId),
        @SysUser2 = [sCommon].[fGetBigIntIdForOrg](2, @OrgId),
        @SysUser3 = [sCommon].[fGetBigIntIdForOrg](3, @OrgId);

    /* ============================================
       USERS WHO NEVER LOGGED IN  (TEST MODE)
       ============================================ */

    INSERT INTO sSecurity.tInActiveUserLog
    (
        UserId,
        OrgId,
        InactiveReason,
        ReferenceDateTime,
        InactiveDays,
        CreatedDateTime
    )
    SELECT
    U.Id,
    @OrgId,
    'NEVER_LOGGED_IN',
    U.CreatedDateTime,
    @InactiveDays,
    @Today
FROM sSecurity.tUser U
LEFT JOIN sSecurity.tUserLog UL
    ON UL.UserId = U.Id
WHERE
    U.IsObsolete = 0
    AND U.OrgId = @OrgId
    AND DATEDIFF(DAY, U.CreatedDateTime, @Today) >= @InactiveDays
    AND UL.UserId IS NULL
    AND U.Id NOT IN (@SysUser1, @SysUser2, @SysUser3)
Order BY U.Id ASC;


    /* ============================================
       USERS INACTIVE AFTER LOGOUT (TEST MODE)
       ============================================ */

    INSERT INTO sSecurity.tInActiveUserLog
    (
        UserId,
        OrgId,
        InactiveReason,
        ReferenceDateTime,
        InactiveDays,
        CreatedDateTime
    )
    SELECT
        U.Id,
        @OrgId,
        'INACTIVE_AFTER_LOGOUT',
        L.LastLogoutDate,
        @InactiveDays,
        @Today
    FROM sSecurity.tUser U
    CROSS APPLY
    (
        SELECT MAX(UL.LoggedOutDateTime) AS LastLogoutDate
        FROM sSecurity.tUserLog UL
        WHERE UL.UserId = U.Id
    ) L
    WHERE 
        U.IsObsolete = 0
        AND U.OrgId = @OrgId
        AND U.Id NOT IN (@SysUser1, @SysUser2, @SysUser3)
        AND L.LastLogoutDate IS NOT NULL
        AND NOT EXISTS
        (
            SELECT 1
            FROM sSecurity.tUserLog UL
            WHERE UL.UserId = U.Id
              AND UL.LoggedOutDateTime IS NULL
        )
        AND DATEDIFF(DAY, L.LastLogoutDate, @Today) >= @InactiveDays;
END

GO
PRINT N'Creating Procedure [sSupport].[pStaffShiftManagementGet]...';


GO

CREATE OR ALTER PROCEDURE [sSupport].[pStaffShiftManagementGet]    
  @rShiftFromDate date = null,
  @rShiftToDate date = null,
  @rEmployeeCode nvarchar(max)='',
  @rIsOffline bit=0,
  @rIsOnline bit =0,
  @rOrgId int = 0
AS  
SET NOCOUNT ON  
BEGIN  
SELECT
    SR.EmployeeId,
    VEME.Code AS EmployeeCode,
    VEME.EmployeeName,

    COUNT(*) AS TotalShifts,

    -- Mode wise
    SUM(CASE WHEN SR.IsOnline = 1 THEN 1 ELSE 0 END) AS VirtualShifts,
    SUM(CASE WHEN SR.IsOffline = 1 THEN 1 ELSE 0 END) AS OnsiteShifts,

    -- Time wise
    SUM(CASE 
            WHEN CAST(SR.FromTime AS time) >= '06:00'
             AND CAST(SR.FromTime AS time) < '14:00'
            THEN 1 ELSE 0 
        END) AS MorningShifts,

    SUM(CASE 
            WHEN CAST(SR.FromTime AS time) >= '14:00'
             AND CAST(SR.FromTime AS time) < '22:00'
            THEN 1 ELSE 0 
        END) AS EveningShifts,

    SUM(CASE 
            WHEN CAST(SR.FromTime AS time) >= '22:00'
              OR CAST(SR.FromTime AS time) < '06:00'
            THEN 1 ELSE 0 
        END) AS NightShifts

FROM [sTm].[tShiftRoaster] SR
INNER JOIN sHrm.vExtEmployeeMaster VEME 
    ON SR.EmployeeId = VEME.Id  
	WHERE (VEME.Code like '%'+@rEmployeeCode+'%' Or IsNull(@rEmployeeCode,'')='')   
	AND (SR.ShiftDate >= @rShiftFromDate OR ISNULL(@rShiftFromDate,'') = '')   
	AND ((SR.IsOnline=1 and @rIsOnline=1) Or (SR.IsOffline=1 and @rIsOffline=1) OR (@rIsOnline=0 and @rIsOffline=0 and (SR.IsOnline=1 OR  SR.IsOffline=1)))
	AND (SR.ShiftDate <= @rShiftToDate OR ISNULL(@rShiftToDate,'') = '')  
GROUP BY
    SR.EmployeeId,
    VEME.Code,
    VEME.EmployeeName

ORDER BY
    VEME.EmployeeName;
END

GO
PRINT N'Creating Procedure [sTm].[pAddCommunicationLog]...';


GO

CREATE OR ALTER PROCEDURE [sTm].[pAddCommunicationLog]
(
    @rOrgId               INT,
    @rId                  INT,
    @rEmployeeId          BIGINT,
    @rShiftRoasterId      INT,
    @rCommunicationDate   DATE,
    @rCommunicationType   SMALLINT,
    @rMode                SMALLINT,
    @rDuration            INT,
    @rRemarks             NVARCHAR(1000),
    @rCreatedUserId       BIGINT
)
WITH EXECUTE AS CALLER
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        BEGIN TRANSACTION;

        DECLARE @lNextNumber INT;

        IF (@rId = 0)
        BEGIN
            /* Get next Id */
            EXEC sCommon.pTableRowIdGet
                @rOrgId,
                'sTm.tShiftCommunicationLog',
                0, 1, 1,
                @outNextNumber = @lNextNumber OUTPUT;

            INSERT INTO [sTm].[tShiftCommunicationLog]
            (
                Id,
                EmployeeId,
                ShiftRoasterId,
                CommunicationDate,
                CommunicationType,
                Mode,
                Duration,
                Remarks,
                IsObsolete,
                OrgId,
                CreatedUserId,
                CreatedDateTime,
                UpdatedUserId,
                UpdatedDateTime
            )
            VALUES
            (
                @lNextNumber,
                @rEmployeeId,
                @rShiftRoasterId,
                @rCommunicationDate,
                @rCommunicationType,
                @rMode,
                @rDuration,
                @rRemarks,
                0,
                @rOrgId,
                @rCreatedUserId,
                sCommon.fGetDate(),
                @rCreatedUserId,
                sCommon.fGetDate()
            );
        END
        ELSE
        BEGIN
            SET @lNextNumber = @rId;

            UPDATE [sTm].[tShiftCommunicationLog]
            SET
                EmployeeId        = @rEmployeeId,
                ShiftRoasterId    = @rShiftRoasterId,
                CommunicationDate = @rCommunicationDate,
                CommunicationType = @rCommunicationType,
                Mode              = @rMode,
                Duration          = @rDuration,
                Remarks           = @rRemarks,
                UpdatedUserId     = @rCreatedUserId,
                UpdatedDateTime   = sCommon.fGetDate()
            WHERE Id = @rId
              AND OrgId = @rOrgId;
        END

        SELECT @lNextNumber AS Result;

        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        SELECT ERROR_MESSAGE() AS Result;
    END CATCH
END
GO
PRINT N'Creating Procedure [sTm].[pGetCommunicationLogSearchList]...';


GO
CREATE OR ALTER PROCEDURE [sTm].[pGetCommunicationLogSearchList]
(
    @rOrgId               INT,
    @rEmployeeId          BIGINT = NULL,
    @rCommunicationType   SMALLINT = NULL,
    @rMode                SMALLINT = NULL,
    @rFromDate            DATE = NULL,
    @rToDate              DATE = NULL
)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        sc.Id,
        sc.EmployeeId,
        CommunicationDate as CommunicationDateString,
        CommunicationDate ,
        CASE sc.CommunicationType
        WHEN 1 THEN 'Call'
        WHEN 2 THEN 'WhatsApp'
        WHEN 3 THEN 'Email'
        WHEN 4 THEN 'Video Consultation'
        ELSE 'Unknown'
    END AS CommunicationTypeTitle,
	sc.CommunicationType,
        sc.Mode,
    CASE sc.Mode
        WHEN 1 THEN 'Virtual'
        WHEN 2 THEN 'Onsite'
        ELSE 'Unknown'
    END AS ModeTitle,
        Duration,
        Remarks,
		ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS EmployeeName,
		em.code as EmployeeCode,
		        CONVERT(VARCHAR(5), FromTime, 108) + ' - ' +
        CONVERT(VARCHAR(5), ToTime, 108) AS ShiftReference,
		sc.ShiftRoasterId
    FROM [sTm].[tShiftCommunicationLog] sc inner join 
	[sTm].[tShiftRoaster] sr on sr.Id = sc.ShiftRoasterId 
	inner join sHrm.tEmployeeMaster EM on em.Id = sc.employeeid
    WHERE
        sc.OrgId = @rOrgId
        AND ( @rEmployeeId IS NULL OR @rEmployeeId = 0 OR sc.EmployeeId = @rEmployeeId )
        AND ( @rCommunicationType IS NULL OR @rCommunicationType = 0 OR CommunicationType = @rCommunicationType )
        AND ( @rMode IS NULL OR @rMode = 0 OR Mode = @rMode )
        AND ( @rFromDate IS NULL OR CommunicationDate >= @rFromDate )
        AND ( @rToDate IS NULL OR CommunicationDate <= @rToDate )

    ORDER BY
        sc.Id DESC;
END
GO
PRINT N'Creating Procedure [sTm].[pGetEmployeeShiftList]...';


GO
CREATE OR ALTER PROCEDURE [sTm].[pGetEmployeeShiftList]
(
    @rOrgId             INT,
    @rStoreLocationId   INT,
    @rCommunicationDate DATE,
    @rEmployeeId      BIGINT
)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        Id AS Value,
        CONVERT(VARCHAR(5), FromTime, 108) + ' - ' +
        CONVERT(VARCHAR(5), ToTime, 108) AS Text
    FROM [sTm].[tShiftRoaster] WITH (NOLOCK)
    WHERE LocationId = @rStoreLocationId
      AND EmployeeId = @rEmployeeId
      AND ShiftDate = @rCommunicationDate
    ORDER BY FromTime;
END
GO
PRINT N'Creating Procedure [sWellness].[pGetProgramParticipants]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pGetProgramParticipants]
(
	@rProgramId BIGINT,
	@rProgramDate DATETIME,
	@rEmpCodeLike VARCHAR(max)='',
	@rIsExport BIT,
	@rViewParameterDetails BIT,
	@rOrgId SMALLINT
)
AS
SET NOCOUNT ON
BEGIN

	IF OBJECT_ID(N'tempdb.dbo.#ProgramAttendance', N'U') IS NOT NULL
    DROP TABLE #ProgramAttendance

	Create Table #ProgramAttendance
	(
		ProgramAttendanceId bigint,
		ProgramId bigint,		
		ProgramName nvarchar(50),
		EmployeeId bigint,
		EmployeeName nvarchar(200),
		EmployeeCode nvarchar(20),
		HasAttended bit
	)

	INSERT INTO #ProgramAttendance 
	(
		ProgramAttendanceId,
		ProgramId,
		ProgramName, 
		EmployeeId, 
		EmployeeName, 
		EmployeeCode, 
		HasAttended
	)

	SELECT 
		PP.Id AS ProgramAttendanceId,
		P.Id AS ProgramId, 
		P.ProgramName,
		EM.ID AS EmployeeId,
		(EM.FirstName +' '+EM.LastName) AS EmployeeName,
		EM.Code AS EmployeeCode,
		PP.HasAttended
	FROM 
		[sWellness].[tProgramParticipants] PP 
	INNER JOIN 
		[sWellness].[tProgram] P on P.Id=PP.ProgramId 
	INNER JOIN 
		[sHrm].[tEmployeeMaster] EM on EM.Id=PP.EmployeeId
	WHERE 
		PP.ProgramId=@rProgramId
	AND 
		((P.ProgramDate=@rProgramDate) OR (ISNULL(@rProgramDate,'')=''))
	AND 
		((ISNULL(EM.Code,'') IN (SELECT item FROM  sCommon.fnsplit(@rEmpCodeLike,','))) or @rEmpCodeLike='')
	
	IF(@rIsExport = 0 AND @rViewParameterDetails = 0)
	BEGIN
		SELECT * FROM #ProgramAttendance
	END
	ELSE IF (@rIsExport = 1 AND @rViewParameterDetails = 0)
	BEGIN
		SELECT 
			EmployeeCode,
			EmployeeName, 
			ProgramName, 
			(CASE WHEN HasAttended=0 THEN 'N' ELSE 'Y' END ) AS HasAttended 
		FROM
			#ProgramAttendance	
	END
	ELSE IF (@rViewParameterDetails = 1)
	BEGIN
		DECLARE @Pivot_Column [NVARCHAR](MAX),
			    @pivotQuery [NVARCHAR](MAX) = '',
				@selectColumns VARCHAR(MAX) = '',
				@innerSelectColumns VARCHAR(MAX) = '';

		CREATE TABLE #ProgramParameters
		(
			ParameterName NVARCHAR(100),
			ProgramParameterId BIGINT,
			OrgId SMALLINT,
			ProgramId BIGINT,
			ParameterTypeId TINYINT,
			ParameterType VARCHAR(10),
			ParameterSourceTypeId SMALLINT,
			ParameterSourceId BIGINT,
			StaticParameterSourceId INT,
			OrderIndex INT,
			CreatedUserId BIGINT, 
			CreatedDateTime DATETIME, 
			UpdatedUserId BIGINT, 
			UpdatedDateTime DATETIME
		)

		INSERT INTO #ProgramParameters 
		(
			ParameterName, 
			ProgramParameterId, 
			OrgId, 
			ProgramId, 
			ParameterTypeId, 
			ParameterType,
			ParameterSourceTypeId,
			ParameterSourceId, 
			StaticParameterSourceId, 
			OrderIndex,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
		EXEC [sWellness].[pGetProgramParameters] @rOrgId, @rProgramId

		SELECT @Pivot_Column= COALESCE(@Pivot_Column+',','')+ QUOTENAME(ParameterName) FROM #ProgramParameters
		
		IF(@rIsExport = 0)
		BEGIN
			SET @selectColumns = 'EmployeeId, EmployeeCode, EmployeeName, ProgramName, HasAttended,'
			SET @innerSelectColumns = 'pa.EmployeeId, pa.EmployeeCode, pa.EmployeeName, pa.ProgramName, pa.HasAttended,'
		END
		ELSE
		BEGIN
			SET @selectColumns = 'EmployeeCode, EmployeeName, ProgramName, HasAttended,'
			SET @innerSelectColumns = 'pa.EmployeeCode, pa.EmployeeName, pa.ProgramName, pa.HasAttended,'
		END

		SET @pivotQuery = 'SELECT '+@selectColumns+' '+@Pivot_Column+
						  ' FROM (SELECT '+@innerSelectColumns+' PP.ParameterName, PPP.ParameterValue '+
								   ' FROM #ProgramParameters PP '+
								   ' INNER JOIN [sWellness].[tProgramParticipantParameter] PPP ON PP.OrgId = PPP.OrgId and PP.ProgramId = PPP.ProgramId '+
								   ' and PP.ParameterSourceTypeId = PPP.ParameterSourceTypeId and PP.ParameterSourceId = PPP.ParameterSourceId '+
							       ' INNER JOIN #ProgramAttendance PA ON PP.ProgramId = PA.ProgramId AND PPP.ParticipantSourceId = PA.EmployeeId )Tab1 '+ 
								   ' PIVOT  ( max(ParameterValue) FOR ParameterName IN ('+@Pivot_Column+')) AS Tab2 '
		
		EXEC  sp_executesql  @pivotQuery 			
	END
END

GO
PRINT N'Altering Procedure [sExamination].[pArchieveExaminationDetaileGet]...';

GO
CREATE OR ALTER PROCEDURE [sExamination].[pArchieveExaminationDetaileGet]
@rId bigint,  
@rMainTyepId int  
AS  
SET NOCOUNT ON  
BEGIN  
 Declare @lPreviousDate datetime = '1900/01/01',@lExaminationDate datetime  
 Declare @lCriteriaGroupId int,@lTargetGroupId int  
 Declare @lEmployeeId bigint  
 SET @lCriteriaGroupId = (SELECT CriteiraGroupId FROM sExamination.tExamination Where Id = @rId)  
 SET @lTargetGroupId = (SELECT TargetGroupId FROM sExamination.tExamination Where Id = @rId)  
 SET @lEmployeeId = (SELECT ParticipantSourceId FROM sExamination.tExamination Where Id = @rId)  
 SET @lExaminationDate = (SELECT ExaminationDate FROM sExamination.tExamination Where Id = @rId)  
 SET @lPreviousDate =   
 (  
  SELECT ExaminationDate FROM   
  (  
   SELECT ExaminationDate,ROW_NUMBER() OVER(ORDER BY ExaminationDate desc) As RowNum  
   FROM sExamination.tExamination E  
   INNER JOIN sExamination.tSetupMaster SM ON SM.Id = E.SetupId  
   INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = SM.SubTypeId  
   where STM.MainTypeId = 1 AND E.ParticipantSourceId = @lEmployeeId  AND ExaminationDate < @lExaminationDate  
  ) As A  
  WHERE A.RowNum =1  
 )  
 IF((@rMainTyepId != 7) AND (@rMainTyepId != 8))  
 BEGIN  
  SELECT E.Id AS ExaminationId,  
  E.OrgId,  
  ST.MainTypeId,  
  MT.Title AS MainTypeName,  
  E.StoreLocationId,  
  SLM.Title AS StoreLocationName,  
  SLM.LocationId,  
  LM.Title AS LocationName,  
  OrganizationDepartmentId,  
  OD.Title AS DepartmentName,  
  E.SetupId,  
  SM.RoundNumber,  
  E.StatusId,  
  ExaminationDate,  
  ParticipantSourceTypeId,  
  ParticipantSourceId,  
  ISNULL(DoctorEmployeeId,0) AS DoctorEmployeeId,  
  ParticipantCode = CASE E.ParticipantSourceTypeId   
  WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,  
  ParticipantName =   
  CASE E.ParticipantSourceTypeId   
  WHEN 1009 THEN  
  (case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end)   
  WHEN 95 THEN EM.FirstName + ' ' + EM.LastName   
  WHEN 1001 THEN EFD.Name END,  
    
  RelationName = CASE E.ParticipantSourceTypeId WHEN  95 THEN 'SELF' WHEN 1001 THEN RM.Title WHEN 1009 THEN 'Other' END,  
  GenderId = CASE E.ParticipantSourceTypeId WHEN 95 THEN EPD.GenderId  
  WHEN 1001 THEN ISNULL([sCommon].[fGenderIdFromRelationIdGet](EFD.RelationshipId),'')  
  WHEN 1009 THEN BM.GenderId END,  
  Gender = CASE E.ParticipantSourceTypeId WHEN 95 THEN GM.Title  
  WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')  
  WHEN 1009 THEN GM2.Title END,  
  DateOfBirth = CASE E.ParticipantSourceTypeId WHEN 95 THEN ISNULL(EPD.DateOfBirth,'')  
  WHEN 1001 THEN ISNULL(EFD.DateOfBirth,'')  
  WHEN 1009 THEN ISNULL(BM.DateOfBirth,'') END,  
  Age = CASE E.ParticipantSourceTypeId  
  WHEN 95 THEN ISNULL(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0)  
  WHEN 1001 THEN ISNULL(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0)  
  WHEN 1009 THEN ISNULL(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) END,  
  isnull(EmployeeDesignationId,0) as EmployeeDesignationId,  
  isnull(E.ProcessTypeId,0) as ProcessTypeId,  
  SM.Title AS Setup,    
  isnull(Height,0) as Height,  
  EC.MobileNumber,  
  CompanyEmail,  
  SSM.Title as StatusName,  
  ISNULL(@lPreviousDate,'1900/01/01') AS PreviousDate,  
  ISNULL(@lCriteriaGroupId,0) AS CriteriaGroupId,  
  isnull(@lTargetGroupId,0) AS TargetGroupId  
  FROM sExamination.tArchieveExamination E  
  INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
  INNER JOIN sExamination.tSubTypeMaster ST on SM.SubTypeId = ST.Id  
  INNER JOIN sExamination.tMainTypeMaster MT on ST.MainTypeId = MT.Id  
  INNER JOIN sIp.tStoreLocationMaster SLM on E.StoreLocationId = SLM.Id  
  INNER JOIN sCommon.tLocationMaster LM on SLM.LocationId = LM.Id  
  LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id  
  LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009  
  LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId  
  LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id  
  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId  
  LEFT JOIN sCommon.tOrganizationDepartmentMaster OD on E.OrganizationDepartmentId = OD.Id  
  LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=EFD.RelationshipId  
  LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId  
  LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId  
  LEFT JOIN sExamination.tStatusMaster SSM on E.StatusId = SSM.Id  
  LEFT JOIN sExamination.tVital V on V.SourceId = E.Id   
  WHERE E.Id = @rId   
 END  
 ELSE  
 BEGIN  
  SELECT E.Id AS ExaminationId,  
  E.OrgId,  
  ST.MainTypeId,  
  MT.Title AS MainTypeName,  
  E.StoreLocationId,  
  SLM.Title AS StoreLocationName,  
  SLM.LocationId,  
  LM.Title AS LocationName,  
  OrganizationDepartmentId,  
  OD.Title AS DepartmentName,  
  E.SetupId,  
  SM.RoundNumber,  
  E.StatusId,  
  ExaminationDate,  
  ParticipantSourceTypeId,  
  ParticipantSourceId,  
  ISNULL(DoctorEmployeeId,0) AS DoctorEmployeeId,  
  ParticipantCode = CASE E.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,  
  ParticipantName = CASE E.ParticipantSourceTypeId WHEN 1009 THEN  
  (case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end)   
  WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END,  
  RelationName = CASE E.ParticipantSourceTypeId WHEN  95 THEN 'SELF' WHEN 1001 THEN RM.Title WHEN 1009 THEN 'Other' END,  
  GenderId = CASE E.ParticipantSourceTypeId WHEN 95 THEN EPD.GenderId  
  WHEN 1001 THEN ISNULL([sCommon].[fGenderIdFromRelationIdGet](EFD.RelationshipId),'')  
  WHEN 1009 THEN BM.GenderId END,  
  Gender = CASE E.ParticipantSourceTypeId WHEN 95 THEN GM.Title  
  WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')  
  WHEN 1009 THEN GM2.Title END,  
  DateOfBirth = CASE E.ParticipantSourceTypeId WHEN 95 THEN ISNULL(EPD.DateOfBirth,'')  
  WHEN 1001 THEN ISNULL(EFD.DateOfBirth,'')  
  WHEN 1009 THEN ISNULL(BM.DateOfBirth,'') END,  
  Age = CASE E.ParticipantSourceTypeId  
  WHEN 95 THEN ISNULL(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0)  
  WHEN 1001 THEN ISNULL(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0)  
  WHEN 1009 THEN ISNULL(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) END,  
  isnull(EmployeeDesignationId,0) as EmployeeDesignationId,  
  isnull(E.ProcessTypeId,0) as ProcessTypeId,  
  SM.Title AS Setup,    
  isnull(Height,0) as Height,  
  EC.MobileNumber,  
  CompanyEmail,  
  SSM.Title as StatusName,  
  ISNULL(@lPreviousDate,'1900/01/01') AS PreviousDate,  
  ISNULL(@lCriteriaGroupId,0) AS CriteriaGroupId,  
  isnull(@lTargetGroupId,0) AS TargetGroupId  
  FROM sExamination.tArchieveExamination E  
  INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
  INNER JOIN sExamination.tSubTypeMaster ST on SM.SubTypeId = ST.Id  
  INNER JOIN sExamination.tMainTypeMaster MT on ST.MainTypeId = MT.Id  
  INNER JOIN sIp.tStoreLocationMaster SLM on E.StoreLocationId = SLM.Id  
  INNER JOIN sCommon.tLocationMaster LM on SLM.LocationId = LM.Id  
  LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= E.Id  
  LEFT JOIN sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95  
  LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on E.ParticipantSourceId = EFD.Id and E.ParticipantSourceTypeId = 1001  
  LEFT JOIN sHrm.tCsrBenefiterMaster BM on E.ParticipantSourceId = BM.Id and E.ParticipantSourceTypeId = 1009  
  LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId  
  LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id  
  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId  
  LEFT JOIN sCommon.tOrganizationDepartmentMaster OD on E.OrganizationDepartmentId = OD.Id  
  LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=EFD.RelationshipId  
  LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EPD.GenderId  
  LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId  
  LEFT JOIN sExamination.tStatusMaster SSM on E.StatusId = SSM.Id  
  LEFT JOIN sExamination.tVital V on V.SourceId = E.Id   
  WHERE E.Id = @rId  
 END  
END
GO
PRINT N'Refreshing Procedure [sAlert].[pSMSLogModify]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pSMSLogModify]';


GO
PRINT N'Refreshing Procedure [sAlert].[pSMSHistoryGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pSMSHistoryGet]';


GO
PRINT N'Refreshing Procedure [sAlert].[pCheckEmailLog]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pCheckEmailLog]';


GO
PRINT N'Refreshing Procedure [sAlert].[pDeleteEventLog]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pDeleteEventLog]';


GO
PRINT N'Refreshing Procedure [sAlert].[pSMSLogGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pSMSLogGet]';


GO
PRINT N'Refreshing Procedure [sCommon].[pMobAppointmenScheduleListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pMobAppointmenScheduleListGet]';


GO
PRINT N'Refreshing Procedure [sAppointment].[pTimeSlotSetupGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAppointment].[pTimeSlotSetupGet]';


GO
PRINT N'Refreshing Procedure [sAppointment].[tTimeSlotMasterGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAppointment].[tTimeSlotMasterGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptFitnessList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptFitnessList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pValidateExaminationDataTable]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pValidateExaminationDataTable]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOpdCancelList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOpdCancelList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptSmallCardMain]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptSmallCardMain]';


GO
PRINT N'Refreshing Procedure [sCwb].[pDoctorEntitlementGetForVendorMaster]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCwb].[pDoctorEntitlementGetForVendorMaster]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOPDPrescriptionListWithBatchNExpiry]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOPDPrescriptionListWithBatchNExpiry]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptAccidentRegisterList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptAccidentRegisterList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptFullHealthCardGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptFullHealthCardGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptFitnessCertificateGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptFitnessCertificateGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptPreEmployeementFormWithDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptPreEmployeementFormWithDetails]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptPreEmployeementForm]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptPreEmployeementForm]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptPeriodicForm]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptPeriodicForm]';


GO
PRINT N'Refreshing Procedure [sHrm].[pGetStatusOfEmployee]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pGetStatusOfEmployee]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOpdPrescriptionList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOpdPrescriptionList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptPathology]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptPathology]';


GO
PRINT N'Refreshing Procedure [sAppointment].[pAppointmentListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAppointment].[pAppointmentListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptPeriodicForm_L]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptPeriodicForm_L]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOpdDayCareList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOpdDayCareList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOPDMedicalCertificate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOPDMedicalCertificate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptPrescription]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptPrescription]';


GO
PRINT N'Refreshing Procedure [sAppointment].[pMobAppointmentNotificationDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAppointment].[pMobAppointmentNotificationDetailGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptSickOPDRegisterList_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptSickOPDRegisterList_New]';


GO
PRINT N'Refreshing Procedure [sHrm].[pImportDoctorDB]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pImportDoctorDB]';


GO
PRINT N'Refreshing Procedure [sCommon].[pDoctorByStoreLocationGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pDoctorByStoreLocationGet]';


GO
PRINT N'Refreshing Procedure [sCwb].[pDoctorDetailsGetForDoctorFeeProcessing]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCwb].[pDoctorDetailsGetForDoctorFeeProcessing]';


GO
PRINT N'Refreshing Procedure [sCwb].[pEmployeeDetailsForDoctorGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCwb].[pEmployeeDetailsForDoctorGet]';


GO
PRINT N'Refreshing Procedure [sCwb].[pRptDoctorFeesPosting]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCwb].[pRptDoctorFeesPosting]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindOPDDropDowns]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindOPDDropDowns]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDoctorDropdwnGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDoctorDropdwnGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDoctorDropdwnGetNg]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDoctorDropdwnGetNg]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationMainTypeGetN]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationMainTypeGetN]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationMainTypeGetNNg]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationMainTypeGetNNg]';


GO
PRINT N'Refreshing Procedure [sExamination].[pInjuryReferEmployeeDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pInjuryReferEmployeeDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDLoadAllDropDownLists]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDLoadAllDropDownLists]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptFitnessCerti]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptFitnessCerti]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptInjuryReferenceLetter]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptInjuryReferenceLetter]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptMedicalCertificate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptMedicalCertificate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOPDActivityCertificate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOPDActivityCertificate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptReferralCertificate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptReferralCertificate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptSicknessReferenceLetter]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptSicknessReferenceLetter]';


GO
PRINT N'Refreshing Procedure [sIncident].[pRptIncidentLogGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sIncident].[pRptIncidentLogGet]';


GO
PRINT N'Refreshing Procedure [sIncident].[pRptIncidentLogGetAll]...';


GO
EXECUTE sp_refreshsqlmodule N'[sIncident].[pRptIncidentLogGetAll]';


GO
PRINT N'Refreshing Procedure [sSecurity].[pUserValidate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSecurity].[pUserValidate]';


GO
PRINT N'Refreshing Procedure [sSecurity].[pUserValidateSso]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSecurity].[pUserValidateSso]';


GO
PRINT N'Refreshing Procedure [sTool].[pEmployeeDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pEmployeeDelete]';


GO
PRINT N'Refreshing Procedure [sCommon].[pCommonControllerGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pCommonControllerGet]';


GO
PRINT N'Refreshing Procedure [sCwb].[pDoctorMasterIncludingSpecailityNotAttachedGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCwb].[pDoctorMasterIncludingSpecailityNotAttachedGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCustomOPDHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCustomOPDHistoryListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptVisitPurposeMajorMinorCount]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptVisitPurposeMajorMinorCount]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptVisitPurposeMajorMinorList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptVisitPurposeMajorMinorList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDHistoryListSearchGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDHistoryListSearchGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDArchiveHistoryListGetWithPagination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDArchiveHistoryListGetWithPagination]';


GO
PRINT N'Refreshing Procedure [sHrm].[PEmpDashboardDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[PEmpDashboardDetailGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCaseDetailReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCaseDetailReport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOPDAnalysis]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOPDAnalysis]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDAllDetailListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDAllDetailListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDDashboard]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDDashboard]';


GO
PRINT N'Refreshing Procedure [sExamination].[pVisitPerposeWiseEmployee]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pVisitPerposeWiseEmployee]';


GO
PRINT N'Refreshing Procedure [dbo].[CommanMisOpdDashboard]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[CommanMisOpdDashboard]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCustomOPDHistoryListGetWithPagination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCustomOPDHistoryListGetWithPagination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCaseDetailListWithArchive]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCaseDetailListWithArchive]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCaseDetailList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCaseDetailList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptDepartementwiseOPDSummary]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptDepartementwiseOPDSummary]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCustomOPDHistoryListGetWithPage]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCustomOPDHistoryListGetWithPage]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDHistoryListGetWithPagination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDHistoryListGetWithPagination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobOpdDashBoardOPDCount]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobOpdDashBoardOPDCount]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptReferCaseSummary]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptReferCaseSummary]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDHistoryListGetNew]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDHistoryListGetNew]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptArchiveCaseDetailCntList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptArchiveCaseDetailCntList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDCustomSearchGenerateReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDCustomSearchGenerateReport]';


GO
PRINT N'Refreshing Procedure [sIncident].[pInjuryListDashletGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sIncident].[pInjuryListDashletGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCustomOPDArchiveHistoryListGetWithPagination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCustomOPDArchiveHistoryListGetWithPagination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOpdHistoryArchiveList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOpdHistoryArchiveList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDConsolidatedcostDashboard]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDConsolidatedcostDashboard]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDashboardInjuryList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDashboardInjuryList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOpdDashBoardOPDCount]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOpdDashBoardOPDCount]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDConsolidatedcost]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDConsolidatedcost]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetSiknessInjuryCount]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetSiknessInjuryCount]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDConsolidatedcostDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDConsolidatedcostDetails]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCaseDetailCntList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCaseDetailCntList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDHistoryListSearchGetNg_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDHistoryListSearchGetNg_new]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetAllExaminationDatasOPD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetAllExaminationDatasOPD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDHistoryListGet]';


GO
PRINT N'Refreshing Procedure [dbo].[DiseaseDetailDataGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[DiseaseDetailDataGet]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_getHospitalReferral_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getHospitalReferral_new]';


GO
PRINT N'Refreshing Procedure [sAlert].[pGetEmployeeTypeCountList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pGetEmployeeTypeCountList]';


GO
PRINT N'Refreshing Procedure [sAlert].[pGetEmployeeTypeCountList_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pGetEmployeeTypeCountList_new]';


GO
PRINT N'Refreshing Procedure [sAlert].[pGetVisitPurposeCountList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pGetVisitPurposeCountList]';


GO
PRINT N'Refreshing Procedure [sAppointment].[pMobAppointmentListByDoctorId]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAppointment].[pMobAppointmentListByDoctorId]';


GO
PRINT N'Refreshing Procedure [sAppointment].[pMobAppointmentListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAppointment].[pMobAppointmentListGet]';


GO
PRINT N'Refreshing Procedure [sCommon].[pCompanySetupAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pCompanySetupAdd]';


GO
PRINT N'Refreshing Procedure [sCommon].[pEntityColorMasterGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pEntityColorMasterGet]';


GO
PRINT N'Refreshing Procedure [sCommon].[pOpdListGetDropDown]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pOpdListGetDropDown]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiseaseSystemGetForAlert]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiseaseSystemGetForAlert]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationCounselingDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationCounselingDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationCount]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationCount]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationCountWithEmployee]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationCountWithEmployee]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExportOPDBasedOnDate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExportOPDBasedOnDate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pFitnessAlertEmployeeDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pFitnessAlertEmployeeDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetCauseDatasById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetCauseDatasById]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetCauseFlags]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetCauseFlags]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetDisaeseByVisitPurpose]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetDisaeseByVisitPurpose]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetFlag]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetFlag]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetIncidentDropDownsNg_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetIncidentDropDownsNg_new]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetOPDRecords]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetOPDRecords]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetVisitPurposeDataset]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetVisitPurposeDataset]';


GO
PRINT N'Refreshing Procedure [sExamination].[pInjuryFormGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pInjuryFormGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMISDashBoardOpdMovement]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMISDashBoardOpdMovement]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobGetEmployeeTypeCountListHtml]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobGetEmployeeTypeCountListHtml]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobGetVisitPurposeCountList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobGetVisitPurposeCountList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobGetVisitPurposeCountListHtml]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobGetVisitPurposeCountListHtml]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobInjuryReferCount]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobInjuryReferCount]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobInjuryReferEmployeeList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobInjuryReferEmployeeList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobSicknessSummary]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobSicknessSummary]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobSicknessSummaryEmployeeList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobSicknessSummaryEmployeeList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobSicknessSummaryList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobSicknessSummaryList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobSicknessSummaryTypeWise]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobSicknessSummaryTypeWise]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDFitnessHistory]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDFitnessHistory]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDListAllDropdowns]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDListAllDropdowns]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPeriodicExaminationAllDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPeriodicExaminationAllDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPeriodicFreezeAnalyticsGetForMIS]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPeriodicFreezeAnalyticsGetForMIS]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptDiseaseSummary]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptDiseaseSummary]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSearchIncidentsListGetNg_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSearchIncidentsListGetNg_new]';


GO
PRINT N'Refreshing Procedure [sExamination].[pVisitPurposeEmployeeTypeWise]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pVisitPurposeEmployeeTypeWise]';


GO
PRINT N'Refreshing Procedure [sIncident].[pIncidentLogDashboardGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sIncident].[pIncidentLogDashboardGet]';


GO
PRINT N'Refreshing Procedure [sIncident].[pIncidentLogGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sIncident].[pIncidentLogGet]';


GO
PRINT N'Refreshing Procedure [sSecurity].[pSecurityDashboardDetailsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSecurity].[pSecurityDashboardDetailsGet]';


GO
PRINT N'Refreshing Procedure [sCommon].[pCompanyInformationAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pCompanyInformationAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExaminationCSRHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExaminationCSRHistoryListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptShiftwiseCaseList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptShiftwiseCaseList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetOPDEmployeeListSidebar]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetOPDEmployeeListSidebar]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCustomIncidentAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCustomIncidentAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pVisitListGetExaminationEntrysNg]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pVisitListGetExaminationEntrysNg]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptGetFurtherActionPatientList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptGetFurtherActionPatientList]';


GO
PRINT N'Refreshing Procedure [sPermit].[sp_GetPermitVertigoWorkers]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPermit].[sp_GetPermitVertigoWorkers]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptIndividualTestwiseCost]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptIndividualTestwiseCost]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptSickOPDRegisterList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptSickOPDRegisterList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportALLOPDExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportALLOPDExamination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptDiseaseCaseListWithArchive]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptDiseaseCaseListWithArchive]';


GO
PRINT N'Refreshing Procedure [sExamination].[pVisitListGetExaminationEntrysNgArchive]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pVisitListGetExaminationEntrysNgArchive]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCaseTotalList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCaseTotalList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptMedicineConsuptionWithArchive]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptMedicineConsuptionWithArchive]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptIndividualPackagewiseCost]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptIndividualPackagewiseCost]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_getDocumentsOPDIdWise]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getDocumentsOPDIdWise]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptEmployeeTestCost]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptEmployeeTestCost]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptAccidentSummary]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptAccidentSummary]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptAccidentList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptAccidentList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOpdPrescriptionListold]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOpdPrescriptionListold]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOpdPrescriptionListOPD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOpdPrescriptionListOPD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptPatientafteropdhours]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptPatientafteropdhours]';


GO
PRINT N'Refreshing Procedure [sExamination].[pInjuryUpdate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pInjuryUpdate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptContractorWiseCaseDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptContractorWiseCaseDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCaseListWithMedicine]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCaseListWithMedicine]';


GO
PRINT N'Refreshing Procedure [sExamination].[tBindDataEntryTemplateFromOPD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[tBindDataEntryTemplateFromOPD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCaseList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCaseList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptDiseaseCaseList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptDiseaseCaseList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptGetNewPatientList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptGetNewPatientList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOPDMedicalCertificate_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOPDMedicalCertificate_new]';


GO
PRINT N'Refreshing Procedure [sExamination].[pServiceListingResultAllGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pServiceListingResultAllGet]';


GO
PRINT N'Refreshing Procedure [sMro].[pMROFullViewArchiveGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sMro].[pMROFullViewArchiveGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pReferralListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pReferralListGet]';


GO
PRINT N'Refreshing Procedure [sIncident].[pIncidentListingGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sIncident].[pIncidentListingGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportTestAddUpdate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportTestAddUpdate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetEmployeeExaminationVisitDatasNg_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetEmployeeExaminationVisitDatasNg_New]';


GO
PRINT N'Refreshing Procedure [sMro].[pVisitsListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sMro].[pVisitsListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pAccidentLogAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pAccidentLogAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[tGetPermitVertigoOPDDaysLimitCheckInformation]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[tGetPermitVertigoOPDDaysLimitCheckInformation]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptMedicineConsuption]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptMedicineConsuption]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_getInjuriesRegistered_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getInjuriesRegistered_new]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_getInjuriesRegistered_Titan]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getInjuriesRegistered_Titan]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_MeargEmployeeWithExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_MeargEmployeeWithExamination]';


GO
PRINT N'Refreshing Procedure [sAlert].[pEventTemplateGetForFurtherAction]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pEventTemplateGetForFurtherAction]';


GO
PRINT N'Refreshing Procedure [sAlert].[pReportingManagerMailIds]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pReportingManagerMailIds]';


GO
PRINT N'Refreshing Procedure [sCommon].[pHrVertigoEmployeeSearchGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pHrVertigoEmployeeSearchGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindNursingListing]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindNursingListing]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindNursingListingHistory]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindNursingListingHistory]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindNursingListingHistoryNg]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindNursingListingHistoryNg]';


GO
PRINT N'Refreshing Procedure [sExamination].[pBindNursingListingNg]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pBindNursingListingNg]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCancelOPD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCancelOPD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pEmployeeExaminationListingGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pEmployeeExaminationListingGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pEmployeeExaminationListingGetDS]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pEmployeeExaminationListingGetDS]';


GO
PRINT N'Refreshing Procedure [sExamination].[pFitUnFitAlertGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pFitUnFitAlertGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetAllDetailsForOPDLog]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetAllDetailsForOPDLog]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetEmployeeDataOnTrackerSelect]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetEmployeeDataOnTrackerSelect]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetEmployeeDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetEmployeeDetails]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetEmployeeExaminationViewDatasNg_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetEmployeeExaminationViewDatasNg_new]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExaminationGender]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExaminationGender]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetInjuryFormDetailsForEmail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetInjuryFormDetailsForEmail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetOPDDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetOPDDetails]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetOPDDetailsForEmail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetOPDDetailsForEmail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetVertigoOPDDetailsByUniqueIdandUniqueIdType]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetVertigoOPDDetailsByUniqueIdandUniqueIdType]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobGetEmployeeExaminationViewDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobGetEmployeeExaminationViewDatas]';


GO
PRINT N'Refreshing Procedure [sExamination].[pNextPreviousOPDGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pNextPreviousOPDGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOtherStockOPDDetailsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOtherStockOPDDetailsGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPrescriptionIssueReturnDataGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPrescriptionIssueReturnDataGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRegistrationAnalysisGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRegistrationAnalysisGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRegistrationAnalysisGetExport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRegistrationAnalysisGetExport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptFitnessCerti_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptFitnessCerti_New]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptGetBMIEvaluationReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptGetBMIEvaluationReport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptGetPrescriptionEmailParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptGetPrescriptionEmailParameters]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOpdPrescriptionRemainderList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOpdPrescriptionRemainderList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOPDRepetitionCount]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOPDRepetitionCount]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSaveNursingRemark]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSaveNursingRemark]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSaveOPDDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSaveOPDDetails]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSaveOtherName]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSaveOtherName]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSaveOtherStockOPDDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSaveOtherStockOPDDetails]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSearchIncidentsListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSearchIncidentsListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestAnalysisExportDetailGet_OLD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestAnalysisExportDetailGet_OLD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pUpdateGender]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pUpdateGender]';


GO
PRINT N'Refreshing Procedure [sExamination].[pUpdateNursingListing]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pUpdateNursingListing]';


GO
PRINT N'Refreshing Procedure [sHrm].[pCsrBenifitOtherSubGroupMasterAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pCsrBenifitOtherSubGroupMasterAdd]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pPharmacyQueueListingGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pPharmacyQueueListingGet]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pPharmacyQueueListingHistoryGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pPharmacyQueueListingHistoryGet]';


GO
PRINT N'Refreshing Procedure [sProcurement].[pOtherStockIssueGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sProcurement].[pOtherStockIssueGet]';


GO
PRINT N'Refreshing Procedure [sSupport].[pAssignSurveyMasterOPDFeedbackGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pAssignSurveyMasterOPDFeedbackGet]';


GO
PRINT N'Refreshing Procedure [sTool].[pArchieveExaminationDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pArchieveExaminationDatas]';


GO
PRINT N'Refreshing Procedure [sTool].[pEmployeeExaminationDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pEmployeeExaminationDelete]';


GO
PRINT N'Refreshing Procedure [sTool].[pRestoreExaminationDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pRestoreExaminationDatas]';


GO
PRINT N'Refreshing Procedure [sTool].[pSubLocationExaminationDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pSubLocationExaminationDelete]';


GO
PRINT N'Refreshing Procedure [dbo].[VisitplanWiseTypeforMisDataGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[VisitplanWiseTypeforMisDataGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pFitnessLogDashboardGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pFitnessLogDashboardGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pFitnessLogGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pFitnessLogGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pFitnessLogGetByExaminationId]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pFitnessLogGetByExaminationId]';


GO
PRINT N'Refreshing Procedure [sHospitalization].[pSubmitRemark]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHospitalization].[pSubmitRemark]';


GO
PRINT N'Refreshing Procedure [sHospitalization].[pHospitalizationReferDoctor]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHospitalization].[pHospitalizationReferDoctor]';


GO
PRINT N'Refreshing Procedure [sHospitalization].[pIntimationDetailsListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHospitalization].[pIntimationDetailsListGet]';


GO
PRINT N'Refreshing Procedure [sHospitalization].[pIntimationDetailsUpdate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHospitalization].[pIntimationDetailsUpdate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisUpdateResultALLTracker]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisUpdateResultALLTracker]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisUpdateResultALLTrackerBySourceIds]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisUpdateResultALLTrackerBySourceIds]';


GO
PRINT N'Refreshing Procedure [sExamination].[pProviderCountGet_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pProviderCountGet_New]';


GO
PRINT N'Refreshing Procedure [sAppointment].[pGetschedulingAppointmentList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAppointment].[pGetschedulingAppointmentList]';


GO
PRINT N'Refreshing Procedure [sAppointment].[pAppointmentListGetscheduling]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAppointment].[pAppointmentListGetscheduling]';


GO
PRINT N'Refreshing Procedure [sAppointment].[pSendAlertAppointmentListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAppointment].[pSendAlertAppointmentListGet]';


GO
PRINT N'Refreshing Procedure [sAlert].[pGetFollowUpList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pGetFollowUpList]';


GO
PRINT N'Refreshing Procedure [sAppointment].[pGetAppointments]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAppointment].[pGetAppointments]';


GO
PRINT N'Refreshing Procedure [sExamination].[pAppointmentListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pAppointmentListGet]';


GO
PRINT N'Refreshing Procedure [sTm].[pShiftRoasterAddBulk]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTm].[pShiftRoasterAddBulk]';
