
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 [sExamination].[pGetEmployeeExaminationVisitDatasNg_New]...';


GO

ALTER PROCEDURE [sExamination].[pGetEmployeeExaminationVisitDatasNg_New]
@rExaminationId bigint,
@rPageIndex int,
@rflg int,
@rPatientType int,
@rorg int,
@rexamID bigint
as
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
begin
	declare @header varchar(max)='',@res varchar(max)='',@lpaging varchar(max)='',@TotalRecords int,@PageSize int=500
	declare @rParticipantSourceTypeId int,@rEmployeeId bigint,@rOrgId int
	
	select @rParticipantSourceTypeId = @rPatientType,@rEmployeeId = @rExaminationId,@rOrgId = @rorg	
	
	declare @tbltmp table(tid int identity(1,1),exid bigint)
	create table #tbltmparchive (tid int identity(1,1),exid bigint)

	if @rflg = 1
	begin
		insert into @tbltmp
		select ED.Id from sExamination.tExamination ED
		left join sExamination.tDiagnosis D ON ED.Id=D.SourceId
		where ((ED.Id = @rexamID) or (@rexamID = 0))
		and OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
		and ParticipantSourceTypeId = @rParticipantSourceTypeId
		and ED.Id not in (select SourceId from sExamination.tPrescription Where IsDirect = 1)
		order by ED.Id desc
		OPTION (RECOMPILE)

		insert into #tbltmparchive
		select ED.Id from sExamination.tArchieveExamination ED
		left join sExamination.tArchieveDiagnosis D ON ED.Id=D.SourceId
		where ((ED.Id = @rexamID) or (@rexamID = 0))
		and OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
		and ParticipantSourceTypeId = @rParticipantSourceTypeId
		and ED.Id not in (select SourceId from sExamination.tArchievePrescription Where IsDirect = 1)
		order by ED.Id desc
		OPTION (RECOMPILE)
	end
	else
	begin
		insert into @tbltmp
		select ED.Id from sExamination.tExamination ED
		inner join sExamination.tSetupMaster SM on ED.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		left join sExamination.tDiagnosis D ON ED.Id=D.SourceId
		where ((ED.Id = @rexamID) or (@rexamID = 0))
		and ED.OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
		and ParticipantSourceTypeId = @rParticipantSourceTypeId and STM.MainTypeId = 8
		and ED.Id not in (select SourceId from sExamination.tPrescription Where IsDirect = 1)
		order by ED.Id desc
		OPTION (RECOMPILE)

		insert into #tbltmparchive
		select ED.Id from sExamination.tArchieveExamination ED
		inner join sExamination.tSetupMaster SM on ED.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		left join sExamination.tArchieveDiagnosis D ON ED.Id=D.SourceId
		where ((ED.Id = @rexamID) or (@rexamID = 0))
		and ED.OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
		and ParticipantSourceTypeId = @rParticipantSourceTypeId and STM.MainTypeId = 8
		and ED.Id not in (select SourceId from sExamination.tArchievePrescription Where IsDirect = 1)
		order by ED.Id desc
		OPTION (RECOMPILE)
	end
	
	select @TotalRecords = count(*)	from @tbltmp
	select @TotalRecords = @TotalRecords + count(*)	from #tbltmparchive
	select @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@rPageindex,@TotalRecords,@PageSize)

	--select * from @tbltmp
		
	select  isnull(Mt.Title,'') as MtTitle,
	 isnull(SL.Title,'') as SLTitle ,
	 convert(varchar(10),isnull(ED.ExaminationDate,''),103) as EDExamnationDate, 
	 isnull(SM.Title,'') as SMTitle,
    case when STM.MainTypeId = 8 then
	Convert(varchar(1000),isnull(sExamination.fDiseaseGet(ED.Id),'')) else Convert(varchar(1000),isnull(D.DiagnosisRemark,'')) end as DiagnosisRemark,
    case when STM.MainTypeId = 8 then '<b>Remark - </b>' + isnull(VIT.Remark, '') + CHAR(13) + CHAR(10) + '<b>FollowUp Remark - </b>' + isnull(APP.FollowupRemark, '')
	else convert(varchar(1000),isnull(D.RecommendationEnglish,'')) END as RecommendationEnglish, 
    convert(varchar,ED.Id) as EDId,
    convert(varchar,ED.ParticipantSourceId) as ParticipantSourceId,
    convert(varchar,ED.ParticipantSourceTypeId) as ParticipantSourceTypeId,
    case when ED.ParticipantSourceTypeId = 95 then convert(varchar,EP.GenderId)
    when ED.ParticipantSourceTypeId = 1001 then convert(varchar,EFD.GenderId) else
    convert(varchar,CS.GenderId) end  as GenderId,
    case when ED.ParticipantSourceTypeId = 95 then convert(varchar,isnull(datediff(yy,EP.DateOfBirth,getdate()),0))
    when ED.ParticipantSourceTypeId = 1001 then convert(varchar,isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)) else
    convert(varchar,isnull(datediff(yy,CS.DateOfBirth,getdate()),0)) end as Age,
    convert(varchar,STM.MainTypeId) as MainTypeId, convert(varchar,SM.Id) as SetupId,
	ParticipantCode = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN CS.Code END,
	ParticipantName = CASE ED.ParticipantSourceTypeId WHEN 1009 THEN
	(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'')) end)
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END,
	ISNULL(ED.ExaminationNumber,'') AS ExaminationNumber
    from sExamination.tExamination ED
    inner join sIp.tStoreLocationMaster SL on ED.StoreLocationId = SL.Id
    inner join sExamination.tSetupMaster SM on ED.SetupId = SM.Id
	inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
	inner join sExamination.tMainTypeMaster Mt on STM.MainTypeId = Mt.Id
	left join sHrm.tEmployeeMaster EM on EM.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 95
	left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 1001
	left join sHrm.tCSRBenefiterMaster CS on CS.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	LEFT JOIN sExamination.tVital VIT ON VIT.SourceId = ED.Id
	LEFT JOIN sAppointment.tAppointment APP ON APP.ReferSourceId = ED.Id
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= ED.Id
	left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
	left join sExamination.tDiagnosis D ON ED.Id=D.SourceId
	inner join @tbltmp tmp On tmp.exid = ED.Id
	where ((ED.Id = @rexamID) or (@rexamID = 0))
	and ED.OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
	and ParticipantSourceTypeId = @rParticipantSourceTypeId
	and ED.Id not in (select SourceId from sExamination.tPrescription Where IsDirect = 1)
	and tid	between ((@PageSize * (@rPageindex-1)) + 1) and (@PageSize * @rPageindex)
	and ISNULL(ED.IsCancel, 0) = 0
	order by ED.ExaminationDate desc
	OPTION (RECOMPILE)
	
	

	select 
	 isnull(Mt.Title,'') as MtTitle ,
	 isnull(SL.Title,'') as SLTitle,
	 convert(varchar(10),isnull(ED.ExaminationDate,''),103) as EDExamnationDate,
	 isnull(SM.Title,'') as SMTitle,
	 case when STM.MainTypeId = 8 then
	 Convert(varchar(1000),isnull(sExamination.fDiseaseGet(ED.Id),'')) else convert(varchar(1000),isnull(D.DiagnosisRemark,'')) end as DiagnosisRemark ,
	 case when STM.MainTypeId = 8 then '<b>Remark - </b>' + isnull(VIT.Remark, '') + CHAR(13) + CHAR(10) + '<b>FollowUp Remark - </b>' + isnull(APP.FollowupRemark, '')
	 else Convert(varchar(1000),isnull(D.RecommendationEnglish,'')) END as RecommendationEnglish,
	 convert(varchar,ED.Id)as EDId,
     convert(varchar,ED.ParticipantSourceId)as ParticipantSourceId,
     convert(varchar,ED.ParticipantSourceTypeId) as ParticipantSourceTypeId ,
     case when ED.ParticipantSourceTypeId = 95 then convert(varchar,EP.GenderId)
    when ED.ParticipantSourceTypeId = 1001 then convert(varchar,EFD.GenderId) else
    convert(varchar,CS.GenderId) end as GenderId,
    case when ED.ParticipantSourceTypeId = 95 then convert(varchar,isnull(datediff(yy,EP.DateOfBirth,getdate()),0))
    when ED.ParticipantSourceTypeId = 1001 then convert(varchar,isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)) else
    convert(varchar,isnull(datediff(yy,CS.DateOfBirth,getdate()),0)) end as Age,
    convert(varchar,STM.MainTypeId) as STMMainTypeId, convert(varchar,SM.Id) as SetupId,
	ParticipantCode = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN CS.Code END,
	ParticipantName = CASE ED.ParticipantSourceTypeId WHEN 1009 THEN
	(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'')) end)
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END,
	ISNULL(ED.ExaminationNumber,'') AS ExaminationNumber
    from sExamination.tArchieveExamination ED
    inner join sIp.tStoreLocationMaster SL on ED.StoreLocationId = SL.Id
    inner join sExamination.tSetupMaster SM on ED.SetupId = SM.Id
	inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id	
	inner join sExamination.tMainTypeMaster Mt on STM.MainTypeId = Mt.Id
	left join sHrm.tEmployeeMaster EM on EM.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 95
	left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 1001
	left join sHrm.tCSRBenefiterMaster CS on CS.Id = ED.ParticipantSourceId and ED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	LEFT JOIN sExamination.tVital VIT ON VIT.SourceId = ED.Id
	LEFT JOIN sAppointment.tAppointment APP ON APP.ReferSourceId = ED.Id
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= ED.Id
	left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
	left join sExamination.tArchieveDiagnosis D ON ED.Id=D.SourceId,#tbltmparchive 
	where exid = ED.Id and ((ED.Id = @rexamID) or (@rexamID = 0))
	and ED.OrgId = @rOrgId and ParticipantSourceId  = @rEmployeeId
	and ParticipantSourceTypeId = @rParticipantSourceTypeId
	and ED.Id not in (select SourceId from sExamination.tArchievePrescription Where IsDirect = 1)
	and tid	between ((@PageSize * (@rPageindex-1)) + 1) and (@PageSize * @rPageindex)
	order by ED.ExaminationDate desc
	OPTION (RECOMPILE)
	
	select @res = isnull(@res,'')
	select @res as result,@lpaging as paging
	OPTION (RECOMPILE)
	Drop Table #tbltmparchive
	SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off
end
GO
PRINT N'Altering Procedure [sExamination].[pSaveEmployeePrescription]...';


GO

ALTER PROCEDURE [sExamination].[pSaveEmployeePrescription]
@rStrXML varchar(max)
as
begin
	declare @lxmlStr xml
	set @lxmlStr = CAST(@rStrXML AS xml)
	
	declare @tblPrescription table(tid int identity(1,1),p_StockItemId int,p_DrugFrequencyId int,p_DrugQuantity varchar(100),
	p_Dosage varchar(100),p_DrugInstruction varchar(200),p_DrugScheduleId int,p_StockRemark varchar(max),
	p_DrugFrequencyPattern varchar(200),p_Duration varchar(100),p_Total varchar(100),
	p_PatientSourceTypeId smallint,p_PatientSourceId bigint)
	insert into @tblPrescription
	select T.c.value('@StockItemId','int') as StockItemId,
	T.c.value('@DrugFrequencyId','int') as DrugFrequencyId,
	T.c.value('@DrugQuantity','varchar(100)') as DrugQuantity,
	T.c.value('@Dosage','varchar(100)') as Dosage,
	T.c.value('@DrugInstruction','varchar(200)') as DrugInstruction,
	T.c.value('@DrugScheduleId','int') as DrugScheduleId,
	T.c.value('@StockRemark','varchar(max)') as StockItemId,
	T.c.value('@DrugFrequencyPattern','varchar(200)') as DrugFrequencyPattern,
	T.c.value('@Duration','varchar(100)') as Duration,
	T.c.value('@Total','varchar(100)') as Total,
	T.c.value('@PatientSourceTypeId','smallint') as PatientSourceTypeId,
	T.c.value('@PatientSourceId','bigint') as PatientSourceId
	from @lxmlStr.nodes('/EmployeePrescription/Prescription')T(c)
	
	delete w from sExamination.tEmployeePrescription w
	inner join @tblPrescription p on w.PatientSourceTypeId = p.p_PatientSourceTypeId
	and w.PatientSourceId = p.p_PatientSourceId
	
	insert into sExamination.tEmployeePrescription
	(
		PatientSourceTypeId,PatientSourceId,StockItemId,DrugInstruction,Remark,
		Dosage,Duration,DurgDosageQty,DrugDosageFrequencyId,
		DrugDosageScheduleId,DrugFrequencyPattern
	)
	select p_PatientSourceTypeId,p_PatientSourceId,p_StockItemId,p_DrugInstruction,
	left(p_StockRemark,400),p_Dosage,p_Duration,p_DrugQuantity,p_DrugFrequencyId,
	p_DrugScheduleId,p_DrugFrequencyPattern from @tblPrescription
	
	select 1 as res
end
GO
PRINT N'Altering Procedure [sExamination].[pEmployeePrescriptionDetailGet]...';


GO

ALTER PROCEDURE [sExamination].[pEmployeePrescriptionDetailGet]
@rPatientId bigint,
@rPatientSourceTypeId smallint
as
begin
	SELECT AutoId as Id,
	StockItemId,
	DrugInstruction AS InstructionName,
	SIM.Title AS StockItem,
	EPD.Remark,
	Dosage,
	Duration,
	ceiling(((Dosage * Duration * DF.DurgQuantity) / case when SIM.DrawSize = 0 then 1 else isnull(SIM.DrawSize,1) end)) * case when SIM.DrawSize = 0 then 1 else isnull(SIM.DrawSize,1) end AS Total,
	IsNotInStore,
	IsAllowDirectIssue AS IsDirectIssue,
	SIM.ItemSubGroupId AS SubGroupId,
	SIM.Reminder,
	sExamination.fMedicineTypeGet(SIM.ItemSubGroupId) as MedicineType,
	EPD.DurgDosageQty,
	EPD.DrugDosageFrequencyId,
	EPD.DrugDosageScheduleId,
	DF.DurgQuantity,
	DQ.Title,
	DF.Title as FreqText,
	DS.Title as SchedText,
	'' as ConsumeUOM,
	SIM.IsBatchWiseTracking, UOM.Title as UOM,
	ISNULL(EPD.DrugFrequencyPattern, '') as DrugFrequencyPattern
	FROM sExamination.tEmployeePrescription EPD	
	INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = EPD.stockItemId
	INNER JOIN sFinanceCommon.tStockUomMaster UOM ON UOM.Id = SIM.IssueStockUomId
	INNER JOIN sIp.tDrugDosageFrequencyMaster DF on EPD.DrugDosageFrequencyId = DF.Id
	INNER JOIN sIp.tDrugScheduleMaster DS on EPD.DrugDosageScheduleId = DS.Id
	INNER JOIN sIp.tDrugDosageQtyMaster DQ on EPD.DurgDosageQty = DQ.DosageQty
	where EPD.PatientSourceTypeId = @rPatientSourceTypeId and PatientSourceId = @rPatientId
end
GO
PRINT N'Altering Procedure [sExamination].[pPeriodicExaminationFreezeDataListGetforSurvey]...';


GO
ALTER PROCEDURE [sExamination].[pPeriodicExaminationFreezeDataListGetforSurvey]
(
    @rSetupId INT = 0,
    @rOrgId INT = 0,
    @rDepartmentId NVARCHAR(MAX) = '',
    @rCode NVARCHAR(MAX) = '',
    @rName NVARCHAR(MAX) = '',
    @rDesignationId INT = 0,
    @rStatusId INT = 0,
    @rLocationId INT = 0,
    @rEmployeeStoreLocationId INT = 0,
    @rTargetGroupId INT = 0,
    @rDurationindays INT = 0,
    @rVerticalId INT = 0,
    @rSectorId INT = 0,
    @rCompanyId INT = 0,
    @GlobalSearch NVARCHAR(MAX) = ''
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @rAgeTo INT,
            @rAgeFrom INT;

    SELECT 
        @rAgeTo = AgeTo,
        @rAgeFrom = AgeFrom
    FROM sExamination.tSetupMaster 
    WHERE Id = @rSetupId;

    SELECT *
    FROM
    (
        SELECT DISTINCT
            SE.EmployeeId,
            EM.Code AS EmployeeCode,
            ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName
        FROM sExamination.tSetupEmployee SE
        INNER JOIN sExamination.tSetupMaster SEM ON SEM.Id = SE.SetupId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = SE.EmployeeId
        LEFT JOIN sHrm.tEmployeeJobDetail JD ON JD.EmployeeId = SE.EmployeeId
        LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = SE.EmployeeId
        LEFT JOIN sCommon.tOrganizationDepartmentMaster DM ON DM.Id = JD.OrganizationDepartmentId
        LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = JD.EmployeeDesignationId
        LEFT JOIN sExamination.tExamination E 
            ON E.ParticipantSourceId = SE.EmployeeId 
            AND E.SetupId = SE.SetupId
        LEFT JOIN sExamination.tStatusMaster SM ON SM.Id = E.StatusId
        LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = SE.EmployeeId
        LEFT JOIN sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = JD.EmployeeCompanyId
        LEFT JOIN sHrm.tCompanyGroupMaster CGM ON CGM.Id = ECM.CompanyGroupId
        LEFT JOIN sHrm.tVerticalMaster VM ON VM.Id = CGM.VerticalId
        LEFT JOIN sHrm.tSectorMaster SCM ON SCM.Id = VM.SectorId
        LEFT JOIN sHrm.tEmployeeLegalEntitymaster ELEM ON ELEM.Id = JD.LegalEntityId

        LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = SE.CentralDoctorId
        LEFT JOIN sHrm.tEmployeeMaster EM2 ON EM2.Id = SE.SiteDoctorId
        LEFT JOIN sHrm.tEmployeeMaster EM3 ON EM3.Id = SE.CentralSpocId
        LEFT JOIN sHrm.tEmployeeMaster EM4 ON EM4.Id = SE.SiteSpocId

        WHERE   
            SE.SetupId = @rSetupId  
            AND EM.OrgId = @rOrgId

            AND (
                EXISTS (
                    SELECT 1
                    FROM sCommon.fnsplit(@rCode, ',') s
                    WHERE 
                        (CHARINDEX(',', @rCode) = 0 AND EM.Code LIKE s.item + '%')
                        OR (CHARINDEX(',', @rCode) > 0 AND EM.Code = s.item)
                )
                OR ISNULL(@rCode,'') = '' 
                OR ISNULL(@rCode,'') = '*'
            )

            AND (
                EXISTS (
                    SELECT 1
                    FROM sCommon.fnsplit(@rName, ',') s
                    WHERE 
                        (CHARINDEX(',', @rName) = 0 AND EM.FirstName LIKE s.item + '%')
                        OR (CHARINDEX(',', @rName) > 0 AND EM.FirstName = s.item)
                )
                OR ISNULL(@rName,'') = '' 
                OR ISNULL(@rName,'') = '*'
            )

            AND (ISNULL(JD.OrganizationDepartmentId,0) IN 
                (SELECT item FROM sCommon.fnsplit(@rDepartmentId,',')) 
                OR ISNULL(@rDepartmentId,'')='')

           -- AND DATEDIFF(YY,EPD.DateOfBirth,sCommon.fGetDate()) BETWEEN @rAgeFrom AND @rAgeTo

            AND (JD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)
            AND (SE.TargetGroupId = @rTargetGroupId OR @rTargetGroupId = 0)

            AND (
                (ISNULL(E.StatusId,0)=0 AND @rStatusId=101)
                OR (E.StatusId=@rStatusId AND @rStatusId<>0)
                OR (@rStatusId=0)
            )

            AND (
                (CASE 
                    WHEN SE.PlannedExaminationDate IS NULL 
                        THEN DATEDIFF(DD,[sExamination].[fGetLatExaminationDate](SE.EmployeeId),sCommon.fGetDate())
                    ELSE DATEDIFF(DD,sCommon.fGetDate(),SE.PlannedExaminationDate)
                END = @rDurationindays)
                OR @rDurationindays = 0
            )

            AND ISNULL(EM.IsObsolete,0)=0
            AND (VM.Id=@rVerticalId OR @rVerticalId=0)
            AND (SCM.Id=@rSectorId OR @rSectorId=0)
            AND (ECM.Id=@rCompanyId OR @rCompanyId=0)

    ) t
    WHERE 
        ISNULL(@GlobalSearch,'') = ''
        OR t.EmployeeCode LIKE '%' + @GlobalSearch + '%'
        OR t.EmployeeName LIKE '%' + @GlobalSearch + '%'
END
GO
PRINT N'Altering Procedure [sExamination].[pRptOHCVisitSummary]...';


GO
ALTER   PROCEDURE [sExamination].[pRptOHCVisitSummary]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int,
	@rStoreLocationId int,
	@rParticipantTypeId int,
	@rCaseCauseId int,
	@rLocationId int,
	@rFunctionId int,
	@rDepartmentGroupId int,
	@rDepartmentId int,
	@rGradeId int,
	@rDesignationId int,
	@rJobTitleId int,
	@rEmployeeTypeId int,
	@rCompanyId int,
	@rContractorId int,
	@rGenderId smallint,
	@rStatusId int,
	@rAgeFrom int=0,
	@rAgeTo int=100,
	@rFromDate datetime = null,
	@rToDate datetime = null,
	@rOrgId int,
	@rEmployeeCode nvarchar(50)='',
	@rEmployeeTypeGroupId int=0,
	@rEmployeeSubTypeId int=0,
	@rEmployeeGroupId int=0,
	@rOtherTypeId int=0,
	@rVisitPurposeIds varchar(max)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	SELECT distinct @rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,
	@rReportId AS ReportId,
EAED.Id as ExaminationId,
	convert(varchar(10),EAED.ExaminationDate,103) as VisitDate,
	
	EmployeeCode = CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
	EmployeeName = CASE EAED.ParticipantSourceTypeId WHEN 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')
	WHEN 1001 THEN EFD.Name WHEN 1009 THEN CASE WHEN isnull(O.OtherName,'') <> '' THEN O.OtherName ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END,
	isnull(ODM.Title,'') AS DepartmentName,
	ISNULL(EDM.Title,'') AS Designation,
	ISNULL(ELE.Title,'') AS SectionWorkStation,
	COM.Remark as ChiefComplaint,
	
ISNULL(CAST(CAST(Temperature AS INT) AS VARCHAR(10)), '0') + ' / ' +
ISNULL(CAST(CAST(Pulse AS INT) AS VARCHAR(10)), '0') + ' / ' +
'(' + ISNULL(CAST(CAST(BloodPressureSystolic AS INT) AS VARCHAR(10)), '0') + ' / ' +
ISNULL(CAST(CAST(BloodPressureDiastolic AS INT) AS VARCHAR(10)), '0') + ')' + ' / ' +
ISNULL(CAST(CAST(V.SPo2 AS INT) AS VARCHAR(10)), '0') + ' / ' +
'0' AS Vital,

	V.Remark as ClinicalFindings,
	FAM.Code as FurtherActionCode,
	isnull(O.FurtherActionRemark,'') as FurtherActionRemark,
	(CASE WHEN CM.IsCustomLog = 1 THEN '' ELSE isnull(convert(varchar(10),SA.AppointmentDate,103),'') END) as FollowupDate, 
	isnull(SA.FollowupRemark,'') as FollowupRemark,

	case when EM5.StatusId <> 10 then     
 EM5.FirstName + ' ' + isnull(EM5.LastName,'')     
     
 else '' end as DoctorName, 
 
	EAED.CreatedDateTime,
	ParticipantType = CASE EAED.ParticipantSourceTypeId WHEN 95 THEN isnull(ETM.Title,'') WHEN 1001 THEN 'Dep'	WHEN 1009 THEN isnull(BTM.Title,'') END,
	case when EAED.ParticipantSourceTypeId = 1009 then    
 case when BM.DateOfBirth = '1900-01-01' then 0 else datediff(yy,BM.DateOfBirth,getdate()) end    
 when EAED.ParticipantSourceTypeId = 1001 then    
 case when EFD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EFD.DateOfBirth,getdate()) end else    
 case when EPD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EPD.DateOfBirth,getdate()) end end AS AGE,
	Gender = CASE EAED.ParticipantSourceTypeId
	WHEN 95 THEN GM1.Title
	WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
	WHEN 1009 THEN CASE WHEN isnull(O.GenderId,0) = 0 THEN GM2.Title ELSE (select Title from sCommon.tGenderMaster where Id = O.GenderId) END END,
	isnull(CM.Id,0) as CauseId,
	isnull(CM.Title,'') AS Cause,
	CL.Title+ ' '+'('+R.ContactPerson+')' as ClinicalSummary,
	[sExamination].[fn_GetEmployeePastHistory_String](@rOrgId,EAED.ParticipantSourceId,EAED.ParticipantSourceTypeId) AS RelevantHistory,

	[sExamination].[fExistingDiseaseGet](EAED.Id) AS ProvisionalDiagnosis,	
	 [sExamination].fn_GetPrescriptionDetails(EAED.Id,@rOrgId) as TreatmentGiven,
	D.DoctorSignature AS DoctorSignature
	
	FROM sExamination.tExamination EAED
	INNER JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserID
	INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = EAED.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on EAED.StoreLocationId = SLM.Id
	LEFT JOIN sCwb.tDoctorMaster D on EAED.DoctorEmployeeId = D.EmployeeId
	--LEFT JOIN sExamination.vExtPrescription P on EAED.Id = P.SourceId	
	--LEFT JOIN sExamination.vExtPrescriptionDetail PD on P.Id = PD.PrescriptionId AND (PD.IsObsolete = 0)
	--LEFT JOIN sIp.tDrugDosageFrequencyMaster DFM on DFM.id=PD.DrugDosageFrequencyId
	--LEFT JOIN sIp.tDrugScheduleMaster DSM on DSM.id=PD.DrugDosageScheduleId
	--LEFT JOIN sIp.tStockItemMaster SIM on PD.DrugStockItemId = SIM.Id
	
	LEFT JOIN sHrm.tEmployeeMaster EM on EAED.ParticipantSourceId = EM.Id and EAED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EAED.ParticipantSourceId = EFD.Id and EAED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id	
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on EAED.ParticipantSourceId = BM.Id and EAED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CsrBenefiterTypeId = BTM.Id
	LEFT JOIN sHrm.tEmployeeJobDetail EJD on EM.Id = EJD.EmployeeId
	LEFT JOIN sHrm.tEmployeeJobDetail EJD2 on EM2.Id = EJD2.EmployeeId
	LEFT JOIN sHrm.tEmployeeLegalEntitymaster ELE ON ELE.ID= EJD.LegalEntityId
	LEFT JOIN sHrm.tEmployeeDesignationMaster EDM on EDM.Id = EJD.EmployeeDesignationId
	LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM on EAED.OrganizationDepartmentId = ODM.Id
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON ODM.DepartmentGroupId = DGM.Id	
	LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id
	LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
	LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id=EJD.ContractorId
	LEFT JOIN sProcurement.tVendorMaster VM2 ON VM.Id=EJD2.ContractorId
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
	
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = EAED.CauseId	
	LEFT JOIN sExamination.tReferral R ON R.SourceId=EAED.Id
	LEFT JOIN sCommon.tClinicMaster CL ON CL.Id=R.ReferToClinicId	
	LEFT JOIN sExamination.tOPD O ON O.ExaminationId = EAED.Id
	 left join sExamination.tVital V on EAED.Id = V.SourceId 
	 left join sExamination.tComplaint COM on COM.SourceId = EAED.Id 
	 left join sSafety.tFurtherActionMaster FAM ON FAM.Id = O.FurtherActionId
	 left join sAppointment.tAppointment SA on EAED.Id = SA.ReferSourceId  
	 left join sHrm.tEmployeeMaster EM5 on EM5.Id = EAED.DoctorEmployeeId 
	 left join sExamination.tAccidentLog A on EAED.Id = A.ExaminationId 

	WHERE STM.MainTypeId = 8 AND isnull(EAED.IsCancel,0) = 0
	AND (EAED.StoreLocationId = @rStoreLocationId)
	AND 
	(
		(EM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EM2.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(BM.Code = @rEmployeeCode AND EAED.ParticipantSourceTypeId = 1009)
		OR
		@rEmployeeCode = ''
	)
	AND (FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND (EAED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (EAED.GradeId=@rGradeId OR @rGradeId=0)
	AND (EAED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	 
	AND
	(
		(EJD.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeJobTitleId = @rJobTitleId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rJobTitleId = 0
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.EmployeeTypeId = @rEmployeeTypeId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(			
		(EJD.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EJD2.ContractorId = @rContractorId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(0 = 0 AND EAED.ParticipantSourceTypeId = 1009)
		OR @rContractorId=0
	)
	AND (EAED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND
	(
		(EPD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 95)
		OR
		(EFD.GenderId = @rGenderId AND EAED.ParticipantSourceTypeId = 1001)
		OR
		((BM.GenderId = @rGenderId or O.GenderId = @rGenderId) AND EAED.ParticipantSourceTypeId = 1009)
		OR @rGenderId=0
	)
	AND (EAED.EmployeeStatusId=@rStatusId OR @rStatusId=0)
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND EAED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeTo,0)=0
	)
	AND
	(
		(isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 95)
		OR
		(isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1001)
		OR
		(isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND EAED.ParticipantSourceTypeId = 1009)			
		OR ISNULL(@rAgeFrom,0)=0
	)
	AND ((EAED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EAED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))
	AND (SLM.LocationId = @rLocationId) 
	AND (EAED.OrgId =  @rOrgId)
	AND (EAED.CauseId=@rCaseCauseId or @rCaseCauseId=0)
	AND (EAED.ParticipantSourceTypeId=@rParticipantTypeId or @rParticipantTypeId=0)	
	AND (ETM.EmployeeTypeGroupId=@rEmployeeTypeGroupId or @rEmployeeTypeGroupId=0)
	AND (EJD.EmployeeSubTypeId=@rEmployeeSubTypeId or @rEmployeeSubTypeId=0)
	AND (EJD.EmployeeGroupId=@rEmployeeGroupId or @rEmployeeGroupId=0)
	AND (BM.CSRBenefiterTypeId=@rOtherTypeId or @rOtherTypeId=0)	
	AND (ISNULL(EAED.CauseId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rVisitPurposeIds,''),','))OR ISNULL(@rVisitPurposeIds,'')='')
	OPTION(RECOMPILE)
END
GO
PRINT N'Altering Procedure [sExamination].[pRptEmployeewiseAllTestValue]...';


GO
ALTER PROCEDURE [sExamination].[pRptEmployeewiseAllTestValue]
@rStoreLocationId int,
@rExaminationTypeId int,
@rRoundId int,
@rFunctionId int,
@rDepartmentGroupId int,
@rDepartmentId int,
@rGradeId int,
@rDesignationId int,
@rJobTitleId int,
@rEmployeeTypeId int,
@rCompanyId int,
@rContractorId int,
@rGenderId smallint,
@rStatusId smallint,
@rAgeFrom int=null,
@rAgeTo int=null,
@rFromDate datetime = '1950-01-01',
@rToDate datetime = '2050-01-01',
@rOrgId int,
@rEmployeeCode nvarchar(50)='',
@rLocationId int,
@rEmployeeTypeGroupId int=0,
@rEmployeeSubTypeId int=0,
@rEmployeeGroupId int=0,
@rSectorId int = 0, 
@rVerticalId int = 0, 
@rCompanyGroupId int = 0, 
@rMedicalAgencyId int = 0,
@rTargetGroupId int =0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	CREATE TABLE #tmpCondition
	(
		Id INT IDENTITY(1, 1),EmployeeId bigint,Code nvarchar(200),EmployeeName nvarchar(200),
		ExaminationId bigint
	)
	INSERT INTO #tmpCondition 
	SELECT EM.Id,EM.Code,EM.FirstName + ' ' + EM.LastName,E.Id
	FROM sHrm.tEmployeeMaster EM INNER JOIN shrm.tEmployeeJobDetail EJD
	ON  EJD.EmployeeId=EM.Id
	INNER JOIN sCommon.tOrganizationDepartmentMaster DM
	ON DM.Id=EJD.OrganizationDepartmentId 
	INNER JOIN sCommon.tDepartmentGroupMaster DGM
	ON DM.DepartmentGroupId = DGM.Id
	INNER JOIN sCommon.tFunctionMaster FM
	ON DGM.FunctionId= FM.Id
	INNER JOIN sHrm.tEmployeePersonalDetail EPD
	ON EPD.EmployeeId=EM.Id
	LEFT JOIN sHrm.tEmployeeCommunications EC
	ON EC.EmployeeId=EM.Id
	LEFT JOIN sExamination.tExamination E
	ON E.ParticipantSourceId = EM.Id AND E.SetupId=@rRoundId
	LEFT JOIN sHrm.tEmployeeDesignationMaster EDM
	ON EDM.Id = EJD.EmployeeDesignationId AND (EDM.IsObsolete=0)
	LEFT JOIN sHrm.tGradeMaster GDM
	ON GDM.Id=EJD.GradeId AND (GDM.IsObsolete=0)
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM  ON EJD.EmployeeTypeId=ETM.Id
	left join sHrm.tEmployeeCompanyMaster CM on EJD.EmployeeCompanyId = CM.Id
	left join sHrm.tCompanyGroupMaster CG on CM.CompanyGroupId = CG.Id
	left join sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id 
	
	WHERE (E.OrgId=@rOrgId OR @rOrgId=0)
	AND(FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND(E.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (E.StoreLocationId= @rStoreLocationId OR @rStoreLocationId=0)
	AND(EJD.GradeId=@rGradeId OR @rGradeId=0)
	AND(EDM.Id = @rDesignationId OR @rDesignationId = 0)
	AND(EJD.EmployeeJobTitleId = @rJobTitleId OR @rJobTitleId = 0)
	AND(EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND(EJD.ContractorId=@rContractorId OR @rContractorId=0)
	AND(EJD.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND(EPD.GenderId=@rGenderId OR @rGenderId=0)
	AND(E.StatusId=@rStatusId OR @rStatusId=0)
	AND ((DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	AND ((DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate < (@rToDate + 1)) OR (ISNULL(@rToDate,'') = ''))
	AND ((EM.Code = @rEmployeeCode ) OR (@rEmployeeCode = ''))
	--AND ((EJD.EmployeeLocationId = @rLocationId))
	AND(ETM.EmployeeTypeGroupId=@rEmployeeTypeGroupId or @rEmployeeTypeGroupId=0)
	AND(EJD.EmployeeSubTypeId=@rEmployeeSubTypeId or @rEmployeeSubTypeId=0)
	AND(EJD.EmployeeGroupId=@rEmployeeGroupId or @rEmployeeGroupId=0)
	and (CM.CompanyGroupId = @rCompanyGroupId or @rCompanyGroupId = 0)
	and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)
	and (VM.SectorId = @rSectorId or @rSectorId = 0)
	and (E.MedicalAgencyId = @rMedicalAgencyId or @rMedicalAgencyId = 0) 
	and (E.TargetGroupId = @rTargetGroupId or @rTargetGroupId = 0) 
	
	CREATE TABLE #tmpServiceValueNumeric
	(
		Id INT IDENTITY (1, 1),TestRequestId bigint,TestParameterId int,
		TestParameter nvarchar(250),SourceId bigint,ServiceValue nvarchar(250)
	)
	INSERT INTO #tmpServiceValueNumeric 
	SELECT TR.Id,TPM.Id,TPM.Title,TR.SourceId,ServiceValue
	FROM sExamination.tTestRequest TR
	INNER JOIN sExamination.tTestRequestDetail TRD
	ON TRD.TestRequestId = TR.Id
	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 AND TPM.ParameterValueTypeId = 1 and isnumeric(ServiceValue)=1
	
	CREATE TABLE #tmpServiceValueList
	(
		Id INT IDENTITY (1, 1),TestRequestId bigint,TestParameterId int,
		TestParameter nvarchar(250),SourceId bigint,ServiceValue nvarchar(250)
	) 
	INSERT INTO #tmpServiceValueList 
	SELECT TR.Id,TPM.Id,TPM.Title,TR.SourceId,ServiceValue
	FROM sExamination.tTestRequest TR
	INNER JOIN sExamination.tTestRequestDetail TRD
	ON TRD.TestRequestId = TR.Id
	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 AND TPM.ParameterValueTypeId != 1 

	DECLARE @cols AS NVARCHAR(MAX),@cols1 AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX)
	Declare @lSetup nvarchar(50)
	Set @lSetup = (Select Title From sExamination.tSetupMaster where Id = @rRoundId)
	
	select @cols = STUFF((SELECT ',' + QUOTENAME(TestParameter)
	from #tmpServiceValueNumeric group by TestParameter order by TestParameter 
	FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,1,'')
	
	select @cols1 = STUFF((SELECT ',' + QUOTENAME(TPM.Title)
	from sExamination.tTestRequest TR
	INNER JOIN sExamination.tTestRequestDetail TRD
	ON TRD.TestRequestId = TR.Id 
	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 AND TPM.ParameterValueTypeId != 1 
	group by TPM.Title order by TPM.Title
	FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
	
	IF(@cols is not null AND @cols1 is not null)
	BEGIN      
		set @query = 'SELECT convert(varchar, TB1.ExaminationDate,103) AS ExaminationDate,TB1.Round,TB1.Code,TB1.EmployeeName,
		TB1.Assigned,' + @cols +', ' + @cols1 +' FROM (SELECT p.ExaminationId, convert(varchar, p.ExaminationDate, 103) AS ExaminationDate,
		p.EmployeeId,p.Round,p.Code,p.EmployeeName,p.Assigned,' + @cols + ' from
		(
			SELECT E.Id as ExaminationId,E.ExaminationDate,TC.EmployeeId,TC.Code,TC.EmployeeName,TestParameter,ServiceValue,
			('''+ CAST(@lSetup AS NVARCHAR(30))+''') AS Round,(CASE WHEN TS.TestRequestId is null THEN '+ '''No'''+ 'ELSE '+ '''Yes'''+ 'END)
			AS Assigned from #tmpCondition  TC LEFT JOIN #tmpServiceValueNumeric TS ON TS.SourceId = TC.ExaminationId
			LEFT JOIN sExamination.tExamination E ON TC.EmployeeId = E.ParticipantSourceId  AND E.ParticipantSourceTypeId = 95
			AND (E.SetupId=' +CAST(@rRoundId AS NVARCHAR(30))+')  AND E.Id = TC.ExaminationId
		) x
		pivot 
		(
			max(ServiceValue) for TestParameter in (' + @cols + ')) p
		) TB1 
		FULL JOIN
		(
			SELECT convert(varchar, p.ExaminationDate, 103) AS ExaminationDate,p.EmployeeId,p.ExaminationId,p.Round,p.Code,p.EmployeeName,
			p.Assigned,' + @cols1 + ' from 
			(
				(
					SELECT E.Id as ExaminationId,E.ExaminationDate,TC.EmployeeId,TC.Code,TC.EmployeeName,TestParameter,
					ServiceValue,('''+ CAST(@lSetup AS NVARCHAR(30))+''') AS Round,
					(CASE WHEN TS.TestRequestId is null THEN '+ '''No '''+ 'ELSE '+ '''Yes'''+ 'END) AS Assigned
					FROM #tmpCondition  TC LEFT JOIN #tmpServiceValueList TS ON TS.SourceId = TC.ExaminationId 
					LEFT JOIN  sExamination.tExamination E ON TC.EmployeeId = E.ParticipantSourceId
					AND E.ParticipantSourceTypeId = 95 AND (E.SetupId=' +CAST(@rRoundId AS NVARCHAR(30))+')
					AND E.Id = TC.ExaminationId
				)
			) x
			pivot 
			( max(ServiceValue) for TestParameter in (' + @cols1 + ')) p
		) TB2 ON TB2.EmployeeId =  TB1.EmployeeId AND TB1.ExaminationId = TB2.ExaminationId '
	END
	ELSE IF (@cols is null)
	BEGIN
		set @query = 'SELECT convert(varchar, p.ExaminationDate, 103) AS ExaminationDate,p.Round,p.Code,p.EmployeeName,p.Assigned,' + @cols1 + '
		from 
		(
			(
				SELECT E.ExaminationDate,TC.EmployeeId,TC.Code,TC.EmployeeName,TestParameter,
				ServiceValue,('''+ CAST(@lSetup AS NVARCHAR(30))+''') AS Round,
				(CASE WHEN TS.TestRequestId is null THEN '+ '''No '''+ 'ELSE '+ '''Yes'''+ 'END) AS Assigned  FROM #tmpCondition  TC 
				LEFT JOIN #tmpServiceValueList TS ON TS.SourceId = TC.ExaminationId
				INNER JOIN  sExamination.tExamination E ON TC.EmployeeId = E.ParticipantSourceId 
				AND (E.SetupId=' +CAST(@rRoundId AS NVARCHAR(30))+')   AND E.Id = TC.ExaminationId
			)
		) x
		pivot 
		(
		max(ServiceValue) for TestParameter in (' + @cols1 + ')
		) p'
	END
	ELSE
	set @query = 'SELECT convert(varchar, p.ExaminationDate, 103) AS ExaminationDate,p.Round,p.Code,p.EmployeeName,p.Assigned,' + @cols + '
	from 
	(
	SELECT E.ExaminationDate,TC.EmployeeId,TC.Code,TC.EmployeeName,TestParameter,ServiceValue,
	('''+ CAST(@lSetup AS NVARCHAR(30))+''') AS Round,
	(CASE WHEN TS.TestRequestId is null THEN '+ '''No '''+ 'ELSE '+ '''Yes'''+ 'END) AS Assigned
	from #tmpCondition  TC LEFT JOIN #tmpServiceValueNumeric TS ON TS.SourceId = TC.ExaminationId
	LEFT JOIN  sExamination.tExaminaion E ON TC.EmployeeId = E.ParticipantSourceId 
	AND (E.SetupId=' +CAST(@rRoundId AS NVARCHAR(30))+') AND E.Id = TC.ExaminationId
	) x
	pivot 
	(
	max(ServiceValue) for TestParameter in (' + @cols + ')
	)p'
	execute(@query) 
	
	DROP TABLE #tmpServiceValueNumeric
	DROP TABLE #tmpServiceValueList
END
GO
PRINT N'Altering Procedure [sExamination].[pDiagnosisPartialValueAdd]...';


GO

ALTER PROCEDURE [sExamination].[pDiagnosisPartialValueAdd]
@rSetupId bigint,
@rSourceId bigint = null,
@rFromDate Datetime = null,
@rToDate Datetime = null
WITH EXECUTE AS CALLER
AS
BEGIN

	SET @rFromDate = ISNULL (@rFromDate, '2000-01-01 00:00:00')
	SET @rToDate = ISNULL (@rToDate, '2090-02-28 00:00:00')


	DECLARE @lExaminationId bigint,
	@lEarnedPoINTs int,
	@lTotalPoINTs int,
	@lParameterId int,
	@FieldName nvarchar(50),
	@lFROMValue nvarchar(50),
	@lToValue nvarchar(50),
	@lPoINTs int,
	@lCount int,
	@lParameterTypeId int,
	@lQueryString1 nvarchar(max),
	@lTestParameterId int,
	@lPercentage decimal(6, 2),
	@lGenderId tinyint,
	@lCountIndicator int,
	@lIndicatorExaminationId bigint,
	@roundgroupid int,
	@rOrgId int,
	@lDiagnosisRemark nvarchar(250)
	
	select @rSourceId = case when @rSourceId is null then 0 else @rSourceId end
	--added by MS for Roundgroup
	select @roundgroupid = SetupGroupId,@rOrgId=OrgId from sExamination.tsetupmaster where id = @rSetupId

	
	CREATE TABLE #tempExamination
	(Id BigInt,
	ExaminationDate date,
	OrgId int,
	SetupId int,
	ParticipantSourceId bigint,
	ParticipantSourceTypeId int,
	GradeId int
	)

	INSERT INTO #tempExamination
	SELECT DISTINCT E.Id, E.ExaminationDate, OrgId, SetupId, E.ParticipantSourceId, E.ParticipantSourceTypeId, E.GradeId FROM sExamination.tExamination E
	LEFT JOIN sExamination.tHealthIndex HI ON  
	E.Id = HI.ExaminationId
	WHERE HI.ID IS NULL 
	AND E.SetupId = @rSetupId AND E.OrgId = @rOrgId
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	
	
	UPDATE DS SET DS.TotalHealthPoints = 0,DS.EarnedHealthPoints = 0,
	DS.HealthIndicatorId = 0,DS.AgeGroupId = 0,DS.HealthIndex = 0
	FROM sExamination.tDiagnosis AS DS
	INNER JOIN #tempExamination AS EX ON EX.Id = DS.SourceId
	WHERE EX.SetupId = @rSetupId and (EX.Id = @rSourceId or isnull(@rSourceId,0) = 0)
	AND ((EX.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EX.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND EX.OrgId=@rOrgId

	DELETE HI FROM sExamination.tDiagnosisPartial AS HI
	INNER JOIN #tempExamination AS EX ON Ex.Id = HI.ExaminationId
	WHERE ex.SetupId = @rSetupId and (EX.Id = @rSourceId or isnull(@rSourceId,0) = 0)
	AND ((EX.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EX.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND EX.OrgId=@rOrgId

	DELETE HI FROM sExamination.tHealthIndex AS HI
	INNER JOIN #tempExamination AS EX ON Ex.Id = HI.ExaminationId
	WHERE ex.SetupId = @rSetupId and (EX.Id = @rSourceId or isnull(@rSourceId,0) = 0)
	AND ((EX.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EX.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND EX.OrgId=@rOrgId

	IF OBJECT_ID('tempdb..#tmpServiceValue') IS NOT NULL begin drop table #tmpServiceValue end
	IF OBJECT_ID('tempdb..#tHealthIndex') IS NOT NULL begin drop table #tHealthIndex end
	IF OBJECT_ID('tempdb..#tTable1') IS NOT NULL begin drop table #tTable1 end

	CREATE TABLE #tmpServiceValue
	(
		Id int IDENTITY(1,1),TestParameterId int,SourceId bigint,ServiceValue float,ParameterName nvarchar(50),
		Remark nvarchar(200),GenderId tinyint
	)
	CREATE TABLE #tHealthIndex
	(
		Id int IDENTITY(1,1),ExaminationId bigint,HealthIndexParameterId int,EarnedPoINTs int,TotalPoINTs int
	)
	CREATE TABLE #tTable1
	(
		Id bigint IDENTITY,HealthIndexParameterId int,ParameterTypeId int,FieldName nvarchar(50),
		FROMValue nvarchar(50),ToValue nvarchar(50),PoINTs int,GenderId tinyint,DiagnosisRemark nvarchar(250)
	)
	DECLARE @ExaminationTable TABLE
	(
		tId int IDENTITY (1, 1),ExaminationId bigint
	)
	DECLARE @TempTable1 TABLE
	(
		tId int IDENTITY(1,1),TempTableId int,ExaminationId bigint
	)
	DECLARE @TempTable2 TABLE
	(
		tId int IDENTITY(1,1),TempTableId int,ExaminationId bigint
	)
	
	INSERT INTO #tmpServiceValue
	SELECT TPM.Id,E.Id,ServiceValue,STPM.UCode,TRD.Remark,PD.GenderId
	FROM #tempExamination E
	INNER JOIN sHrm.tEmployeePersonalDetail PD ON E.ParticipantSourceId = PD.EmployeeId
	INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.Id
	INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id 
	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 AND TPM.ParameterValueTypeId = 1
	INNER JOIN SOrderEntry.tStaticTestParameterMaster STPM ON TPM.StaticTestParameterId = STPM.Id
	WHERE ISNUMERIC(TRD.ServiceValue) = 1 AND TRD.ServiceValue <> '+' AND (ISNULL(TRD.ServiceValue, '') != '')
	AND E.SetupId = @rSetupId and (E.Id = @rSourceId or isnull(@rSourceId,0) = 0)
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND E.OrgId=@rOrgId
			
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
	if(@configval='Priority' or @configval='Priority Abnormal')
		begin
			-- changes as per mentis issue no:12021 - 2020-07-08 (Rahul,Raju sir,das sir) discussion
			INSERT INTO #tTable1
			SELECT HealthIndexParameterId,HealthIndexParameterTypeId,FieldName,FROMValue,ToValue,PoINTs,GenderId,DiagnosisRemark
			FROM sExamination.tHealthIndexParameterDetail HD
			INNER JOIN sExamination.tHealthIndexParameterMaster HIM ON HIM.Id = HD.HealthIndexParameterId	
			WHERE HIM.IsObsolete = 0 AND HD.OrgId=@rOrgId AND HIM.OrgId=@rOrgId and HIM.StaticHealthIndexParameterId in(
			select distinct HealthIndexParameterId from sExamination.tHealthIndexGroupParameter where roundgroupid=@roundgroupid
			)
			OR (        
				HIM.StaticHealthIndexParameterId IN (18,19,21)
				AND EXISTS (
					SELECT 1 
					FROM sExamination.tHealthIndexGroupParameter 
					WHERE RoundGroupId = @roundgroupid
					AND HealthIndexParameterId = 2
				)
			)
			--union
			--select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','4.00','5.60',10,1,''
			--union
			--select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','4.00','5.60',10,2,''
			--union
			--select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','5.61','6.40',6,1,''
			--union
			--select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','5.61','6.40',6,2,''
			--union
			--select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','6.41','200',3,1,''
			--union
			--select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','6.41','200',3,2,''
			--union
			--select [sCommon].[fGetIntIdForOrg](20,@rOrgId),2,'DIABETIC_PPBS','0','140.00',10,1,''
			--union
			--select [sCommon].[fGetIntIdForOrg](20,@rOrgId),2,'DIABETIC_PPBS','0','140.00',10,2,''
			--union
			--select [sCommon].[fGetIntIdForOrg](20,@rOrgId),2,'DIABETIC_PPBS','140.01','199.00',6,1,''
			--union
			--select [sCommon].[fGetIntIdForOrg](20,@rOrgId),2,'DIABETIC_PPBS','140.01','199.00',6,2,''
			--union
			--select [sCommon].[fGetIntIdForOrg](20,@rOrgId),2,'DIABETIC_PPBS','199.01','1000',3,1,''
			--union
			--select [sCommon].[fGetIntIdForOrg](20,@rOrgId),2,'DIABETIC_PPBS','199.01','1000',3,2,''
			--union
			--select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','0','120.50',10,1,''
			--union
			--select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','0','120.50',10,2,''
			--union
			--select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','120.51','159.50',6,1,''
			--union
			--select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','120.51','159.50',6,2,''
			--union
			--select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','159.51','1000',3,1,''
			--union
			--select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','159.51','1000',3,2,''
	end
	else
	begin
			INSERT INTO #tTable1
			SELECT HealthIndexParameterId,HealthIndexParameterTypeId,FieldName,FROMValue,ToValue,PoINTs,GenderId,DiagnosisRemark
			FROM sExamination.tHealthIndexParameterDetail HD
			INNER JOIN sExamination.tHealthIndexParameterMaster HIM ON HIM.Id = HD.HealthIndexParameterId	
			WHERE HIM.IsObsolete = 0 AND HD.OrgId=@rOrgId AND HIM.OrgId=@rOrgId and HIM.StaticHealthIndexParameterId in(
			select distinct HealthIndexParameterId from sExamination.tHealthIndexGroupParameter where roundgroupid=@roundgroupid
			)
	end

	--select * from #tTable1			
	SELECT @lCount = COUNT(Id) FROM #tTable1
	
	WHILE @lCount > 0
	BEGIN
		SELECT @lParameterId = 0,@FieldName = '',@lParameterTypeId = 0,@lFROMValue = 0,@lToValue = 0,
		@lPoINTs = 0,@lGenderId = 0,@lTestParameterId = 0,@lDiagnosisRemark = ''
		
		SELECT @lParameterId = HealthIndexParameterId,@FieldName = FieldName,@lParameterTypeId = ParameterTypeId,
		@lFROMValue = FROMValue, @lToValue = ToValue, @lPoINTs = PoINTs, @lGenderId = GenderId, @lDiagnosisRemark = DiagnosisRemark
		FROM #tTable1 WHERE Id = @lCount
		
		IF (@lParameterTypeId = 1)
		BEGIN
			--Vital
			SET @lQueryString1 = '  SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10
			FROM #tempExamination E
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
			INNER JOIN sExamination.tVital V ON V.SourceId=E.Id
			WHERE  (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ')
			AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))
			AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
			AND (' + CAST(@lFROMValue AS nvarchar(30)) + '<=' + CAST(@FieldName AS nvarchar(30)) + ')
			AND (' + CAST(@FieldName AS nvarchar(30)) + '<=' + CAST(@lToValue AS nvarchar(30)) + ')
			AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))
			AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'
			--0<=bmi and bmi<=20			
		END
		ELSE IF (@lParameterTypeId = 2)
		BEGIN
			--Numeric Test
			SELECT @lTestParameterId = TestParameterId
			FROM #tmpServiceValue WHERE ParameterName LIKE @FieldName
			
			--select @FieldName,@lTestParameterId
			
			SET @lQueryString1 = 'SELECT SourceId,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10
			FROM #tmpServiceValue WHERE TestParameterId = (' + CAST(@lTestParameterId AS nvarchar(30)) + ')' + '
			AND (' + CAST(@lFROMValue AS nvarchar(30)) + ' <= ServiceValue' + ')
			AND (GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ')  OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
			AND ( ServiceValue <=' + CAST(@lToValue AS nvarchar(30)) + ')'
		END
		ELSE IF (@lParameterTypeId = 3)
		BEGIN
			--List Test			
			SELECT @lTestParameterId = TestParameterId
			FROM #tempExamination E
			INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.id
			INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id
			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 AND TPM.ParameterValueTypeId = 2
			WHERE TPM.Title LIKE @FieldName
			
			SET @lQueryString1 = 'SELECT SourceId,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10
			FROM #tempExamination E
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
			INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.id
			INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id
			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 AND TPM.ParameterValueTypeId = 2
			WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' AND E.ParticipantSourceTypeId = 95
			AND (E.Id=' + CAST(@rSourceId AS nvarchar(30)) + ' OR ' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0)
			AND (EPD.GenderId=' + CAST(@lGenderId AS nvarchar(30)) + ' OR ' + CAST(@lGenderId AS nvarchar(30)) + ' = 0)
			AND TestParameterId = ' + CAST(@lTestParameterId AS nvarchar(30)) + '
			AND ServiceValue = ''' + CAST(@lFROMValue AS nvarchar(30)) + '''' + 'AND ServiceValue <> ''''
			AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))
			AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'
		END
		ELSE IF (@lParameterTypeId = 4)
		BEGIN
			IF (CAST(@FieldName AS int) = 2)
			BEGIN
				--Habit
				SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10
				FROM #tempExamination E
				INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
				INNER JOIN sExamination.tHabitHygine H ON H.SourceId=E.Id
				LEFT JOIN sExamination.tHabitHygineDetail HD ON HD.HabitHygineId=H.Id AND HD.IsObsolete=0
				WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '
				AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))
				AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
				AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))
			AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))
				Group by E.Id,HD.HabitHygineId having (COUNT(HD.HabitHygineId) >=' + CAST(@FieldName AS nvarchar(30)) + ')'
			END
			ELSE IF (CAST(@FieldName AS int) = 1)
			BEGIN
				SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10
				FROM #tempExamination E
				INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
				INNER JOIN sExamination.tHabitHygine H ON H.SourceId=E.Id
				LEFT JOIN sExamination.tHabitHygineDetail HD ON HD.HabitHygineId=H.Id AND HD.IsObsolete=0
				WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '
				AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))
				AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
				AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))
			AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))
				Group by E.Id,HD.HabitHygineId having (COUNT(HD.HabitHygineId) =' + CAST(@FieldName AS nvarchar(30)) + ')'
			END
			ELSE IF (CAST(@FieldName AS int) = 0)
			BEGIN
				SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10
				FROM #tempExamination E
				INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
				LEFT JOIN sExamination.tHabitHygine H ON H.SourceId=E.Id
				LEFT JOIN sExamination.tHabitHygineDetail HD ON HD.HabitHygineId=H.Id AND HD.IsObsolete=0
				WHERE HD.Id is null AND  E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '
				AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))
				AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
				AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))
				AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'
			END
		END
		ELSE IF (@lParameterTypeId = 5)
		BEGIN
			IF (CAST(@FieldName AS int) = 2)
			BEGIN
				--Life Style Disease
				SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10
				FROM #tempExamination E
				INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
				INNER JOIN sExamination.tExistingDisease ED ON ED.SourceId=E.Id
				inner JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId=ED.Id AND EDD.IsObsolete=0
				WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '
				AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))
				AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
				AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))
				AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))
				Group by E.Id,EDD.ExistingDiseaseId having (COUNT(EDD.ExistingDiseaseId) >=' + CAST(@FieldName AS nvarchar(30)) + ')'
			END
			ELSE IF (CAST(@FieldName AS int) = 1)
			BEGIN
				SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10
				FROM #tempExamination E
				INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
				INNER JOIN sExamination.tExistingDisease ED ON ED.SourceId=E.Id
				inner JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId=ED.Id AND EDD.IsObsolete=0
				WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '
				AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))
				AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
				AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))
				AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))
				Group by E.Id,EDD.ExistingDiseaseId having (COUNT(EDD.ExistingDiseaseId) =' + CAST(@FieldName AS nvarchar(30)) + ')'
			END
			ELSE IF (CAST(@FieldName AS int) = 0)
			BEGIN
				SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10
				FROM #tempExamination E
				INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
				LEFT JOIN sExamination.tExistingDisease ED ON ED.SourceId=E.Id
				WHERE ED.Id IS NULL and E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '
				AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
				AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))
				AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))
				UNION SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10
				FROM #tempExamination E
				INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
				INNER JOIN sExamination.tExistingDisease ED ON ED.SourceId=E.Id
				LEFT JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId=ED.Id AND EDD.IsObsolete=0
				WHERE EDD.Id IS NULL  AND  E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '
				AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))
				AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
				AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))
				AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'
				--and ISNULL(ED.Remark,'''') <> ''''
			END
		END
		ELSE IF (@lParameterTypeId = 11)
		BEGIN
			--Shift Duty
			SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',0
			FROM #tempExamination E
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=E.ParticipantSourceId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
			WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '
			AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))
			AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
			AND EJD.IsWorkingInShift = 1
			AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))
			AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'
		END
		ELSE
		IF (@lParameterTypeId = 12)
		BEGIN
			--Hazard Process
			SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',0
			FROM #tempExamination E
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
			WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '
			AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))
			AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0)) AND E.ProcessTypeId = 1
			AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))
			AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'
		END
		IF (@lParameterTypeId = 13)  
		BEGIN  
		   --Audiometry  
		   SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
		   FROM sExamination.tExamination E
		   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
		   INNER JOIN sExamination.tAudiometry AUD ON AUD.SourceId=E.Id
		   INNER JOIN sExamination.tAudiometryResultMaster ARM ON ARM.Id = CASE WHEN AUD.AudiometryAcResultLeftId > AUD.AudiometryAcResultRightId 
																		   THEN AUD.AudiometryAcResultLeftId ELSE AUD.AudiometryAcResultRightId END
		   WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
		   AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
		   AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
		   AND UPPER(LTRIM(RTRIM(ARM.Title))) = UPPER(''' + @lDiagnosisRemark + ''')
		   AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
		   AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'  
		END
	    IF (@lParameterTypeId = 14)  
		BEGIN  
		   --Pulmonary  
		   SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
		   FROM sExamination.tExamination E
		   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
		   INNER JOIN sExamination.tPulmonary PUL ON PUL.SourceId=E.Id
		   WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
		   AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
		   AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
		   AND UPPER(LTRIM(RTRIM(ISNULL(PUL.PulmonaryResulIntensity,'''') + '' '' + ISNULL(PUL.PulmonaryResult,'''')))) = UPPER(''' + @lDiagnosisRemark + ''')
		   AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
		   AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'  
		END
	
		print @lQueryString1			
		INSERT INTO #tHealthIndex
		EXECUTE sp_executesql @lQueryString1
		SET @lCount = @lCount - 1

		
	END
	
	--select * from #tHealthIndex
	--return
	print @configval
	if(@configval='Priority')
		begin
			-- changes as per mentis issue no:12021 - 2020-07-08 (Rahul,Raju sir,das sir) discussion
			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](19,@rOrgId)
			) 
			and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](2,@rOrgId)
			) and HealthIndexParameterId 
			in ([sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
	
			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId)
			) and HealthIndexParameterId in ([sCommon].[fGetIntIdForOrg](21,@rOrgId))

			--update #tHealthIndex set HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](2,@rOrgId)
			--where (HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](19,@rOrgId) 
			--or HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](18,@rOrgId) 
			--or HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](21,@rOrgId))
		end
	else if(@configval='Priority Abnormal')
		begin
			
			-- changes as per mentis issue no:12372 - 2020-07-08 (Rahul,Raju sir,das sir) discussion
			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](19,@rOrgId) and isnull(EarnedPoINTs,0)=3
			) 
			and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](2,@rOrgId) and isnull(EarnedPoINTs,0)=3
			) and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId) and isnull(EarnedPoINTs,0)=3
			) and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](21,@rOrgId) and isnull(EarnedPoINTs,0)=3
			) and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](19,@rOrgId) and isnull(EarnedPoINTs,0)=6
			) 
			and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](2,@rOrgId) and isnull(EarnedPoINTs,0)=6
			) and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId) and isnull(EarnedPoINTs,0)=6
			) and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId) and isnull(EarnedPoINTs,0)=6
			) and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](21,@rOrgId) and isnull(EarnedPoINTs,0)=6
			) and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](19,@rOrgId) and isnull(EarnedPoINTs,0)=10
			) 
			and HealthIndexParameterId 
			in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			--in ([sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](2,@rOrgId) and isnull(EarnedPoINTs,0)=10
			) and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId) and isnull(EarnedPoINTs,0)=10
			) and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))

			delete from #tHealthIndex
			where ExaminationId in (
			Select ExaminationId
			From #tHealthIndex
			Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](21,@rOrgId) and isnull(EarnedPoINTs,0)=10
			) and HealthIndexParameterId 
			--in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))
			in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId))
			
			--update #tHealthIndex set HealthIndexParameterId =  [sCommon].[fGetIntIdForOrg](2,@rOrgId)
			--where (HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](19,@rOrgId) 
			--or HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](18,@rOrgId) 
			--or HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](21,@rOrgId))

		end

		--select * from #tHealthIndex
		--return

	if @rSourceId > 0
	begin	
		delete from #tHealthIndex where ExaminationId <> @rSourceId
	end
	
	insert into @TempTable1
	SELECT h.Id,h.ExaminationId FROM #tHealthIndex as h
	inner join #tempExamination as exm on exm.Id=h.ExaminationId
	INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = h.HealthIndexParameterId AND pm.OrgId=@rOrgId
	inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @roundgroupid
	where exm.SetupId=@rSetupId and (exm.Id = @rSourceId or isnull(@rSourceId,0) = 0) AND pm.StaticHealthIndexParameterId IN (12)
	AND ((exm.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((exm.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND exm.OrgId=@rOrgId
	--AND exm.GradeId   IN (300100120, 300100121, 300100122, 300100123, 300100124, 300100125, 300100126)
		
	insert into @TempTable2
	SELECT h.Id,h.ExaminationId FROM #tHealthIndex as h
	inner join #tempExamination as exm on exm.Id=h.ExaminationId
	INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = h.HealthIndexParameterId AND pm.OrgId=@rOrgId
	inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @roundgroupid
	where exm.SetupId=@rSetupId and (exm.Id = @rSourceId or isnull(@rSourceId,0) = 0)
	AND pm.StaticHealthIndexParameterId IN (14)
	AND ((exm.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((exm.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND exm.OrgId=@rOrgId
	--AND exm.GradeId   IN (300100120, 300100121, 300100122, 300100123, 300100124, 300100125, 300100126)
	
	DELETE FROM #tHealthIndex WHERE Id IN
	(
		SELECT h.id FROM #tHealthIndex AS h
		INNER JOIN #tempExamination AS exm ON exm.Id = h.ExaminationId
		INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = h.HealthIndexParameterId AND pm.OrgId=@rOrgId
		inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @roundgroupid
		WHERE exm.SetupId = @rSetupId and (exm.Id = @rSourceId or isnull(@rSourceId,0) = 0) AND pm.StaticHealthIndexParameterId NOT IN 
		(
			select HealthIndexParameterId from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @roundgroupid
		)
		AND NOT
		(
		    pm.StaticHealthIndexParameterId IN (18,19,21)
		    AND EXISTS (
		    	SELECT 1 
		    	FROM sExamination.tHealthIndexGroupParameter 
		    	WHERE RoundGroupId = @roundgroupid
		    	AND HealthIndexParameterId = 2
		    )
		)
		AND ((exm.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((exm.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		UNION ALL

		SELECT t2.TempTableId FROM @TempTable1 AS t
		INNER JOIN @TempTable2 AS t2 ON t.ExaminationId = t2.ExaminationId
	)
	
	declare @ParameterCountNonExcutive int = 0, @MaleParameterCountNonExcutive int = 0, @FemaleParameterCountNonExcutive int = 0;
	declare @ParameterCountExcutive int = 0;
	select @ParameterCountNonExcutive=count(1) from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=2  and ISNULL(RoundGroupId,0) = @roundgroupid  
	select @ParameterCountExcutive=count(1) from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=1  and ISNULL(RoundGroupId,0) = @roundgroupid  
   
	select @MaleParameterCountNonExcutive = (select Count(0) from (
		select GenderId, HIPM.Title from sExamination.tHealthIndexGroupParameter HIGP
		INNER JOIN sExamination.tStaticHealthIndexParameterDetail HIPD ON HIPD.StaticHealthIndexParameterId = HIGP.HealthIndexParameterId
		INNER JOIN sExamination.tStaticHealthIndexParameterMaster HIPM ON HIPM.Id = HIPD.StaticHealthIndexParameterId
		where HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @roundgroupid and GenderId = 1
		Group BY GenderId,HIPM.Title
	) male)

	select @FemaleParameterCountNonExcutive = (select Count(0) from (
		select GenderId, HIPM.Title from sExamination.tHealthIndexGroupParameter HIGP
		INNER JOIN sExamination.tStaticHealthIndexParameterDetail HIPD ON HIPD.StaticHealthIndexParameterId = HIGP.HealthIndexParameterId
		INNER JOIN sExamination.tStaticHealthIndexParameterMaster HIPM ON HIPM.Id = HIPD.StaticHealthIndexParameterId
		where HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @roundgroupid and GenderId = 2
		Group BY GenderId,HIPM.Title
	) female)

	INSERT INTO sExamination.tHealthIndex
	SELECT  T.ExaminationId,T.HealthIndexParameterId,MAX(T.EarnedPoINTs),Max(T.TotalPoINTs) 
	FROM #tHealthIndex T
	Group by T.ExaminationId,T.HealthIndexParameterId
	--left join sExamination.tHealthIndex H On H.examinationid=T.ExaminationId and H.Healthindexparameterid=T.HealthIndexParameterId
	--where T.examinationid is null and T.HealthIndexParameterId is null
			
	INSERT INTO @ExaminationTable
	SELECT exm.Id
	FROM #tempExamination AS exm
	INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = exm.ParticipantSourceId
	INNER JOIN sExamination.tSetupMaster AS stp ON stp.Id = exm.SetupId
	INNER JOIN sExamination.tDiagnosis AS dis ON dis.SourceId = exm.Id
	INNER JOIN sExamination.tHealthIndex AS hei ON hei.ExaminationId = exm.Id
	INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = hei.HealthIndexParameterId
	inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @roundgroupid
	--inner join sExamination.tHealthIndexGroupParameter as gpm on gpm.HealthIndexParameterId=pm.StaticHealthIndexParameterId and gpm.HealthIndexGroupId=2 and ISNULL(gpm.RoundGroupId,0) = @roundgroupid
	WHERE exm.SetupId = @rSetupId and (exm.Id = @rSourceId or isnull(@rSourceId,0) = 0) 
	AND ((exm.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((exm.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND EXM.OrgId=@rOrgId
	AND (pm.StaticHealthIndexParameterId IN (select HealthIndexParameterId from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @roundgroupid)
     OR (pm.StaticHealthIndexParameterId in (18,19,21) AND EXISTS (SELECT 1 FROM sExamination.tHealthIndexGroupParameter 
             WHERE RoundGroupId = @roundgroupid AND HealthIndexParameterId = 2)))
	GROUP BY exm.Id, EPD.GenderId HAVING COUNT(0) >= CASE 
                     WHEN EPD.GenderId = 1 THEN @MaleParameterCountNonExcutive
                     WHEN EPD.GenderId = 2 THEN @FemaleParameterCountNonExcutive
                   END

	UNION aLL

	SELECT exm.Id
	FROM #tempExamination AS exm
	INNER JOIN sExamination.tSetupMaster AS stp ON stp.Id = exm.SetupId
	INNER JOIN sExamination.tDiagnosis AS dis ON dis.SourceId = exm.Id
	INNER JOIN sExamination.tHealthIndex AS hei ON hei.ExaminationId = exm.Id
	INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = hei.HealthIndexParameterId
	inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @roundgroupid
	WHERE exm.SetupId = @rSetupId and (exm.Id = @rSourceId or isnull(@rSourceId,0) = 0) 
	AND pm.StaticHealthIndexParameterId IN (12, 14) 
	AND ((exm.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((exm.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND EXM.OrgId=@rOrgId
	UNION ALL
	SELECT exm.Id
	FROM #tempExamination AS exm
	INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = exm.ParticipantSourceId
	INNER JOIN sExamination.tSetupMaster AS stp ON stp.Id = exm.SetupId
	INNER JOIN sExamination.tDiagnosis AS dis ON dis.SourceId = exm.Id
	INNER JOIN sExamination.tHealthIndex AS hei ON hei.ExaminationId = exm.Id
	INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = hei.HealthIndexParameterId AND pm.OrgId=@rOrgId
	inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @roundgroupid 
	--inner join sExamination.tHealthIndexGroupParameter as gpm on gpm.HealthIndexParameterId=pm.StaticHealthIndexParameterId and gpm.HealthIndexGroupId=1 and ISNULL(gpm.RoundGroupId,0) = @roundgroupid
	WHERE exm.SetupId = @rSetupId and (exm.Id = @rSourceId or isnull(@rSourceId,0) = 0) AND pm.StaticHealthIndexParameterId not IN (12, 14)
	AND ((exm.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((exm.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND EXM.OrgId=@rOrgId
	AND (pm.StaticHealthIndexParameterId IN (select HealthIndexParameterId from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @roundgroupid)
     OR (pm.StaticHealthIndexParameterId in (18,19,21) AND EXISTS (SELECT 1 FROM sExamination.tHealthIndexGroupParameter 
             WHERE RoundGroupId = @roundgroupid AND HealthIndexParameterId = 2)))
	GROUP BY exm.Id, EPD.GenderId HAVING COUNT(0) >= CASE 
                     WHEN EPD.GenderId = 1 THEN @MaleParameterCountNonExcutive
                     WHEN EPD.GenderId = 2 THEN @FemaleParameterCountNonExcutive
                   END
	
	INSERT INTO sExamination.tDiagnosisPartial
	(
		ExaminationId,TotalHealthPoints,EarnedHealthPoints,HealthIndicatorId,AgeGroupId,HealthIndex
	)
	SELECT Distinct EX.ExaminationId,EX.TotalPoints,EX.EarnedPoints,EX.HealthIndicatorId,EX.AgeGroupId,
	CONVERT(decimal(6, 2),(CONVERT(decimal(6, 2),ISNULL(EX.EarnedPoints, 0)) * 100) / CONVERT(decimal(6, 2),
	ISNULL(EX.TotalPoints, 0)))
	FROM sExamination.tDiagnosis AS DS
	INNER JOIN
	(
		SELECT a.ExaminationId,a.EarnedPoints,a.TotalPoints,a.Percentage,
		(
			SELECT ID
			FROM [sExamination].[tHealthIndicatorMaster]
			WHERE RangeTo >= a.Percentage
			AND a.Percentage > RangeFrom
		)
		HealthIndicatorId,[dbo].[fGetAgeGroupId](ISNULL(DATEDIFF(yy, EPD.DateOfBirth, sCommon.fGetDate()), 0),EPD.OrgId) AgeGroupId
		FROM
		(
			SELECT ExaminationId,SUM(EarnedPoints) EarnedPoints,SUM(TotalPoints) TotalPoints,
			ISNULL(CONVERT(decimal(18, 2), ((CONVERT(decimal(6, 2), SUM(EarnedPoints)) * 100) / CONVERT(decimal(6, 2),
			SUM(TotalPoints)))), 0) Percentage
			FROM sExamination.tHealthIndex
			GROUP BY ExaminationId
			HAVING SUM(TotalPoINTs) > 0
		) AS a
		INNER JOIN #tempExamination E ON e.id = a.ExaminationId AND E.SetupId = @rSetupId AND e.OrgId=@rOrgId
		and (E.Id = @rSourceId or isnull(@rSourceId,0) = 0)
		AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		LEFT JOIN sHrm.tEmployeePersonalDetail AS EPD ON EPD.EmployeeId = e.ParticipantSourceId
	) AS EX ON EX.ExaminationId = DS.SourceId
	left join @ExaminationTable e2 on e2.ExaminationId=ds.SourceId
	where e2.ExaminationId is null 

	UPDATE DS SET DS.TotalHealthPoints = EX.TotalPoints,
	DS.EarnedHealthPoints = EX.EarnedPoints,DS.HealthIndicatorId = EX.HealthIndicatorId,
	DS.AgeGroupId = EX.AgeGroupId,
	DS.HealthIndex = CONVERT(decimal(6, 2), (CONVERT(decimal(6, 2), ISNULL(EX.EarnedPoints, 0)) * 100) / CONVERT(decimal(6, 2), ISNULL(EX.TotalPoints, 0)))
	FROM sExamination.tDiagnosis AS DS
	INNER JOIN
	(
		SELECT a.ExaminationId,a.EarnedPoints,a.TotalPoints,a.Percentage,
		(
			SELECT ID FROM [sExamination].[tHealthIndicatorMaster]
			WHERE RangeTo >= a.Percentage AND a.Percentage > RangeFrom
		)
		HealthIndicatorId,[dbo].[fGetAgeGroupId](ISNULL(DATEDIFF(yy, EPD.DateOfBirth, sCommon.fGetDate()), 0), EPD.OrgId) AgeGroupId
		FROM
		(
			SELECT ExaminationId,SUM(EarnedPoints) EarnedPoints,SUM(TotalPoints) TotalPoints,
			ISNULL(CONVERT(decimal(18, 2), ((CONVERT(decimal(6, 2), SUM(EarnedPoints)) * 100) / CONVERT(decimal(6, 2), SUM(TotalPoints)))), 0) Percentage
			FROM sExamination.tHealthIndex GROUP BY ExaminationId HAVING SUM(TotalPoINTs) > 0
		) AS a INNER JOIN #tempExamination E
		ON e.id = a.ExaminationId AND E.SetupId = @rSetupId and (E.Id = @rSourceId or isnull(@rSourceId,0) = 0) AND e.OrgId=@rOrgId
		AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		LEFT JOIN sHrm.tEmployeePersonalDetail AS EPD ON EPD.EmployeeId = e.ParticipantSourceId
	) AS EX	ON EX.ExaminationId = DS.SourceId
	left join @ExaminationTable as e2 on e2.ExaminationId=ds.SourceId
	where e2.ExaminationId is not null 

	DELETE HI FROM sExamination.tHealthIndexPartial AS HI
	INNER JOIN #tempExamination AS EX ON Ex.Id = HI.ExaminationId
	left join @ExaminationTable as e2 on e2.ExaminationId=hi.ExaminationId
	WHERE ex.SetupId = @rSetupId and (ex.Id = @rSourceId or isnull(@rSourceId,0) = 0) and e2.ExaminationId is null
	AND ((EX.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EX.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND ex.OrgId=@rOrgId

	INSERT INTO sExamination.tHealthIndexPartial
	(
		ExaminationId,HealthIndexParameterId,EarnedPoints,TotalPoints
	)
	SELECT HI.ExaminationId,HI.HealthIndexParameterId,HI.EarnedPoints,HI.TotalPoints
	FROM sExamination.tHealthIndex AS HI
	INNER JOIN #tempExamination AS EX ON Ex.Id = HI.ExaminationId
	LEFT JOIN @ExaminationTable as e2 on e2.ExaminationId=hi.ExaminationId
	WHERE ex.SetupId = @rSetupId and (ex.Id = @rSourceId or isnull(@rSourceId,0) = 0) and e2.ExaminationId is null
	AND ((EX.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EX.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND ex.OrgId=@rOrgId

	DELETE HI FROM sExamination.tHealthIndex AS HI
	INNER JOIN #tempExamination AS EX ON Ex.Id = HI.ExaminationId
	LEFT JOIN @ExaminationTable as e2 on e2.ExaminationId=hi.ExaminationId
	WHERE ex.SetupId = @rSetupId and (ex.Id = @rSourceId or isnull(@rSourceId,0) = 0) and e2.ExaminationId is null
	AND ((EX.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((EX.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
	AND ex.OrgId=@rOrgId

	update sExamination.tSetupMaster set IsHealthIndexUpdated =1 where Id=@rSetupId 
	declare @cnt int  
	select @cnt = count(1) from #tempExamination 
	IF OBJECT_ID(N'tempdb..#tempExamination') IS NOT NULL
	BEGIN
		DROP TABLE #tempExamination
	END
	
	SELECT @cnt AS Result


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


GO
   
ALTER PROCEDURE [sExamination].[pImportALLContractExaminationDatas]      
@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,      
@rUserId bigint ,  
@rstrEmployeeDetail  nvarchar(max) = '',  
@rstrEmployeeJobDetail  nvarchar(max) = '',  
@rstrEmployeePersonalDetail  nvarchar(max) = '',  
@rstrEmployeeCommunication  nvarchar(max) = ''  
as      
begin       
 declare @loXMLExamination xml,@loXMLVital xml,@loXMLDisease xml,@loXMLHabit xml,@loXMLHistory xml,      
 @loXMLDiagnisis xml,@loXMLTest xml,@loXMLGeneral xml,@loXMLPulmonary xml,@loXMLAudiometry xml,  
 @loXMLEmployeeDetail xml,@loXMLEmployeeJobDetail xml ,@loXMLEmployeePersonalDetail xml ,@loXMLEmployeeCommunication xml     
       
 declare @exceptiondetail varchar(max),@orgid int      
       
 set @orgid =(select Top 1 Orgid from sExamination.tExamination where Orgid != 0)      
      
 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)    
  SET @loXMLEmployeeDetail = CAST(@rstrEmployeeDetail AS xml)      
  SET @loXMLEmployeeJobDetail = CAST(@rstrEmployeeJobDetail AS xml)      
  SET @loXMLEmployeePersonalDetail = CAST(@rstrEmployeePersonalDetail AS xml)      
  SET @loXMLEmployeeCommunication = CAST(@rstrEmployeeCommunication 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..#tbltmpEmployeeDetail') IS NOT NULL      
 DROP TABLE #tbltmpEmployeeDetail      
      
  DECLARE @lNextNumberEmp BIGINT,@lNextNumberEmpFamily bigint,@lOrgIdEmp int  
  Create table #tbltmpEmployeeDetail      
  (      
   tid int identity(1,1),e_Id bigint,e_Code nvarchar(20),e_Name nvarchar(200),e_FatherName nvarchar(200),e_OrgId int     
  )        
  insert into #tbltmpEmployeeDetail      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@Code','nvarchar(20)') as Code,      
  T.c.value('@Name','nvarchar(200)') as Name,      
  T.c.value('@FatherName','nvarchar(200)') as FatherName,  
  T.c.value('@OrgId','int') as OrgId      
  from @loXMLEmployeeDetail.nodes('/Employees/Employee')T(c)    
      
  select top 1 @lOrgIdEmp = e_OrgId from #tbltmpEmployeeDetail  
  ---select * from #tbltmpEmployeeDetail  
  EXECUTE sCommon.pTableRowIdGet @lOrgIdEmp, 'sHrm.tEmployeeMaster', 0, 1, 1,@outNextNumber = @lNextNumberEmp output  
  print @lNextNumberEmp  
  MERGE sHrm.tEmployeeMaster AS Target USING       
  (      
   SELECT e_Id,e_Code,e_Name,e_FatherName,e_OrgId,tid  
   FROM #tbltmpEmployeeDetail TT LEFT JOIN sHrm.tEmployeeMaster T ON TT.e_Code = T.Code and T.OrgId = @lOrgIdEmp     
  ) AS Source ON Target.Code = Source.e_Code and Target.OrgId = @lOrgIdEmp      
  WHEN MATCHED THEN      
   UPDATE SET Target.FirstName = ISNULL(e_Name,''),Target.MiddleName  = ISNULL(e_FatherName,''),TargetGroupId = 10002,            
   Target.UpdatedDateTime = sCommon.fGetDate(),Target.UpdatedUserId = @rUserId  
          
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    OrgID,Id,Code,FirstName,MiddleName,LastName,StatusId,IsObsolete,CreatedUserId,CreatedDateTime,  
 UpdatedUserId,UpdatedDateTime,IsTemporary,TemporaryCode,TargetGroupId,ImportReferenceId,  
 WorkLocationId,ReferenceCode        
   )      
   VALUES      
   (      
          
    e_OrgId,(@lNextNumberEmp + tid),e_Code,ISNULL(e_Name,''),      
    ISNULL(e_FatherName,''),'',10,0,@rUserId,sCommon.fGetDate(),@rUserId,sCommon.fGetDate(),0,e_Code,10002,0, 0,''      
   );        
     
     
      
  update #tbltmpEmployeeDetail set e_Id = Id from sHrm.tEmployeeMaster where Code = e_Code      
  and OrgId = e_OrgId  
     
  Select @lNextNumberEmp  = Max(Id) from sHrm.tEmployeeMaster where OrgId = @lOrgIdEmp        
  exec sCommon.pTableRowIdModify @lOrgIdEmp, @rTableTitle = 'sHrm.tEmployeeMaster', @rCurrentNumber = @lNextNumberEmp  
  --select * from #tbltmpEmployeeDetail  
  --Name from sHrm.tEmployeeFamilyDetails where  OrgId=@orgid and RelationshipId=2 and EmployeeId=@EmployeeId  
  exec sCommon.pTableRowIdGet @lOrgIdEmp, 'sHrm.tEmployeeFamilyDetails', 0, 1, 1,@outNextNumber = @lNextNumberEmpFamily output  
  
   MERGE sHrm.tEmployeeFamilyDetails AS Target USING       
  (      
   SELECT e_Id,e_Code,e_Name,e_FatherName,e_OrgId,tid  
   FROM #tbltmpEmployeeDetail TT LEFT JOIN sHrm.tEmployeeFamilyDetails T ON TT.e_Id = T.EmployeeId and T.OrgId = @lOrgIdEmp and T.RelationshipId = 2     
  ) AS Source ON Target.EmployeeId = Source.e_Id and Target.OrgId = @lOrgIdEmp  and Target.RelationshipId = 2     
  WHEN MATCHED THEN      
   UPDATE SET Target.Name = ISNULL(e_FatherName,''),            
   Target.UpdatedDateTime = sCommon.fGetDate(),Target.UpdatedUserId = @rUserId  
          
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    OrgID,Id,EmployeeId,RelationshipId,Name,ISActive,GenderId,CreatedUserId,CreatedDateTime,  
 UpdatedUserId,UpdatedDateTime      
   )      
   VALUES      
   (      
          
    e_OrgId,(@lNextNumberEmpFamily + tid),e_Id,2,ISNULL(e_FatherName,''),0,1      
    ,@rUserId,sCommon.fGetDate(),@rUserId,sCommon.fGetDate()      
   );    
     
  
   Select @lNextNumberEmpFamily  = Max(Id) from sHrm.tEmployeeFamilyDetails where OrgId = @lOrgIdEmp        
  exec sCommon.pTableRowIdModify @lOrgIdEmp, @rTableTitle = 'sHrm.tEmployeeFamilyDetails', @rCurrentNumber = @lNextNumberEmpFamily  
  print @lNextNumberEmpFamily  
  --select * from #tbltmpEmployeeDetail  
 END TRY   
 BEGIN CATCH  
  
   insert into tbl_ImportExaminationErrorLog      
  select '',11,'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..#tbltmpEmployeePersonalDetail') IS NOT NULL      
 DROP TABLE #tbltmpEmployeePersonalDetail      
      
    
  Create table #tbltmpEmployeePersonalDetail      
  (      
   tid int identity(1,1),e_Uid nvarchar(50),e_Code nvarchar(20),e_GenderId smallint,e_DateofBirth nvarchar(200),e_OrgId int ,e_EmployeeId bigint    
  )        
  insert into #tbltmpEmployeePersonalDetail      
  select T.c.value('@UIDNumber','nvarchar(50)') as UIDNumber,      
  T.c.value('@Code','nvarchar(20)') as Code,      
  T.c.value('@GenderId','smallint') as GenderId,      
  T.c.value('@DateofBirth','nvarchar(200)') as DateofBirth,  
  T.c.value('@OrgId','int') as OrgId ,0     
  from @loXMLEmployeePersonalDetail.nodes('/EmployeesPersonals/EmployeePersonal')T(c)    
  -- select * from #tbltmpEmployeePersonalDetail  
  update #tbltmpEmployeePersonalDetail set e_EmployeeId = Id from sHrm.tEmployeeMaster where Code = e_Code      
  and OrgId = e_OrgId   
    
  --select * from #tbltmpEmployeePersonalDetail  
  MERGE sHrm.tEmployeePersonalDetail AS Target USING       
  (      
   SELECT e_EmployeeId,e_OrgId ,e_Uid,e_DateofBirth,      
    e_GenderId     
   FROM #tbltmpEmployeePersonalDetail TT LEFT JOIN sHrm.tEmployeeMaster T ON TT.e_EmployeeId = T.Id      
  ) AS Source ON Target.EmployeeId = Source.e_EmployeeId      
  WHEN MATCHED THEN      
   UPDATE SET Target.UIDNumber = e_Uid,Target.GenderId  = e_GenderId,Target.DateofBirth = (case when len(e_DateofBirth) = 10 then convert(Datetime, e_DateofBirth, 104) else CONVERT(VARCHAR(11), e_DateofBirth) end),            
   Target.UpdatedDateTime = sCommon.fGetDate(),Target.UpdatedUserId = @rUserId  
          
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    OrgID,EmployeeId,UIDNumber,DateOfBirth,GenderId,IsDisability,IsDisabilityCertified,IsFireTraining,  
 IsFirstAidTraining, UpdatedUserId,UpdatedDateTime  
   )      
   VALUES      
   (      
          
    e_OrgId,e_EmployeeId,e_Uid,(case when len(e_DateofBirth) = 10 then convert(Datetime, e_DateofBirth, 104) else CONVERT(VARCHAR(11), e_DateofBirth) end),      
    e_GenderId,0,0,0,0,@rUserId,sCommon.fGetDate()  
   );        
         
   
 --select * from #tbltmpEmployeePersonalDetail  
  
 END TRY   
 BEGIN CATCH  
  
   insert into tbl_ImportExaminationErrorLog      
  select '',12,'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..#tbltmpEmployeeJobDetail') IS NOT NULL      
 DROP TABLE #tbltmpEmployeeJobDetail      
      
    
  Create table #tbltmpEmployeeJobDetail      
  (      
   tid int identity(1,1),e_ContractorId int,e_Code nvarchar(20),e_ProcessTypeId smallint,e_LocationId int,e_OrgId int
   ,e_EmployeeId bigint    , e_EmployeeDesignationId int,e_OrganizationDepartmentId int,e_EmployeeTypeId  int ,e_EmployeeCompanyId  int ,e_EmployeeGroupId int,e_GradeId int,e_EmployeeSubTypeId int,
    e_EmployeeStoreLocationId int
  )        
  insert into #tbltmpEmployeeJobDetail      
  select T.c.value('@ContractorId','int') as ContractorId,      
  T.c.value('@Code','nvarchar(20)') as Code,      
  T.c.value('@ProcessTypeId','smallint') as ProcessTypeId,   
  T.c.value('@LocationId','int') as LocationId,   
  T.c.value('@OrgId','int') as OrgId ,0,
  T.c.value('@EmployeeDesignationId','int') as EmployeeDesignationId   ,
  T.c.value('@DepartmentId','int') as OrganizationDepartmentId   ,
  T.c.value('@EmployeeTypeId','int') as EmployeeTypeId   ,
  T.c.value('@EmployeeCompanyId','int') as EmployeeCompanyId,
  T.c.value('@EmployeeGroupId','int') as EmployeeGroupId   ,
  T.c.value('@GradeId','int') as GradeId   ,
  T.c.value('@EmployeeSubTypeId','int') as EmployeeSubTypeId,
  T.c.value('@StoreLocationId','int') as EmployeeStoreLocationId


  
  
  from @loXMLEmployeeJobDetail.nodes('/EmployeesJobs/EmployeeJob')T(c)    
     
  update #tbltmpEmployeeJobDetail set e_EmployeeId = Id from sHrm.tEmployeeMaster where Code = e_Code      
  and OrgId = e_OrgId   
    
  MERGE sHrm.tEmployeeJobDetail AS Target USING       
  (      
   SELECT e_EmployeeId,e_OrgId,e_ContractorId ,e_ProcessTypeId,e_LocationId  , e_EmployeeDesignationId,e_OrganizationDepartmentId,e_EmployeeTypeId ,e_EmployeeCompanyId  ,
  e_EmployeeGroupId,e_GradeId,e_EmployeeSubTypeId,e_EmployeeStoreLocationId
  FROM #tbltmpEmployeeJobDetail TT LEFT JOIN sHrm.tEmployeeMaster T ON TT.e_EmployeeId = T.Id      
  ) AS Source ON Target.EmployeeId = Source.e_EmployeeId      
  WHEN MATCHED THEN      
   UPDATE SET Target.ContractorId = e_ContractorId,Target.ProcessTypeId  = e_ProcessTypeId, EmployeeDesignationId = e_EmployeeDesignationId,       
   OrganizationDepartmentId=e_OrganizationDepartmentId,   EmployeeTypeId=e_EmployeeTypeId, EmployeeCompanyId=e_EmployeeCompanyId
   , EmployeeGroupId=e_EmployeeGroupId, GradeId=e_GradeId, EmployeeSubTypeId=e_EmployeeSubTypeId,EmployeeStoreLocationId=e_EmployeeStoreLocationId,Target.UpdatedDateTime = sCommon.fGetDate(),Target.UpdatedUserId = @rUserId  
          
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    OrgID,EmployeeId,EmployeeDesignationId,EmployeeLocationId,OrganizationDepartmentId,IsSkilled,EmployeeTypeId,EmployeeCompanyId,ContractorId,ProcessTypeId,EmployeeStoreLocationId,EmployeeGroupId,GradeId,EmployeeSubTypeId, UpdatedUserId,UpdatedDateTime  
   )      
   VALUES      
   (      
          
    e_OrgId,e_EmployeeId,e_EmployeeDesignationId,e_LocationId,e_OrganizationDepartmentId, 0,e_EmployeeTypeId,e_EmployeeCompanyId,0,e_ProcessTypeId,e_EmployeeStoreLocationId,e_EmployeeGroupId,e_GradeId,e_EmployeeSubTypeId,@rUserId,sCommon.fGetDate()  
   );        
         
   
 --select * from #tbltmpEmployeeJobDetail  
  
 END TRY   
 BEGIN CATCH  
  
   insert into tbl_ImportExaminationErrorLog      
  select '',13,'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..#tbltmpEmployeeCommunication') IS NOT NULL      
 DROP TABLE #tbltmpEmployeeCommunication      
      
    
  Create table #tbltmpEmployeeCommunication      
  (      
   tid int identity(1,1),e_PresentStreetOne nvarchar(150),e_Code nvarchar(20),e_OrgId int ,e_EmployeeId bigint    
  )        
  insert into #tbltmpEmployeeCommunication      
  select T.c.value('@PresentStreetOne','nvarchar(150)') as PresentStreetOne,      
  T.c.value('@Code','nvarchar(20)') as Code,  
  T.c.value('@OrgId','int') as OrgId ,0     
  from @loXMLEmployeeCommunication.nodes('/EmployeesCommunications/EmployeeCommunication')T(c)    
     
  update #tbltmpEmployeeCommunication set e_EmployeeId = Id from sHrm.tEmployeeMaster where Code = e_Code      
  and OrgId = e_OrgId   
    
  MERGE [sHrm].[tEmployeeCommunications] AS Target USING       
  (      
   SELECT e_EmployeeId,e_OrgId,e_PresentStreetOne     
   FROM #tbltmpEmployeeCommunication TT LEFT JOIN sHrm.tEmployeeMaster T ON TT.e_EmployeeId = T.Id      
  ) AS Source ON Target.EmployeeId = Source.e_EmployeeId      
  WHEN MATCHED THEN      
   UPDATE SET Target.PresentStreetOne = e_PresentStreetOne,            
   Target.UpdatedDateTime = sCommon.fGetDate(),Target.UpdatedUserId = @rUserId  
          
  WHEN NOT MATCHED THEN      
   INSERT      
   (      
    EmployeeId,PresentStreetOne, UpdatedUserId,UpdatedDateTime, CreatedUserId,CreatedDateTime  
   )      
   VALUES      
   (      
          
    e_EmployeeId,e_PresentStreetOne,@rUserId,sCommon.fGetDate(),@rUserId,sCommon.fGetDate()  
   );        
         
   
  
  
 END TRY   
 BEGIN CATCH  
  
   insert into tbl_ImportExaminationErrorLog      
  select '',14,'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_Code nvarchar(20),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(100),  
   e_ParticipantSourceId bigint     
  )        
  insert into #tbltmpExamination      
  select T.c.value('@Code','nvarchar(20)') as Code,      
  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      
  from @loXMLExamination.nodes('/Examinations/Examination')T(c)      
    
  update #tbltmpExamination set e_ParticipantSourceId  = Id from sHrm.tEmployeeMaster where Code = e_Code      
  and OrgId = @orgid   
  print @orgid  
  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)      
          
  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      
    
         
  --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 =  1,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,      
   Target.PastHistorySelf=e_PastHistorySelf        
  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,PastHistorySelf         
   )      
   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,e_PastHistorySelf      
   );        
         
  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   
    
 --select * from #tbltmpExamination       
 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_Code nvarchar(20),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),v_ParticipantSourceId bigint  
  )      
  insert into #tbltmpVitals      
  select T.c.value('@Code','nvarchar(20)') as Code,      
  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,0  
  from @loXMLVital.nodes('/Vitals/Vital')T(c)      
        
   update #tbltmpVitals set v_ParticipantSourceId  = Id from sHrm.tEmployeeMaster where Code = v_Code      
  and OrgId = @orgid   
  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       
  
  --select * from #tbltmpVitals  
 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_Code nvarchar(20),d_Diagnosis varchar(1000),      
   d_Recommendation varchar(1000),d_examinationid bigint,d_id bigint,d_date varchar(50),d_ParticipantSourceId bigint      
  )      
  insert into #tbltmpDiagnosis      
  select T.c.value('@Code','nvarchar(20)') as Code,      
  T.c.value('@Diagnosis','varchar(200)') as Diagnosis,      
T.c.value('@Recommendation','varchar(200)') as Recommendation,0,null,'' ,0     
  from @loXMLDiagnisis.nodes('/Diagnosiss/Diagnosis')T(c)      
     
     
   update #tbltmpDiagnosis set d_ParticipantSourceId  = Id from sHrm.tEmployeeMaster where Code = d_Code      
  and OrgId = @orgid   
     
  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     
    
  --select * from #tbltmpDiagnosis  
      
 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_Code varchar(20),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    ,h_ParticipantSourceId bigint  
  )      
  insert into #tbltmpHabitss      
  select T.c.value('@Code','nvarchar(20)') as Code,      
  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 ,0   
  from @loXMLHabit.nodes('/Habits/Habit')T(c)       
    
   update #tbltmpHabitss set h_ParticipantSourceId  = Id from sHrm.tEmployeeMaster where Code = h_Code      
  and OrgId = @orgid   
  
  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_Code varchar(20), d_DiseaseName varchar(500),      
   d_ExaminationId bigint,d_OrgId int,d_AreaId int,d_ParticipantAreaId bigint,d_ExistingDiseaseId bigint,d_OtherDisease varchar(500),d_ParticipantSourceId bigint      
  )      
  insert into #tbltmpDisease      
  select T.c.value('@Code','nvarchar(20)') as Code,        
  replace(T.c.value('@DiseaseSelf','varchar(500)'),'+',',') as DiseaseSelf,0,0,0,0,null,      
  replace(T.c.value('@OtherDiseaseSelf','varchar(500)'),'+',',') as OtherDiseaseSelf ,0     
  from @loXMLDisease.nodes('/Diseases/Disease')T(c)       
    
  
  update #tbltmpDisease set d_ParticipantSourceId  = Id from sHrm.tEmployeeMaster where Code = d_Code      
  and OrgId = @orgid   
  
  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      
  )      
  insert into #tbltmpDiseaseDetailsNull      
  select Distinct HD.DiseaseId,HD.OrgId,H.dd_ParticipantSourceId,null      
  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        
  WHERE HH.OrgId = @lOrgId AND HD.OrgId = @lOrgId AND STM.MainTypeId <> 8      
  AND HH.SourceTypeId = 1002      
  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      
     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      
     )      
     VALUES      
     (      
  ed_ExistingDiseaseId,ed_HabitId,ed_OrgId,0      
     );      
   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 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      
  )      
  VALUES      
  (      
   d_ExistingDiseaseId,d_DiseaseId,d_OrgId,0,''      
  );      
      
  update #tbltmpDiseaseN set d_ExisitingDiseaseDetailId = Id from sExamination.tExistingDiseaseDetail where ExistingDiseaseId = d_ExistingDiseaseId      
  and DiseaseId = d_DiseaseId      
      
        
 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_Code nvarchar(20),h_Self varchar(200),h_Mother varchar(200),      
   h_Father varchar(200),h_Brother varchar(200),h_Sister varchar(200),h_Surgery varchar(1000),h_ExaminationId bigint,h_OrgId int,      
   h_ParticipantAreaId bigint,h_AreaId int,AreaName varchar(200),h_HistoryId bigint, h_TreatmentHistoryRemark varchar(200),h_PastHistoryRemark varchar(200),h_ParticipantSourceId bigint      
  )      
  insert into @tbltmpHistory      
  select T.c.value('@Code','nvarchar(20)') as Code,      
  replace(T.c.value('@PastHistorySelf','varchar(200)'),'+',',') 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('@Surgery','varchar(200)') as Surgery,0,0,null,null,'Past History',null,T.c.value('@TreatmentHistoryRemark','varchar(200)') as TreatmentHistoryRemark      
  ,T.c.value('@PastHistoryRemark','varchar(200)') as PastHistoryRemark ,0     
  from @loXMLHistory.nodes('/Historys/History')T(c)         
    
   update @tbltmpHistory set h_ParticipantSourceId  = Id from sHrm.tEmployeeMaster where Code = h_Code      
  and OrgId = @orgid   
       
  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,TT.e_examinationid 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 ;      
      
      
  -----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_Code nvarchar(20),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  ,t_ParticipantSourceId bigint    
  )      
  insert into #tbltmpTests      
  select T.c.value('@Code','nvarchar(20)') as Code,      
  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,0     
  from @loXMLTest.nodes('/Tests/Test')T(c)      
    
  update #tbltmpTests set t_ParticipantSourceId  = Id from sHrm.tEmployeeMaster where Code = t_Code      
  and OrgId = @orgid   
  
  IF EXISTS (SELECT 1 FROM sys.indexes WHERE NAME = N'IX_tTestRequestDetail'
			   AND object_id = OBJECT_ID('sExamination.tTestRequestDetail'))      
  BEGIN
    DROP INDEX IX_tTestRequestDetail ON sExamination.tTestRequestDetail
  END      
  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)      
  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)      
    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)      
    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)      
    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)      
    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)      
     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)      
     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)      
     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)      
     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)      
  from sExamination.tTestRequestDetail inner join #tbltmpRatio on r_TestRequestDetailId = Id      
 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_Code nvarchar(20),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 ,g_EmpId bigint    
  )      
  insert into #tblGeneral      
  select T.c.value('@Code','nvarchar(20)') as Code,      
  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,0      
  from @loXMLGeneral.nodes('/General/Clinic')T(c) where T.c.value('@Result','varchar(1000)') <> ''      
     
   update #tblGeneral set g_EmpId  = Id from sHrm.tEmployeeMaster where Code = g_Code      
  and OrgId = @orgid     
  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      
        
  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_Code nvarchar(20),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_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_ParticipantId bigint     
 -- )      
 -- insert into #tblPulmonary      
 -- select T.c.value('@Code','nvarchar(20)') as Code,      
 -- 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('@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,0      
 -- from @loXMLPulmonary.nodes('/Pulmonarys/Pulmonary')T(c)      
    
 -- update #tblPulmonary set pl_ParticipantId  = Id from sHrm.tEmployeeMaster where Code = pl_Code      
 -- and OrgId = @orgid  
  
 -- 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,'')=''      
              
 -- 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 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      
         
 -- 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      
 --  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      
 -- 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      
 --  )      
 --  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         
 --  );        
        
 --  --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)      
      
 -- 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_Code nvarchar(20),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_ParticipantSourceId bigint   
 -- )      
         
 -- insert into #tbltmpAudiometry      
 -- select T.c.value('@Code','nvarchar(20)') as Code,      
 -- 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,0 from @loXMLAudiometry.nodes('/Examinations/Examination')T(c)      
     
 -- update #tbltmpAudiometry set a_ParticipantSourceId  = Id from sHrm.tEmployeeMaster where Code = a_Code      
 -- and OrgId = @orgid  
        
 -- 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,'')=''       
        
 -- 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      
 -- )      
        
 -- 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 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      
         
 -- 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 = LeftAcValue,AcValueRight = RightAcValue,      
 --  BcValueLeft = LeftBcValue,BcValueRight = RightBcValue      
 -- 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'      
        
 -- 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)      
 --  select @lAudiomentryId = e_AudiometryId from #tbltmpExaminationN where tid = @i      
         
 --  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)      
         
 --  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      
 --  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'  
 when e_type=11 then 'Error In Importing Employee Data'  
 when e_type=12 then 'Error In Importing Employee Personal Data'  
 when e_type=13 then 'Error In Importing Employee Job Data'  
 when e_type=14 then 'Error In Importing Employee Communication Data'      
    else 'Error In Importing Data'      
    end as e_Message      
  from tbl_ImportExaminationErrorLog where e_UserId =@rUserId and (DATEDIFF(minute,e_CreatedDate,getdate())<=5)      
      
--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   
--Drop table #tbltmpEmployeeDetail  
--Drop table #tbltmpEmployeePersonalDetail  
--Drop table #tbltmpEmployeeJobDetail  
--Drop table #tbltmpEmployeeCommunication  

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..#tbltmpTestsN') IS NOT NULL 
--    DROP TABLE #tbltmpTestsN;
--IF OBJECT_ID('tempdb..#tbltmpRatioN') IS NOT NULL 
--    DROP TABLE #tbltmpRatioN;
--IF OBJECT_ID('tempdb..#tbltmpRatio') IS NOT NULL 
--    DROP TABLE #tbltmpRatio;
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..#tblGeneralParameters') IS NOT NULL 
--    DROP TABLE #tblGeneralParameters;
--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;
IF OBJECT_ID('tempdb..#tbltmpEmployeeDetail') IS NOT NULL 
    DROP TABLE #tbltmpEmployeeDetail;
IF OBJECT_ID('tempdb..#tbltmpEmployeePersonalDetail') IS NOT NULL 
    DROP TABLE #tbltmpEmployeePersonalDetail;
IF OBJECT_ID('tempdb..#tbltmpEmployeeJobDetail') IS NOT NULL 
    DROP TABLE #tbltmpEmployeeJobDetail;
IF OBJECT_ID('tempdb..#tbltmpEmployeeCommunication') IS NOT NULL 
    DROP TABLE #tbltmpEmployeeCommunication;

     
end
GO
PRINT N'Altering Procedure [sExamination].[pImportALLExaminationDataTableDatas]...';


GO

ALTER proc [sExamination].[pImportALLExaminationDataTableDatas]
@rExaminationDt [sExamination].[ExaminationList] readonly,
@rVitalDt [sExamination].[VitalList] readonly,
@rDiseaseDt [sExamination].[DiseaseList] readonly,
@rHabitDt [sExamination].[HabitList] readonly,
@rHistoryDt [sExamination].[HistoryList] readonly,
@rDiagnosisDt [sExamination].[DiagnosisList] readonly,
@rTestDt [sExamination].[TestList] readonly,
@rMainTypeId int,    
@rstr varchar(50),    
@rGeneralDt [sExamination].[GeneralList] readonly,
@rPulmonaryDt [sExamination].[PulmonaryList] readonly,
@rAudiometryDt [sExamination].[AudiometryList] readonly,
@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)    
    
 --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(100)    
  )      
  insert into #tbltmpExamination    
  select ParticipantSourceId, LocationId, SetupId, NatureId, convert(varchar, convert(Date, Examination_Date, 103), 103), Doctor, DoctorId,
	0,0,0,0,0,0,0,0,null,MedicalId,null,ProcessId,TargetGroupId,ColorVisionId,0,''
	from @rExaminationDt
  --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,''    
  --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)    
        
  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    
  
       
  --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 =  1,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,    
   Target.PastHistorySelf=e_PastHistorySelf      
  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,PastHistorySelf       
   )    
   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,e_PastHistorySelf    
   );      
       
  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 'Examination',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)    
  )    
  insert into #tbltmpVitals    
  select ParticipantSourceId,
  Height,Weight,Pulse,BPSys,BPDia,Respiration,AbdominalGirth,ChestExpansion,Waist,    
  Hip,ElbowWidth,Temperature,null,0,0,0,0,Inhalation,Exhalation   
  from @rVitalDt
      
  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    
   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    
  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    
   )    
   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    
   );    
        
  --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 'Vital',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 ParticipantSourceId,Diagnosis,Recommendation,0,null,''
  from @rDiagnosisDt
      
  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 'Diagnosis',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 ParticipantSourceId,    
  Alcohol,    
  Chewer,    
  Smoker,    
  AlcoholSocial,    
  Drug,0,0,0,0,0,null,    
  case Alcohol when 'y' then 'Alcohol' when 'yes' then 'Alcohol' when '1' then 'Alcohol' else '' end,    
  case Chewer when 'y' then 'Chewer' when 'yes' then 'Chewer' when '1' then 'Chewer' else '' end,    
  case Smoker when 'y' then 'Smoker' when 'yes' then 'Smoker' when '1' then 'Smoker' else '' end,    
  case AlcoholSocial when 'y' then 'Alcohol-Social' when 'yes' then 'Alcohol-Social' when '1' then 'Alcohol-Social' else '' end,    
  case Drug when 'y' then 'Drugs' when 'yes' then 'Drugs' when '1' then 'Drugs' else '' end,    
  0,0,null,null,null,null,null,null,0    
  from @rHabitDt     
        
  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 'Habit',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(500)    
  )    
  insert into #tbltmpDisease    
  select ParticipantSourceId,    
  replace(DiseaseSelf,'+',',') as DiseaseSelf,0,0,0,0,null,    
  replace(OtherDiseaseSelf,'+',',') as OtherDiseaseSelf
  from @rDiseaseDt
    
  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    
  )    
  insert into #tbltmpDiseaseDetailsNull    
  select Distinct HD.DiseaseId,HD.OrgId,H.dd_ParticipantSourceId,null    
  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      
  WHERE HH.OrgId = @lOrgId AND HD.OrgId = @lOrgId AND STM.MainTypeId <> 8    
  AND HH.SourceTypeId = 1002    
  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    
     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    
     )    
     VALUES    
     (    
      ed_ExistingDiseaseId,ed_HabitId,ed_OrgId,0    
     );    
   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 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    
  )    
  VALUES    
  (    
   d_ExistingDiseaseId,d_DiseaseId,d_OrgId,0,''    
  );    
    
  update #tbltmpDiseaseN set d_ExisitingDiseaseDetailId = Id from sExamination.tExistingDiseaseDetail where ExistingDiseaseId = d_ExistingDiseaseId    
  and DiseaseId = d_DiseaseId    
    
      
 END TRY    
 BEGIN CATCH    
  insert into tbl_ImportExaminationErrorLog    
  select 'Disease',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(200),h_Mother varchar(200),    
   h_Father varchar(200),h_Brother varchar(200),h_Sister varchar(200),h_Surgery varchar(1000),h_ExaminationId bigint,h_OrgId int,    
   h_ParticipantAreaId bigint,h_AreaId int,AreaName varchar(200),h_HistoryId bigint, h_TreatmentHistoryRemark varchar(200),h_PastHistoryRemark varchar(200)    
  )    
  insert into @tbltmpHistory    
  select ParticipantSourceId,    
  replace(PastHistorySelf,'+',',') as PastHistorySelf,    
  replace(PastHistoryMother,'+',',') as PastHistoryMother,    
  replace(PastHistoryFather,'+',',') as PastHistoryFather,    
  replace(PastHistoryBrother,'+',',') as PastHistoryBrother,    
  replace(PastHistorySister,'+',',') as PastHistorySister,    
  Surgery,0,0,null,null,'Past History',null,TreatmentHistoryRemark as TreatmentHistoryRemark    
  ,PastHistoryRemark as PastHistoryRemark
  from @rHistoryDt
      
  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,TT.e_examinationid 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 ;    
    
    
  -----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 'History',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 ParticipantSourceId,
  TestDetailId,
  TestResult,
  TestRemark,
  null,null,null,null,null,null,null,null
  from @rTestDt
      
  IF EXISTS (SELECT 1 FROM sys.indexes WHERE NAME = N'IX_tTestRequestDetail'
				AND object_id = OBJECT_ID('sExamination.tTestRequestDetail'))    
  BEGIN
    DROP INDEX IX_tTestRequestDetail ON sExamination.tTestRequestDetail
  END   
  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)    
  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)    
    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)    
    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)    
    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)    
    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)    
     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)    
     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)    
     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)    
     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)    
  from sExamination.tTestRequestDetail inner join #tbltmpRatio on r_TestRequestDetailId = Id    
 END TRY    
 BEGIN CATCH    
  insert into tbl_ImportExaminationErrorLog    
  select 'Test',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 ParticipantSourceId,
  ParameterId,
  GeneralResult,
  GeneralRemark,null,null,null,null,null
  from @rGeneralDt where GeneralResult <> ''    
      
  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    
      
  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    
      
  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 'General',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_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    
  )    
  insert into #tblPulmonary    
  select ParticipantSourceId,    
  FVC,
  FEV1,
  PEFR,
  FVCP,
  FEV1P,
  FEV3P,    
  PEFP,
  FEF2575P,
  FEF212P,
  FEF25P,
  FEF50P,
  FEF75P,
  SVCP,
  null,null,null,null,null,null,null,null,null,null,null,null,    
  MVVP,null,null
  from @rPulmonaryDt
      
  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,'')=''    
            
  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 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    
       
  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    
   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    
  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    
   )    
   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       
   );      
      
   --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)    
    
  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 'Pulmonary',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    
  )    
       
  insert into #tbltmpAudiometry
  select ParticipantSourceId,
  LocationId,
  SetupId,
  LeftAcRemarkId,
  RightAcRemarkId,
  case when By_Rule = 'y' or By_Rule = 'yes' or By_Rule = '1' then 1 else 0 end as By_Rule,
  AudioLeftACIds,
  AudioRightACIds,
  AudioLeftBCIds,
  AudioRightBCIds,
  null,null,null,null,null from @rAudiometryDt    
      
  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,'')=''     
      
  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    
  )    
      
  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 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    
       
  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 = LeftAcValue,AcValueRight = RightAcValue,    
   BcValueLeft = LeftBcValue,BcValueRight = RightBcValue    
  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'    
      
  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)    
   select @lAudiomentryId = e_AudiometryId from #tbltmpExaminationN where tid = @i    
       
   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)    
       
   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    
   select @i = @i + 1    
  end    
 END TRY    
 BEGIN CATCH    
  insert into tbl_ImportExaminationErrorLog    
  select 'Audiometry',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)    
    
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].[pRptEmployeewiseTestValue]...';


GO
ALTER PROCEDURE [sExamination].[pRptEmployeewiseTestValue]
@rStoreLocationId int,
@rExaminationTypeId int,
@rRoundId int,
@rFunctionId int,
@rDepartmentGroupId int,
@rDepartmentId int,
@rGradeId int,
@rDesignationId int,
@rJobTitleId int,
@rEmployeeTypeId int,
@rCompanyId int,
@rContractorId int,
@rGenderId smallint,
@rStatusId smallint,
@rAgeFrom int=null,
@rAgeTo int=null,
@rFromDate datetime = '1950-01-01',
@rToDate datetime = '2050-01-01',
@rOrgId int,
@rEmployeeCode nvarchar(50)='',
@rTestId bigint,
@rLocationId int,
@rEmployeeTypeGroupId int=0,
@rEmployeeSubTypeId int=0,
@rEmployeeGroupId int=0,
@rSectorId int = 0, 
@rVerticalId int = 0, 
@rCompanyGroupId int = 0, 
@rMedicalAgencyId int = 0,
@rTargetGroupId int =0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	CREATE TABLE #tmpCondition
	(
		Id INT IDENTITY(1, 1),EmployeeId bigint,Code nvarchar(200),EmployeeName nvarchar(200),
		ExaminationId bigint
	)
	INSERT INTO #tmpCondition 
	SELECT EM.Id,EM.Code,EM.FirstName + ' ' + EM.LastName,E.Id
	FROM sHrm.tEmployeeMaster EM
	INNER JOIN shrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.Id
	INNER JOIN sCommon.tOrganizationDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId 
	INNER JOIN sCommon.tDepartmentGroupMaster DGM ON DM.DepartmentGroupId = DGM.Id
	INNER JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id
	INNER JOIN sHrm.tEmployeePersonalDetail EPD	ON EPD.EmployeeId=EM.Id
	LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.Id
	LEFT JOIN sExamination.tExamination E ON E.ParticipantSourceId = EM.Id AND E.SetupId=@rRoundId
	LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = EJD.EmployeeDesignationId AND (EDM.IsObsolete=0)
	LEFT JOIN sHrm.tGradeMaster GDM	ON GDM.Id=EJD.GradeId AND (GDM.IsObsolete=0)
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM  ON EJD.EmployeeTypeId=ETM.Id
	left join sHrm.tEmployeeCompanyMaster CM on EJD.EmployeeCompanyId = CM.Id
	left join sHrm.tCompanyGroupMaster CG on CM.CompanyGroupId = CG.Id
	left join sHrm.tVerticalMaster VM on CG.VerticalId = VM.Id 
	
	WHERE (E.OrgId=@rOrgId OR @rOrgId=0)
	AND(FM.Id = @rFunctionId OR @rFunctionId = 0)
	AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)
	AND(E.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (E.StoreLocationId= @rStoreLocationId OR @rStoreLocationId=0)
	AND(EJD.GradeId=@rGradeId OR @rGradeId=0)
	AND(EDM.Id = @rDesignationId OR @rDesignationId = 0)
	AND(EJD.EmployeeJobTitleId = @rJobTitleId OR @rJobTitleId = 0)
	AND(EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)
	AND(EJD.ContractorId=@rContractorId OR @rContractorId=0)
	AND(EJD.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND(EPD.GenderId=@rGenderId OR @rGenderId=0)
	AND(E.StatusId=@rStatusId OR @rStatusId=0)
	AND ((DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom)OR (ISNULL(@rAgeFrom,0)=0))
	AND ((DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo) OR (ISNULL(@rAgeTo,0)=0))
	AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((E.ExaminationDate < (@rToDate + 1)) OR (ISNULL(@rToDate,'') = ''))
	AND ((EM.Code = @rEmployeeCode ) OR (@rEmployeeCode = ''))
	--AND ((EJD.EmployeeLocationId = @rLocationId))
	AND(ETM.EmployeeTypeGroupId=@rEmployeeTypeGroupId or @rEmployeeTypeGroupId=0)
	AND(EJD.EmployeeSubTypeId=@rEmployeeSubTypeId or @rEmployeeSubTypeId=0)
	AND(EJD.EmployeeGroupId=@rEmployeeGroupId or @rEmployeeGroupId=0)
	and (CM.CompanyGroupId = @rCompanyGroupId or @rCompanyGroupId = 0)
	and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)
	and (VM.SectorId = @rSectorId or @rSectorId = 0)
	and (E.MedicalAgencyId = @rMedicalAgencyId or @rMedicalAgencyId = 0) 
	and (E.TargetGroupId = @rTargetGroupId or @rTargetGroupId = 0) 
	
	CREATE TABLE #tmpServiceValueNumeric
	(
		Id INT IDENTITY (1, 1),TestRequestId bigint,TestParameterId int,
		TestParameter nvarchar(250),SourceId bigint,ServiceValue nvarchar(250)
	)
	INSERT INTO #tmpServiceValueNumeric 
	SELECT TR.Id,TPM.Id,TPM.Title,TR.SourceId,ServiceValue
	FROM sExamination.tTestRequest TR
	INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id
	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 AND TPM.ParameterValueTypeId = 1
	AND TM.Id = @rTestId and isnumeric(ServiceValue)=1 and ServiceValue <> '.'
	
	CREATE TABLE #tmpServiceValueList
	(
		Id INT IDENTITY (1, 1),TestRequestId bigint,TestParameterId int,
		TestParameter nvarchar(250),SourceId bigint,ServiceValue nvarchar(250)
	) 
	INSERT INTO #tmpServiceValueList 
	SELECT TR.Id,TPM.Id,TPM.Title,TR.SourceId,ServiceValue
	FROM sExamination.tTestRequest TR
	INNER JOIN sExamination.tTestRequestDetail TRD
	ON TRD.TestRequestId = TR.Id
	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 AND TPM.ParameterValueTypeId != 1 AND TM.Id = @rTestId

	DECLARE @cols AS NVARCHAR(MAX),@cols1 AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX),@query1  AS NVARCHAR(MAX)
	Declare @lSetup nvarchar(50)
	Set @lSetup = (Select Title From sExamination.tSetupMaster where Id = @rRoundId)
	
	select @cols = STUFF((SELECT ',' + QUOTENAME(TestParameter)
	from #tmpServiceValueNumeric group by TestParameter order by TestParameter 
	FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,1,'')
	
	select @cols1 = STUFF((SELECT ',' + QUOTENAME(TPM.Title) 
	from sExamination.tTestRequest TR
	INNER JOIN sExamination.tTestRequestDetail TRD
	ON TRD.TestRequestId = TR.Id 
	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 AND TPM.ParameterValueTypeId != 1 AND TM.Id = @rTestId
	group by TPM.Title order by TPM.Title
	FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
	
	IF(@cols is not null AND @cols1 is not null)
	BEGIN      
		set @query = 'SELECT convert(date, TB1.ExaminationDate,23) AS ExaminationDate,TB1.Round,TB1.Code,TB1.EmployeeName,
		TB1.Assigned,' + @cols +', ' + @cols1 +' FROM (SELECT p.ExaminationId, convert(date, p.ExaminationDate, 23) AS ExaminationDate,
		p.EmployeeId,p.Round,p.Code,p.EmployeeName,p.Assigned,' + @cols + ' from
		(
			SELECT E.Id as ExaminationId,E.ExaminationDate,TC.EmployeeId,TC.Code,TC.EmployeeName,TestParameter,ServiceValue,
			('''+ CAST(@lSetup AS NVARCHAR(30))+''') AS Round,(CASE WHEN TS.TestRequestId is null THEN '+ '''No'''+ 'ELSE '+ '''Yes'''+ 'END)
			AS Assigned from #tmpCondition  TC LEFT JOIN #tmpServiceValueNumeric TS ON TS.SourceId = TC.ExaminationId
			LEFT JOIN sExamination.tExamination E ON TC.EmployeeId = E.ParticipantSourceId  AND E.ParticipantSourceTypeId = 95
			AND (E.SetupId=' +CAST(@rRoundId AS NVARCHAR(30))+')  AND E.Id = TC.ExaminationId
		) x
		pivot 
		(
			max(ServiceValue) for TestParameter in (' + @cols + ')) p
		) TB1 
		FULL JOIN
		(
			SELECT convert(date, p.ExaminationDate, 23) AS ExaminationDate,p.EmployeeId,p.ExaminationId,p.Round,p.Code,p.EmployeeName,
			p.Assigned,' + @cols1 + ' from 
			(
				(
					SELECT E.Id as ExaminationId,E.ExaminationDate,TC.EmployeeId,TC.Code,TC.EmployeeName,TestParameter,
					ServiceValue,('''+ CAST(@lSetup AS NVARCHAR(30))+''') AS Round,
					(CASE WHEN TS.TestRequestId is null THEN '+ '''No '''+ 'ELSE '+ '''Yes'''+ 'END) AS Assigned
					FROM #tmpCondition  TC LEFT JOIN #tmpServiceValueList TS ON TS.SourceId = TC.ExaminationId 
					LEFT JOIN sExamination.tExamination E ON TC.EmployeeId = E.ParticipantSourceId
					AND E.ParticipantSourceTypeId = 95 AND (E.SetupId=' +CAST(@rRoundId AS NVARCHAR(30))+')
					AND E.Id = TC.ExaminationId
				)
			) x
			pivot 
			( max(ServiceValue) for TestParameter in (' + @cols1 + ')) p
		) TB2 ON TB2.EmployeeId =  TB1.EmployeeId AND TB1.ExaminationId = TB2.ExaminationId '
	END
	ELSE IF (@cols is null)
	BEGIN
		set @query = 'SELECT convert(date, p.ExaminationDate, 23) AS ExaminationDate,p.Round,p.Code,p.EmployeeName,p.Assigned,' + @cols1 + '
		from 
		(
			(
				SELECT E.ExaminationDate,TC.EmployeeId,TC.Code,TC.EmployeeName,TestParameter,
				ServiceValue,('''+ CAST(@lSetup AS NVARCHAR(30))+''') AS Round,
				(CASE WHEN TS.TestRequestId is null THEN '+ '''No '''+ 'ELSE '+ '''Yes'''+ 'END) AS Assigned  FROM #tmpCondition  TC 
				LEFT JOIN #tmpServiceValueList TS ON TS.SourceId = TC.ExaminationId
				INNER JOIN  sExamination.tExamination E ON TC.EmployeeId = E.ParticipantSourceId 
				AND (E.SetupId=' +CAST(@rRoundId AS NVARCHAR(30))+')   AND E.Id = TC.ExaminationId
			)
		) x
		pivot 
		(
		max(ServiceValue) for TestParameter in (' + @cols1 + ')
		) p'
	END
	ELSE
	set @query = 'SELECT convert(date, p.ExaminationDate, 23) AS ExaminationDate,p.Round,p.Code,p.EmployeeName,p.Assigned,' + @cols + '
	from 
	(
	SELECT E.ExaminationDate,TC.EmployeeId,TC.Code,TC.EmployeeName,TestParameter,ServiceValue,
	('''+ CAST(@lSetup AS NVARCHAR(30))+''') AS Round,
	(CASE WHEN TS.TestRequestId is null THEN '+ '''No '''+ 'ELSE '+ '''Yes'''+ 'END) AS Assigned
	from #tmpCondition  TC LEFT JOIN #tmpServiceValueNumeric TS ON TS.SourceId = TC.ExaminationId
	LEFT JOIN  sExamination.tExamination E ON TC.EmployeeId = E.ParticipantSourceId 
	AND (E.SetupId=' +CAST(@rRoundId AS NVARCHAR(30))+')    AND E.Id = TC.ExaminationId
	) x
	pivot 
	(
	max(ServiceValue) for TestParameter in (' + @cols + ')
	)p'
	execute(@query) 
	
	DROP TABLE #tmpServiceValueNumeric
	DROP TABLE #tmpServiceValueList
END
GO
PRINT N'Altering Procedure [sAppointment].[pGetschedulingAppointmentList]...';


GO

ALTER PROCEDURE [sAppointment].[pGetschedulingAppointmentList]      
    @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,
	@rDescription nvarchar(4000)=''
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,
		ISNULL(A.VisitTypeId, 0) AS VisitTypeId
    FROM     
        sAppointment.vExtPatientAppointmentDetail A    
    LEFT JOIN     
        sExamination.tExamination E ON A.ExaminationId = E.Id    
        OR A.ReferSourceId = E.Id    
	LEFT JOIN
	    sHrm.tEmployeeMaster EM ON EM.Id = A.EmployeeId AND A.PatientSourceTypeId=95
    WHERE     
        A.ApprovalStatusId = 548   
		AND A.AppointmentDate = CONVERT(DATE, sCommon.fGetDate())
       -- 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 ((ISNULL(Relation, '')  Like @rDescription + '%') OR(@rDescription = ''))
        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 ISNULL(A.ExaminationId, 0) = 0    
        AND ISNULL(E.IsCancel, 0) = 0  
		AND (
    A.PatientSourceTypeId <> 95
    OR
    (
        A.PatientSourceTypeId = 95
        AND (
            ((EM.StatusId = 9 OR EM.IsObsolete = 1) AND A.ExaminationId > 0)
            OR
            (EM.StatusId <> 9 AND EM.IsObsolete <> 1)
        )
    )
)
		AND A.Id NOT IN (SELECT IsNull(AppointmentId,0) FROM sExamination.tRegistration WHERE OrgId =@rOrgId)
	ORDER BY A.Id DESC;
END
GO
PRINT N'Altering Procedure [sMro].[pExaminationGenerateReport]...';


GO

ALTER PROCEDURE [sMro].[pExaminationGenerateReport]    
 @rId bigint = 0,    
 @rTitle nvarchar(50),    
 @rColumnName nvarchar(max) = '',    
 @rColumnIds nvarchar(max) = '',    
 @rOrgId int,    
 @rExaminationTypeId int = 0,    
 @rRoundGroupId int = 0,    
 @rRoundId int = 0,
 @rNationalId [nvarchar](max) = '',
 @rStoreLocationId int = 0,    
 @rEmployeeCode [nvarchar](20) = '',    
 @rCodeLike [nvarchar](max) = '',    
 @rEmployeeName [nvarchar](200) = '',		
 @rEmployeeId BigInt = 0,     
 @rFromDate Date = '0001-01-01',    
 @rToDate Date = '9999-12-31',    
 @rExaminationStatusId int = 0,    
 @rEmployeeTypeId int = 0,    
 @rDepartmentGroupIds [nvarchar](max) = '',    
 @rDepartmentIds [nvarchar](max) = '',    
 @rDesignationIds [nvarchar](max) = '',    
 @rTargetGroupIds [nvarchar](max) = '',    
 @rCompanyGroupIds [nvarchar](max) = '',    
 @rCompanyIds [nvarchar](max) = '',    
 @rCreatedUserId bigint    ,
 @rBusinessIds nvarchar(max) = '', -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024
 @rSubBusinessIds nvarchar(max) = '',-- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024
 @rIsBusinessWise bit -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024
WITH RECOMPILE  
AS    
BEGIN
SET NOCOUNT ON   SET NOCOUNT ON;
    SET XACT_ABORT ON;

    BEGIN TRY
        BEGIN TRANSACTION;

        IF (@rFromDate IS NULL) 
            SET @rFromDate = '0001-01-01';

        IF (@rToDate IS NULL)
            SET @rToDate = CONVERT(date, sCommon.fGetDate());

        -- Save preset
        IF (@rTitle <> N'' AND @rId = 0)
        BEGIN
            DECLARE @lNextNumber BIGINT;
            EXEC sCommon.pTableRowIdGet 
                @rOrgId, 
                'sHrm.tExaminationCustomSearch', 
                0, 1, 1, 
                @outNextNumber = @lNextNumber OUTPUT;

            INSERT INTO sHrm.tExaminationCustomSearch
            (
                Id, Title, ColumnName, OrgId, ExaminationTypeId, RoundGroupId, RoundId,
                StoreLocationId, EmployeeCode, CodeLike, EmployeeName, EmployeeId,
                FromDate, ToDate, ExaminationStatusId, EmployeeTypeId, DepartmentGroupIds,
                DepartmentIds, DesignationIds, TargetGroupIds, CompanyGroupIds, CompanyIds,
                CreatedUserId, CreatedDateTime, ColumnIds
            )
            VALUES
            (
                @lNextNumber, @rTitle, @rColumnName, @rOrgId, @rExaminationTypeId, @rRoundGroupId, @rRoundId,
                @rStoreLocationId, @rEmployeeCode, @rCodeLike, @rEmployeeName, @rEmployeeId,
                @rFromDate, @rToDate, @rExaminationStatusId, @rEmployeeTypeId, @rDepartmentGroupIds,
                @rDepartmentIds, @rDesignationIds, @rTargetGroupIds, @rCompanyGroupIds, @rCompanyIds,
                @rCreatedUserId, sCommon.fGetDate(), @rColumnIds
            );
        END

        -- Load preset
        IF (@rId > 0)
        BEGIN
            SELECT
                @rColumnName        = ColumnName,    
                @rOrgId             = OrgId,    
                @rExaminationTypeId = ExaminationTypeId,    
                @rRoundGroupId      = RoundGroupId,    
                @rRoundId           = RoundId,    
                @rStoreLocationId   = StoreLocationId,    
                @rEmployeeCode      = EmployeeCode,    
                @rCodeLike          = CodeLike,    
                @rEmployeeName      = EmployeeName,     
                @rEmployeeId        = EmployeeId,     
                @rFromDate          = FromDate,    
                @rToDate            = ToDate,    
                @rExaminationStatusId = ExaminationStatusId,    
                @rEmployeeTypeId    = EmployeeTypeId,    
                @rDepartmentGroupIds= DepartmentGroupIds,    
                @rDepartmentIds     = DepartmentIds,    
                @rDesignationIds    = DesignationIds,    
                @rTargetGroupIds    = TargetGroupIds,    
                @rCompanyGroupIds   = CompanyGroupIds,    
                @rCompanyIds        = CompanyIds        
            FROM sHrm.tExaminationCustomSearch
            WHERE Id = @rId;
        END

        ------------------------------------------------------------
        -- CLEAN TEMP OBJECTS (idempotent)
        ------------------------------------------------------------
        IF OBJECT_ID('tempdb..#ExaminationDetail') IS NOT NULL DROP TABLE #ExaminationDetail;    
        IF OBJECT_ID('tempdb..#tblExaminationGeneralTemplates') IS NOT NULL DROP TABLE #tblExaminationGeneralTemplates;    
        IF OBJECT_ID('tempdb..#tblGeneral') IS NOT NULL DROP TABLE #tblGeneral;    
        IF OBJECT_ID('tempdb..#tblExaminationTests') IS NOT NULL DROP TABLE #tblExaminationTests;    
        IF OBJECT_ID('tempdb..#tblTests') IS NOT NULL DROP TABLE #tblTests;    
        IF OBJECT_ID('tempdb..##tblMainTable') IS NOT NULL DROP TABLE ##tblMainTable;    
        IF OBJECT_ID('tempdb..#tblExaminationAudiometrys') IS NOT NULL DROP TABLE #tblExaminationAudiometrys;    
        IF OBJECT_ID('tempdb..#tblAudiometry') IS NOT NULL DROP TABLE #tblAudiometry;    
        IF OBJECT_ID('tempdb..#ColumnTable') IS NOT NULL DROP TABLE #ColumnTable;    
        IF OBJECT_ID('tempdb..#ColumnTable1') IS NOT NULL DROP TABLE #ColumnTable1;    

        ------------------------------------------------------------
        -- BASE DETAIL
        ------------------------------------------------------------
        CREATE TABLE #ExaminationDetail
        (
            ExaminationId            bigint        NOT NULL,
            ExaminationDate          varchar(100)  NULL,
            MainTypeName             varchar(100)  NULL,
            StoreLocationName        varchar(100)  NULL,
            RoundGroup               varchar(200)  NULL,
            Round                    varchar(100)  NULL,
            Doctor                   varchar(100)  NULL,
            EmployeeType             varchar(100)  NULL,
            Code                     varchar(100)  NULL,
            EmployeeName             varchar(200)  NULL,
            Gender                   varchar(100)  NULL,
            Department               varchar(100)  NULL,
            Company                  varchar(500)  NULL,
            Designation              varchar(100)  NULL,
            BloodGroup               varchar(100)  NULL,
            Age                      varchar(50)   NULL,
            Height                   varchar(100)  NULL,
            [Weight]                 varchar(100)  NULL,
            BMI                      varchar(100)  NULL,
            Temperature              varchar(100)  NULL,
            Pulse                    varchar(100)  NULL,
            BloodPressureSystolic    varchar(100)  NULL,
            BloodPressureDiastolic   varchar(100)  NULL,
            Respiration              varchar(100)  NULL,
            ElbowWidth               varchar(100)  NULL,
            AbdominalGirth           varchar(100)  NULL,
            Inhalation               varchar(100)  NULL,
            Exhalation               varchar(100)  NULL,
            ChestExpansion           varchar(100)  NULL,
            Waist                    varchar(100)  NULL,
            Hip                      varchar(100)  NULL,
            Disease                  varchar(max)  NULL,
            History                  varchar(max)  NULL,
            Allergy                  varchar(max)  NULL,
            Habit                    varchar(max)  NULL,
            DiagnosisRemark          varchar(max)  NULL,
            Recommendation           varchar(max)  NULL,
            Hospital                 varchar(100)  NULL,
            ReferDoctor              varchar(100)  NULL,
            TargetGroup              nvarchar(200) NULL,
            UIDNumber                nvarchar(50)  NULL,
            Nationality              nvarchar(100) NULL,
            Business                 nvarchar(max) NULL,
            SubBusiness              nvarchar(max) NULL,
            CompanyGroup             nvarchar(max) NULL,
            ProcessType              nvarchar(100) NULL,
			Contractor               varchar(500)  NULL,
        );

        INSERT INTO #ExaminationDetail
        SELECT 
            EED.ExaminationId,
            CONVERT(varchar(10), EED.ExaminationDate, 103),
            EED.MainTypeName,
            EED.StoreLocationName,
            SGM.Title,
            EED.SetupName,
            EED.DoctorName,
            EED.ParticipantType,
            EED.ParticipantCode,
            EED.ParticipantName,
            EED.Gender,
            EED.DepartmentName,
            CASE WHEN @rOrgId <> 3001 THEN ECM.Title ELSE ISNULL(EED.EmployeeLegalEntity, '') END,
            ISNULL(EDM.Title,''),
            ISNULL(BG.Title,''),
            DATEDIFF(yyyy, EED.DateOfBirth, sCommon.fGetDate()),
            V.Height,
            V.BodyWeight,
            V.BMI,
            V.Temperature,
            V.Pulse,
            V.BloodPressureSystolic,
            V.BloodPressureDiastolic,
            V.Respiration,
            V.ElbowWidth,
            V.AbdominalGirth,
            V.ChestExpansionInhalation,
            V.ChestExpansionExhalation,
            V.ChestExpansion,
            V.Waist,
            V.Hip,
            [sExamination].[fExistingDiseaseGet](EED.ExaminationId),
            [sExamination].[fHistoryGet](EED.EmployeeId),
            [sExamination].[fAllergyGet](EED.EmployeeId),
            [sExamination].[fHabitHygineGet](EED.ExaminationId),
            REPLACE(REPLACE(ISNULL(D.DiagnosisRemark, ''), CHAR(13), ' '), CHAR(10), ' '),
            REPLACE(REPLACE(ISNULL(D.RecommendationEnglish, ''), CHAR(13), ' '), CHAR(10), ' '),
            CL.Title,
            CL.DoctorName,
            EED.EmployeeTargetGroupName,
            EED.UIDNumber,
            NM.Title,
            SCT.Title,
            VTM.Title,
            CGM.Title,
            ISNULL(PTM.Title,''),
			ISNULL(CONV.Title,'')
        FROM sExamination.vExtEmployeeExaminationDetail AS EED
        INNER JOIN sExamination.tSetupMaster               AS SM   ON SM.Id = EED.SetupId
        LEFT  JOIN sHrm.tEmployeePersonalDetail            AS EPD  ON EED.EmployeeId = EPD.EmployeeId 
        LEFT  JOIN sHrm.tEmployeeJobDetail                 AS EJD  ON EJD.EmployeeId = EED.EmployeeId 
        LEFT  JOIN sHrm.tNationalityMaster                 AS NM   ON NM.Id = EPD.NationalityId
        LEFT  JOIN sExamination.tSetupGroupMaster          AS SGM  ON SGM.Id = SM.SetupGroupId    
        LEFT  JOIN sHrm.tEmployeeCompanyMaster             AS ECM  ON ECM.Id = (CASE WHEN @rIsBusinessWise = 0 THEN EED.EmployeeCompanyId ELSE EJD.EmployeeCompanyId END)
        LEFT  JOIN sCommon.tDepartmentGroupMaster          AS DGM  ON EED.DepartmentGroupId = DGM.Id AND DGM.IsObsolete = 0    
        LEFT  JOIN sCommon.tFunctionMaster                 AS FM   ON DGM.FunctionId = FM.Id AND FM.IsObsolete = 0    
        INNER JOIN sIp.tStoreLocationMaster                AS SLM  ON SLM.Id = EED.StoreLocationId    
        INNER JOIN sSecurity.tUserLocation                 AS UL   ON SLM.Id = UL.StoreLocationId    
        INNER JOIN sCommon.tLocationMaster                 AS LM   ON LM.Id = SLM.LocationId    
        LEFT  JOIN sHrm.tEmployeeDesignationMaster         AS EDM  ON EED.EmployeeDesignationId = EDM.Id    
        LEFT  JOIN sHrm.tGradeMaster                       AS GM   ON GM.Id = EED.GradeId AND GM.IsObsolete = 0    
        LEFT  JOIN sCommon.tBloodGroupMaster               AS BG   ON EED.BloodGroupId = BG.Id    
        LEFT  JOIN sExamination.tVital                     AS V    ON EED.ExaminationId = V.SourceId    
        LEFT  JOIN sExamination.tDiagnosis                 AS D    ON EED.ExaminationId = D.SourceId     
        LEFT  JOIN sExamination.tReferral                  AS R    ON R.SourceId = EED.ExaminationId    
        LEFT  JOIN sCommon.tClinicMaster                   AS CL   ON CL.Id = R.ReferToClinicId   
        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.tProcessTypeMaster              AS PTM  ON PTM.Id = EED.ProcessTypeId
		LEFT  JOIN sProcurement.tVendorMaster              AS CONV  ON CONV.Id = (CASE WHEN @rIsBusinessWise = 0 THEN EED.ExaminationContractorId ELSE EJD.ContractorId END)
        WHERE ((EED.StoreLocationId = @rStoreLocationId) OR @rStoreLocationId = 0)    
          AND ((EED.ParticipantCode IN (SELECT item FROM sCommon.fnsplit(@rEmployeeCode, ','))) OR @rEmployeeCode = N'')
          AND ((EED.ParticipantName LIKE @rEmployeeName + N'%') OR @rEmployeeName = N'')       
          AND ((EED.MainTypeId = @rExaminationTypeId) OR @rExaminationTypeId = 0)    
          AND (EED.MainTypeId <> 8)    
          AND ((EED.ExaminationDate >= @rFromDate) OR ISNULL(@rFromDate, '') = N'')    
          AND ((EED.ExaminationDate <= @rToDate)   OR ISNULL(@rToDate,   '') = N'')     
          AND (EED.OrgId = @rOrgId)     
          AND (UL.UserId = @rCreatedUserId)     
          AND (EED.StatusId = @rExaminationStatusId OR @rExaminationStatusId = 0)    
          AND (EED.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)    
          AND ((EED.SetupId = @rRoundId) OR ISNULL(@rRoundId, 0) IN (0, -1))
          AND ((ISNULL(EPD.NationalityId, 0) IN (SELECT item FROM sCommon.fnsplit(@rNationalId, ','))) OR ISNULL(@rNationalId, '') = N'')
          AND ((SM.SetupGroupId = @rRoundGroupId) OR ISNULL(@rRoundGroupId, 0) = 0)    
          AND ((EED.EmployeeCompanyId       IN (SELECT item FROM sCommon.fnsplit(@rCompanyIds, ',')))        OR ISNULL(@rCompanyIds, '') = N'')    
          AND ((EED.OrganizationDepartmentId IN (SELECT item FROM sCommon.fnsplit(@rDepartmentIds, ',')))    OR ISNULL(@rDepartmentIds, '') = N'')    
          AND ((EED.DepartmentGroupId        IN (SELECT item FROM sCommon.fnsplit(@rDepartmentGroupIds, ',')))OR ISNULL(@rDepartmentGroupIds, '') = N'')    
          AND ((EED.EmployeeDesignationId    IN (SELECT item FROM sCommon.fnsplit(@rDesignationIds, ',')))   OR ISNULL(@rDesignationIds, '') = N'')    
          AND (EED.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)    
          AND ((EED.EmployeeTargetGroupId    IN (SELECT item FROM sCommon.fnsplit(@rTargetGroupIds, ',')))   OR @rTargetGroupIds = N'')
          AND (ISNULL(@rCompanyGroupIds, '') = N'' OR ISNULL(ECM.CompanyGroupId, 0) IN (SELECT CAST(item AS int) FROM sCommon.fnsplit(@rCompanyGroupIds, ',')))
          AND ((VTM.SectorId  IN (SELECT item FROM sCommon.fnsplit(@rBusinessIds, ',')))     OR ISNULL(@rBusinessIds,    '') = N'')
          AND ((CGM.VerticalId IN (SELECT item FROM sCommon.fnsplit(@rSubBusinessIds, ','))) OR ISNULL(@rSubBusinessIds, '') = N'');

        -- Helpful index for joins that follow
        CREATE CLUSTERED INDEX IX_ExaminationDetail_ExaminationId ON #ExaminationDetail(ExaminationId);

        ------------------------------------------------------------
        -- GENERAL TEMPLATE -> PIVOT
        ------------------------------------------------------------
        CREATE TABLE #tblExaminationGeneralTemplates
        (
            tid int IDENTITY(1,1) PRIMARY KEY,
            g_ExaminationId bigint,
            g_Value varchar(500),
            g_Remark varchar(500),
            g_Title varchar(300)
        );

        INSERT INTO #tblExaminationGeneralTemplates(g_ExaminationId, g_Value, g_Remark, g_Title)
        SELECT ED.Id,
               GED.ParameterValue,
               GED.Remark,
               GP.Title
        FROM sExamination.tExamination                    AS ED
        INNER JOIN #ExaminationDetail                     AS EED ON ED.Id = EED.ExaminationId    
        INNER JOIN sExamination.tSetupMaster              AS SSM ON ED.SetupId = SSM.Id    
        INNER JOIN sHrm.tEmployeeMaster                   AS EM  ON ED.ParticipantSourceId = EM.Id    
        INNER JOIN sHrm.tEmployeeJobDetail                AS EJD ON EJD.EmployeeId = ED.ParticipantSourceId    
        LEFT  JOIN sExamination.tGeneralTemplateExamination      AS GE  ON ED.Id = GE.SourceId    
        LEFT  JOIN sExamination.tGeneralTemplateExaminationDetail AS GED ON GE.Id = GED.GeneralTemplateExaminationId    
        LEFT  JOIN sExamination.tGeneralTemplateParameter         AS GP  ON GP.Id = GED.GeneralTEmplateParameterId;

        DECLARE @GeneralCols  nvarchar(max) = N'';
        DECLARE @GeneralCols1 nvarchar(max) = N'';
        DECLARE @lQueryExisting nvarchar(max) = N'';

        SELECT @GeneralCols =
        STUFF((
            SELECT DISTINCT ',' + QUOTENAME(GTP.Title)
            FROM sExamination.tGeneralTemplateParameter GTP
            INNER JOIN sExamination.tGeneralTemplateMaster GTM ON GTM.Id = GTP.GeneralTemplateId
            WHERE GTM.GeneralTemplateGroupId <> 4 AND GTP.OrgId = @rOrgId AND GTP.IsObsolete = 0
            FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');

        SELECT @GeneralCols1 =
        STUFF((
            SELECT DISTINCT ',' + QUOTENAME(GTP.Title) + ' varchar(300)'
            FROM sExamination.tGeneralTemplateParameter GTP
            INNER JOIN sExamination.tGeneralTemplateMaster GTM ON GTM.Id = GTP.GeneralTemplateId
            WHERE GTM.GeneralTemplateGroupId <> 4 AND GTP.OrgId = @rOrgId AND GTP.IsObsolete = 0
            FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');
			
        -- Step 1: Create the base temp table
CREATE TABLE #tblGeneral (
    tid INT IDENTITY(1,1) PRIMARY KEY,
    d_ExamId BIGINT
);

-- Step 1: Add dynamic columns if any
IF (@GeneralCols1 <> '')
BEGIN
    -- Add columns dynamically
    SET @lQueryExisting = N'ALTER TABLE #tblGeneral ADD ' + @GeneralCols1;
    EXEC sp_executesql @lQueryExisting;

    -- Insert pivoted data
    SET @lQueryExisting = N'
        INSERT INTO #tblGeneral (d_ExamId, ' + @GeneralCols + ')
        SELECT g_ExaminationId,' + @GeneralCols + '
        FROM
        (
            SELECT g_ExaminationId, g_Value, g_Title
            FROM #tblExaminationGeneralTemplates
        ) src
        PIVOT
        (
            MAX(g_Value) FOR g_Title IN (' + @GeneralCols + ')
        ) piv;
    ';
    EXEC sp_executesql @lQueryExisting;
END

        CREATE NONCLUSTERED INDEX IX_tblGeneral_d_ExamId ON #tblGeneral(d_ExamId);
        ------------------------------------------------------------
        -- TESTS -> PIVOT
        ------------------------------------------------------------
        -- Narrow the TR set first
        CREATE TABLE #tmpTR (TestRequestId bigint, ExaminationId bigint);
        INSERT INTO #tmpTR(TestRequestId, ExaminationId)
        SELECT TR.Id, EED.ExaminationId
        FROM sExamination.tTestRequest AS TR
        INNER JOIN #ExaminationDetail AS EED ON EED.ExaminationId = TR.SourceId;

        CREATE TABLE #tblExaminationTests
        (
            tid int IDENTITY(1,1) PRIMARY KEY,
            g_ExaminationId bigint,
            g_Value varchar(max),
            g_Remark varchar(max),
            g_Title varchar(max)
        );

        INSERT INTO #tblExaminationTests(g_ExaminationId, g_Value, g_Remark, g_Title)
        SELECT GE.ExaminationId,
               GED.ServiceValue,
               GED.Remark,
               GP.Title
        FROM #tmpTR AS GE
        LEFT JOIN sExamination.tTestRequestDetail   AS GED ON GE.TestRequestId = GED.TestRequestId
        LEFT JOIN sOrderEntry.tTestDetail           AS TD  ON TD.Id = GED.TestDetailId
        LEFT JOIN sOrderEntry.tTestParameterMaster  AS GP  ON GP.Id = TD.TestParameterId;
		

        DECLARE @TestCols  nvarchar(max) = N'';
        DECLARE @TestCols1 nvarchar(max) = N'';

        SELECT @TestCols =
        STUFF((
            SELECT DISTINCT ',' + QUOTENAME(Title)
            FROM sOrderEntry.tTestParameterMaster
            WHERE OrgId = @rOrgId AND IsObsolete = 0
            FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');

        SELECT @TestCols1 =
        STUFF((
            SELECT DISTINCT ',' + QUOTENAME(Title) + ' varchar(300)'
            FROM sOrderEntry.tTestParameterMaster
            WHERE OrgId = @rOrgId AND IsObsolete = 0
            FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');

       -- Step 1: Create base temp table
CREATE TABLE #tblTests (
    tid INT IDENTITY(1,1) PRIMARY KEY,
    d_ExamId BIGINT
);

-- Step 2: Add dynamic columns if present
IF (@TestCols1 <> '')
BEGIN
    SET @lQueryExisting = N'ALTER TABLE #tblTests ADD ' + @TestCols1;
    EXEC sp_executesql @lQueryExisting;
END

        IF (@TestCols <> '')
        BEGIN
            SET @lQueryExisting = N'
                INSERT INTO #tblTests (d_ExamId,' + @TestCols + ')
                SELECT g_ExaminationId,' + @TestCols + '
                FROM (
                    SELECT g_ExaminationId, g_Value, g_Title
                    FROM #tblExaminationTests
                    GROUP BY g_ExaminationId, g_Value, g_Remark, g_Title
                ) AS src
                PIVOT (MAX(g_Value) FOR g_Title IN (' + @TestCols + ')) AS piv;';
            EXEC sp_executesql @lQueryExisting;
        END

        CREATE NONCLUSTERED INDEX IX_tblTests_d_ExamId ON #tblTests(d_ExamId);

        ------------------------------------------------------------
        -- FLAGS FOR SPECIAL BLOCKS (329=Audiometry, 330=Pulmonary)
        ------------------------------------------------------------
        DECLARE @isAudiometry bit = 0, @isPulmonary bit = 0;

        ;WITH SplitIds AS
        (
            SELECT TRY_CAST(item AS int) AS ColumnId
            FROM sCommon.fnsplit(@rColumnIds, ',')
        )
        SELECT
            @isAudiometry = CASE WHEN EXISTS(SELECT 1 FROM SplitIds WHERE ColumnId = 329) THEN 1 ELSE 0 END,
            @isPulmonary  = CASE WHEN EXISTS(SELECT 1 FROM SplitIds WHERE ColumnId = 330) THEN 1 ELSE 0 END;

        -- Remove 329/330 from @rColumnIds so they don't try to map to tExaminationCustomColumns
        IF (@isAudiometry = 1)
            SELECT @rColumnIds = REVERSE(STUFF(REVERSE(STUFF(REPLACE(',' + @rColumnIds + ',', ',329,', ','), 1, 1, '')), 1, 1, ''));
        IF (@isPulmonary = 1)
            SELECT @rColumnIds = REVERSE(STUFF(REVERSE(STUFF(REPLACE(',' + @rColumnIds + ',', ',330,', ','), 1, 1, '')), 1, 1, ''));

        ------------------------------------------------------------
        -- BUILD REPORT COLUMN LISTS FROM sHrm.tExaminationCustomColumns
        ------------------------------------------------------------
        CREATE TABLE #ColumnTable1(Id1 int IDENTITY(1,1) PRIMARY KEY, ColumnId1 int);
        CREATE TABLE #ColumnTable (Id int IDENTITY(1,1) PRIMARY KEY, ColumnId int);

        INSERT INTO #ColumnTable1(ColumnId1)
        SELECT item FROM sCommon.fnsplit(@rColumnIds, ',');

        INSERT INTO #ColumnTable(ColumnId)
        SELECT DISTINCT ColumnId1 FROM #ColumnTable1 ORDER BY ColumnId1 ASC;

        DECLARE @ColCount int = (SELECT COUNT(*) FROM #ColumnTable);
        DECLARE @ReportCols   nvarchar(max) = N'';
        DECLARE @ReportColVal nvarchar(max) = N'';

       IF (@ColCount > 0)
        BEGIN
       -- Build column definitions with datatype
       -- Build column definitions with datatype
-- Build column + datatype list
SELECT @ReportCols =
    STUFF((
        SELECT ',' + QUOTENAME(ECC.ColumnName) + ' ' + ECC.DataType
        FROM #ColumnTable CT
        INNER JOIN sHrm.tExaminationCustomColumns ECC 
            ON ECC.Id = CT.ColumnId
        WHERE 
            (
                -- Check in General Templates
                EXISTS (
                    SELECT 1 
                    FROM #tblExaminationGeneralTemplates T 
                    WHERE T.g_Title = ECC.ColumnName
                )
                OR
                -- Check in Examination Tests
                EXISTS (
                    SELECT 1 
                    FROM #tblExaminationTests TT 
                    WHERE TT.g_Title = ECC.ColumnName
                )
                OR
                -- Check in #ExaminationDetail temp table columns
                EXISTS (
                    SELECT 1
                    FROM tempdb.sys.columns sc
                    INNER JOIN tempdb.sys.objects so 
                        ON sc.object_id = so.object_id
                    WHERE so.name LIKE '#ExaminationDetail%' 
                      AND sc.name = ECC.ColumnName
                )
            )
        ORDER BY CT.ColumnId
        FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, ''
    );

-- Build only column list (no datatype)
SELECT @ReportColVal =
    STUFF((
        SELECT ',' + QUOTENAME(ECC.ColumnName)
        FROM #ColumnTable CT
        INNER JOIN sHrm.tExaminationCustomColumns ECC 
            ON ECC.Id = CT.ColumnId
        WHERE 
            (
                EXISTS (
                    SELECT 1 
                    FROM #tblExaminationGeneralTemplates T 
                    WHERE T.g_Title = ECC.ColumnName
                )
                OR
                EXISTS (
                    SELECT 1 
                    FROM #tblExaminationTests TT 
                    WHERE TT.g_Title = ECC.ColumnName
                )
                OR
                EXISTS (
                    SELECT 1
                    FROM tempdb.sys.columns sc
                    INNER JOIN tempdb.sys.objects so 
                        ON sc.object_id = so.object_id
                    WHERE so.name LIKE '#ExaminationDetail%' 
                      AND sc.name = ECC.ColumnName
                )
            )
        ORDER BY CT.ColumnId
        FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, ''
    );
end

        ------------------------------------------------------------
        -- AUDIO PIVOT (if requested)
        ------------------------------------------------------------
        IF (@isAudiometry = 1)
        BEGIN
            CREATE TABLE #tblExaminationAudiometrys
            (
                tid int IDENTITY(1,1) PRIMARY KEY,
                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),
                ED.Id,
                ISNULL(A.IsDoneLeft, 0),
                ISNULL(A.IsDoneRight, 0),
                ISNULL(AD.AcValueLeft, 0),
                ISNULL(AD.AcValueRight, 0),
                ISNULL(AD.FrequencyId, 0),
                ISNULL(A.AudiometryAcResultLeftId, 0),
                ISNULL(A.AudiometryAcResultRightId, 0),
                ISNULL(A.AudiometryResultRemarkLeftId, 0),
                ISNULL(A.AudiometryResultRemarkRightId, 0)
            FROM sExamination.tExamination         AS ED
            INNER JOIN #ExaminationDetail          AS EED ON ED.Id = EED.ExaminationId    
            INNER JOIN sExamination.tSetupMaster   AS SSM ON ED.SetupId = SSM.Id    
            INNER JOIN sHrm.tEmployeeMaster        AS EM  ON ED.ParticipantSourceId = EM.Id    
            INNER JOIN sHrm.tEmployeeJobDetail     AS EJD ON EJD.EmployeeId = ED.ParticipantSourceId    
            LEFT  JOIN sExamination.tAudiometry    AS A   ON A.SourceId = ED.Id    
            LEFT  JOIN sExamination.tAudiometryDetail AS AD ON AD.AudiomentryId = A.Id;

            CREATE NONCLUSTERED INDEX IX_tblExaminationAudiometrys_Exam ON #tblExaminationAudiometrys(ExaminationId);

            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)
);

            DECLARE @AudioInsert nvarchar(max) = N'
                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,
                    ISNULL(LeftPivot.AudiometryAcResultLeft, ''''),
                    ISNULL(LeftPivot.AudiometryResultRemarkLeft, ''''),
                    LeftPivot.[250],LeftPivot.[500],LeftPivot.[1000],LeftPivot.[2000],LeftPivot.[4000],LeftPivot.[6000],LeftPivot.[8000],
                    CASE WHEN RightPivot.IsDoneRight = 1 THEN ''TRUE'' ELSE ''FALSE'' END,
                    RightPivot.AudiometryAcResultRight,
                    RightPivot.AudiometryResultRemarkRight,
                    RightPivot.[250],RightPivot.[500],RightPivot.[1000],RightPivot.[2000],RightPivot.[4000],RightPivot.[6000],RightPivot.[8000]
                FROM
                (
                    SELECT pvt.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 AS 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
                ) AS LeftPivot
                INNER JOIN
                (
                    SELECT pvt.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 AS 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
                ) AS RightPivot
                ON LeftPivot.ExaminationId = RightPivot.ExaminationId;';
            EXEC sp_executesql @AudioInsert;

            CREATE NONCLUSTERED INDEX IX_tblAudiometry_aExamId ON #tblAudiometry(a_ExamId);
        END

        ------------------------------------------------------------
        -- MAIN RESULT TABLE (dynamic shape)
        ------------------------------------------------------------
-- Step 1: Create temp table with no (or minimal) columns
 DECLARE @lMainQuery NVARCHAR(MAX) = ''    

SELECT @lMainQuery = 
'CREATE TABLE ##tblMainTable ('+ @ReportCols 
+ CASE WHEN (@ReportCols <> '' AND @isAudiometry= 1) THEN ',' ELSE '' END 
+ CASE WHEN @isAudiometry = 1 THEN '    
 IsDoneLeft bit,AudiometryAcResultLeft varchar(200),AudiometryResultRemarkLeft varchar(200),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)'  
ELSE '' END 

+ CASE WHEN (@isAudiometry= 1 AND @isPulmonary = 1) THEN ',' 
       ELSE (CASE WHEN (@ReportCols <> '' AND @isPulmonary= 1) THEN ',' ELSE '' END) END 

+ CASE WHEN @isPulmonary = 1 THEN '    
 FVCPredicted varchar(200),FVCObserved varchar(200),PerOfPredictedFVC varchar(200),FEV1Predicted varchar(200),FEV1Observed varchar(200),    
 PerOfFEV1 varchar(200),PerOfFEV1ByFVC varchar(200),PulmonaryResult varchar(200))' 
ELSE ')' END    

EXEC(@lMainQuery);

 





        ------------------------------------------------------------
        -- INSERT MAIN DATA
        ------------------------------------------------------------
        ------------------------------------------------------------
-- Step 1: Create the temp table (base columns only)
------------------------------------------------------------


------------------------------------------------------------
-- Step 2: Add dynamic columns safely
------------------------------------------------------------
-- Step 1: Split and clean column names into a table
-- Step 1: Split @ReportColVal into individual column names

------------------------------------------------------------
-- Step 4: Build dynamic insert
------------------------------------------------------------
IF ISNULL(@ReportColVal,'') <> ''
BEGIN	
    DECLARE @InsertMain NVARCHAR(MAX) = N'
       insert into ##tblMainTable select ' + @ReportColVal +  (case when (@ReportColVal <> '' and @isAudiometry= 1) then ',' else '' end) + case when @isAudiometry = 1 then +    
 ' IsDoneLeft,AudiometryAcResultLeft,AudiometryResultRemarkLeft,L250,L500,    
 L1000,L2000,L4000,L6000,L8000,IsDoneRight,AudiometryAcResultRight,AudiometryResultRemarkRight,    
 R250,R500,R1000,R2000,R4000,R6000,R8000' Else ' ' END +  (case when (@isAudiometry= 1 and @isPulmonary = 1) then ',' else (case when (@ReportColVal <> '' and @isPulmonary= 1) then ',' else '' end) end) + case when @isPulmonary = 1 then +  ' FVCPredicted,
  
FVCObserved,PerOfPredictedFVC,FEV1Predicted,FEV1Observed,PerOfFEV1,PerOfFEV1ByFVC,    
 PulmonaryResult = P.PulmonaryResulIntensity + '' '' + P.PulmonaryResult ' else ' ' END +'     
     
 from #ExaminationDetail EA     
 left join #tblGeneral GE on EA.ExaminationId = GE.d_ExamId    
 left join #tblTests TE on EA.ExaminationId = TE.d_ExamId '     
 + case when @isAudiometry = 1 then +    
 ' left join #tblAudiometry AA on EA.ExaminationId = AA.a_ExamId '  Else ' ' END +'     
 left join sExamination.tPulmonary P on EA.ExaminationId = P.SourceId'
   
    EXEC sp_executesql @InsertMain;
END

----------------------------------------------------------
 --Step 5: Return results
----------------------------------------------------------
SELECT DISTINCT * 
FROM ##tblMainTable;


        ------------------------------------------------------------
        -- CLEANUP
        ------------------------------------------------------------
        DROP TABLE IF EXISTS #tmpTR;
        -- others dropped automatically at scope end; explicit not necessary but ok:
        -- DROP TABLE IF EXISTS #ExaminationDetail, #tblExaminationGeneralTemplates, #tblGeneral, #tblExaminationTests, #tblTests, #tblExaminationAudiometrys, #tblAudiometry, #ColumnTable, #ColumnTable1, #tblMainTable;

        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        --IF (XACT_STATE() <> 0) ROLLBACK TRANSACTION;
        ---- Optional: uncomment to debug
        --SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_LINE() AS ErrorLine, ERROR_PROCEDURE() AS ErrorProcedure;
        --SELECT 
        --ERROR_NUMBER() AS ErrorNumber,       -- The error number
        --ERROR_MESSAGE() AS ErrorMessage,     -- The detailed error message
        --ERROR_SEVERITY() AS ErrorSeverity,   -- The severity of the error
        --ERROR_STATE() AS ErrorState,         -- The state of the error
        --ERROR_LINE() AS ErrorLine,           -- The line where the error occurred
        --ERROR_PROCEDURE() AS ErrorProcedure  
		 SELECT -1 AS Result
    END CATCH
END
GO
PRINT N'Altering Procedure [sWellness].[pLastExaminationConsultationParameter]...';


GO

ALTER PROCEDURE [sWellness].[pLastExaminationConsultationParameter]
@rParticipantSourceTypeId int,
@rParticipantSourceId bigint,
@rOrgId int
as
begin   
	 Declare @rHeight nvarchar(10), @rWeight nvarchar(10), @rBMI nvarchar(10), 
	 @rBPSys nvarchar(10), @rBPDia nvarchar(10), @rHBA1C nvarchar(10), @rLDL nvarchar(10);
	 
	 set @rHeight = (select Top 1 CAST(Isnull(GTCD.ParameterValue,'') AS NVARCHAR(10)) AS Height from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tGeneralTemplateConsultation GTC ON GTC.SourceId = WC.Id
	 INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	 INNER JOIN sExamination.tGeneralTemplateParameter GTM ON GTM.Id = GTCD.GeneralTemplateParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and GTM.StaticGeneralTemplateParameterId = 502 and Isnull(CAST(GTCD.ParameterValue as float),0) > 0
	 order by WC.Id desc)

	 set @rWeight = (select Top 1 CAST(Isnull(GTCD.ParameterValue,'') AS NVARCHAR(10)) AS [Weight] from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tGeneralTemplateConsultation GTC ON GTC.SourceId = WC.Id
	 INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	 INNER JOIN sExamination.tGeneralTemplateParameter GTM ON GTM.Id = GTCD.GeneralTemplateParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and GTM.StaticGeneralTemplateParameterId = 501 and Isnull(CAST(GTCD.ParameterValue as float),0) > 0
	 order by WC.Id desc)

	 set @rBMI = (select Top 1 CAST(Isnull(GTCD.ParameterValue,'') AS NVARCHAR(10)) AS BMI from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tGeneralTemplateConsultation GTC ON GTC.SourceId = WC.Id
	 INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	 INNER JOIN sExamination.tGeneralTemplateParameter GTM ON GTM.Id = GTCD.GeneralTemplateParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and GTM.StaticGeneralTemplateParameterId = 503 and Isnull(CAST(GTCD.ParameterValue as float),0) > 0
	 order by WC.Id desc)

	 set @rBPSys = (select Top 1 CAST(Isnull(GTCD.ParameterValue,'') AS NVARCHAR(10)) AS BPSys from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tGeneralTemplateConsultation GTC ON GTC.SourceId = WC.Id
	 INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	 INNER JOIN sExamination.tGeneralTemplateParameter GTM ON GTM.Id = GTCD.GeneralTemplateParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and GTM.StaticGeneralTemplateParameterId = 506 and Isnull(CAST(GTCD.ParameterValue as float),0) > 0
	 order by WC.Id desc)
	 
	 set @rBPDia = (select Top 1 CAST(Isnull(GTCD.ParameterValue,'') AS NVARCHAR(10)) AS BPDia from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tGeneralTemplateConsultation GTC ON GTC.SourceId = WC.Id
	 INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	 INNER JOIN sExamination.tGeneralTemplateParameter GTM ON GTM.Id = GTCD.GeneralTemplateParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and GTM.StaticGeneralTemplateParameterId = 507 and Isnull(CAST(GTCD.ParameterValue as float),0) > 0
	 order by WC.Id desc)

	 set @rHBA1C = (select Top 1 CAST(Isnull(CTRD.ServiceValue,'') AS NVARCHAR(10)) AS HBA1C from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tConsultationTestRequest CTR ON CTR.SourceId = WC.Id
	 INNER JOIN sWellness.tConsultationTestRequestDetail CTRD ON CTRD.TestRequestId = CTR.Id
	 INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = CTRD.TestDetailId
	 INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and TPM.StaticTestParameterId = 25 and Isnull(CAST(CTRD.ServiceValue as float),0) > 0
	 order by WC.Id desc)
	 
	 set @rLDL = (select Top 1 CAST(Isnull(CTRD.ServiceValue,'') AS NVARCHAR(10)) AS LDL from sWellness.tWellnessConsultation WC
	 INNER JOIN sWellness.tConsultationTestRequest CTR ON CTR.SourceId = WC.Id
	 INNER JOIN sWellness.tConsultationTestRequestDetail CTRD ON CTRD.TestRequestId = CTR.Id
	 INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = CTRD.TestDetailId
	 INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
	 WHERE WC.ParticipantSourceId = @rParticipantSourceId and WC.ParticipantSourceTypeId = @rParticipantSourceTypeId
	 and TPM.StaticTestParameterId = 34 and Isnull(CAST(CTRD.ServiceValue as float),0) > 0
	 order by WC.Id desc)

	 IF (ISNULL(@rHeight,'') = '' AND ISNULL(@rWeight,'') = '')
	 BEGIN
		 Select Top 1 @rHeight=CAST(ISNULL(V.Height,0) AS NVARCHAR(10)),
						@rWeight=CAST(ISNULL(V.BodyWeight,0) AS NVARCHAR(10)),
						@rBMI=CAST(ISNULL(V.BMI,0) AS NVARCHAR(10)) 
		 FROM sExamination.tExamination E 
		 LEFT JOIN sExamination.tVital V ON V.SourceId = E.Id
		 where E.ParticipantSourceId = @rParticipantSourceId and E.ParticipantSourceTypeId = @rParticipantSourceTypeId
		 and E.SetupId <> [sCommon].[fGetIntIdForOrg](8, @rOrgId) 
		 and Isnull(V.Height,0)>0 and Isnull(V.BodyWeight,0)>0 and Isnull(V.BMI,0)>0
		 order by E.id desc
	 END
	 IF (ISNULL(@rBPSys,'') = '' AND ISNULL(@rBPDia,'') = '')
	 BEGIN
		 Select Top 1 @rBPSys=CAST(ISNULL(BloodPressureSystolic,0) AS NVARCHAR(10)), 
					  @rBPDia=CAST(ISNULL(BloodPressureDiastolic,0) AS NVARCHAR(10)) 
		 FROM sExamination.tExamination E 
		 LEFT JOIN sExamination.tVital V ON V.SourceId = E.Id
		 where E.ParticipantSourceId = @rParticipantSourceId and E.ParticipantSourceTypeId = @rParticipantSourceTypeId
		 and E.SetupId <> [sCommon].[fGetIntIdForOrg](8, @rOrgId)
		 and ISNUMERIC(V.BloodPressureSystolic) = 1 and ISNUMERIC(V.BloodPressureDiastolic) = 1
		 and Isnull(V.BloodPressureSystolic,0)>0 and Isnull(V.BloodPressureDiastolic,0)>0
		 order by E.id desc
	 END
	 IF (ISNULL(@rHBA1C,'') = '')
	 BEGIN
		 set @rHBA1C = (select Top 1 CAST(Isnull(TRD.ServiceValue,'') AS NVARCHAR(10)) AS HBA1C 
		 from sExamination.tExamination E
		 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 sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
		 WHERE E.ParticipantSourceId = @rParticipantSourceId and E.ParticipantSourceTypeId = @rParticipantSourceTypeId
		 and TPM.StaticTestParameterId = 25 and ISNUMERIC(TRD.ServiceValue) = 1
		 AND (CASE 
			  WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' 
			  		AND TRD.ServiceValue <> ''
			  THEN CAST(TRD.ServiceValue AS FLOAT)
			  ELSE 0
		 END) > 0
		 order by E.Id desc)
	 END
	 IF (ISNULL(@rLDL,'') = '')
	 BEGIN
		 set @rLDL = (select Top 1 CAST(Isnull(TRD.ServiceValue,'') AS NVARCHAR(10)) AS LDL 
		 from sExamination.tExamination E
		 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 sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
		 WHERE E.ParticipantSourceId = @rParticipantSourceId and E.ParticipantSourceTypeId = @rParticipantSourceTypeId
		 and TPM.StaticTestParameterId = 34 and ISNUMERIC(TRD.ServiceValue) = 1 
		 AND (CASE 
			  WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' 
			  		AND TRD.ServiceValue <> ''
			  THEN CAST(TRD.ServiceValue AS FLOAT)
			  ELSE 0
		 END) > 0
		 order by E.Id desc)
	 END

	 select @rHeight as Height, @rWeight as [Weight], @rBMI as BMI, 
			@rBPSys as BPSys, @rBPDia as BPDia,
			@rHBA1C as HBA1C, @rLDL as LDL;
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_ContractorId int,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,'',null,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, 
  e_ContractorId = JD.ContractorId 
  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,e_ContractorId      
   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,ContractorId    
   )      
   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,e_ContractorId
   );        
         
  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' 
              AND object_id = OBJECT_ID('sExamination.tTestRequestDetail'))      
  BEGIN
    DROP INDEX IX_tTestRequestDetail ON sExamination.tTestRequestDetail
  END     
  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(@lTestDetail1Id > 0)
   BEGIN
	   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      
   END
   
   IF(@lTestDetail2Id > 0)
   BEGIN
   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    
   END
   print @lVLDL      
   Print @lLDL      
   if @lConfValueAuto = 1      
   begin  
   IF(@lTestDetail3Id > 0)
   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      
    END  
	
	IF(@lTestDetail4Id > 0)
	BEGIN
		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
   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].[pOPDDashboard]...';


GO

ALTER PROCEDURE [sExamination].[pOPDDashboard]
(
	@rStoreLocationId int,
	@rParticipantTypeId int,
	@rCaseCauseId int,
	@rVisitTypeId int,
	@rShiftId int,
	@rLocationId int,
	@rFunctionId int,
	@rDepartmentGroupId int,
	@rDepartmentId int,
	@rGradeId int,
	@rDesignationId int,
	@rJobTitleId int=0,
	@rEmployeeTypeId int=0,
	@rCompanyId int=0,
	@rContractorId int,
	@rGenderId smallint,
	@rStatusId smallint,
	@rAgeFrom int,
	@rAgeTo int=100,
	@rFromDate datetime = null,
	@rToDate datetime = null,
	@rOrgId int,
	@rEmployeeCode nvarchar(50)='',
	@rUserId bigint
)
AS
BEGIN
SET NOCOUNT ON;

DECLARE @CurrentDate DATETIME = GETDATE();
DECLARE @ShiftTitle nvarchar(100) = '';
IF (@rShiftId > 0)
BEGIN
     set @ShiftTitle = (select Title from sCommon.tCompanyShiftMaster where Id = @rShiftId)
END

SELECT
	ED.Id AS ExaminationId,
	ED.StoreLocationId AS LocationId,
	ED.OrganizationDepartmentId,
	ISNULL(OD.Title,'N/A') AS DepartmentName,
	CM.Id AS CauseId,
	ISNULL(CM.Title,'N/A') AS CauseName,
	UL.UserId,
	U.DisplayTitle AS LoginTitle,
	ED.ParticipantSourceTypeId,
	CASE 
		WHEN ED.ParticipantSourceTypeId = 95 THEN PD.GenderId
		WHEN ED.ParticipantSourceTypeId = 1001 THEN EFD.GenderId
		ELSE BM.GenderId
	END AS GenderId,
	CASE 
		WHEN ED.ParticipantSourceTypeId = 95 THEN ISNULL(GM.Title,'Not Known')
		WHEN ED.ParticipantSourceTypeId = 1001 THEN 
			(SELECT ISNULL(Title,'Not Known') FROM sCommon.tGenderMaster WHERE Id = EFD.GenderId)
		ELSE (CASE WHEN OP.GenderId > 0 THEN (select ISNULL(Title,'Not Known') from sCommon.tGenderMaster where Id = OP.GenderId) ELSE ISNULL(GM2.Title,'Not Known') END)
	END AS Gender,
	CASE ED.ParticipantSourceTypeId
		WHEN 95 THEN ISNULL(ETM.Title,'NA')
		WHEN 1001 THEN 'Dependent'
		WHEN 1009 THEN ISNULL(BTM.Title,'NA')
	END AS ParticipantType,
	CASE ED.ParticipantSourceTypeId
		WHEN 95 THEN 'Employee'
		WHEN 1001 THEN 'Dependent'
		WHEN 1009 THEN 'Other'
	END AS EMPType,
	NM.Title AS Nationality,
	ISNULL(VTM.Title, 'Direct Consultation') as VisitType,
	[dbo].[fGetShift](OP.OPDTime,@rOrgId) as Shifts
INTO #BaseData
FROM sExamination.tExamination ED
LEFT JOIN sHrm.tEmployeeMaster EM ON ED.ParticipantSourceId = EM.Id AND ED.ParticipantSourceTypeId = 95
LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON ED.ParticipantSourceId = EFD.Id AND ED.ParticipantSourceTypeId = 1001
LEFT JOIN sHrm.tCsrBenefiterMaster BM ON BM.Id = ED.ParticipantSourceId AND ED.ParticipantSourceTypeId = 1009
LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
LEFT JOIN sHrm.tEmployeePersonalDetail PD ON EM.Id = PD.EmployeeId
LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = PD.GenderId
LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId

LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
LEFT JOIN sHrm.tEmployeeJobDetail EJD2 ON EFD.EmployeeId = EJD2.EmployeeId

LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM ON BM.CSRBenefiterTypeId = BTM.Id

LEFT JOIN sCommon.tOrganizationDepartmentMaster OD ON ED.OrganizationDepartmentId = OD.Id
LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON OD.DepartmentGroupId = DGM.Id
LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId = FM.Id

LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = ED.CauseId
LEFT JOIN sExamination.tOPD OP on ED.Id = OP.ExaminationId
LEFT JOIN sExamination.tVisitTypeMaster VTM on VTM.Id = OP.VisitTypeId
LEFT JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = ED.StoreLocationId
LEFT JOIN sSecurity.tUser U ON U.Id = ED.CreatedUserId
LEFT JOIN sHrm.tNationalityMaster NM ON PD.NationalityId = NM.Id

INNER JOIN sExamination.tSetupMaster SSM ON ED.SetupId = SSM.Id
INNER JOIN sExamination.tSubTypeMaster ST ON SSM.SubTypeId = ST.Id

WHERE 
	ST.MainTypeId = 8
	AND ISNULL(ED.IsCancel,0) = 0
	AND ED.OrgId = @rOrgId
	AND (
	@rEmployeeCode = '' OR
		(
			(ED.ParticipantSourceTypeId = 95 AND EM.Code = @rEmployeeCode)
			OR (ED.ParticipantSourceTypeId = 1001 AND EM2.Code = @rEmployeeCode)
			OR (ED.ParticipantSourceTypeId = 1009 AND BM.Code = @rEmployeeCode)
		)
	)
	AND (
	@rJobTitleId = 0 OR
		(
			(ED.ParticipantSourceTypeId = 95 AND EJD.EmployeeJobTitleId = @rJobTitleId)
			OR (ED.ParticipantSourceTypeId = 1001 AND EJD2.EmployeeJobTitleId = @rJobTitleId)
			OR (ED.ParticipantSourceTypeId = 1009)
		)
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId and ED.ParticipantSourceTypeId = 95)
		OR (EJD2.ContractorId = @rEmployeeTypeId and ED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND ED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(
		(EJD.ContractorId = @rContractorId and ED.ParticipantSourceTypeId = 95)
		OR (EJD2.ContractorId = @rContractorId and ED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND ED.ParticipantSourceTypeId = 1009)
		OR @rContractorId = 0
	)	
	AND (ED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND
	(
		(PD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 95)
		OR (EFD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1001)
		OR (BM.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1009)
		OR @rGenderId = 0
	)
	AND (EM.StatusId=@rStatusId OR @rStatusId=0)
	AND (@rDesignationId = 0 OR ED.EmployeeDesignationId = @rDesignationId)
	AND (@rDepartmentId = 0 OR ED.OrganizationDepartmentId = @rDepartmentId)
	AND (@rGradeId = 0 OR ED.GradeId = @rGradeId)
	AND (
		@rAgeTo = 0 OR
		(
			(ED.ParticipantSourceTypeId = 95 AND PD.DateOfBirth >= DATEADD(YEAR, -@rAgeTo, @CurrentDate))
			OR (ED.ParticipantSourceTypeId = 1001 AND EFD.DateOfBirth >= DATEADD(YEAR, -@rAgeTo, @CurrentDate))
			OR (ED.ParticipantSourceTypeId = 1009 AND BM.DateOfBirth >= DATEADD(YEAR, -@rAgeTo, @CurrentDate))
		)
	)
	AND (
		@rAgeFrom = 0 OR
		(
			(ED.ParticipantSourceTypeId = 95 AND PD.DateOfBirth <= DATEADD(YEAR, -@rAgeFrom, @CurrentDate))
			OR (ED.ParticipantSourceTypeId = 1001 AND EFD.DateOfBirth <= DATEADD(YEAR, -@rAgeFrom, @CurrentDate))
			OR (ED.ParticipantSourceTypeId = 1009 AND BM.DateOfBirth <= DATEADD(YEAR, -@rAgeFrom, @CurrentDate))
		)
	)
	AND (@rStoreLocationId = 0 OR ED.StoreLocationId = @rStoreLocationId)
	AND (@rDepartmentId = 0 OR ED.OrganizationDepartmentId = @rDepartmentId)
	AND (@rCaseCauseId = 0 OR ED.CauseId = @rCaseCauseId)
	AND (@rVisitTypeId = 0 OR OP.VisitTypeId = @rVisitTypeId)
	AND (@ShiftTitle = '' OR @ShiftTitle = [dbo].[fGetShift](OP.OPDTime,@rOrgId))
	AND (@rParticipantTypeId = 0 OR ED.ParticipantSourceTypeId = @rParticipantTypeId)
	AND (@rFunctionId = 0 OR FM.Id = @rFunctionId)
	AND (@rDepartmentGroupId = 0 OR DGM.Id = @rDepartmentGroupId)

	AND (@rFromDate IS NULL OR ED.ExaminationDate >= @rFromDate)
	AND (@rToDate IS NULL OR ED.ExaminationDate <= @rToDate)

	AND UL.UserId = @rUserId;

SELECT 
	B.LocationId,
	DSM.Title AS Disease,
	DSM.Id AS DiseaseId
INTO #Disease

FROM #BaseData B
INNER JOIN sExamination.tExaminDiseaseDetail EDD ON EDD.ExaminDiseaseId = B.ExaminationId AND EDD.IsObsolete = 0
INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = EDD.DiseaseId
INNER JOIN sExamination.tDiseaseSystemMaster DSM ON DSM.Id = DM.DiseaseSystemId;

SELECT 
	B.LocationId,
	DSI.Disease,
	DSI.DiseaseId
INTO #DiseaseUnique
FROM #BaseData B
INNER JOIN
(
	SELECT *
	FROM
	(
		SELECT 
			EDD.ExaminDiseaseId AS ExaminationId,
			DSM.Title AS Disease,
			DSM.Id AS DiseaseId,
			ROW_NUMBER() OVER (PARTITION BY EDD.ExaminDiseaseId ORDER BY EDD.Id DESC) rn
		FROM sExamination.tExaminDiseaseDetail EDD
		INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id = EDD.DiseaseId
		INNER JOIN sExamination.tDiseaseSystemMaster DSM ON DSM.Id = DM.DiseaseSystemId
		WHERE EDD.IsObsolete = 0
	) X
	WHERE rn = 1
) DSI ON DSI.ExaminationId = B.ExaminationId;

-- Participant
SELECT ParticipantType, COUNT(*) Cnt, EMPType
FROM #BaseData
GROUP BY ParticipantType, EMPType;

-- Department
SELECT DepartmentName, COUNT(*) DepartmentCnt
FROM #BaseData
GROUP BY DepartmentName;

-- Cause
SELECT CauseName, COUNT(*) CauseCnt
FROM #BaseData
GROUP BY CauseName;

-- User
SELECT LoginTitle, COUNT(*) UserCnt
FROM #BaseData
GROUP BY LoginTitle;

-- Gender
SELECT Gender, COUNT(*) Gendercnt
FROM #BaseData
GROUP BY Gender;

-- Total
SELECT COUNT(*) TotalExaminationId FROM #BaseData;

-- Disease
SELECT Disease, COUNT(*) DiseaseId
FROM #Disease
GROUP BY Disease;

-- Nationality
SELECT Nationality, COUNT(*) Nationalitycnt
FROM #BaseData
GROUP BY Nationality;

SELECT 
	ISNULL(Disease,'N/A') AS Disease,
	COUNT(ISNULL(DiseaseId,0)) AS DiseaseId
FROM #DiseaseUnique TM
INNER JOIN sIp.tStoreLocationMaster L ON TM.LocationId = L.Id
WHERE L.IsActiveHealth = 1
GROUP BY Disease
ORDER BY DiseaseId DESC;

-- VisitType
SELECT VisitType, COUNT(*) VisitTypecnt
FROM #BaseData
GROUP BY VisitType;

-- Shifts
SELECT Shifts, COUNT(*) Shiftscnt
FROM #BaseData
GROUP BY Shifts;

DROP TABLE #BaseData;
DROP TABLE #Disease;
DROP TABLE #DiseaseUnique;

END
GO
PRINT N'Altering Procedure [dbo].[CommanMisOpdDashboard]...';


GO

ALTER PROCEDURE [dbo].[CommanMisOpdDashboard]  
 @rStoreLocationId int = 0,  
 @rParticipantTypeId int = 0 ,  
 @rCaseCauseId int = 0, 
 @rVisitTypeId int,
 @rShiftId int,
 @rLocationId int = 0,  
 @rFunctionId int = 0,  
 @rDepartmentGroupId int = 0,  
 @rDepartmentId int = 0,  
 @rGradeId int = 0,  
 @rDesignationId int = 0,  
 @rJobTitleId int=0,  
 @rEmployeeTypeId int=0,  
 @rCompanyId int=0,  
 @rContractorId int = 0,  
 @rGenderId smallint,  
 @rStatusId int,  
 @rAgeFrom int,  
 @rAgeTo int=100,  
 @rFromDate datetime = null,  
 @rToDate datetime = null,  
 @rOrgId int,  
 @rEmployeeCode nvarchar(50)='',  
 @rUserId bigint = 0,  
 @rSectorId bigint = 0,  
 @rVerticalId bigint = 0,  
 @rCompnayGroupId bigint = 0  ,
 @rTargetGroupIds Nvarchar(Max) = ''
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON BEGIN  

DECLARE @ShiftTitle nvarchar(100) = '';
IF (@rShiftId > 0)
BEGIN
     set @ShiftTitle = (select Title from sCommon.tCompanyShiftMaster where Id = @rShiftId)
END

 SELECT SLM.Title,(select isnull(convert(decimal(18,2),Sum(Amount)),0) as 'Other Expance'  
 from sAccounting.tExpense SA where SA.StoreLocationId = SLM.Id  And  ((SA.ExpenseDate >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((SA.ExpenseDate <= (@rToDate) ) OR (ISNULL(@rToDate, '') = ''))) as 'Other Expance',  
 (select isnull(convert(decimal(18,2),Sum(Amount)),0) as TotalVehicleExpance  
 from sSupport.tVehicleMaintenance Vm  
 inner join sSupport.tVehicleMaintenanceDetail vmd on vmd.VehicleMaintenanceId = vm.id  
 where vm.StoreLocationId = SLM.Id And ((Vm.MaintenanceDate >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((Vm.MaintenanceDate <= (@rToDate) ) OR (ISNULL(@rToDate, '') = ''))) as 'Vehicle Expance',  
 (select isnull(convert(decimal(18,2),Sum(Amount)),0) as BioMedicalExpance  
 from sSupport.tBioMedicalWaste SB where SB.StoreLocationId = SLM.Id  And ((SB.CollectionDate >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((SB.CollectionDate <= (@rToDate) ) OR (ISNULL(@rToDate, '') = ''))) as 'Bio-Medical Expance',  
 (select isnull(convert(decimal(18,2),Sum(MaintenenceCost)),0) as 'MaintenenceExpance'  
   
   
 from sAssetManagement.tMaintenence AM where AM.StoreLocationId = SLM.ID  And ((AM.MaintenenceDate >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((AM.MaintenenceDate <= (@rToDate) ) OR (ISNULL(@rToDate, '') = ''))) as MaintenenceExpance,  
 (select isnull(convert(decimal(18,2),Sum(( isnull(SIB.Quantity,0) - isnull(innercount.RetQty,0 ) ) * isnull(WeightedAverageCost,1))),0) as 'First Aid Expance'  
 from sProcurement.tStockIssue SI   
 inner join sProcurement.tStockIssueDetail SIDT on SIDT.StockIssueId = SI.Id  
 left join sProcurement.tStockIssueBatch SIB on SIB.StockIssueDetailId = SIDT.Id  
 left join sIp.tStockItemPlanning SIP on SIP.StockItemId = SIDT.StockItemId and SIP.StoreLocationId = SI.FromStoreLocationId  
 left join (   
   
 select sum(isnull(SRB.ReturnQuantity,0)) as 'RetQty',SRB.StockIssueBatchId    
 from  sProcurement.tStockIssueReturn SIR   
 inner join  sProcurement.tStockIssueReturnBatch  SRB on SRB.StockIssueReturnId = SIR.Id    
 group by  SRB.StockIssueBatchId ) as innercount on innercount.StockIssueBatchId = SIB.Id  
 where SI.FromStoreLocationId = SLM.Id And ((convert(date,SI.CreatedDateTime) >= convert(Date,@rFromDate) ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((convert(date,SI.CreatedDateTime) <= convert(Date,@rToDate) ) OR (ISNULL(@rToDate, '') = ''))  
 and OtherLocationSourceTypeId is not null and OtherLocationSourceTypeId  in (120) and OtherLocationSourceTypeId not in(0)) as 'First Aid Expance',
   
 (select isnull(convert(decimal(18,2),Sum(( isnull(SIB.Quantity,0) - isnull(innercount.RetQty,0 ) ) * isnull(WeightedAverageCost,1))),0) as 'Ambulance Medicine'  
 from sProcurement.tStockIssue SI   
 inner join sProcurement.tStockIssueDetail SIDT on SIDT.StockIssueId = SI.Id  
 left join sProcurement.tStockIssueBatch SIB on SIB.StockIssueDetailId = SIDT.Id  
 left join sIp.tStockItemPlanning SIP on SIP.StockItemId = SIDT.StockItemId and SIP.StoreLocationId = SI.FromStoreLocationId  
 left join ( select sum(isnull(SRB.ReturnQuantity,0)) as 'RetQty',SRB.StockIssueBatchId    
 from  sProcurement.tStockIssueReturn SIR   
 inner join  sProcurement.tStockIssueReturnBatch  SRB on SRB.StockIssueReturnId = SIR.Id    
 group by  SRB.StockIssueBatchId ) as innercount on innercount.StockIssueBatchId = SIB.Id  
 where SI.FromStoreLocationId = SLM.Id And ((convert(date,SI.CreatedDateTime) >= convert(Date,@rFromDate) ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((convert(date,SI.CreatedDateTime) <= convert(Date,@rToDate) ) OR (ISNULL(@rToDate, '') = ''))  
 and OtherLocationSourceTypeId is not null and OtherLocationSourceTypeId  in (121) and OtherLocationSourceTypeId not in(0)) as 'Ambulance Medicine',  
   
   
 (select isnull(convert(decimal(18,2),Sum(( isnull(SIB.Quantity,0) - isnull(innercount.RetQty,0 ) ) * isnull(WeightedAverageCost,1))),0)   
 as 'Other Stock Issue'  
 from sProcurement.tStockIssue SI   
 inner join sProcurement.tStockIssueDetail SIDT on SIDT.StockIssueId = SI.Id  
 left join sProcurement.tStockIssueBatch SIB on SIB.StockIssueDetailId = SIDT.Id  
 --inner join  (  
 -- Select isnull(WeightedAverageCost,1) as 'WeightedAverageCost',SIB.Id from sIp.tWeightedAverageCostLog SIPD   
 -- inner join sProcurement.tStockIssueBatch SIB  ON SIPD.SourceId = SIB.Id and SIPD.SourceTypeId = 51  
 -- )  as ABC on   ABC.Id = SIB.Id  
 left join sIp.tStockItemPlanning SIP on SIP.StockItemId = SIDT.StockItemId   and SIP.StoreLocationId = SI.FromStoreLocationId  
 left join ( select sum(isnull(SRB.ReturnQuantity,0)) as 'RetQty',SRB.StockIssueBatchId    
 from  sProcurement.tStockIssueReturn SIR   
 inner join  sProcurement.tStockIssueReturnBatch  SRB on SRB.StockIssueReturnId = SIR.Id    
 group by  SRB.StockIssueBatchId ) as innercount on innercount.StockIssueBatchId = SIB.Id  
 where SI.FromStoreLocationId = SLM.Id   
 And ((convert(date,SI.CreatedDateTime) >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))  
 AND ((convert(date,SI.CreatedDateTime) <= (@rToDate) ) OR (ISNULL(@rToDate, '') = ''))  
 and OtherLocationSourceTypeId is not null and OtherLocationSourceTypeId  in (122) and OtherLocationSourceTypeId not in(0)) as 'Other Stock Issue'  
   
 ,  
 (SELECT ISNULL(convert(decimal(18,2),SUM((DB.Quantity - DB.ReturnQuantity) * DB.UnitCost)),0) as 'MedicineExpance'  
 FROM sExamination.tPrescription P INNER JOIN sExamination.tPrescriptionDetail PD ON PD.PrescriptionId = P.Id  
 INNER JOIN sPharmacy.tDispense D ON D.PrescriptionDetailId=PD.Id INNER JOIN sPharmacy.tDispenseBatch DB ON DB.DispenseId = D.Id  
 INNER JOIN sExamination.tExamination EAED ON P.SourceId=EAED.Id  
 INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = EAED.StoreLocationId AND UL.UserId = @rUserId  
 INNER JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserId where EAED.StoreLocationId = SLM.Id  
 and ISNULL(convert(decimal(18,2),(DB.Quantity - DB.ReturnQuantity) * DB.UnitCost),0) > 0 --Shivam DT-13/06/23; id - 25595
 and ((EAED.ExaminationDate >= @rFromDate ) OR (ISNULL(@rFromDate, '') = ''))  
 and ((EAED.ExaminationDate <= (@rToDate) ) OR (ISNULL(@rToDate, '') = ''))) as 'Medicine Expance'  
 
 from sIp.tStoreLocationMaster SLM  
 INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id  
 WHERE  
  UL.UserId =@rUserId   
 AND SLM.OrgId=@rOrgId And ((SLM.Id  = @rStoreLocationId ) OR (ISNULL(@rStoreLocationId, '') = ''))  
 And SLM.IsActiveHealth='1'   AND SLM.IsOPDSetup = 1 AND   SLM.IsObsolete=0   order by SLM.Title asc    
 
 CREATE TABLE #TempTable  
 (  
  ExaminationId  bigint,DepartmentName nvarchar(150),OrganizationDepartmentId int,ParticipantCode nvarchar(50),  
  ParticipantName nvarchar(300),GenderId tinyint,Gender nvarchar(20),CauseId int,CauseName nvarchar(100),  
  ParticipantType nvarchar(100),ParticipantSourceTypeId smallint,EMPType nvarchar(100),LoginTitle nvarchar(100),  
  UserId bigint,LocationId int,Disease varchar(200),DiseseSystem varchar(200),DiseaseId bigint  
 )  
 INSERT INTO #TempTable  
 (  
  ExaminationId,DepartmentName,OrganizationDepartmentId,ParticipantCode,ParticipantName,GenderId,Gender,  
  CauseId,CauseName,ParticipantType,ParticipantSourceTypeId,EMPType,LoginTitle,UserId,LocationId,Disease,DiseseSystem,DiseaseId  
 )  
 SELECT ED.Id AS ExaminationId,  
 ODM.Title AS DepartmentName,  
 ED.OrganizationDepartmentId,  
 ParticipantCode = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,  
 ParticipantName = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')  
 WHEN 1001 THEN EFD.Name WHEN 1009 THEN  
  CASE WHEN isnull(O.OtherName,'') <> '' THEN O.OtherName   
  ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END,  
 GenderId = CASE ED.ParticipantSourceTypeId  
 WHEN 95 THEN EPD.GenderId  
 WHEN 1001 THEN ISNULL([sCommon].[fGenderIdFromRelationIdGet](EFD.RelationshipId),'')  
 WHEN 1009 THEN BM.GenderId END,  
 Gender = CASE ED.ParticipantSourceTypeId  
 WHEN 95 THEN GM1.Title  
 WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')  
 WHEN 1009 THEN GM2.Title END,  
 CM.Id As CauseId,  
 CM.Title As CauseName,  
 ParticipantType = CASE ED.ParticipantSourceTypeId WHEN 95 THEN ETM.Title WHEN 1001 THEN 'Dep' WHEN 1009 THEN BTM.Code END,  
 ParticipantSourceTypeId,  
 CASE ParticipantSourceTypeId WHEN 95 THEN 'Employee' WHEN 1001 THEN 'Dep' WHEN 1009 THEN 'Oth' END AS EMPType,  
 U.LoginTitle,  
 UL.UserId,  
 ED.StoreLocationId,  
 DM.Title AS Disease,  
 ISNULL(DS.Title,'Blank') AS DiseseSystem,  
 DM.Id AS DiseaseId  
 FROM sExamination.tExamination ED   
 INNER JOIN sExamination.tExaminDisease ED1 ON ED1.SourceId=ED.Id  
 INNER JOIN sExamination.tExaminDiseaseDetail EDD ON EDD.ExaminDiseaseId = ED1.Id  
 INNER JOIN sExamination.tDiseaseMaster DM ON DM.Id=EDD.DiseaseId   
 INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = ED.StoreLocationId  
 INNER JOIN sSecurity.tUser U ON U.Id = ED.CreatedUserId  
 INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = ED.SetupId  
 INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id  
 INNER JOIN sIp.tStoreLocationMaster SLM on ED.StoreLocationId = SLM.Id  
   
 LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = ED.CauseId and CM.OrgId = @rOrgId  
 LEFT JOIN sHrm.tEmployeeCompanyMaster ECM on ED.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 sHrm.tEmployeeMaster EM on ED.ParticipantSourceId = EM.Id and ED.ParticipantSourceTypeId = 95  
 LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId  
 LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on ED.ParticipantSourceId = EFD.Id and ED.ParticipantSourceTypeId = 1001  
 LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id   
 LEFT JOIN sHrm.tCsrBenefiterMaster BM on ED.ParticipantSourceId = BM.Id and ED.ParticipantSourceTypeId = 1009  
 LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CsrBenefiterTypeId = BTM.Id  
 LEFT JOIN sHrm.tEmployeeJobDetail EJD on EM.Id = EJD.EmployeeId  
 LEFT JOIN sHrm.tEmployeeJobDetail EJD2 on EM2.Id = EJD2.EmployeeId  
 LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM on ED.OrganizationDepartmentId = ODM.Id  
 LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON ODM.DepartmentGroupId = DGM.Id   
 LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id  
 LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId  
 LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId   
 LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId  
 LEFT JOIN sExamination.tDiseaseSystemMaster DS ON DS.Id = DM.DiseaseSystemId  
 LEFT JOIN sExamination.tOPD O ON O.ExaminationId = ED.Id  
     
 WHERE STM.MainTypeId = 8 and isnull(IsCancel,0) = 0 -- 7 for caselist  
 AND ED1.IsObsolete = 0  
 AND EDD.IsObsolete = 0  
 AND ((ED.StoreLocationId = @rStoreLocationId)OR @rStoreLocationId=0)  
 AND  
 (  
  (EM.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EM2.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (BM.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  @rEmployeeCode = ''  
 )  
 AND (ED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)  
 AND(ED.GradeId=@rGradeId OR @rGradeId=0)  
 AND(ED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)  
 AND  
 (  
  (EJD.EmployeeJobTitleId = @rJobTitleId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EJD2.EmployeeJobTitleId = @rJobTitleId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (0 = 0 AND ED.ParticipantSourceTypeId = 1009)  
  OR @rJobTitleId = 0  
 )  
 AND  
 (  
  (EJD.EmployeeTypeId = @rEmployeeTypeId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EJD2.EmployeeTypeId = @rEmployeeTypeId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (0 = 0 AND ED.ParticipantSourceTypeId = 1009)  
  OR @rEmployeeTypeId = 0  
 )   
 AND  
 (     
  (EJD.ContractorId = @rContractorId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EJD2.ContractorId = @rContractorId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (0 = 0 AND ED.ParticipantSourceTypeId = 1009)  
  OR @rContractorId=0  
 )  
 AND(ED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)  
 AND  
 (  
  (EPD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EFD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (BM.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1009)  
  OR @rGenderId=0  
 )  
 AND(ED.EmployeeStatusId=@rStatusId OR @rStatusId=0)  
 AND  
 (  
  (isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND ED.ParticipantSourceTypeId = 1009)  
  OR ISNULL(@rAgeTo,0)=0  
 )  
 AND  
 (  
  (isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND ED.ParticipantSourceTypeId = 1009)     
  OR ISNULL(@rAgeFrom,0)=0  
 )  
 AND ((ED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((ED.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))  
 --AND (SLM.LocationId = @rLocationId or @rLocationId = 0)  
 AND (ED.OrgId =  @rOrgId)  
 AND ((ED.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))  
 AND (@rVisitTypeId = 0 OR O.VisitTypeId = @rVisitTypeId)
 AND (@ShiftTitle = '' OR @ShiftTitle = [dbo].[fGetShift](O.OPDTime,@rOrgId))
 AND ((ED.ParticipantSourceTypeId=@rParticipantTypeId) or (@rParticipantTypeId=0))  
 AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)  
 AND (FM.Id = @rFunctionId OR @rFunctionId = 0)  
 and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)  
 and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)  
 and (VM.SectorId = @rSectorId or @rSectorId = 0)  
 AND UL.UserId = @rUserId  
 AND ((ED.TargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupIds,',') )) or @rTargetGroupIds='') --Nidhi DT-17/01/23; id - 22910
  
   CREATE TABLE #TempTableNew  
 (  
  ExaminationId  bigint,DepartmentName nvarchar(150),OrganizationDepartmentId int,ParticipantCode nvarchar(50),  
  ParticipantName nvarchar(300),GenderId tinyint,Gender nvarchar(20),CauseId int,CauseName nvarchar(100),  
  ParticipantType nvarchar(100),ParticipantSourceTypeId smallint,EMPType nvarchar(100),LoginTitle nvarchar(100),  
  UserId bigint,LocationId int,VisitType nvarchar(100),Shifts nvarchar(100),FurtherAction nvarchar(100)  
 )  
 INSERT INTO #TempTableNew
 (  
  ExaminationId,DepartmentName,OrganizationDepartmentId,ParticipantCode,ParticipantName,GenderId,Gender,  
  CauseId,CauseName,ParticipantType,ParticipantSourceTypeId,EMPType,LoginTitle,UserId,LocationId,VisitType,
  Shifts, FurtherAction
 )  
   
 SELECT ED.Id AS ExaminationId,  
 ODM.Title AS DepartmentName,  
 ED.OrganizationDepartmentId,  
 ParticipantCode = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,  
 ParticipantName = CASE ED.ParticipantSourceTypeId WHEN 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')  
 WHEN 1001 THEN EFD.Name WHEN 1009 THEN  
  CASE WHEN isnull(O.OtherName,'') <> '' THEN O.OtherName   
  ELSE BM.FirstName + ' ' + isnull(BM.LastName,'') END END,  
 GenderId = CASE ED.ParticipantSourceTypeId  
 WHEN 95 THEN EPD.GenderId  
 WHEN 1001 THEN ISNULL([sCommon].[fGenderIdFromRelationIdGet](EFD.RelationshipId),'')  
 WHEN 1009 THEN BM.GenderId END,  
 Gender = CASE ED.ParticipantSourceTypeId  
 WHEN 95 THEN GM1.Title  
 WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')  
 WHEN 1009 THEN GM2.Title END,  
 CM.Id As CauseId,  
 CM.Title As CauseName,  
 ParticipantType = CASE ED.ParticipantSourceTypeId WHEN 95 THEN ETM.Title WHEN 1001 THEN 'Dep' WHEN 1009 THEN 'Oth' END,  
 ParticipantSourceTypeId,  
 CASE ParticipantSourceTypeId WHEN 95 THEN 'Employee' WHEN 1001 THEN 'Dep' WHEN 1009 THEN 'Oth' END AS EMPType,  
 U.LoginTitle,  
 UL.UserId,  
 ED.StoreLocationId, 
 ISNULL(VTM.Title, 'Direct Consultation') as VisitType, [dbo].[fGetShift](O.OPDTime,@rOrgId) as Shifts,
 FAM.Title as FurtherAction
 FROM sExamination.tExamination ED   
 INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = ED.StoreLocationId  
 INNER JOIN sSecurity.tUser U ON U.Id = ED.CreatedUserId  
 INNER JOIN sExamination.tSetupMaster SMM on SMM.Id = ED.SetupId  
 INNER JOIN sExamination.tSubTypeMaster STM on SMM.SubTypeId = STM.Id 
 INNER JOIN sIp.tStoreLocationMaster SLM on ED.StoreLocationId = SLM.Id   
 INNER JOIN sExamination.tCauseMaster CM ON CM.Id = ED.CauseId and CM.OrgId = @rOrgId  
 LEFT JOIN sHrm.tEmployeeCompanyMaster ECM on ED.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 sHrm.tEmployeeMaster EM on ED.ParticipantSourceId = EM.Id and ED.ParticipantSourceTypeId = 95  
 LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId  
 LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on ED.ParticipantSourceId = EFD.Id and ED.ParticipantSourceTypeId = 1001  
 LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id   
 LEFT JOIN sHrm.tCsrBenefiterMaster BM on ED.ParticipantSourceId = BM.Id and ED.ParticipantSourceTypeId = 1009  
 LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CsrBenefiterTypeId = BTM.Id  
 LEFT JOIN sHrm.tEmployeeJobDetail EJD on EM.Id = EJD.EmployeeId  
 LEFT JOIN sHrm.tEmployeeJobDetail EJD2 on EM2.Id = EJD2.EmployeeId  
 LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM on ED.OrganizationDepartmentId = ODM.Id  
 LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON ODM.DepartmentGroupId = DGM.Id   
 LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id  
 LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId  
 LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId   
 LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId  
 LEFT JOIN sExamination.tOPD O ON O.ExaminationId = ED.Id
 LEFT JOIN sExamination.tVisitTypeMaster VTM ON VTM.Id = O.VisitTypeId
 LEFT JOIN sSafety.tFurtherActionMaster FAM ON FAM.Id = O.FurtherActionId     
 WHERE STM.MainTypeId = 8 and isnull(IsCancel,0) = 0 -- 7 for caselist   
 AND ((ED.StoreLocationId = @rStoreLocationId)OR @rStoreLocationId=0)  
 AND   
 (  
  (EM.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EM2.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (BM.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  @rEmployeeCode = ''  
 )  
 AND (ED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)  
 AND(ED.GradeId=@rGradeId OR @rGradeId=0)  
 AND(ED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)  
 AND  
 (  
  (EJD.EmployeeJobTitleId = @rJobTitleId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EJD2.EmployeeJobTitleId = @rJobTitleId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (0 = 0 AND ED.ParticipantSourceTypeId = 1009)  
  OR @rJobTitleId = 0  
 )  
 AND  
 (  
  (EJD.EmployeeTypeId = @rEmployeeTypeId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EJD2.EmployeeTypeId = @rEmployeeTypeId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (0 = 0 AND ED.ParticipantSourceTypeId = 1009)  
  OR @rEmployeeTypeId = 0  
 )   
 AND  
 (     
  (EJD.ContractorId = @rContractorId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EJD2.ContractorId = @rContractorId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (0 = 0 AND ED.ParticipantSourceTypeId = 1009)  
  OR @rContractorId=0  
 )  
 AND(ED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)  
 AND  
 (  
  (EPD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (EFD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (BM.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1009)  
  OR @rGenderId=0  
 )  
 AND(ED.EmployeeStatusId=@rStatusId OR @rStatusId=0)  
 AND  
 (  
  (isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) <= @rAgeTo AND ED.ParticipantSourceTypeId = 1009)  
  OR ISNULL(@rAgeTo,0)=0  
 )  
 AND  
 (  
  (isnull(DATEDIFF(yy,EPD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND ED.ParticipantSourceTypeId = 95)  
  OR  
  (isnull(DATEDIFF(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND ED.ParticipantSourceTypeId = 1001)  
  OR  
  (isnull(DATEDIFF(yy,BM.DateOfBirth,sCommon.fGetDate()),0) >= @rAgeFrom AND ED.ParticipantSourceTypeId = 1009)     
  OR ISNULL(@rAgeFrom,0)=0  
 )  
 AND ((ED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((ED.ExaminationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))  
 --AND (SLM.LocationId = @rLocationId or @rLocationId = 0)  
 AND (ED.OrgId =  @rOrgId)  
 AND ((ED.CauseId=@rCaseCauseId )or (@rCaseCauseId=0))  
 AND (@rVisitTypeId = 0 OR O.VisitTypeId = @rVisitTypeId)
 AND (@ShiftTitle = '' OR @ShiftTitle = [dbo].[fGetShift](O.OPDTime,@rOrgId))
 AND ((ED.ParticipantSourceTypeId=@rParticipantTypeId) or (@rParticipantTypeId=0))  
 AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)  
 AND (FM.Id = @rFunctionId OR @rFunctionId = 0)  
 and (ECM.CompanyGroupId = @rCompnayGroupId or @rCompnayGroupId = 0)  
 and (CG.VerticalId = @rVerticalId or @rVerticalId = 0)  
 and (VM.SectorId = @rSectorId or @rSectorId = 0)  
 AND UL.UserId = @rUserId 
 AND ((ED.TargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupIds,',') )) or @rTargetGroupIds='') --Nidhi DT-17/01/23; id - 22910
  
   
 SELECT SLM.Title,(select Count(*) as 'Oth' from #TempTableNew T where T.EMPType='Oth'  
 and t.LocationId = SLM.id And SLM.IsActiveHealth='1' AND SLM.IsOpdSetup = 1 and T.ParticipantType is not null ) as 'Oth',  
 (select Count(*) as 'Employee' from #TempTableNew T where T.EMPType='Employee' and T.LocationId = SLM.id  
 And SLM.IsActiveHealth='1' AND SLM.IsOpdSetup = 1 and T.ParticipantType is not null ) as 'Employee',  
 (select Count(*) as 'Dep' from #TempTableNew T where T.EMPType='Dep' and T.LocationId = SLM.id And SLM.IsActiveHealth='1'  
 AND SLM.IsOpdSetup = 1 and T.ParticipantType is not null ) as 'Dep'   
 from sIp.tStoreLocationMaster SLM  
 INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id  
  WHERE UL.UserId =@rUserId AND SLM.OrgId=@rOrgId  
 And ((SLM.Id  = @rStoreLocationId ) OR (ISNULL(@rStoreLocationId, '') = '')) And SLM.IsActiveHealth='1' AND SLM.IsOpdSetup = 1  
 order by SLM.Title asc
  
 declare @query varchar(max)='',@cols varchar(max)  
      
 select @cols = STUFF((SELECT Distinct ',' + QUOTENAME(CASE ParticipantSourceTypeId WHEN 95 THEN T.Title WHEN 1001 THEN 'Dep' WHEN 1009 THEN 'Oth' end)   
    from sExamination.tExamination E  
    left join sHrm.tEmployeeMaster M on E.ParticipantSourceId = M.Id and E.ParticipantSourceTypeId = 95  
    inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id  
    inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id  
    left join sHrm.tEmployeeJobDetail J on J.EmployeeId = M.Id  
    left join sHrm.tEmployeeTypeMaster T on J.EmployeeTypeId = T.Id   
    where E.OrgId = @rOrgId and MainTypeId = 8 and isnull(IsCancel,0) = 0 group by T.Title,  
    ParticipantSourceTypeId FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')    
   
 if @cols <> ''  
 begin   
  select @query = @query + 'SELECT * FROM  
  (  
   SELECT L.Title,ParticipantType AS ''ParticipantType'',COUNT(Isnull(ParticipantType,0)) AS Cnt  
   FROM #TempTableNew TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY ParticipantType,TM.LocationId,L.Title  
  ) as s  
  PIVOT  
  (  
   max(Cnt) FOR ParticipantType IN (' + @cols + ')  
  )AS pvt'  
  exec (@query)  
 end
 ELSE
 BEGIN
	select 0 as Result
 END
   
 declare @query11 varchar(max)='',@cols11 varchar(max)  
       
    select @cols11 = STUFF((SELECT Distinct ',' + QUOTENAME(CauseName) from #TempTableNew FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
  
    if @cols11 <> ''  
 begin   
  select @query11 = @query11 + 'SELECT * FROM  
  (  
   SELECT  L.Title ,CauseName AS CauseName,COUNT(Isnull(CauseId,0)) AS CauseCnt  
   FROM #TempTableNew TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where CauseName is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY CauseName,L.Title  
  ) as s  
  PIVOT  
  (  
   max(CauseCnt) FOR CauseName IN (' + @cols11 + ')  
  )AS pvt'  
  exec (@query11)  
 end 
 ELSE
 BEGIN
	select 0 as Result
 END
   
 declare @query2 varchar(max)='',@cols2 varchar(max)  
      
    select @cols2 = STUFF((SELECT Distinct ',' + QUOTENAME(CauseName) from #TempTableNew where CauseName is not null  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
    if @cols2 <> ''  
 begin   
  select @query2 = @query2 + 'SELECT * FROM  
  (  
   SELECT  L.Title ,CauseName AS CauseName,CauseId  
   FROM #TempTableNew TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where CauseName is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY CauseName,L.Title,CauseId  
  ) as s  
  PIVOT  
  (  
   max(CauseId) FOR CauseName IN (' + @cols2 + ')  
  )AS pvt'  
  exec (@query2)  
 end
 ELSE
 BEGIN
	select 0 as Result
 END
   
 declare @query3 varchar(max)='',@cols3 varchar(max)  
      
    select @cols3 = STUFF((SELECT Distinct ',' + QUOTENAME(DiseseSystem) from #TempTable where DiseseSystem is not null  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
 if @cols3 <> ''  
 begin   
  select @query3 = @query3 + 'SELECT * FROM  
  (  
   SELECT  L.Title ,DiseseSystem AS DiseseSystem,COUNT(Isnull(DiseaseId,0)) AS DiseaseCnt  
   FROM #TempTable TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where DiseseSystem is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY DiseseSystem,L.Title  
  ) as s  
  PIVOT  
  (  
   max(DiseaseCnt) FOR DiseseSystem IN (' + @cols3 + ')  
  )AS pvt'  
  exec (@query3)  
 end
 ELSE
 BEGIN
	select 0 as Result
 END
    
 declare @query4 varchar(max)='',@cols4 varchar(max)  
      
    select @cols4 = STUFF((SELECT Distinct ',' + QUOTENAME(DiseseSystem) from #TempTable where DiseseSystem is not null  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
 if @cols4 <> ''  
 begin   
  select @query4 = @query4 + 'SELECT * FROM  
  (  
   SELECT  L.Title ,DiseseSystem AS DiseseSystem,DiseaseId  
   FROM #TempTable TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where DiseseSystem is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY DiseseSystem,L.Title,DiseaseId  
  ) as s  
  PIVOT  
  (  
   max(DiseaseId) FOR DiseseSystem IN (' + @cols4 + ')  
  )AS pvt'  
  exec (@query4)  
 end
 ELSE
 BEGIN
	select 0 as Result
 END
   
 SELECT SLM.Title,(select Count(*) as 'High Risk' from #TempTableNew T
					Inner Join sExamination.tExamination EXM on EXM.Id = T.ExaminationId
  where ISNULL(EXM.RiskCategoryId, 0) = 1 and t.LocationId = SLM.id) as 'High Risk',
 (select Count(*) as 'Pediatric' from #TempTableNew T
	Inner Join sExamination.tOPD OPD on OPD.ExaminationId = T.ExaminationId
  where ISNULL(OPD.IsPediatric, 0) = 1 and t.LocationId = SLM.id) as 'Pediatric'
 from sIp.tStoreLocationMaster SLM  
 INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SLM.Id  
  WHERE UL.UserId =@rUserId AND SLM.OrgId=@rOrgId  
 And ((SLM.Id  = @rStoreLocationId ) OR (ISNULL(@rStoreLocationId, '') = '')) And SLM.IsActiveHealth='1' AND SLM.IsOpdSetup = 1  
 order by SLM.Title asc
   
declare @query5 varchar(max)='',@cols5 varchar(max)  
      
    select @cols5 = STUFF((SELECT Distinct ',' + QUOTENAME(VisitType) from #TempTableNew where VisitType is not null  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
 if @cols5 <> ''  
 begin   
  select @query5 = @query5 + 'SELECT * FROM  
  (  
   SELECT L.Title, VisitType AS VisitType,COUNT(VisitType) AS VisitTypeCnt  
   FROM #TempTableNew TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where VisitType is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY VisitType,L.Title  
  ) as s
  PIVOT  
  (  
   max(VisitTypeCnt) FOR VisitType IN (' + @cols5 + ')  
  )AS pvt'
  exec (@query5)
 end
 ELSE
 BEGIN
	select 0 as Result
 END

 declare @query6 varchar(max)='',@cols6 varchar(max)  
      
    select @cols6 = STUFF((SELECT Distinct ',' + QUOTENAME(Shifts) from #TempTableNew where Shifts is not null  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
 if @cols6 <> ''  
 begin   
  select @query6 = @query6 + 'SELECT * FROM  
  (  
   SELECT L.Title, Shifts AS Shifts,COUNT(Shifts) AS ShiftsCnt  
   FROM #TempTableNew TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where Shifts is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY Shifts,L.Title  
  ) as s
  PIVOT  
  (  
   max(ShiftsCnt) FOR Shifts IN (' + @cols6 + ')  
  )AS pvt'
  exec (@query6)
 end
 ELSE
 BEGIN
	select 0 as Result
 END

  declare @query7 varchar(max)='',@cols7 varchar(max)  
      
    select @cols7 = STUFF((SELECT Distinct ',' + QUOTENAME(FurtherAction) from #TempTableNew where FurtherAction is not null  
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')  
      
 if @cols7 <> ''  
 begin   
  select @query7 = @query7 + 'SELECT * FROM  
  (  
   SELECT L.Title, FurtherAction AS FurtherAction,COUNT(FurtherAction) AS FurtherActionCnt  
   FROM #TempTableNew TM inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id  
   where FurtherAction is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1 GROUP BY FurtherAction,L.Title  
  ) as s
  PIVOT  
  (  
   max(FurtherActionCnt) FOR FurtherAction IN (' + @cols7 + ')
  )AS pvt'
  exec (@query7)
 end
 ELSE
 BEGIN
	select 0 as Result
 END

  declare @query8 varchar(max)='', @cols8 varchar(max)  
       
  select @cols8 = STUFF((SELECT Distinct ',' + QUOTENAME(ISNULL(EM.Firstname,'') + ' ' + ISNULL(EM.Lastname,'')) from sAppointment.tAppointment AP
							inner join shrm.tEmployeemaster EM on EM.Id = AP.DoctorEmployeeId
							inner join sIp.tStoreLocationMaster L on AP.StoreLocationId = L.Id
                         where DoctorEmployeeId is not null
						 and (AP.StoreLocationId=@rStoreLocationId OR @rStoreLocationId=0)
  FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
      
 if @cols8 <> ''  
 begin  
  select @query8 = @query8 + 'SELECT * FROM  
  (  
   SELECT L.Title, ISNULL(EM.Firstname,'''') + '' '' + ISNULL(EM.Lastname,'''') AS DoctorName,
   COUNT(AP.DoctorEmployeeId) AS DoctorCnt
   FROM sAppointment.tAppointment AP
   inner join shrm.tEmployeemaster EM on EM.Id = AP.DoctorEmployeeId
   inner join sIp.tStoreLocationMaster L on AP.StoreLocationId = L.Id
   where DoctorEmployeeId is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1
   and (AP.StoreLocationId=' + CAST(@rStoreLocationId AS NVARCHAR(12)) + ' or ' + CAST(@rStoreLocationId AS NVARCHAR(12)) + ' = 0)
   GROUP BY EM.Firstname,EM.Lastname,L.Title
  ) as s
  PIVOT
  (  
   max(DoctorCnt) FOR DoctorName IN (' + @cols8 + ')
  )AS pvt'
  exec (@query8)
 end
 ELSE
 BEGIN
	select 0 as Result
 END

   declare @query9 varchar(max)='', @cols9 varchar(max)  
       
  select @cols9 = STUFF((SELECT Distinct ',' + QUOTENAME(ISNULL(EM.Firstname,'') + ' ' + ISNULL(EM.Lastname,'')) from sExamination.tRegistration REG
							inner join shrm.tEmployeemaster EM on EM.Id = REG.DoctorEmployeeId
							inner join sIp.tStoreLocationMaster L on REG.StoreLocationId = L.Id
                         where DoctorEmployeeId is not null
						 and (REG.StoreLocationId=@rStoreLocationId OR @rStoreLocationId=0)
  FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
      
 if @cols9 <> ''  
 begin  
  select @query9 = @query9 + 'SELECT * FROM  
  (  
   SELECT L.Title, ISNULL(EM.Firstname,'''') + '' '' + ISNULL(EM.Lastname,'''') AS DoctorName,
   COUNT(REG.DoctorEmployeeId) AS DoctorCnt
   FROM sExamination.tRegistration REG
   inner join shrm.tEmployeemaster EM on EM.Id = REG.DoctorEmployeeId
   inner join sIp.tStoreLocationMaster L on REG.StoreLocationId = L.Id
   where DoctorEmployeeId is not null and L.IsActiveHealth=1 AND L.IsOpdSetup = 1
   and (REG.StoreLocationId=' + CAST(@rStoreLocationId AS NVARCHAR(12)) + ' or ' + CAST(@rStoreLocationId AS NVARCHAR(12)) + ' = 0)
   GROUP BY EM.Firstname,EM.Lastname,L.Title
  ) as s
  PIVOT
  (  
   max(DoctorCnt) FOR DoctorName IN (' + @cols9 + ')
  )AS pvt'
  exec (@query9)
 end
 ELSE
 BEGIN
	select 0 as Result
 END

 DROP TABLE #TempTable  
 DROP TABLE #TempTableNew       

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


GO
      
ALTER PROC [sExamination].[prc_GetHealthAnalysisEmployeeExportWithPagination]      
  @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,      
  @PageSize int = 20,      
  @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, CASE WHEN HM.Code IN ('HBA1C','PPBS','RBS') THEN 'F B S' ELSE HM.Code END  
        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, 19, 21, 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;'      
      
 print @lQueryExisting      
    EXEC (@lQueryExisting)      
      
      
      
      
 ;WITH PageNumbers AS(      
    SELECT      
  ROW_NUMBER() OVER(      
   ORDER BY CASE WHEN @SortColumnName = 'Code' AND @IsAscendingOrder = 0 THEN UPPER(ISNULL(EMP.Code, '')) END DESC,      
      CASE WHEN @SortColumnName = 'Code' AND @IsAscendingOrder = 1 THEN UPPER(ISNULL(EMP.Code, '')) END,      
      CASE WHEN @SortColumnName = 'Name' AND @IsAscendingOrder = 0 THEN ISNULL(EMP.FirstName, '') + ' ' + ISNULL(EMP.LastName, '') END DESC,      
      CASE WHEN @SortColumnName = 'Name' AND @IsAscendingOrder = 1 THEN ISNULL(EMP.FirstName, '') + ' ' + ISNULL(EMP.LastName, '') END,      
      CASE WHEN @SortColumnName = 'Grade' AND @IsAscendingOrder = 0 THEN ISNULL(GRD.Title,'') END DESC,      
      CASE WHEN @SortColumnName = 'Grade' AND @IsAscendingOrder = 1 THEN ISNULL(GRD.Title,'') END,      
      CASE WHEN @SortColumnName = 'TotalPoints' AND @IsAscendingOrder = 0 THEN CONVERT(varchar, isnull(DIA.TotalHealthPoints,0)) END DESC,      
      CASE WHEN @SortColumnName = 'TotalPoints' AND @IsAscendingOrder = 1 THEN CONVERT(varchar, isnull(DIA.TotalHealthPoints,0)) END,      
      CASE WHEN @SortColumnName = 'EarnedPoints' AND @IsAscendingOrder = 0 THEN CONVERT(varchar, isnull(DIA.EarnedHealthPoints,0)) END DESC,      
      CASE WHEN @SortColumnName = 'EarnedPoints' AND @IsAscendingOrder = 1 THEN CONVERT(varchar, isnull(DIA.EarnedHealthPoints,0)) END,      
      CASE WHEN @SortColumnName = 'HealthIndex' AND @IsAscendingOrder = 0 THEN CONVERT(varchar, isnull(DIA.HealthIndex,0)) END DESC,      
      CASE WHEN @SortColumnName = 'HealthIndex' AND @IsAscendingOrder = 1 THEN CONVERT(varchar, isnull(DIA.HealthIndex,0)) END,      
      CASE WHEN @SortColumnName = 'Indicator' AND @IsAscendingOrder = 0 THEN ISNULL(HIM.title,'') END DESC,      
      CASE WHEN @SortColumnName = 'Indicator' AND @IsAscendingOrder = 1 THEN ISNULL(HIM.title,'') END,      
      CASE WHEN @SortColumnName = 'BMI' AND @IsAscendingOrder = 0 THEN ISNULL(m.[BMI], '') END DESC,      
      CASE WHEN @SortColumnName = 'BMI' AND @IsAscendingOrder = 1 THEN ISNULL(m.[BMI], '') END,      
      CASE WHEN @SortColumnName = 'FBS' AND @IsAscendingOrder = 0 THEN ISNULL(m.[F B S], '') END DESC,      
      CASE WHEN @SortColumnName = 'FBS' AND @IsAscendingOrder = 1 THEN ISNULL(m.[F B S], '') END,      
      CASE WHEN @SortColumnName = 'Cholesterol' AND @IsAscendingOrder = 0 THEN ISNULL(m.[CHOLESTEROL], '') END DESC,      
      CASE WHEN @SortColumnName = 'Cholesterol' AND @IsAscendingOrder = 1 THEN ISNULL(m.[CHOLESTEROL], '') END,      
      CASE WHEN @SortColumnName = 'Triglyceride' AND @IsAscendingOrder = 0 THEN ISNULL(m.[TRIGLYCERIDE], '') END DESC,      
      CASE WHEN @SortColumnName = 'Triglyceride' AND @IsAscendingOrder = 1 THEN ISNULL(m.[TRIGLYCERIDE], '') END,      
      CASE WHEN @SortColumnName = 'LDL' AND @IsAscendingOrder = 0 THEN ISNULL(m.[LDL], '') END DESC,      
      CASE WHEN @SortColumnName = 'LDL' AND @IsAscendingOrder = 1 THEN ISNULL(m.[LDL], '') END,      
      CASE WHEN @SortColumnName = 'HDL' AND @IsAscendingOrder = 0 THEN ISNULL(m.[HDL], '') END DESC,      
      CASE WHEN @SortColumnName = 'HDL' AND @IsAscendingOrder = 1 THEN ISNULL(m.[HDL], '') END,      
      CASE WHEN @SortColumnName = 'SGPT' AND @IsAscendingOrder = 0 THEN ISNULL(m.[SGPT], '') END DESC,      
      CASE WHEN @SortColumnName = 'SGPT' AND @IsAscendingOrder = 1 THEN ISNULL(m.[SGPT], '') END,      
      CASE WHEN @SortColumnName = 'SerumCreatinine' AND @IsAscendingOrder = 0 THEN ISNULL(m.[SERUM CREATININE], '') END DESC,      
      CASE WHEN @SortColumnName = 'SerumCreatinine' AND @IsAscendingOrder = 1 THEN ISNULL(m.[SERUM CREATININE], '') END,   
   CASE WHEN @SortColumnName = 'PSA' AND @IsAscendingOrder = 0 THEN ISNULL(m.[PSA], '') END DESC,     
      CASE WHEN @SortColumnName = 'PSA' AND @IsAscendingOrder = 1 THEN ISNULL(m.[PSA], '') END,  
      CASE WHEN @SortColumnName = 'UricAcid' AND @IsAscendingOrder = 0 THEN ISNULL(m.[URIC ACID], '') END DESC,      
      CASE WHEN @SortColumnName = 'UricAcid' AND @IsAscendingOrder = 1 THEN ISNULL(m.[URIC ACID], '') END,      
      CASE WHEN @SortColumnName = 'Sonography' AND @IsAscendingOrder = 0 THEN ISNULL(m.[SONOGRAPHY], '') END DESC,      
      CASE WHEN @SortColumnName = 'Sonography' AND @IsAscendingOrder = 1 THEN ISNULL(m.[SONOGRAPHY], '') END,      
      CASE WHEN @SortColumnName = 'ECHO' AND @IsAscendingOrder = 0 THEN ISNULL(m.[ECHO], '') END DESC,      
      CASE WHEN @SortColumnName = 'ECHO' AND @IsAscendingOrder = 1 THEN ISNULL(m.[ECHO], '') END,      
      CASE WHEN @SortColumnName = 'ECG' AND @IsAscendingOrder = 0 THEN ISNULL(m.[ECG], '') END DESC,      
      CASE WHEN @SortColumnName = 'ECG' AND @IsAscendingOrder = 1 THEN ISNULL(m.[ECG], '') END,      
      CASE WHEN @SortColumnName = 'TMT' AND @IsAscendingOrder = 0 THEN ISNULL(m.[TMT], '') END DESC,      
      CASE WHEN @SortColumnName = 'TMT' AND @IsAscendingOrder = 1 THEN ISNULL(m.[TMT], '') END,      
   CASE WHEN @SortColumnName = 'Habit' AND @IsAscendingOrder = 0 THEN ISNULL(m.[Habit], '') END DESC,      
      CASE WHEN @SortColumnName = 'Habit' AND @IsAscendingOrder = 1 THEN ISNULL(m.[Habit], '') END,  
      CASE WHEN @SortColumnName = 'ExistingDisease' AND @IsAscendingOrder = 0 THEN ISNULL(m.[Existing Disease], '') END DESC,      
      CASE WHEN @SortColumnName = 'ExistingDisease' AND @IsAscendingOrder = 1 THEN ISNULL(m.[Existing Disease], '') END,      
      CASE WHEN @SortColumnName = 'BloodPressureDiastolic' AND @IsAscendingOrder = 0 THEN ISNULL(m.[Blood Pressure Diastolic], '') END DESC,      
      CASE WHEN @SortColumnName = 'BloodPressureDiastolic' AND @IsAscendingOrder = 1 THEN ISNULL(m.[Blood Pressure Diastolic], '') END,      
      CASE WHEN @SortColumnName = 'BloodPressureSystolic' AND @IsAscendingOrder = 0 THEN ISNULL(m.[Blood Pressure Systolic], '') END DESC,      
      CASE WHEN @SortColumnName = 'BloodPressureSystolic' AND @IsAscendingOrder = 1 THEN ISNULL(m.[Blood Pressure Systolic], '') END,      
      CASE WHEN @SortColumnName = 'WaistCircumference' AND @IsAscendingOrder = 0 THEN ISNULL(m.[Waist Circumference], '') END DESC,      
      CASE WHEN @SortColumnName = 'WaistCircumference' AND @IsAscendingOrder = 1 THEN ISNULL(m.[Waist Circumference], '') END,      
   CASE WHEN @SortColumnName = 'HB' AND @IsAscendingOrder = 0 THEN ISNULL(m.[HB], '') END DESC,      
      CASE WHEN @SortColumnName = 'HB' AND @IsAscendingOrder = 1 THEN ISNULL(m.[HB], '') END,   
   CASE WHEN @SortColumnName = 'Audiometry' AND @IsAscendingOrder = 0 THEN ISNULL(m.[Audiometry], '') END DESC,      
      CASE WHEN @SortColumnName = 'Audiometry' AND @IsAscendingOrder = 1 THEN ISNULL(m.[Audiometry], '') END,   
   CASE WHEN @SortColumnName = 'Pulmonary' AND @IsAscendingOrder = 0 THEN ISNULL(m.[Pulmonary], '') END DESC,      
      CASE WHEN @SortColumnName = 'Pulmonary' AND @IsAscendingOrder = 1 THEN ISNULL(m.[Pulmonary], '') END,   
      CASE WHEN @SortColumnName = '' THEN UPPER(ISNULL(EMP.FirstName, '') + ' ' + ISNULL(EMP.LastName, '') + ' - ' + ISNULL(EMP.Code, '')) END      
  ) ID,      
  COUNT(*) OVER() 'RecordCount',      
  UPPER(ISNULL(EMP.Code, '')) COLLATE Latin1_General_CI_AI 'Code' ,      
  ISNULL(EMP.FirstName, '') + ' ' + ISNULL(EMP.LastName, '') 'Name',      
  ISNULL(GRD.Title,'') 'Grade',      
  --CONVERT(varchar, isnull(DIA.TotalHealthPoints,0)) 'TotalPoints',      
  --CONVERT(varchar, isnull(DIA.EarnedHealthPoints,0)) 'EarnedPoints',      
  --CONVERT(varchar, isnull(DIA.HealthIndex,0)) 'HealthIndex',      
  --(CASE WHEN ISNULL(HIM.HealthIndicatorLabel, '') != '' and HIM.IsObsolete = 0 THEN HIM.HealthIndicatorLabel ELSE HIM.Title END) 'Indicator',  
  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',  
     @Header 'Header'      
    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,'')+'%'   
            )      
    )      
 SELECT  *      
 FROM    PageNumbers      
 WHERE  (@PageSize = -1 OR ID  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize))       
      
  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].[pExaminationCustomSearchListGetWithPagination]...';


GO

ALTER proc [sExamination].[pExaminationCustomSearchListGetWithPagination]      
@rPageIndex int,      
@rOrgId [int],        
@rDepartmentId nvarchar(max)='' ,       
@rSetupId nvarchar(max)='' ,        
@rCode [nvarchar](20),        
@rName [nvarchar](50),        
@rDesignationId nvarchar(max)='' ,      
@rMainTypeId int,      
@rStatusId nvarchar(max)='' ,      
@rStoreLocationId int,      
@rFromDate Date = '',      
@rToDate Date = '',      
@rHealthIndicatorId int,      
@rTag int,      
@rEmployeeStoreLocationId int=0,      
@rCompanyId nvarchar(max)='' ,      
@lPageSize int = 10,      
@rDOJ date = '',      
@rEmployeeTypeGroupId nvarchar(max)='' ,      
@rFlag int = 0,  ---PME Contract Worker change by Nidhi Pandey      
@SortColumnName NVARCHAR(MAX)= '',      
@IsAscendingOrder bit= 0,      
@PageNumber int = 1,      
@PageSize int = 20,      
@GlobalSearch NVARCHAR(MAX)= '',      
@rDoctorId nvarchar(max)=''  ,    
@rContractorId nvarchar(max)=''    
as      
begin      
 --declare @lTotalRec int = 0,@lTotalPage int = 0      
 select @rCode = case when @rCode = '*' then '' else @rCode end      
 select @rName = case when @rName = '*' then '' else @rName end      
       
 SET @rCode = sCommon.fSearchStringGet(@rCode)      
 SET @rName = sCommon.fSearchStringGet(@rName)      
 declare @tbltmp table(tid int identity(1,1),eid bigint)      
       
 IF @rMainTypeId = 9      
 BEGIN      
  insert into @tbltmp(eid)      
  SELECT E.Id      
  FROM sExamination.tExamination E        
  inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id      
  inner join sExamination.tDiagnosis D ON D.SourceId= E.Id      
  inner join sExamination.tExaminationRequest ER ON E.Id = ER.ExaminationId        
  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 EM2 on EFD.EmployeeId = EM2.Id      
      
  left join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=E.ParticipantSourceId --[NEHA -Mintis Id : 0018767]      
  left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id      
  left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId    
 left join sProcurement.tVendorMaster CONT on CONT.Id =EJD.ContractorId        
          
  WHERE ((ISNULL(D.HealthindicatorId,0)=0 AND @rTag != 1) OR (@rTag = 1 AND ISNULL(D.HealthindicatorId,0) >= 0))       
  AND E.OrgId = @rOrgId      
  AND (EM.Code Like @rCode or EM2.Code Like @rCode or CS.Code Like @rCode OR ISNULL(@rCode,'') = '' OR ISNULL(@rCode,'') = '*')      
  AND (EM.FirstName Like @rName  + '%' or EFD.Name like @rName  + '%' or CS.FirstName like @rName  + '%' OR ISNULL(@rName,'') = '' OR ISNULL(@rName,'') = '*')      
  AND ((E.OrganizationDepartmentId in (SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))      
  AND ((E.EmployeeDesignationId in (SELECT item FROM sCommon.fnsplit(@rDesignationId,','))) OR (ISNULL(@rDesignationId,'') = ''))      
  AND (ER.SubTypeId = @rMainTypeId) AND ((E.SetupId  IN(SELECT item FROM sCommon.fnsplit(@rSetupId,','))) OR (ISNULL(@rSetupId,'') = ''))        
  AND ((E.StatusId in (SELECT item FROM sCommon.fnsplit(@rStatusId,','))) OR (ISNULL(@rStatusId,'') = ''))      
  AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)      
  AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))      
  AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))       
  AND ((D.HealthIndicatorId = @rHealthIndicatorId) OR (ISNULL(@rHealthIndicatorId,0) = 0))      
  AND ((E.EmployeeCompanyId in (SELECT item FROM sCommon.fnsplit(@rCompanyId,','))) OR (ISNULL(@rCompanyId,'') = ''))      
  --and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)      
  AND ((ETM.Id in (SELECT item FROM sCommon.fnsplit(@rEmployeeTypeGroupId,','))) OR (ISNULL(@rEmployeeTypeGroupId,'') = '0'))      
  AND ((cast(EJD.DateOfJoining as date) = cast(@rDOJ as date)) OR (ISNULL(@rDOJ,'') = ''))      
  AND EM.IsObsolete=0 AND EM2.IsObsolete=0      
  AND ((E.DoctorEmployeeId in (SELECT item FROM sCommon.fnsplit(@rDoctorId,','))) OR (ISNULL(@rDoctorId,'') = ''))    
    AND ((CONT.Id in (SELECT item FROM sCommon.fnsplit(@rContractorId,','))) OR (ISNULL(@rContractorId,'') = ''))     
      
  order by E.ExaminationDate desc      
        
  insert into @tbltmp(eid)      
  SELECT E.Id      
  FROM sExamination.tExamination E      
  inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id      
  inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id      
  LEFT JOIN sExamination.tDiagnosis D ON D.SourceId = 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 CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009      
  left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id      
        
  left join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=E.ParticipantSourceId --[NEHA -Mintis Id : 0018767]      
  left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id      
  left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId    
  left join sProcurement.tVendorMaster CONT on CONT.Id =EJD.ContractorId       
        
  WHERE ((ISNULL(D.HealthindicatorId,0)=0 AND @rTag != 1) OR (@rTag = 1 AND ISNULL(D.HealthindicatorId,0) >= 0)       
  or (D.HealthindicatorId is null)) AND E.OrgId = @rOrgId      
  AND (EM.Code Like @rCode or EM2.Code Like @rCode or CS.Code Like @rCode OR ISNULL(@rCode,'') = '' OR ISNULL(@rCode,'') = '*')      
  AND (EM.FirstName Like @rName  + '%' or EFD.Name like @rName  + '%' or CS.FirstName like @rName  + '%' OR ISNULL(@rName,'') = '' OR ISNULL(@rName,'') = '*')      
  AND ((E.OrganizationDepartmentId in (SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))      
  AND ((E.EmployeeDesignationId in (SELECT item FROM sCommon.fnsplit(@rDesignationId,','))) OR (ISNULL(@rDesignationId,'') = ''))      
  AND ((E.StatusId in (SELECT item FROM sCommon.fnsplit(@rStatusId,','))) OR (ISNULL(@rStatusId,'') = ''))      
  AND ((E.EmployeeCompanyId IN(SELECT item FROM sCommon.fnsplit(@rCompanyId,','))) OR (isnull(@rCompanyId,'') = ''))      
        
  AND (STM.MainTypeId = @rMainTypeId) AND ((E.SetupId  IN(SELECT item FROM sCommon.fnsplit(@rSetupId,','))) OR (ISNULL(@rSetupId,'') = ''))      
  AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)       
  AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))      
  AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))       
  AND ((D.HealthIndicatorId = @rHealthIndicatorId) OR (ISNULL(@rHealthIndicatorId,0) = 0))      
--  and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)      
  AND ((ETM.Id in (SELECT item FROM sCommon.fnsplit(@rEmployeeTypeGroupId,','))) OR (ISNULL(@rEmployeeTypeGroupId,'') = '0'))      
  AND ((cast(EJD.DateOfJoining as date) = cast(@rDOJ as date)) OR (ISNULL(@rDOJ,'') = ''))      
  AND ((E.DoctorEmployeeId in (SELECT item FROM sCommon.fnsplit(@rDoctorId,','))) OR (ISNULL(@rDoctorId,'') = ''))     
    AND ((CONT.Id in (SELECT item FROM sCommon.fnsplit(@rContractorId,','))) OR (ISNULL(@rContractorId,'') = ''))     
  order by E.ExaminationDate desc      
        
  ;WITH PageNumbers AS(      
 select       
 ROW_NUMBER() OVER(      
   ORDER BY CASE WHEN @SortColumnName = 'ExamDate' AND @IsAscendingOrder = 0 THEN t.ExamDate END DESC,      
      CASE WHEN @SortColumnName = 'ExamDate' AND @IsAscendingOrder = 1 THEN t.ExamDate END,      
      CASE WHEN @SortColumnName = 'Setup' AND @IsAscendingOrder = 0 THEN t.Setup END DESC,      
      CASE WHEN @SortColumnName = 'Setup' AND @IsAscendingOrder = 1 THEN t.Setup END,      
      CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 0 THEN t.ParticipantCode END DESC,      
      CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 1 THEN t.ParticipantCode END,      
      CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 0 THEN t.ParticipantName END DESC,      
      CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 1 THEN t.ParticipantName END,      
      CASE WHEN @SortColumnName = 'Department' AND @IsAscendingOrder = 0 THEN t.Department END DESC,      
      CASE WHEN @SortColumnName = 'Department' AND @IsAscendingOrder = 1 THEN t.Department END,      
      CASE WHEN @SortColumnName = 'Status' AND @IsAscendingOrder = 0 THEN t.[Status] END DESC,      
      CASE WHEN @SortColumnName = 'Status' AND @IsAscendingOrder = 1 THEN t.[Status] END,      
      CASE WHEN @SortColumnName = '' THEN t.Id END DESC      
  ) RID,      
  COUNT(*) OVER() 'RecordCount',      
  * from (      
  select t1.* from (        
   SELECT E.Id,      
   convert(varchar(10),E.ExaminationDate,103) as ExaminationDate,      
   E.ExaminationDate as ExamDate, --Nidhi pandey; due to sorting issue; DT - 05/07/2022      
   EDM.Title as Designation,      
   ODM.Title as Department,      
   SM.RoundNumber,      
   ParticipantCode = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.Code      
   when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,      
   ParticipantName = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + isnull(EM.LastName,'')      
   when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + isnull(CS.LastName,'') end,      
   Gender = CASE WHEN E.ParticipantSourceTypeId = 95 then GM.Title      
   when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')      
   else GM2.Title end,      
   'Post Accident' as Setup,      
   ST.Title as [Status],      
   isnull(E.ProcessTypeId,0) as ProcessId,      
   PT.Title as ProcessType,      
   MobileNumber as MobileNo,      
   CompanyEmail,      
   D.HealthindicatorId,      
   E.ParticipantSourceTypeId,      
   E.ParticipantSourceId,      
   E.SetupId,      
   E.StatusId,      
   Age = CASE WHEN E.ParticipantSourceTypeId = 95 then isnull(datediff(yy,EP.DateOfBirth,getdate()),0)      
   when E.ParticipantSourceTypeId = 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)      
   else isnull(datediff(yy,CS.DateOfBirth,getdate()),0) end,      
   GenderId = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.GenderId      
   when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')      
   else CS.GenderId end,      
   DateOfBirth = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.DateOfBirth      
   when E.ParticipantSourceTypeId = 1001 then EFD.DateOfBirth      
   else CS.DateOfBirth end,      
   V.Height,      
   EP.IsBirthDateUnknown,      
   isnull(E.CriteiraGroupId,0) as CriteriaGroupId,      
   isnull(E.TargetGroupId,0) as TargetGroupId,      
   E.OrganizationDepartmentId as DepartmentId,      
   E.EmployeeDesignationId as DesignationId      
      
   FROM sExamination.tExamination E       
        
   inner join @tbltmp t on t.eid = E.Id      
   inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id      
   INNER JOIN sExamination.tDiagnosis D ON D.SourceId= E.Id      
   INNER JOIN sExamination.tExaminationRequest ER ON E.Id = ER.ExaminationId       
   left join sCommon.tProcessTypeMaster PT on PT.Id = E.ProcessTypeId      
   left join sHrm.tEmployeeDesignationMaster EDM on E.EmployeeDesignationId = EDM.Id      
   left join sCommon.tOrganizationDepartmentMaster ODM on E.OrganizationDepartmentId = ODM.Id      
   left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95      
   left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1001      
   left join sHrm.tCSRBenefiterMaster CS on CS.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1009      
   left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id      
   left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId      
   left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId      
   left join sExamination.tStatusMaster ST on E.StatusId = ST.Id      
   left join sCommon.tGenderMaster GM on EP.GenderId = GM.Id      
   left join sCommon.tGenderMaster GM2 on CS.GenderId = GM.Id      
   left join sExamination.tVital V on V.SourceId = E.Id      
      
   --where tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)        
  ) t1      
        
  union all      
        
  select t2.* from(      
   SELECT E.Id AS Id,      
   convert(varchar(10),E.ExaminationDate,103) as ExaminationDate,      
   E.ExaminationDate as ExamDate, --Nidhi pandey; due to sorting issue; DT - 05/07/2022      
   EDM.Title as Designation,      
   ODM.Title as Department,      
   SM.[RoundNumber],      
   ParticipantCode = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.Code      
   when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,      
   ParticipantName = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + isnull(EM.LastName,'')      
   when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + isnull(CS.LastName,'') end,      
   Gender = CASE WHEN E.ParticipantSourceTypeId = 95 then GM.Title      
   when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')      
   else GM2.Title end,      
   Setup = SM.Title,      
   ST.Title as [Status],      
   E.ProcessTypeId as ProcessId,      
   PT.Title as ProcessType,      
   MobileNumber as MobileNo,      
   CompanyEmail,      
   D.HealthindicatorId,      
   E.ParticipantSourceTypeId,      
   E.ParticipantSourceId,      
   E.SetupId,      
   E.StatusId,      
   Age = CASE WHEN E.ParticipantSourceTypeId = 95 then isnull(datediff(yy,EP.DateOfBirth,getdate()),0)      
   when E.ParticipantSourceTypeId = 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)      
   else isnull(datediff(yy,CS.DateOfBirth,getdate()),0) end,      
   GenderId = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.GenderId      
   when E.ParticipantSourceTypeId = 1001 then ISNULL(EFD.GenderId,'')      
   else CS.GenderId end,      
   DateOfBirth = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.DateOfBirth      
   when E.ParticipantSourceTypeId = 1001 then EFD.DateOfBirth      
   else CS.DateOfBirth end,      
   V.Height,      
   EP.IsBirthDateUnknown,      
   isnull(E.CriteiraGroupId,0) as CriteriaGroupId,      
   isnull(E.TargetGroupId,0) as TargetGroupId,      
   E.OrganizationDepartmentId as DepartmentId,      
   E.EmployeeDesignationId as DesignationId      
   FROM sExamination.tExamination E       
        
   inner join @tbltmp t on t.eid = E.Id       
   inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id      
   LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= E.Id      
   left join sCommon.tProcessTypeMaster PT on PT.Id=E.ProcessTypeId      
   left join sHrm.tEmployeeDesignationMaster EDM on E.EmployeeDesignationId = EDM.Id      
   left join sCommon.tOrganizationDepartmentMaster ODM on E.OrganizationDepartmentId = ODM.Id      
   left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95      
   left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1001      
   left join sHrm.tCSRBenefiterMaster CS on CS.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1009      
   left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id      
   left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId      
   left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId      
   left join sExamination.tStatusMaster ST on E.StatusId = ST.Id      
   left join sCommon.tGenderMaster GM on EP.GenderId = GM.Id      
   left join sCommon.tGenderMaster GM2 on CS.GenderId = GM.Id      
   left join sExamination.tVital V on V.SourceId = E.Id      
      
   --where tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)        
  ) t2      
  ) t      
  where (ISNULL(@GlobalSearch,'') = '' OR ISNULL(t.ExamDate,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(t.Setup,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(t.ParticipantCode,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(t.ParticipantName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(t.Department,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(t.[Status],'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%')      
 )      
  SELECT  *      
  FROM    PageNumbers      
  WHERE  (@PageSize = -1 OR RID  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize))      
 end      
 ELSE      
 BEGIN      
   if(@rFlag = 1)      
   BEGIN      
  insert into @tbltmp(eid)      
  SELECT E.Id      
  FROM sExamination.tExamination E      
  inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id      
  inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id      
  LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= 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 CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009      
  left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id      
        
  left join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=E.ParticipantSourceId --[NEHA -Mintis Id : 0018767]      
  left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id      
  left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId      
  left join sProcurement.tVendorMaster CONT on CONT.Id =EJD.ContractorId      
      
  WHERE ((ISNULL(D.HealthindicatorId,0)=0 AND @rTag != 1) OR (@rTag = 1 AND ISNULL(D.HealthindicatorId,0) >= 0)      
  or (D.HealthindicatorId is null)) AND E.OrgId = @rOrgId      
  AND (EM.Code Like @rCode or EM2.Code Like @rCode or CS.Code Like @rCode OR ISNULL(@rCode,'') = '' OR ISNULL(@rCode,'') = '*')      
  AND (EM.FirstName Like @rName  + '%' or EFD.Name like @rName  + '%' or CS.FirstName like @rName  + '%' OR ISNULL(@rName,'') = '' OR ISNULL(@rName,'') = '*')      
  AND ((E.OrganizationDepartmentId in (SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))      
  AND ((E.EmployeeDesignationId in (SELECT item FROM sCommon.fnsplit(@rDesignationId,','))) OR (ISNULL(@rDesignationId,'') = ''))      
  AND (STM.MainTypeId = @rMainTypeId) AND ((E.SetupId  IN(SELECT item FROM sCommon.fnsplit(@rSetupId,','))) OR (ISNULL(@rSetupId,'') = ''))      
  AND ((E.StatusId in (SELECT item FROM sCommon.fnsplit(@rStatusId,','))) OR (ISNULL(@rStatusId,'') = ''))      
  AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)       
  AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))      
  AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))       
  AND ((D.HealthIndicatorId = @rHealthIndicatorId) OR (ISNULL(@rHealthIndicatorId,0) = 0))      
  AND ((E.EmployeeCompanyId in (SELECT item FROM sCommon.fnsplit(@rCompanyId,','))) OR (ISNULL(@rCompanyId,'') = ''))      
  --and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)      
    AND ((ETM.Id  in (SELECT item FROM sCommon.fnsplit(@rEmployeeTypeGroupId ,','))) OR (ISNULL(@rEmployeeTypeGroupId ,'') = '0'))      
  AND ((cast(EJD.DateOfJoining as date) = cast(@rDOJ as date)) OR (ISNULL(@rDOJ,'') = ''))      
  AND Isnull(EM.IsObsolete,0)=0 AND Isnull(EM2.IsObsolete,0)=0      
  AND EM.TargetGroupId = 10002      
  AND ((E.DoctorEmployeeId in (SELECT item FROM sCommon.fnsplit(@rDoctorId,','))) OR (ISNULL(@rDoctorId,'') = ''))    
    AND ((CONT.Id in (SELECT item FROM sCommon.fnsplit(@rContractorId,','))) OR (ISNULL(@rContractorId,'') = ''))     
  order by E.ExaminationDate desc      
        
      
  ;WITH PageNumbers AS(      
 select       
 ROW_NUMBER() OVER(      
   ORDER BY CASE WHEN @SortColumnName = 'ExamDate' AND @IsAscendingOrder = 0 THEN ty.ExamDate END DESC,      
      CASE WHEN @SortColumnName = 'ExamDate' AND @IsAscendingOrder = 1 THEN ty.ExamDate END,      
      CASE WHEN @SortColumnName = 'Setup' AND @IsAscendingOrder = 0 THEN ty.Setup END DESC,      
      CASE WHEN @SortColumnName = 'Setup' AND @IsAscendingOrder = 1 THEN ty.Setup END,      
      CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 0 THEN ty.ParticipantCode END DESC,      
      CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 1 THEN ty.ParticipantCode END,      
      CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 0 THEN ty.ParticipantName END DESC,      
      CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 1 THEN ty.ParticipantName END,      
      CASE WHEN @SortColumnName = 'Department' AND @IsAscendingOrder = 0 THEN ty.Department END DESC,      
      CASE WHEN @SortColumnName = 'Department' AND @IsAscendingOrder = 1 THEN ty.Department END,      
      CASE WHEN @SortColumnName = 'Status' AND @IsAscendingOrder = 0 THEN ty.[Status] END DESC,      
      CASE WHEN @SortColumnName = 'Status' AND @IsAscendingOrder = 1 THEN ty.[Status] END,      
      CASE WHEN @SortColumnName = '' THEN ty.Id END DESC      
  ) RID,      
  COUNT(*) OVER() 'RecordCount',      
  * from (      
  SELECT E.Id,      
  convert(varchar(10),E.ExaminationDate,103) as ExaminationDate,      
  E.ExaminationDate as ExamDate,--Nidhi pandey; due to sorting issue; DT - 05/07/2022      
  EDM.Title as Designation,      
  ODM.Title as Department,      
  SM.[RoundNumber],      
  ParticipantCode = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.Code      
  when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,      
  ParticipantName = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + isnull(EM.LastName,'')      
  when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + isnull(CS.LastName,'') end,      
  Gender = CASE WHEN E.ParticipantSourceTypeId = 95 then GM.Title      
  when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')      
  else GM2.Title end,      
  Setup = SM.Title,      
  ST.Title as [Status],      
  IsBirthDateUnknown,      
  isnull(E.ProcessTypeId,0) as ProcessId,      
  PT.Title as ProcessType,      
  MobileNumber as MobileNo,      
  CompanyEmail,      
  D.HealthindicatorId,      
  E.ParticipantSourceTypeId,      
  E.ParticipantSourceId,      
  E.SetupId,      
  E.StatusId,      
  Age = CASE WHEN E.ParticipantSourceTypeId = 95 then isnull(datediff(yy,EP.DateOfBirth,getdate()),0)      
  when E.ParticipantSourceTypeId = 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)      
  else isnull(datediff(yy,CS.DateOfBirth,getdate()),0) end,      
  GenderId = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.GenderId      
  when E.ParticipantSourceTypeId = 1001 then ISNULL(EFD.GenderId,0)      
  else CS.GenderId end,      
  DateOfBirth = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.DateOfBirth      
  when E.ParticipantSourceTypeId = 1001 then EFD.DateOfBirth      
  else CS.DateOfBirth end,      
  V.Height,      
  isnull(E.CriteiraGroupId,0) as CriteriaGroupId,      
  isnull(E.TargetGroupId,0) as TargetGroupId,      
  E.OrganizationDepartmentId as DepartmentId,      
  E.EmployeeDesignationId as DesignationId      
      
  FROM sExamination.tExamination E        
  inner join @tbltmp t on t.eid = E.Id      
  inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id      
  LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= E.Id       
  left join sCommon.tProcessTypeMaster PT on PT.Id=E.ProcessTypeId      
  left join sHrm.tEmployeeDesignationMaster EDM on E.EmployeeDesignationId = EDM.Id      
  left join sCommon.tOrganizationDepartmentMaster ODM on E.OrganizationDepartmentId = ODM.Id      
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95      
  left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1001      
  left join sHrm.tCSRBenefiterMaster CS on CS.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1009      
  left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id      
  left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId      
  left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId      
  left join sExamination.tStatusMaster ST on E.StatusId = ST.Id      
  left join sCommon.tGenderMaster GM on EP.GenderId = GM.Id      
  left join sCommon.tGenderMaster GM2 on CS.GenderId = GM.Id      
  left join sExamination.tVital V on V.SourceId = E.Id      
        
  --where tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)      
  --order by tid       
  ) ty      
  where (ISNULL(@GlobalSearch,'') = '' OR ISNULL(ty.ExamDate,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(ty.Setup,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(ty.ParticipantCode,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(ty.ParticipantName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(ty.Department,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(ty.[Status],'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%')      
  )      
  SELECT  *      
  FROM    PageNumbers      
  WHERE  (@PageSize = -1 OR RID  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize))      
   End      
   else      
   BEGIN      
  insert into @tbltmp(eid)      
  SELECT E.Id      
  FROM sExamination.tExamination E      
  inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id      
  inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id      
  LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= 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 CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009      
  left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id      
        
  left join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=E.ParticipantSourceId --[NEHA -Mintis Id : 0018767]      
  left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id      
  left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId    
  left join sProcurement.tVendorMaster CONT on CONT.Id =EJD.ContractorId       
      
  WHERE ((ISNULL(D.HealthindicatorId,0)=0 AND @rTag != 1) OR (@rTag = 1 AND ISNULL(D.HealthindicatorId,0) >= 0)      
  or (D.HealthindicatorId is null)) AND E.OrgId = @rOrgId      
  AND (EM.Code Like @rCode or EM2.Code Like @rCode or CS.Code Like @rCode OR ISNULL(@rCode,'') = '' OR ISNULL(@rCode,'') = '*')      
  AND (EM.FirstName Like @rName  + '%' or EFD.Name like @rName  + '%' or CS.FirstName like @rName  + '%' OR ISNULL(@rName,'') = '' OR ISNULL(@rName,'') = '*')      
  AND ((E.OrganizationDepartmentId in (SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))      
  AND ((E.EmployeeDesignationId in (SELECT item FROM sCommon.fnsplit(@rDesignationId,','))) OR (ISNULL(@rDesignationId,'') = ''))      
  AND (STM.MainTypeId = @rMainTypeId) AND ((E.SetupId  IN(SELECT item FROM sCommon.fnsplit(@rSetupId,','))) OR (ISNULL(@rSetupId,'') = ''))      
  AND ((E.StatusId in (SELECT item FROM sCommon.fnsplit(@rStatusId,','))) OR (ISNULL(@rStatusId,'') = ''))      
  AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)       
  AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))      
  AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))       
  AND ((D.HealthIndicatorId = @rHealthIndicatorId) OR (ISNULL(@rHealthIndicatorId,0) = 0))      
  AND ((E.EmployeeCompanyId in (SELECT item FROM sCommon.fnsplit(@rCompanyId,','))) OR (ISNULL(@rCompanyId,'') = ''))      
--  and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)      
  AND ((ETM.Id  in (SELECT item FROM sCommon.fnsplit(@rEmployeeTypeGroupId ,','))) OR (ISNULL(@rEmployeeTypeGroupId ,'') = '0'))      
    
  AND ((cast(EJD.DateOfJoining as date) = cast(@rDOJ as date)) OR (ISNULL(@rDOJ,'') = ''))      
  AND Isnull(EM.IsObsolete,0)=0 AND Isnull(EM2.IsObsolete,0)=0      
  AND ((E.DoctorEmployeeId in (SELECT item FROM sCommon.fnsplit(@rDoctorId,','))) OR (ISNULL(@rDoctorId,'') = ''))      
   AND ((CONT.Id in (SELECT item FROM sCommon.fnsplit(@rContractorId,','))) OR (ISNULL(@rContractorId,'') = ''))     
  order by E.ExaminationDate desc      
        
      
  ;WITH PageNumbers AS(      
 select       
 ROW_NUMBER() OVER(      
   ORDER BY CASE WHEN @SortColumnName = 'ExamDate' AND @IsAscendingOrder = 0 THEN tx.ExamDate END DESC,      
      CASE WHEN @SortColumnName = 'ExamDate' AND @IsAscendingOrder = 1 THEN tx.ExamDate END,      
      CASE WHEN @SortColumnName = 'Setup' AND @IsAscendingOrder = 0 THEN tx.Setup END DESC,      
      CASE WHEN @SortColumnName = 'Setup' AND @IsAscendingOrder = 1 THEN tx.Setup END,      
      CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 0 THEN tx.ParticipantCode END DESC,      
      CASE WHEN @SortColumnName = 'ParticipantCode' AND @IsAscendingOrder = 1 THEN tx.ParticipantCode END,      
      CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 0 THEN tx.ParticipantName END DESC,      
      CASE WHEN @SortColumnName = 'ParticipantName' AND @IsAscendingOrder = 1 THEN tx.ParticipantName END,      
      CASE WHEN @SortColumnName = 'Department' AND @IsAscendingOrder = 0 THEN tx.Department END DESC,      
      CASE WHEN @SortColumnName = 'Department' AND @IsAscendingOrder = 1 THEN tx.Department END,      
      CASE WHEN @SortColumnName = 'Status' AND @IsAscendingOrder = 0 THEN tx.[Status] END DESC,      
      CASE WHEN @SortColumnName = 'Status' AND @IsAscendingOrder = 1 THEN tx.[Status] END,      
      CASE WHEN @SortColumnName = '' THEN tx.ExaminationDate END DESC      
  ) RID,      
  COUNT(*) OVER() 'RecordCount',      
  * from (      
  SELECT E.Id,      
  convert(varchar(10),E.ExaminationDate,103) as ExaminationDate,      
  E.ExaminationDate as ExamDate, --Nidhi pandey; due to sorting issue; DT - 05/07/2022      
  EDM.Title as Designation,      
  ODM.Title as Department,      
  SM.[RoundNumber],      
  ParticipantCode = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.Code      
  when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,      
  ParticipantName = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + isnull(EM.LastName,'')      
  when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + isnull(CS.LastName,'') end,      
  Gender = CASE WHEN E.ParticipantSourceTypeId = 95 then GM.Title      
  when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')      
  else GM2.Title end,      
  Setup = SM.Title,      
  ST.Title as [Status],      
  IsBirthDateUnknown,      
  isnull(E.ProcessTypeId,0) as ProcessId,      
  PT.Title as ProcessType,      
  MobileNumber as MobileNo,      
  CompanyEmail,      
  D.HealthindicatorId,      
  E.ParticipantSourceTypeId,      
  E.ParticipantSourceId,      
  E.SetupId,      
  E.StatusId,      
  Age = CASE WHEN E.ParticipantSourceTypeId = 95 then isnull(datediff(yy,EP.DateOfBirth,getdate()),0)      
  when E.ParticipantSourceTypeId = 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)      
  else isnull(datediff(yy,CS.DateOfBirth,getdate()),0) end,      
  GenderId = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.GenderId      
  when E.ParticipantSourceTypeId = 1001 then ISNULL(EFD.GenderId,0)      
  else CS.GenderId end,      
  DateOfBirth = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.DateOfBirth      
  when E.ParticipantSourceTypeId = 1001 then EFD.DateOfBirth      
  else CS.DateOfBirth end,      
  V.Height,      
  isnull(E.CriteiraGroupId,0) as CriteriaGroupId,      
  isnull(E.TargetGroupId,0) as TargetGroupId,      
  E.OrganizationDepartmentId as DepartmentId,      
  E.EmployeeDesignationId as DesignationId      
      
  FROM sExamination.tExamination E        
  inner join @tbltmp t on t.eid = E.Id      
  inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id      
  LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= E.Id       
  left join sCommon.tProcessTypeMaster PT on PT.Id=E.ProcessTypeId      
  left join sHrm.tEmployeeDesignationMaster EDM on E.EmployeeDesignationId = EDM.Id      
  left join sCommon.tOrganizationDepartmentMaster ODM on E.OrganizationDepartmentId = ODM.Id      
  left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95      
  left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1001      
  left join sHrm.tCSRBenefiterMaster CS on CS.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1009      
  left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id      
  left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId      
  left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId      
  left join sExamination.tStatusMaster ST on E.StatusId = ST.Id      
  left join sCommon.tGenderMaster GM on EP.GenderId = GM.Id      
  left join sCommon.tGenderMaster GM2 on CS.GenderId = GM.Id      
  left join sExamination.tVital V on V.SourceId = E.Id      
        
  --where tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)      
  --order by tid       
  ) tx      
  where (ISNULL(@GlobalSearch,'') = '' OR ISNULL(tx.ExamDate,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(tx.Setup,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(tx.ParticipantCode,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(tx.ParticipantName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(tx.Department,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'      
             OR ISNULL(tx.[Status],'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%')      
  )      
  SELECT  *      
  FROM    PageNumbers      
  WHERE  (@PageSize = -1 OR RID  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize))
  OPTION (RECOMPILE)
   End      
 end      
       
 --select @lTotalRec = count(*) from @tbltmp      
       
 --if @lTotalRec % @lPageSize = 0      
 -- set @lTotalPage = @lTotalRec / @lPageSize      
 --else      
 -- set @lTotalPage =  @lTotalRec / @lPageSize + 1      
        
 --select @lTotalPage as TotalPage,@lTotalRec as TotalRec      
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,
  [Morbidly Obese] 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], (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 = 'Morbidly Obese')  
        [Morbidly Obese]
        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','Morbidly 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].[pRptOpdPrescriptionList]...';


GO

ALTER PROCEDURE [sExamination].[pRptOpdPrescriptionList]
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',
@rReportId int,
@rStoreLocationId int,
@rParticipantTypeId int,
@rCaseCauseId int,
@rLocationId int,
@rFunctionId int,
@rDepartmentGroupId int,
@rDepartmentId int,
@rGradeId int,
@rDesignationId int,
@rJobTitleId int,
@rEmployeeTypeId int,
@rCompanyId int,
@rContractorId int,
@rGenderId smallint,
@rStatusId int,
@rAgeFrom int=0,
@rAgeTo int=100,
@rFromDate date = null,
@rToDate datetime = null,
@rOrgId int,
@rEmployeeCode nvarchar(50)='',
@rEmployeeTypeGroupId int=0,
@rEmployeeSubTypeId int=0,
@rEmployeeGroupId int=0,
@rOtherTypeId int=0,
@rExaminationId bigint=0,
@rLogo bit = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN 

	-- Validate @rEmployeeCode entries
    IF EXISTS 
    (
        SELECT SplitValues.item
        FROM sCommon.fnsplit(@rEmployeeCode, ',') AS SplitValues
        WHERE NOT EXISTS 
        (
            SELECT 1 FROM sHrm.tEmployeeMaster EM WHERE EM.Code = SplitValues.item
            UNION
            SELECT 1 FROM sHrm.tCsrBenefiterMaster BM WHERE BM.Code = SplitValues.item
        )
    )
    BEGIN
        RAISERROR('One or more Employee Codes are invalid / Not Exists.', 16, 1);
        RETURN;
    END

	select @rAgeTo = case when @rAgeTo = '' or @rAgeTo = 100 then 1000 end
	select @rAgeFrom = case when @rAgeFrom = '' then 0 end	

	Declare @rConfig varchar(10), @rConfig1 varchar(10);

	Set @rConfig = (select sConfig.fConfigurationValueGet('Examination.IsTempChangetoCelsius',@rOrgId,0,0,0))

	Set @rConfig1 = (case @rConfig When 'true' Then '°C' Else '°F' END)

	declare @lEnableConfigVal varchar(5);            
	select @lEnableConfigVal = sConfig.fConfigurationValueGet('OPD.PrescriptionFrequencyPattern',@rOrgId,0,0,0)  

	--DECLARE @TestTable TABLE (TestName varchar(200))
	--declare @results varchar(Max) 

	--INSERT INTO @TestTable
	--select TPM.Title from sExamination.tTestRequest TR
	--inner join sOrderEntry.tTestDetail OTD on TR.TestId = OTD.TestId
	--inner join sExamination.tTestRequestDetail TD on TR.Id = TD.TestRequestId and TD.TestDetailId = OTD.Id
	--inner join  sOrderEntry.tTestParameterMaster TPM on TPM.Id = OTD.TestParameterId 
	--where  TR.OrgId = @rOrgId and sourceid = @rExaminationId
	--Order by TPM.Title

	--select @results = coalesce(@results + ', ', '') +  convert(varchar(200),TestName) from @TestTable

	select EED.Id AS ExaminationId,
	EP.Id as prescriptionId,
	ParticipantCode = CASE EED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code WHEN 1009 THEN BM.Code END,
	ParticipantName = CASE EED.ParticipantSourceTypeId WHEN 1009 THEN
	CASE WHEN isnull(O.OtherName,'')='' THEN
	isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'') ELSE O.OtherName END
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END,
	PatientCategory = CASE EED.ParticipantSourceTypeId WHEN 95 THEN isnull(ETM.Title,'') WHEN 1001 THEN isnull(RM.Title,'') WHEN 1009 THEN isnull(BTM.Title,'') END,
	--Gender = CASE EED.ParticipantSourceTypeId
	--WHEN 95 THEN GM.Title
	--WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
	--WHEN 1009 THEN CASE WHEN isnull(O.GenderId,0) = 0 THEN GM2.Title ELSE isnull((SELECT Title FROM sCommon.tGenderMaster where O.GenderId = Id),'') END END,
	Gender = CASE EED.ParticipantSourceTypeId
	WHEN 95 THEN GM.Title
	WHEN 1001 THEN ISNULL(GM3.Title,'')
	WHEN 1009 THEN CASE WHEN isnull(O.GenderId,0) = 0 THEN GM2.Title ELSE isnull((SELECT Title FROM sCommon.tGenderMaster where O.GenderId = Id),'') END END,
	
	--EED.CreatedDateTime as ExaminationDate,
	
	case when isnull(O.OPDTime,'')='' then convert(varchar,EED.CreatedDateTime,103) else convert(varchar,EED.CreatedDateTime,103)  end as ExaminationDate,
	isnull(O.OPDOutTime,'') as OPDOutTime,
	
	Age = CASE EED.ParticipantSourceTypeId WHEN 95 THEN isnull(datediff(yy,PD.DateOfBirth,sCommon.fGetDate()),0)
	WHEN 1001 THEN isnull(datediff(yy,EFD.DateOfBirth,sCommon.fGetDate()),0) WHEN 1009 THEN isnull(O.Age,isnull(datediff(yy,BM.DateOfBirth,sCommon.fGetDate()),0)) end,
	V.Pulse,
	convert(varchar(20),V.Temperature) + convert(varchar(20),@rConfig1) as Temperature,
	V.BloodPressureSystolic,
	V.BloodPressureDiastolic,
	R.ContactPerson,
	O.OutsideMedicine,
	O.OutsideTest,
	[sExamination].[fExistingDiseaseGet](EED.Id) AS Diagnosis,
	(select top 1 isnull(Remark,'') from sExamination.tComplaint where SourceId = EED.Id) as problems,
	case when isnull(EPD.DrugInstruction,'') = '' then SM.Title else EPD.DrugInstruction end as DrugInstruction,
	SIM.Title as Medicines,
	convert(varchar(20),EPD.Dosage) as MedicineQty,
	convert(varchar(20),EPD.DispensedQuantity)DispensedQuantity,
	convert(varchar,EPD.Duration)Duration,
	convert(varchar(20),EPD.PrescribedQuantity)PrescribedQuantity,
	EED.ParticipantSourceId,
	Isnull(SIM.Id,0) as StockId,
	SIM.DrawSize,
	--DFM.Title as MedicineDosage,

	CASE 
    WHEN @lEnableConfigVal = 'false' THEN 
        DFM.Title
    ELSE 
        ISNULL(EPD.DrugFrequencyPattern, '')
	END AS MedicineDosage,

	convert(varchar(20),(EPD.PrescribedQuantity-EPD.DispensedQuantity)) as RemainingQty,	
	'' as UpdatedDateTime,
	CASE 
		WHEN D.EmployeeId IS NOT NULL THEN (CASE 
                WHEN ISNULL(LTRIM(RTRIM(EM3.EmployeePrefix)), '') = '' 
                    THEN '' 
                    ELSE EM3.EmployeePrefix + ' ' 
              END) + EM3.FirstName + ' ' + EM3.LastName
		WHEN VD.Id IS NOT NULL THEN 'Dr. ' + VD.FirstName + ' ' + VD.LastName
		ELSE ''																																									
	END AS RefferedName,
	Convert(varchar,D.MedicalRegistrationNo)MedicalRegistrationNo,
	ISNULL(EED.ExaminationNumber,'') as ExaminationNumber,
	ISNULL(CM.Title,'') as CauseTitle,
	isnull(OD.Title,'') as DepartmentName,
	--ISNULL(D.DoctorSignature, CONVERT(VARBINARY(MAX), 0))AS DoctorSignature,
	D.DoctorSignature AS DoctorSignature,
	CASE WHEN @rLogo = 0 THEN null 
    ELSE CID.Logo END AS Logo,
	 isnull(LM.SmallAddress1,'') as SmallAddress1,
	isnull(LM.SmallAddress2,'') as SmallAddress2,
	CI.Title as CompanyName,
	isnull(V.Remark,'') as Advice,
	--case when Isnull(SIM.Isnotinstore,0)= 1 then 'Outside' else --commented this for adani prescription report
	isnull(O.FurtherActionRemark,'') 
	--end --commented this for adani prescription report
	as FurtherActionRemark,
	'1' orderindex,
	[sExamination].[fTestParameterGetbyExaminationId](EED.Id, @rOrgId) AS TestName,	
	ISNULL(R.ContactPerson,'') as ReferedDoctor,
	ISNULL((Select Title from sCommon.tClinicMaster CCM where CCM.Id = R.ReferToClinicId),'') as ReferedHospital,
	ISNULL((select Title from [sFinanceCommon].[tStockUomMaster] FSUM where FSUM.Id = SIM.IssueStockUomId),'') as IssueUOM,
	AP.FollowupRemark as FollowupRemark,
	V.Remark as VitalRemark,
	V.SPo2,
	(FAM.Title + ISNULL((CASE 
		WHEN FAM.CODE='REFER TO HOSPITAL'
		THEN ISNULL((SELECT CASE 
				WHEN (ISNULL(CLM.Title,'') != '') AND (ISNULL(R.ContactPerson,'') != '') THEN (' - ' + CLM.Title + ' - ' + R.ContactPerson)
				WHEN (ISNULL(CLM.Title,'') != '') OR (ISNULL(R.ContactPerson,'') != '') THEN (' - ' + ISNULL(CLM.Title,'') + ISNULL(R.ContactPerson,'')) 
				ELSE ''
				END),'') 
		WHEN FAM.CODE='109' OR FAM.CODE='110'
		THEN ' - ' + ISNULL(RTDEM.EmployeePrefix + ' ','') + RTDEM.FirstName + ' ' + RTDEM.LastName
		END),'')) AS FurtherAction,
	--( --commented this for adani prescription report
	CONVERT(varchar(10), AP.AppointmentDate, 103) 
    --+ ' and ' + CAST(DATEDIFF(DAY, EED.ExaminationDate, AP.AppointmentDate) AS varchar(10))) --commented this for adani prescription report
	AS FollowUpDate
	from sExamination.tExamination EED
	LEFT JOIN sCwb.tDoctorMaster D on EED.DoctorEmployeeId = D.EmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EM3 on D.EmployeeId = EM3.Id
	LEFT JOIN sExamination.tVital V	ON EED.Id = V.SourceId	
	LEFT JOIN sExamination.tReferral R on R.SourceId = EED.Id 
	LEFT JOIN sExamination.tOPD O on EED.Id = O.ExaminationId
	LEFT JOIN sExamination.vExtPrescription EP on EED.Id = EP.SourceId AND (EP.IsObsolete = 0)
	LEFT JOIN sExamination.vExtPrescriptionDetail EPD on EP.Id = EPD.PrescriptionId AND EPD.StoreLocationId = @rStoreLocationId AND (EPD.IsObsolete = 0)
	LEFT JOIN sIp.tStockItemMaster SIM on EPD.DrugStockItemId = SIM.Id 
	LEFT JOIN sCommon.tOrganizationDepartmentMaster OD on EED.OrganizationDepartmentId = OD.Id
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON OD.DepartmentGroupId = DGM.Id
	LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id
	LEFT JOIN sIp.tDrugDosageFrequencyMaster DFM on DFM.Id=EPD.DrugDosageFrequencyid
	LEFT JOIN sIp.tDrugScheduleMaster SM on SM.Id = EPD.DrugDosageScheduleId	
	LEFT JOIN sHrm.tEmployeeMaster EM on EED.ParticipantSourceId = EM.Id and EED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EED.ParticipantSourceId = EFD.Id and EED.ParticipantSourceTypeId = 1001
	LEFT JOIN sCommon.tRelationshipMaster RM on RM.Id = EFD.RelationshipId and EED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on BM.Id = EED.ParticipantSourceId and EED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM on BM.CSRBenefiterTypeId = BTM.Id
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	LEFT JOIN sHrm.tEmployeePersonalDetail PD on EM.Id = PD.EmployeeId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = PD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
	LEFT JOIN sCommon.tGenderMaster GM3 ON GM3.Id = EFD.GenderId
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  
	LEFT JOIN sHrm.tEmployeeJobDetail EJD2 ON EM2.Id = EJD2.EmployeeId	
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM on ETM.Id = EJD.EmployeeTypeId
	LEFT JOIN sAppointment.tVisitingDoctorMaster VD on EED.DoctorEmployeeId = VD.Id
	LEFT JOIN sExamination.tCauseMaster CM on CM.Id = EED.CauseId 
	INNER JOIN sExamination.tSetupMaster SSM on EED.SetupId = SSM.Id
	INNER JOIN sExamination.tSubTypeMaster ST on SSM.SubTypeId = ST.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id = EED.StoreLocationId
	INNER JOIN sCommon.tLocationMaster LM ON SLM.LocationId = LM.Id
	INNER JOIN sCommon.tCompanyInformation CI ON LM.OrgId = CI.Id	
	INNER JOIN sCommon.tCompanyInformationDetail CID on ci.ID = CID.orgid
	LEFT JOIN sAppointment.tAppointment AP on AP.ReferSourceId = EED.Id
	LEFT JOIN sSafety.tFurtherActionMaster FAM ON O.FurtherActionId = FAM.Id
	LEFT JOIN sCommon.tClinicMaster CLM ON R.ReferToClinicId = CLM.Id
	LEFT JOIN sHrm.tEmployeeMaster RTDEM ON O.ReferToDoctorId = RTDEM.Id
	WHERE (EED.Id = @rExaminationId OR @rExaminationId = 0)
	AND ST.MainTypeId = 8 and isnull(EED.Iscancel,0) = 0
	AND (EED.StoreLocationId = @rStoreLocationId)	
	AND 
	(
		ISNULL(@rEmployeeCode, '') = ''
		OR EXISTS 
		(
			SELECT 1
			FROM sCommon.fnsplit(@rEmployeeCode, ',') AS SplitValues
			WHERE 
			(
				CHARINDEX(',', @rEmployeeCode) = 0 
				AND 
				(
					(EM.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 95)
					OR (EM2.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 1001)
					OR (BM.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 1009)
				)
			)
			OR
			(
				CHARINDEX(',', @rEmployeeCode) > 0 
				AND 
				(
					(EM.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 95)
					OR (EM2.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 1001)
					OR (BM.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 1009)
				)
			)
		)
	)
	AND (EED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)	
	AND (EED.GradeId = @rGradeId OR @rGradeId=0)	
	AND (EED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)	
	AND
	(
		(EJD.EmployeeJobTitleId = @rJobTitleId AND EED.ParticipantSourceTypeId = 95)
		OR (EJD2.EmployeeJobTitleId = @rJobTitleId AND EED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND EED.ParticipantSourceTypeId = 1009)
		OR @rJobTitleId = 0
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId and EED.ParticipantSourceTypeId = 95)
		OR (EJD2.ContractorId = @rEmployeeTypeId and EED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND EED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(
		(EJD.ContractorId = @rContractorId and EED.ParticipantSourceTypeId = 95)
		OR (EJD2.ContractorId = @rContractorId and EED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND EED.ParticipantSourceTypeId = 1009)
		OR @rContractorId = 0
	)	
	AND (EED.EmployeeCompanyId = @rCompanyId OR @rCompanyId=0)	
	AND
	(
		(PD.GenderId = @rGenderId AND EED.ParticipantSourceTypeId = 95)
		OR (EFD.GenderId = @rGenderId AND EED.ParticipantSourceTypeId = 1001)
		OR (BM.GenderId = @rGenderId AND EED.ParticipantSourceTypeId = 1009)
		OR @rGenderId = 0
	)		
	AND (EED.EmployeeStatusId = @rStatusId OR @rStatusId=0) 	
	AND
	(
		(DATEDIFF(yy,PD.DateOfBirth,sCommon.fGetDate()) <= @rAgeTo AND EED.ParticipantSourceTypeId = 95)
		OR (DATEDIFF(yy,isnull(EFD.DateOfBirth,'2050-01-01'),sCommon.fGetDate()) <= @rAgeTo AND EED.ParticipantSourceTypeId = 1001)
		OR (DATEDIFF(yy,isnull(BM.DateOfBirth,'2050-01-01'),sCommon.fGetDate()) <= @rAgeTo AND EED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeTo,0)=0
	)
	AND
	(
		(DATEDIFF(yy,PD.DateOfBirth,sCommon.fGetDate()) >= @rAgeFrom AND EED.ParticipantSourceTypeId = 95)
		OR (DATEDIFF(yy,isnull(EFD.DateOfBirth,'1900-12-31'),sCommon.fGetDate()) >= @rAgeFrom AND EED.ParticipantSourceTypeId = 1001)
		OR (DATEDIFF(yy,isnull(BM.DateOfBirth,'1900-12-31'),sCommon.fGetDate()) >= @rAgeFrom AND EED.ParticipantSourceTypeId = 1009)
		OR ISNULL(@rAgeFrom,0)=0
	)
		
	AND ((EED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))	
	AND ((EED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))	
	AND (SLM.LocationId = @rLocationId) 	
	AND (EED.StoreLocationId = @rStoreLocationId) 	
	AND (EED.OrgId = @rOrgId)	
	AND (EED.CauseId = @rCaseCauseId or @rCaseCauseId=0)	
	AND (EED.ParticipantSourceTypeId = @rParticipantTypeId or @rParticipantTypeId=0)	
	AND (ETM.EmployeeTypeGroupId = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId=0)	
	AND (EJD.EmployeeSubTypeId = @rEmployeeSubTypeId or @rEmployeeSubTypeId=0)	
	AND (EJD.EmployeeGroupId = @rEmployeeGroupId or @rEmployeeGroupId=0)	
	AND (BM.CsrBenefiterTypeId = @rOtherTypeId or @rOtherTypeId=0)
	
	union

	select EED.Id AS ExaminationId,
	OSP.id as prescriptionId,
	'' as ParticipantCode,
	'' as ParticipantName,
	'' as PatientCategory,	
	'' as Gender,
	'' as ExaminationDate,
	'' as OPDOutTime,	
	0 as Age,
	'' Pulse,
	'0' Temperature,
	'' BloodPressureSystolic,
	'' BloodPressureDiastolic,
	'' ContactPerson,
	'' OutsideMedicine,
	'' OutsideTest,
	'' AS Diagnosis,
	'' as problems,
	Isnull(DSM.Title,'') as DrugInstruction,
	Isnull(OSPD.StockItemName,'') as Medicines,
	Isnull(OSPD.DrugInstruction,'0.00') as MedicineQty,
	'0.00' DispensedQuantity,
	Isnull(OSPD.Duration,'') Duration,
	case when Isnull(OSPD.PrescribedQuantity,'')='' then '0' else Isnull(OSPD.PrescribedQuantity,'0') end PrescribedQuantity,
	EED.ParticipantSourceId,
	OSPD.id as StockId,
	0 DrawSize,
	--DFM.Title as MedicineDosage,
	CASE 
    WHEN @lEnableConfigVal = 'false' THEN 
        DFM.Title
    ELSE 
        ISNULL(OSPD.DrugFrequencyPattern, '')
	END AS MedicineDosage,

	case when Isnull(OSPD.PrescribedQuantity,'')='' then '0' else Isnull(OSPD.PrescribedQuantity,'0') end  as RemainingQty,	
	GetDate() as UpdatedDateTime,
	'' as RefferedName,
	'' MedicalRegistrationNo,
	ISNULL(EED.ExaminationNumber,'') as ExaminationNumber,
	'' as CauseTitle,
	'' as DepartmentName,	
	convert(varbinary,'0') AS DoctorSignature,
	convert(varbinary,'0') Logo,
	'' as SmallAddress1,
	'' as SmallAddress2,
	'' as CompanyName,
	'' as Advice,
	'Outside' as FurtherActionRemark,
	'2' orderindex,
	[sExamination].[fTestParameterGetbyExaminationId](EED.Id, @rOrgId) AS TestName,	
	'' as ReferedDoctor,
	'' as ReferedHospital,
	'' as IssueUOM,
	'' as FollowupRemark,
	'' as VitalRemark,
	0 as SPo2,
	'' as FurtherAction,
	'' as FollowUpDate

	from sExamination.tExamination EED
	inner join sExamination.tOutSidePrescription OSP on OSP.Sourceid=EED.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
	LEFT JOIN sHrm.tEmployeeMaster EM on EED.ParticipantSourceId = EM.Id and EED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EED.ParticipantSourceId = EFD.Id and EED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on BM.Id = EED.ParticipantSourceId and EED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id

	WHERE (EED.Id = @rExaminationId OR @rExaminationId = 0)
	and isnull(EED.Iscancel,0) = 0
	AND (EED.StoreLocationId = @rStoreLocationId)		
	AND (EED.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)	
	AND (EED.GradeId = @rGradeId OR @rGradeId=0)	
	AND (EED.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)		
	AND (EED.EmployeeCompanyId = @rCompanyId OR @rCompanyId=0)			
	AND (EED.EmployeeStatusId = @rStatusId OR @rStatusId=0) 		
	AND ((EED.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))	
	AND ((EED.ExaminationDate < @rToDate + 1) OR (ISNULL(@rToDate,'') = ''))			
	AND (EED.OrgId = @rOrgId)	
	AND (EED.CauseId = @rCaseCauseId or @rCaseCauseId=0)	
	AND (EED.ParticipantSourceTypeId = @rParticipantTypeId or @rParticipantTypeId=0)		
	AND 
	(
		ISNULL(@rEmployeeCode, '') = ''
		OR EXISTS 
		(
			SELECT 1
			FROM sCommon.fnsplit(@rEmployeeCode, ',') AS SplitValues
			WHERE 
			(
				CHARINDEX(',', @rEmployeeCode) = 0 
				AND 
				(
					(EM.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 95)
					OR (EM2.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 1001)
					OR (BM.Code LIKE SplitValues.item + '%' AND EED.ParticipantSourceTypeId = 1009)
				)
			)
			OR
			(
				CHARINDEX(',', @rEmployeeCode) > 0 
				AND 
				(
					(EM.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 95)
					OR (EM2.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 1001)
					OR (BM.Code = SplitValues.item AND EED.ParticipantSourceTypeId = 1009)
				)
			)
		)
	)
	order by orderindex
	OPTION(RECOMPILE)
end
GO
PRINT N'Altering Procedure [sExamination].[pCommonExaminationHistoryListGetCustomSearch]...';


GO
ALTER proc [sExamination].[pCommonExaminationHistoryListGetCustomSearch]
@rPageIndex int,
@rOrgId [int],  
@rDepartmentId nvarchar(max)='' , 
@rSetupId nvarchar(max)='' ,  
@rCode [nvarchar](20),  
@rName [nvarchar](50),  
@rDesignationId nvarchar(max)='' ,
@rMainTypeId int,
@rStatusId nvarchar(max)='' ,
@rStoreLocationId int,
@rFromDate Date = '',
@rToDate Date = '',
@rHealthIndicatorId int,
@rTag int,
@rEmployeeStoreLocationId int=0,
@rCompanyId nvarchar(max)='' ,
@lPageSize int = 10,
@rDOJ date = '',
@rEmployeeTypeGroupId int = 0,
@rFlag int = 0 , ---PME Contract Worker change by Nidhi Pandey
@rContractorId nvarchar(max)=''     

as
begin
	select @rCode = case when @rCode = '*' then '' else @rCode end
	select @rName = case when @rName = '*' then '' else @rName end
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rName = sCommon.fSearchStringGet(@rName)
	declare @tbltmp table(tid int identity(1,1),eid bigint)
	
	IF @rMainTypeId = 9
	BEGIN
		insert into @tbltmp(eid)
		SELECT E.Id
		FROM sExamination.tExamination E		
		inner join sExamination.tSetupMaster SM on E.SetupId = SM.Id
		inner join sExamination.tDiagnosis D ON D.SourceId= E.Id
		inner join sExamination.tExaminationRequest ER ON E.Id = ER.ExaminationId		
		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 EM2 on EFD.EmployeeId = EM2.Id
		inner join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=E.ParticipantSourceId
		left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id
		left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId
		  left join sProcurement.tVendorMaster CONT on CONT.Id =EJD.ContractorId         
				
		WHERE ((ISNULL(D.HealthindicatorId,0)=0	AND @rTag != 1) OR (@rTag = 1 AND ISNULL(D.HealthindicatorId,0) >= 0)) 
		AND E.OrgId = @rOrgId
		AND (EM.Code Like @rCode or EM2.Code Like @rCode or CS.Code Like @rCode OR ISNULL(@rCode,'') = '' OR ISNULL(@rCode,'') = '*')
		AND (EM.FirstName Like @rName  + '%' or EFD.Name like @rName  + '%' or CS.FirstName like @rName  + '%' OR ISNULL(@rName,'') = '' OR ISNULL(@rName,'') = '*')
		AND ((E.OrganizationDepartmentId in (SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))
		AND ((E.EmployeeDesignationId in (SELECT item FROM sCommon.fnsplit(@rDesignationId,','))) OR (ISNULL(@rDesignationId,'') = ''))
		AND (ER.SubTypeId = @rMainTypeId) AND ((E.SetupId  IN(SELECT item FROM sCommon.fnsplit(@rSetupId,','))) OR (ISNULL(@rSetupId,'') = ''))  
		AND ((E.StatusId in (SELECT item FROM sCommon.fnsplit(@rStatusId,','))) OR (ISNULL(@rStatusId,'') = ''))
		AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)
		AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))	
		AND ((D.HealthIndicatorId = @rHealthIndicatorId) OR (ISNULL(@rHealthIndicatorId,0) = 0))
		AND ((E.EmployeeCompanyId in (SELECT item FROM sCommon.fnsplit(@rCompanyId,','))) OR (ISNULL(@rCompanyId,'') = ''))
		and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)
		AND ((cast(EJD.DateOfJoining as date) = cast(@rDOJ as date)) OR (ISNULL(@rDOJ,'') = ''))
		   AND ((CONT.Id in (SELECT item FROM sCommon.fnsplit(@rContractorId,','))) OR (ISNULL(@rContractorId,'') = ''))  
		AND EM.IsObsolete=0 AND EM2.IsObsolete=0
		order by E.ExaminationDate desc
		
		insert into @tbltmp(eid)
		SELECT E.Id
		FROM sExamination.tExamination E
		inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		LEFT JOIN sExamination.tDiagnosis D ON D.SourceId = 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 CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009
		left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		
		inner join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=E.ParticipantSourceId
		left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id
		left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId
		  left join sProcurement.tVendorMaster CONT on CONT.Id =EJD.ContractorId         
		
		WHERE ((ISNULL(D.HealthindicatorId,0)=0 AND @rTag != 1) OR (@rTag = 1 AND ISNULL(D.HealthindicatorId,0) >= 0) 
		or (D.HealthindicatorId is null)) AND E.OrgId = @rOrgId
		AND (EM.Code Like @rCode or EM2.Code Like @rCode or CS.Code Like @rCode OR ISNULL(@rCode,'') = '' OR ISNULL(@rCode,'') = '*')
		AND (EM.FirstName Like @rName  + '%' or EFD.Name like @rName  + '%' or CS.FirstName like @rName  + '%' OR ISNULL(@rName,'') = '' OR ISNULL(@rName,'') = '*')
		AND ((E.OrganizationDepartmentId in (SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))
		AND ((E.EmployeeDesignationId in (SELECT item FROM sCommon.fnsplit(@rDesignationId,','))) OR (ISNULL(@rDesignationId,'') = ''))
		AND ((E.StatusId in (SELECT item FROM sCommon.fnsplit(@rStatusId,','))) OR (ISNULL(@rStatusId,'') = ''))
		AND ((E.EmployeeCompanyId IN(SELECT item FROM sCommon.fnsplit(@rCompanyId,','))) OR (isnull(@rCompanyId,'') = ''))
		
		AND (STM.MainTypeId = @rMainTypeId) AND ((E.SetupId  IN(SELECT item FROM sCommon.fnsplit(@rSetupId,','))) OR (ISNULL(@rSetupId,'') = ''))
		AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) 
		AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))	
		AND ((D.HealthIndicatorId = @rHealthIndicatorId) OR (ISNULL(@rHealthIndicatorId,0) = 0))
		and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)
		AND ((cast(EJD.DateOfJoining as date) = cast(@rDOJ as date)) OR (ISNULL(@rDOJ,'') = ''))
		   AND ((CONT.Id in (SELECT item FROM sCommon.fnsplit(@rContractorId,','))) OR (ISNULL(@rContractorId,'') = ''))  
		order by E.ExaminationDate desc
		
		select t1.* from (		
			SELECT E.Id,
			convert(varchar(10),E.ExaminationDate,103) as ExaminationDate,
			EDM.Title as Designation,
			ODM.Title as Department,
			SM.RoundNumber,
			ParticipantCode = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.Code
			when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,
			ParticipantName = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + isnull(EM.LastName,'')
			when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + isnull(CS.LastName,'') end,
			Gender = CASE WHEN E.ParticipantSourceTypeId = 95 then GM.Title
			when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
			else GM2.Title end,
			'Post Accident' as Setup,
			ST.Title as [Status],
			isnull(E.ProcessTypeId,0) as ProcessId,
			PT.Title as ProcessType,
			MobileNumber as MobileNo,
			CompanyEmail,
			D.HealthindicatorId,
			E.ParticipantSourceTypeId,
			E.ParticipantSourceId,
			E.SetupId,
			E.StatusId,
			Age = CASE WHEN E.ParticipantSourceTypeId = 95 then isnull(datediff(yy,EP.DateOfBirth,getdate()),0)
			when E.ParticipantSourceTypeId = 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)
			else isnull(datediff(yy,CS.DateOfBirth,getdate()),0) end,
			GenderId = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.GenderId
			when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
			else CS.GenderId end,
			DateOfBirth = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.DateOfBirth
			when E.ParticipantSourceTypeId = 1001 then EFD.DateOfBirth
			else CS.DateOfBirth end,
			V.Height,
			EP.IsBirthDateUnknown,
			isnull(E.CriteiraGroupId,0) as CriteriaGroupId,
			isnull(E.TargetGroupId,0) as TargetGroupId,
			TG.Title as TargetGroup,
			E.OrganizationDepartmentId as DepartmentId,
			E.EmployeeDesignationId as DesignationId

			FROM sExamination.tExamination E	
		
			inner join @tbltmp t on t.eid = E.Id
			inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
			INNER JOIN sExamination.tDiagnosis D ON D.SourceId= E.Id
			INNER JOIN sExamination.tExaminationRequest ER ON E.Id = ER.ExaminationId 
			left join sCommon.tProcessTypeMaster PT	on PT.Id = E.ProcessTypeId
			left join sHrm.tEmployeeDesignationMaster EDM on E.EmployeeDesignationId = EDM.Id
			left join sCommon.tOrganizationDepartmentMaster ODM on E.OrganizationDepartmentId = ODM.Id
			left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
			left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1001
			left join sHrm.tCSRBenefiterMaster CS on CS.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1009
			left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
			left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
			left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
			left join sExamination.tStatusMaster ST on E.StatusId = ST.Id
			left join sCommon.tGenderMaster GM on EP.GenderId = GM.Id
			left join sCommon.tGenderMaster GM2 on CS.GenderId = GM.Id
			left join sExamination.tVital V on V.SourceId = E.Id
			left join sHrm.tTargetGroupMaster TG on TG.Id = E.TargetGroupId    
			--where tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)		
		) t1
		
		union all
		
		select t2.* from(
			SELECT E.Id AS Id,
			convert(varchar(10),E.ExaminationDate,103) as ExaminationDate,
			EDM.Title as Designation,
			ODM.Title as Department,
			SM.[RoundNumber],
			ParticipantCode = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.Code
			when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,
			ParticipantName = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + isnull(EM.LastName,'')
			when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + isnull(CS.LastName,'') end,
			Gender = CASE WHEN E.ParticipantSourceTypeId = 95 then GM.Title
			when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
			else GM2.Title end,
			Setup = SM.Title,
			ST.Title as [Status],
			E.ProcessTypeId as ProcessId,
			PT.Title as ProcessType,
			MobileNumber as MobileNo,
			CompanyEmail,
			D.HealthindicatorId,
			E.ParticipantSourceTypeId,
			E.ParticipantSourceId,
			E.SetupId,
			E.StatusId,
			Age = CASE WHEN E.ParticipantSourceTypeId = 95 then isnull(datediff(yy,EP.DateOfBirth,getdate()),0)
			when E.ParticipantSourceTypeId = 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)
			else isnull(datediff(yy,CS.DateOfBirth,getdate()),0) end,
			GenderId = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.GenderId
			when E.ParticipantSourceTypeId = 1001 then ISNULL(EFD.GenderId,'')
			else CS.GenderId end,
			DateOfBirth = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.DateOfBirth
			when E.ParticipantSourceTypeId = 1001 then EFD.DateOfBirth
			else CS.DateOfBirth end,
			V.Height,
			EP.IsBirthDateUnknown,
			isnull(E.CriteiraGroupId,0) as CriteriaGroupId,
			isnull(E.TargetGroupId,0) as TargetGroupId,
			TG.Title as TargetGroup,
			E.OrganizationDepartmentId as DepartmentId,
			E.EmployeeDesignationId as DesignationId
			FROM sExamination.tExamination E	
		
			inner join @tbltmp t on t.eid = E.Id	
			inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
			LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= E.Id
			left join sCommon.tProcessTypeMaster PT	on PT.Id=E.ProcessTypeId
			left join sHrm.tEmployeeDesignationMaster EDM on E.EmployeeDesignationId = EDM.Id
			left join sCommon.tOrganizationDepartmentMaster ODM on E.OrganizationDepartmentId = ODM.Id
			left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
			left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1001
			left join sHrm.tCSRBenefiterMaster CS on CS.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1009
			left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
			left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
			left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
			left join sExamination.tStatusMaster ST on E.StatusId = ST.Id
			left join sCommon.tGenderMaster GM on EP.GenderId = GM.Id
			left join sCommon.tGenderMaster GM2 on CS.GenderId = GM.Id
			left join sExamination.tVital V on V.SourceId = E.Id
			left join sHrm.tTargetGroupMaster TG on TG.Id = E.TargetGroupId

			--where tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)		
		) t2
	end
	ELSE
	BEGIN
	  if(@rFlag = 1)
	  BEGIN
		insert into @tbltmp(eid)
		SELECT E.Id
		FROM sExamination.tExamination E
		inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= 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 CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009
		left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		inner join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=E.ParticipantSourceId
		left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id
		left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId
		  left join sProcurement.tVendorMaster CONT on CONT.Id =EJD.ContractorId         

		WHERE ((ISNULL(D.HealthindicatorId,0)=0 AND @rTag != 1)	OR (@rTag = 1 AND ISNULL(D.HealthindicatorId,0) >= 0)
		or (D.HealthindicatorId is null)) AND E.OrgId = @rOrgId
		AND (EM.Code Like @rCode or EM2.Code Like @rCode or CS.Code Like @rCode OR ISNULL(@rCode,'') = '' OR ISNULL(@rCode,'') = '*')
		AND (EM.FirstName Like @rName  + '%' or EFD.Name like @rName  + '%' or CS.FirstName like @rName  + '%' OR ISNULL(@rName,'') = '' OR ISNULL(@rName,'') = '*')
		AND ((E.OrganizationDepartmentId in (SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))
		AND ((E.EmployeeDesignationId in (SELECT item FROM sCommon.fnsplit(@rDesignationId,','))) OR (ISNULL(@rDesignationId,'') = ''))
		AND (STM.MainTypeId = @rMainTypeId) AND ((E.SetupId  IN(SELECT item FROM sCommon.fnsplit(@rSetupId,','))) OR (ISNULL(@rSetupId,'') = ''))
		AND ((E.StatusId in (SELECT item FROM sCommon.fnsplit(@rStatusId,','))) OR (ISNULL(@rStatusId,'') = ''))
		AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) 
		AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))	
		AND ((D.HealthIndicatorId = @rHealthIndicatorId) OR (ISNULL(@rHealthIndicatorId,0) = 0))
		AND ((E.EmployeeCompanyId in (SELECT item FROM sCommon.fnsplit(@rCompanyId,','))) OR (ISNULL(@rCompanyId,'') = ''))
		and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)
		AND ((cast(EJD.DateOfJoining as date) = cast(@rDOJ as date)) OR (ISNULL(@rDOJ,'') = ''))
		   AND ((CONT.Id in (SELECT item FROM sCommon.fnsplit(@rContractorId,','))) OR (ISNULL(@rContractorId,'') = ''))  
		AND Isnull(EM.IsObsolete,0)=0 AND Isnull(EM2.IsObsolete,0)=0
		AND EM.TargetGroupId = 10002
		order by E.ExaminationDate desc
		
		SELECT E.Id,
		convert(varchar(10),E.ExaminationDate,103) as ExaminationDate,
		EDM.Title as Designation,
		ODM.Title as Department,
		SM.[RoundNumber],
		ParticipantCode = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.Code
		when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,
		ParticipantName = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + isnull(EM.LastName,'')
		when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + isnull(CS.LastName,'') end,
		Gender = CASE WHEN E.ParticipantSourceTypeId = 95 then GM.Title
		when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
		else GM2.Title end,
		Setup = SM.Title,
		ST.Title as [Status],
		IsBirthDateUnknown,
		isnull(E.ProcessTypeId,0) as ProcessId,
		PT.Title as ProcessType,
		MobileNumber as MobileNo,
		CompanyEmail,
		D.HealthindicatorId,
		E.ParticipantSourceTypeId,
		E.ParticipantSourceId,
		E.SetupId,
		E.StatusId,
		Age = CASE WHEN E.ParticipantSourceTypeId = 95 then isnull(datediff(yy,EP.DateOfBirth,getdate()),0)
		when E.ParticipantSourceTypeId = 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)
		else isnull(datediff(yy,CS.DateOfBirth,getdate()),0) end,
		GenderId = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.GenderId
		when E.ParticipantSourceTypeId = 1001 then ISNULL(EFD.GenderId,0)
		else CS.GenderId end,
		DateOfBirth = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.DateOfBirth
		when E.ParticipantSourceTypeId = 1001 then EFD.DateOfBirth
		else CS.DateOfBirth end,
		V.Height,
		IsBirthDateUnknown,
		isnull(E.CriteiraGroupId,0) as CriteriaGroupId,
		isnull(E.TargetGroupId,0) as TargetGroupId,
		TG.Title as TargetGroup,
		E.OrganizationDepartmentId as DepartmentId,
		E.EmployeeDesignationId as DesignationId

		FROM sExamination.tExamination E		
		inner join @tbltmp t on t.eid = E.Id
		inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
		LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= E.Id 
		left join sCommon.tProcessTypeMaster PT	on PT.Id=E.ProcessTypeId
		left join sHrm.tEmployeeDesignationMaster EDM on E.EmployeeDesignationId = EDM.Id
		left join sCommon.tOrganizationDepartmentMaster ODM on E.OrganizationDepartmentId = ODM.Id
		left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1001
		left join sHrm.tCSRBenefiterMaster CS on CS.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1009
		left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
		left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
		left join sExamination.tStatusMaster ST on E.StatusId = ST.Id
		left join sCommon.tGenderMaster GM on EP.GenderId = GM.Id
		left join sCommon.tGenderMaster GM2 on CS.GenderId = GM.Id
		left join sExamination.tVital V on V.SourceId = E.Id
		left join sHrm.tTargetGroupMaster TG on TG.Id = E.TargetGroupId
	 
		--where tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)
		order by tid	
	  End
	  else
	  BEGIN
		insert into @tbltmp(eid)
		SELECT E.Id
		FROM sExamination.tExamination E
		inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
		inner join sExamination.tSubTypeMaster STM on SM.SubTypeId = STM.Id
		LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= 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 CS on E.ParticipantSourceId = CS.Id and E.ParticipantSourceTypeId = 1009
		left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		inner join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId=E.ParticipantSourceId
		left join sHrm.tEmployeeTypeMaster TM on EJD.EmployeeTypeId = TM.Id
		left join sHrm.tEmployeeTypeGroupMaster ETM on ETM.Id =TM.EmployeeTypeGroupId
		  left join sProcurement.tVendorMaster CONT on CONT.Id =EJD.ContractorId         

		WHERE ((ISNULL(D.HealthindicatorId,0)=0 AND @rTag != 1)	OR (@rTag = 1 AND ISNULL(D.HealthindicatorId,0) >= 0)
		or (D.HealthindicatorId is null)) AND E.OrgId = @rOrgId
		AND (EM.Code Like @rCode or EM2.Code Like @rCode or CS.Code Like @rCode OR ISNULL(@rCode,'') = '' OR ISNULL(@rCode,'') = '*')
		AND (EM.FirstName Like @rName  + '%' or EFD.Name like @rName  + '%' or CS.FirstName like @rName  + '%' OR ISNULL(@rName,'') = '' OR ISNULL(@rName,'') = '*')
		AND ((E.OrganizationDepartmentId in (SELECT item FROM sCommon.fnsplit(@rDepartmentId,','))) OR (ISNULL(@rDepartmentId,'') = ''))
		AND ((E.EmployeeDesignationId in (SELECT item FROM sCommon.fnsplit(@rDesignationId,','))) OR (ISNULL(@rDesignationId,'') = ''))
		AND (STM.MainTypeId = @rMainTypeId) AND ((E.SetupId  IN(SELECT item FROM sCommon.fnsplit(@rSetupId,','))) OR (ISNULL(@rSetupId,'') = ''))
		AND ((E.StatusId in (SELECT item FROM sCommon.fnsplit(@rStatusId,','))) OR (ISNULL(@rStatusId,'') = ''))
		AND (E.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0) 
		AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))	
		AND ((D.HealthIndicatorId = @rHealthIndicatorId) OR (ISNULL(@rHealthIndicatorId,0) = 0))
		AND ((E.EmployeeCompanyId in (SELECT item FROM sCommon.fnsplit(@rCompanyId,','))) OR (ISNULL(@rCompanyId,'') = ''))
		   AND ((CONT.Id in (SELECT item FROM sCommon.fnsplit(@rContractorId,','))) OR (ISNULL(@rContractorId,'') = ''))  
		and (ETM.Id = @rEmployeeTypeGroupId or @rEmployeeTypeGroupId = 0)
		AND ((cast(EJD.DateOfJoining as date) = cast(@rDOJ as date)) OR (ISNULL(@rDOJ,'') = ''))
		AND Isnull(EM.IsObsolete,0)=0 AND Isnull(EM2.IsObsolete,0)=0
		order by E.ExaminationDate desc
		
		SELECT E.Id,
		convert(varchar(10),E.ExaminationDate,103) as ExaminationDate,
		EDM.Title as Designation,
		ODM.Title as Department,
		SM.[RoundNumber],
		ParticipantCode = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.Code
		when E.ParticipantSourceTypeId = 1001 then EM2.Code else CS.Code end,
		ParticipantName = CASE WHEN E.ParticipantSourceTypeId = 95 then EM.FirstName + ' ' + isnull(EM.LastName,'')
		when E.ParticipantSourceTypeId = 1001 then EFD.Name else CS.FirstName + ' ' + isnull(CS.LastName,'') end,
		Gender = CASE WHEN E.ParticipantSourceTypeId = 95 then GM.Title
		when E.ParticipantSourceTypeId = 1001 then ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
		else GM2.Title end,
		Setup = SM.Title,
		ST.Title as [Status],
		IsBirthDateUnknown,
		isnull(E.ProcessTypeId,0) as ProcessId,
		PT.Title as ProcessType,
		MobileNumber as MobileNo,
		CompanyEmail,
		D.HealthindicatorId,
		E.ParticipantSourceTypeId,
		E.ParticipantSourceId,
		E.SetupId,
		E.StatusId,
		Age = CASE WHEN E.ParticipantSourceTypeId = 95 then isnull(datediff(yy,EP.DateOfBirth,getdate()),0)
		when E.ParticipantSourceTypeId = 1001 then isnull(datediff(yy,EFD.DateOfBirth,getdate()),0)
		else isnull(datediff(yy,CS.DateOfBirth,getdate()),0) end,
		GenderId = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.GenderId
		when E.ParticipantSourceTypeId = 1001 then ISNULL(EFD.GenderId,0)
		else CS.GenderId end,
		DateOfBirth = CASE WHEN E.ParticipantSourceTypeId = 95 then EP.DateOfBirth
		when E.ParticipantSourceTypeId = 1001 then EFD.DateOfBirth
		else CS.DateOfBirth end,
		V.Height,
		IsBirthDateUnknown,
		isnull(E.CriteiraGroupId,0) as CriteriaGroupId,
		isnull(E.TargetGroupId,0) as TargetGroupId,
		TG.Title as TargetGroup,
		E.OrganizationDepartmentId as DepartmentId,
		E.EmployeeDesignationId as DesignationId

		FROM sExamination.tExamination E		
		inner join @tbltmp t on t.eid = E.Id
		inner join sExamination.tSetupMaster SM	on E.SetupId = SM.Id
		LEFT JOIN sExamination.tDiagnosis D ON D.SourceId= E.Id 
		left join sCommon.tProcessTypeMaster PT	on PT.Id=E.ProcessTypeId
		left join sHrm.tEmployeeDesignationMaster EDM on E.EmployeeDesignationId = EDM.Id
		left join sCommon.tOrganizationDepartmentMaster ODM on E.OrganizationDepartmentId = ODM.Id
		left join sHrm.tEmployeeMaster EM on E.ParticipantSourceId = EM.Id and E.ParticipantSourceTypeId = 95
		left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1001
		left join sHrm.tCSRBenefiterMaster CS on CS.Id = E.ParticipantSourceId and E.ParticipantSourceTypeId = 1009
		left join sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
		left join sHrm.tEmployeePersonalDetail EP on EM.Id = EP.EmployeeId
		left join sHrm.tEmployeeCommunications EC on EM.Id = EC.EmployeeId
		left join sExamination.tStatusMaster ST on E.StatusId = ST.Id
		left join sCommon.tGenderMaster GM on EP.GenderId = GM.Id
		left join sCommon.tGenderMaster GM2 on CS.GenderId = GM.Id
		left join sExamination.tVital V on V.SourceId = E.Id
		left join sHrm.tTargetGroupMaster TG on TG.Id = E.TargetGroupId
	 
		--where tid between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)
		order by tid	
	  End
	end
	
	--select @lTotalRec = count(*) from @tbltmp
	
	--if @lTotalRec % @lPageSize = 0
	--	set @lTotalPage = @lTotalRec / @lPageSize
	--else
	--	set @lTotalPage =  @lTotalRec / @lPageSize + 1
		
	--select @lTotalPage as TotalPage,@lTotalRec as TotalRec
end
GO
PRINT N'Altering Procedure [sExamination].[pExaminationStatusDetail]...';


GO

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 [sAppointment].[pAppointmentListGet]...';


GO
ALTER PROCEDURE [sAppointment].[pAppointmentListGet]
    @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      
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,    
	    ISNULL(A.CompliantRemark, '') AS CompliantRemark,   
        A.Age,    
        A.Months,    
        A.GenderId,    
        A.ExaminationId,    
        A.Timeslot, 
		(CASE WHEN A.PatientSourceTypeId = 95 THEN sExamination.fGetLatestHeight(A.PatientSourceId) ELSE 0 END) as Height
    FROM     
        sAppointment.vExtPatientAppointmentDetail A    
    LEFT JOIN     
        sExamination.tExamination E ON A.ExaminationId = E.Id    
        OR A.ReferSourceId = E.Id
	LEFT JOIN
	    sHrm.tEmployeeMaster EM ON EM.Id = A.EmployeeId AND A.PatientSourceTypeId=95
    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.PatientSourceTypeId <> 95
    OR
    (
        A.PatientSourceTypeId = 95
        AND (
            ((EM.StatusId = 9 OR EM.IsObsolete = 1) AND A.ExaminationId > 0)
            OR
            (EM.StatusId <> 9 AND EM.IsObsolete <> 1)
        )
    )
)
        --AND (A.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)
		AND (
             (
               @rStoreLocationId = 0
               AND EXISTS (
                    SELECT 1
                    FROM sCwb.tDoctorStoreLocation DSL
                    WHERE DSL.EmployeeId = @rDoctorEmployeeId
                      AND DSL.SubLocationId = A.StoreLocationId
               )
             )
             OR (
                 @rStoreLocationId <> 0
                 AND A.StoreLocationId = @rStoreLocationId
                 AND EXISTS (
                      SELECT 1
                      FROM sCwb.tDoctorStoreLocation DSL
                      WHERE DSL.EmployeeId = @rDoctorEmployeeId
                        AND DSL.SubLocationId = @rStoreLocationId
                 )
                )
            )
        AND (A.LocationId = @rLocationId OR @rLocationId = 0)    
        AND (A.SetupId = @rSetupId OR @rSetupId = 0)    
        --AND (A.DoctorEmployeeId = @rDoctorEmployeeId OR @rDoctorEmployeeId = 0 OR A.DoctorEmployeeId = 0) 
		AND (
             (
               -- Case 1: @rDoctorEmployeeId = 0 → A.DoctorEmployeeId must exist in DoctorMaster
               @rDoctorEmployeeId = 0
               AND EXISTS (
                   SELECT 1
                   FROM sCwb.tDoctorMaster DM
                   WHERE DM.EmployeeId = A.DoctorEmployeeId
               )
             )
             OR
             (
               -- Case 2: @rDoctorEmployeeId <> 0 → A.DoctorEmployeeId = @rDoctorEmployeeId OR 0
               @rDoctorEmployeeId <> 0
               AND (
                    A.DoctorEmployeeId = @rDoctorEmployeeId
                    OR A.DoctorEmployeeId = 0
               )
               AND EXISTS (
                   SELECT 1
                   FROM sCwb.tDoctorMaster DM
                   WHERE DM.EmployeeId = @rDoctorEmployeeId
               )
             )
            )
        AND ISNULL(A.ExaminationId, 0) = 0    
        AND ISNULL(E.IsCancel, 0) = 0    
        AND A.Id NOT IN (SELECT IsNull(AppointmentId,0) FROM sExamination.tRegistration WHERE OrgId =@rOrgId)
    UNION ALL    
    SELECT     
        ER.Id,    
        NULL AS AppointmentNumber,    
        ER.ParticipantSourceTypeId AS PatientSourceTypeId,    
        ER.ParticipantSourceId AS PatientSourceId,    
        ISNULL(E.FirstName + ' ', '') + ISNULL(E.MiddleName + ' ', '') + ISNULL(E.LastName, '') AS PatientName,    
        ER.RequestedDate AS AppointmentDate,    
         ISNULL(ER.RequestedDate, CONVERT(DATETIME, ER.RequestedDate)) FromTime,    
     ISNULL(ER.RequestedDate, CONVERT(DATETIME, ER.RequestedDate)) AS ToTime,   
        ISNULL(ER.DoctorEmployeeId, 0) AS DoctorEmployeeId,    
        NULL AS EmployeeCode,    
        NULL AS EmployeeId,    
        NULL AS Relation,    
        NULL AS Gender,    
        NULL AS DoctorName,    
        ER.OrgId,    
        NULL AS IsRegister,    
        NULL AS IsObsolete,    
        NULL AS StatusName,    
        NULL AS DepartmentName,    
        NULL AS DepartmentId,    
        NULL AS DependentId,    
        ER.StoreLocationId,    
        ER.SetupId,    
        NULL AS ExaminationTypeId,    
        ST.Title AS MainType,    
  NULL AS Setup,    
        NULL AS ReferSourceId,    
        NULL AS LocationId,    
        NULL AS CauseId,    
        NULL AS StoreLocation,    
        NULL AS OtherName,    
        ER.Reason AS FollowupRemark,    
        NULL AS Age,    
        NULL AS Months,    
        NULL AS GenderId,    
        ER.ExaminationId,    
        NULL AS Timeslot,
		null AS CompliantRemark, 0 as Height
    FROM     
        sExamination.tExaminationRequest ER    
    LEFT JOIN     
        sHrm.tEmployeeMaster E ON E.Id = ER.DoctorEmployeeId    
    inner JOIN     
        (    
            SELECT     
                ST1.MainTypeId,     
                ST1.Title,    
                ROW_NUMBER() OVER (PARTITION BY ST1.MainTypeId ORDER BY ST1.Title) AS RowNum    
            FROM     
                sExamination.tSubTypeMaster ST1    
            WHERE     
                ST1.MainTypeId IS NOT NULL and ST1.MainTypeId=2    
        ) ST ON ST.MainTypeId = ER.SubTypeId AND ST.RowNum = 1     
    WHERE     
        ER.OrgId = @rOrgId    
        AND ER.StatusId = 101    
        AND ER.RequestedDate BETWEEN ISNULL(@rFromDate, sCommon.fGetDate()) AND ISNULL(@rToDate, sCommon.fGetDate())    
        AND (ER.Id = @rId OR @rId = 0)    
        AND (ER.StoreLocationId = @rStoreLocationId OR @rStoreLocationId = 0)    
        AND (ER.SetupId = @rSetupId OR @rSetupId = 0)    
        AND (ER.DoctorEmployeeId = @rDoctorEmployeeId OR @rDoctorEmployeeId = 0)    
    
    ORDER BY     
        Id DESC;    
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 [sAppointment].[pAppointmentListGetscheduling]...';


GO
ALTER PROCEDURE [sAppointment].[pAppointmentListGetscheduling]      
    @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) = '',
	@rAppointmentStatus BIT = NULL
AS      
BEGIN    
    SET @rEmployeeCode = CASE     
        WHEN CHARINDEX('*', @rEmployeeCode) > 0    
            THEN REPLACE(@rEmployeeCode, '*', '%')    
        ELSE '%' + @rEmployeeCode + '%'    
    END;    

	print @rAppointmentStatus;
    
    SELECT * FROM (SELECT     
        A.Id,    
        A.AppointmentNumber,    
        A.PatientSourceTypeId,    
        A.PatientSourceId,    
        A.PatientName,    
        A.AppointmentDate,    
        Convert(varchar,AppointmentDate,103)AppointmentDateStr,    
        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,
		CASE 
            WHEN A.ApprovalStatusId = 550 THEN 1
            WHEN EXISTS (SELECT 1 FROM sExamination.tRegistration R WHERE R.OrgId = @rOrgId AND ISNULL(R.AppointmentId, 0) = A.Id) THEN 1
            ELSE 0 
        END AS IsAppointmentUsed,
		ISNULL(A.VisitTypeId, 0) AS VisitTypeId
    FROM     
        sAppointment.vExtPatientAppointmentDetail A    
    LEFT JOIN 
        sExamination.tExamination E ON
        --A.ExaminationId = E.Id  OR 
         A.ReferSourceId = E.Id    
	LEFT JOIN
	    sHrm.tEmployeeMaster EM ON EM.Id = A.EmployeeId AND A.PatientSourceTypeId=95
    WHERE     
        (A.ApprovalStatusId = 548 OR A.ApprovalStatusId = 550)   
        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 sExamination.tRegistration WHERE OrgId =@rOrgId);
		AND (
    A.PatientSourceTypeId <> 95
    OR
    (
        A.PatientSourceTypeId = 95
        AND (
            ((EM.StatusId = 9 OR EM.IsObsolete = 1) AND A.ExaminationId > 0)
            OR
            (EM.StatusId <> 9 AND EM.IsObsolete <> 1)
        )
    )
)) AS Final
WHERE (@rAppointmentStatus IS NULL OR Final.IsAppointmentUsed = @rAppointmentStatus)
		
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 [sSupport].[pAHCCounsellingListGet]...';


GO

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);    
     
 ---------------------------------------------------              
    -- Cache EventTemplate (IMPORTANT)              
    ---------------------------------------------------              
    DECLARE              
        @MailSubject NVARCHAR(MAX),              
        @MailTemplate NVARCHAR(MAX);              
              
    SELECT TOP 1              
        @MailSubject = MailSubject,              
        @MailTemplate = Template              
    FROM sAlert.tEventTemplate              
    WHERE OrgId = @rOrgId              
      AND EventId = 87              
      AND IsAutoSend = 1;              
      
    
  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, ''), CompanyEmail = ISNULL(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(EMM1.FirstName, '') + ' ' + ISNULL(EMM1.LastName, '') AS AssignedDoctor    
 ,ISNULL(ECD1.ExtensionNo,'') as DoctorExtensionNo    
 ,sm1.title as HealthIndicator,    
 @MailSubject AS MailSubject,    
 @MailTemplate AS MailTemplate,    
 ISNULL(ECD1.CompanyEmail, '') + CASE WHEN ECD1.CompanyEmail IS NOT NULL AND ECD2.CompanyEmail IS NOT NULL 
    THEN ', ' ELSE '' END + ISNULL(ECD2.CompanyEmail, '') as Reportingmanagermail  
 ,VECD1.Gender
 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 sCommon.tStatusMaster SM1 WITH (NOLOCK) ON SM1.Id = PA.HealthIndicatorId      
 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 sHrm.tEmployeeCommunications AS ECD2 WITH (NOLOCK) ON ECD2.EmployeeId = EJD.ReportingMangerEmployeeId
 LEFT JOIN sCommon.tOrganizationDepartmentMaster AS ODM WITH (NOLOCK) ON ODM.Id = EJD.OrganizationDepartmentId        
 LEFT JOIN sHrm.vEmployeeCustomSearch AS VECD1 WITH (NOLOCK) ON VECD1.EmployeeId =  ECD.EmployeeId     
 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 [sExamination].[pSaveAllExaminationDatas]...';


GO

ALTER PROCEDURE [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),1000),                
  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, 6),((v_BodyWeight) / CAST(SQUARE((CASE WHEN (v_height) <= 0 THEN 1                 
   ELSE CAST((v_height) AS DECIMAL(9, 6)) END)/ 100) AS DECIMAL(9, 6)))) END), 3) else 0 end,                
   0,v_CreatedUserId,sCommon.fGetDate(),v_OrgId,  
   left([sSetup].[fPortalXMLTagsReplaceReverse](v_Remark),1000),  
   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, o_VisitTypeId 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,   
 [sSetup].[fPortalXMLTagsReplaceReverse](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,
 T.c.value('@VisitTypeId','int') as VisitTypeId
 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,VisitTypeId,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,o_VisitTypeId,                
    case when a_OtherName <> '' then a_OtherName else null end,left(a_FollowupRemark,1000),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_DrugFrequencyPattern 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 DrugFrequencyText,
 T.c.value('@DrugFrequencyPattern','varchar(200)') as DrugFrequencyPattern,
 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_DrugFrequencyPattern,                
  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,                
  DrugFrequencyPattern = pp_DrugFrequencyPattern,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,DrugFrequencyPattern,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_DrugFrequencyPattern,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(1000),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, o_VisitTypeId int, 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(1000)'),1000) 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('@VisitTypeId','int') as VisitTypeId,
 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,o_VisitTypeId,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,VisitTypeId=o_VisitTypeId,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, VisitTypeId, 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,o_VisitTypeId,m_MobileNumber  
  );
            
  Declare @rCauseId int = 0, @rIsTrackIncidentLog bit = 0, @rIsTrackForFitness bit = 0, 
  @rIsFit bit = 0, @rUnfitListingId bigint = 0, @rFitnessStatus int;            
  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);
  set @rFitnessStatus = (select ISNULL(o_FitnessStatus, 0) from @tblOthers);
            
  IF (@rFitnessStatus <= 5 AND ((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 [sSupport].[pAHCCounsellingReferDoctor]...';


GO

ALTER PROCEDURE [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 AND CAST(Details.[PSA] AS Float) <= 10 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 OR ot.HealthIndicatorCurrentStatus = 608)
						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 OR ot.HealthIndicatorCurrentStatus = 608)
						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 OR ot.HealthIndicatorCurrentStatus = 608)
						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 OR AHCT.HealthIndicatorCurrentStatus = 608)

						--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 OR AHCT.HealthIndicatorCurrentStatus = 608)
			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 [sExamination].[pImportTestAddUpdate]...';


GO

ALTER PROCEDURE [sExamination].[pImportTestAddUpdate]	 
@rXML nvarchar(max),
@rUserId bigint,
@rUserSourceId bigint,
@rstrExaminationXML nvarchar(max) = '',
@rIsUpdate bit,
@rOrgId int,
@rStoreLocationId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	declare @loXMLExamination xml,@loXMLVital xml,@loXMLDisease xml,@loXMLHabit xml,@loXMLHistory xml,
	@loXMLDiagnisis xml,@loXMLTest xml,@loXMLGeneral xml,@loXMLPulmonary xml,@loXMLAudiometry xml, @incExam int
	
	declare @exceptiondetail varchar(max),@orgid int
	
	set @orgid =@rOrgId

	BEGIN TRY	
			
		SET @loXMLTest = CAST(@rXML AS xml)
		SET @loXMLExamination = CAST(@rstrExaminationXML AS xml)		
		
		
	END TRY
	BEGIN CATCH
		insert into tbl_ImportExaminationErrorLog
		select '',0,'Error ' + ERROR_MESSAGE(),sCommon.fGetDate(),@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 @rOrgId,'DBError',5000,@exceptiondetail,sCommon.fGetDate(),@rUserId
	END CATCH
	
	BEGIN TRY
	IF OBJECT_ID('tempdb..#tbltmpExamination') IS NOT NULL
	DROP TABLE #tbltmpExamination

	if(@rstrExaminationXML != '')
	BEGIN
		
		Create table #tbltmpExamination 
		(
			tid int identity(1,1),e_ParticipantSourceId bigint,e_ParticipantSourceTypeId int,
		e_ExaminationDate varchar(200),e_CauseId int,e_SetupId int,e_DeptId int,e_MainTypeId int,
		e_DiseaseAll varchar(max),e_Name varchar(300),e_ExamNumber varchar(200),e_ExaminationId bigint,e_ProcessTypeId int,e_CriteriaGroupId int,
		e_CompanyId int,e_TargetGroupId int,e_DesignationId int,e_GradeId int,e_orgid int
		)		
		insert into #tbltmpExamination
		select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,
		T.c.value('@ParticipantSourceTypeId','int') as ParticipantSourceTypeId,
		T.c.value('@ExaminationDate','varchar(200)') as ExaminationDate,
		T.c.value('@CauseId','int') as CauseId,
		T.c.value('@SetupId','int') as SetupId,
		T.c.value('@DeptId','int') as DeptId,
		T.c.value('@MainTypeId','int') as MainTypeId,
		T.c.value('@Disease','varchar(max)') as Disease,
		T.c.value('@Name','varchar(300)') as Name,
		T.c.value('@OPDNumber','varchar(200)') as ExamNumber,
		0,null,null,null,null,null,null,@rOrgId
		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_orgid = EM.OrgId	
		from #tbltmpExamination inner join sHrm.tEmployeeMaster EM on (Case when(e_ParticipantSourceId = 0) then (Select ParticipantSourceId from sExamination.tExamination where ExaminationNumber = e_ExamNumber and OrgId = @rOrgId and StoreLocationId = @rStoreLocationId) else e_ParticipantSourceId END) = EM.Id  
		inner join sHrm.tEmployeeJobDetail JD on (Case when(e_ParticipantSourceId = 0) then (Select ParticipantSourceId from sExamination.tExamination where ExaminationNumber = e_ExamNumber and OrgId = @rOrgId and StoreLocationId = @rStoreLocationId) else e_ParticipantSourceId END) = JD.EmployeeId
		
		update #tbltmpExamination set e_examinationid =  Id from sExamination.tExamination where ExaminationNumber = Case when (e_ExamNumber != '') then e_ExamNumber else 'NILL' END

		

		select @incExam = count(*) from sExamination.tExamination where isnull(Examinationnumber,'') <> ''
		and DATEDIFF(day,CreatedDateTime,sCommon.fGetDate())>=0 and SetupId = sCommon.fGetIntIdForOrg(8,@rOrgId)
		and StoreLocationId = @rStoreLocationId	
		
		
				
		declare @cntExam int
		select @cntExam = count(*) from #tbltmpExamination
		
		--update #tbltmpExamination set e_examinationid = Id from sExamination.tExamination where ParticipantSourceId = e_ParticipantSourceId
		--and ParticipantSourceTypeId = e_ParticipantSourceTypeId and  SetupId = e_SetupId and Convert(varchar(200),ExaminationDate,103) = Convert(varchar(200),e_ExaminationDate,103)
				
		--select * from #tbltmpExamination

		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
		
		--select * from #tbltmpExaminationNull
		declare @lNextNumber bigint,@lFromNextNumber bigint,@lOrgId int,@lCount int
		select top 1 @lOrgId = e_orgid from #tbltmpExamination
		--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_SetupId,e_ExaminationDate,e_ProcessTypeId,e_CriteriaGroupId,
		e_CompanyId,e_TargetGroupId,e_DesignationId,e_GradeId,e_DeptId,e_ParticipantSourceTypeId,		
		e_examinationid,e_CauseId,tid
		FROM #tbltmpExamination TT LEFT JOIN sExamination.tExamination T ON TT.e_examinationid = T.Id
		) AS Source ON Target.Id = Source.e_examinationid	
		WHEN NOT MATCHED THEN
		INSERT
		(
			OrgId,ParticipantSourceTypeId,ParticipantSourceId,OrganizationDepartmentId,SetupId,
			RoundNumber,StatusId,ExaminationDate,CreatedUserId,CreatedDateTime,
			UpdatedUserId,UpdatedDateTime,ParentExaminationId,StoreLocationId,CauseId,ProcessTypeId,
			EmployeeCompanyId,TargetGroupId,EmployeeDesignationId,CriteiraGroupId,GradeId,DoctorEmployeeId,
			ExaminationNumber
		)
		VALUES
		(
			@rOrgId,e_ParticipantSourceTypeId,e_ParticipantSourceId,e_DeptId,e_SetupId,0,1,
			case when len(e_ExaminationDate) = 10 then convert(Datetime, e_ExaminationDate, 104) else CONVERT(VARCHAR(11), e_ExaminationDate) end,
			@rUserId,sCommon.fGetDate(),@rUserId,sCommon.fGetDate(),0,@rStoreLocationId,e_CauseId,
			e_ProcessTypeId,e_CompanyId,e_TargetGroupId,e_DesignationId,e_CriteriaGroupId,e_GradeId,@rUserSourceId,
			'OPD-' + sCommon.fGetFormattedDate() + RIGHT(10000 + (@incExam + tid) ,4)
		);

		select @lFromNextNumber = SCOPE_IDENTITY(),@lNextNumber=SCOPE_IDENTITY()

		--select @lFromNextNumber,@lNextNumber
		select @cntExam = count(*),@incExam = 1 from #tbltmpExamination
		END

		

		--update #tbltmpExamination set e_ExaminationId = (Case When (e_ExamNumber <> '') then (select Top 1 Id from sExamination.tExamination where ParticipantSourceId = e_ParticipantSourceId
		--and ParticipantSourceTypeId = e_ParticipantSourceTypeId and e_SetupId = SetupId and  Convert(varchar(200),e_ExaminationDate,103) = Convert(varchar(200),ExaminationDate,103)
		--order by convert(datetime, UpdatedDateTime, 103) DESC)
		--else (select Id from sExamination.tExamination where ExaminationNumber = e_ExamNumber) END )

		update #tbltmpExamination set e_ExaminationId = (Select Top 1 Id from sExamination.tExamination where ParticipantSourceId = e_ParticipantSourceId
		and ParticipantSourceTypeId = e_ParticipantSourceTypeId and e_SetupId = SetupId and  Convert(varchar(200),e_ExaminationDate,103) = Convert(varchar(200),ExaminationDate,103)
		order by convert(datetime, UpdatedDateTime, 103) DESC)
		

		update #tbltmpExamination set e_examinationid =  Id from sExamination.tExamination where ExaminationNumber = Case when (e_ExamNumber != '') then e_ExamNumber else 'NILL' END

		select * from #tbltmpExamination
			
		MERGE sExamination.tExaminDisease AS Target USING 
		(
		SELECT Id,e_examinationid,tid
		FROM #tbltmpExamination TT LEFT JOIN sExamination.tExaminDisease T ON TT.e_examinationid = T.SourceId
		) AS Source ON Target.SourceId = Source.e_examinationid	
		WHEN NOT MATCHED THEN
		INSERT
		(
			Id,SourceTypeId,SourceId,Remark,OrgId,IsObsolete
		)
		VALUES
		(
			e_examinationid,1002,e_examinationid,'',@rOrgId,0
		);
	
	--select @lCount = COUNT(1) FROM @tblExamination 
	--SET @lNextNumber  = @lCount + @lFromNextNumber	
	--exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tExaminDisease', @rCurrentNumber = @lNextNumber
	
	declare @tblDisease table
	(
		tid int identity(1,1),d_DisaeseId int,d_ParticipantSoruceId bigint,d_ParticipantSourceTypeId int,d_ExaminationId bigint,
		d_ExaminDiseaseId bigint,d_Name varchar(200)
	)
	insert into @tblDisease
	select null,e_ParticipantSourceId,e_ParticipantSourceTypeId,e_examinationid,null,Item
	from #tbltmpExamination cross apply dbo.fSplitStr(replace(e_DiseaseAll,'+',','),',') where Item <> ''
	
	--select * from @tblDisease
	-- NIL for Empty Disease Name
	update @tblDisease set d_DisaeseId = Id from sExamination.tDiseaseMaster where OrgId = @rOrgId and d_Name = Title
	update @tblDisease set d_DisaeseId = 0 where d_Name = 'NIL'

	--select * from @tblDisease

	update @tblDisease set d_ExaminDiseaseId = Id from sExamination.tExaminDisease where SourceId = d_ExaminationId
	
	
	declare @tblDiseaseN table
	(
		tid int identity(1,1),d_DisaeseId int,d_ParticipantSoruceId bigint,d_ParticipantSourceTypeId int,d_ExaminationId bigint,
		d_ExaminDiseaseId bigint,d_Name varchar(200)
	)
	insert into @tblDiseaseN
	select distinct d_DisaeseId,d_ParticipantSoruceId,d_ParticipantSourceTypeId,d_ExaminationId,d_ExaminDiseaseId,d_Name
	from @tblDisease
	
	--exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tExaminDiseaseDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	--SET @lFromNextNumber = @lNextNumber - 1
	
	MERGE sExamination.tExaminDiseaseDetail AS Target USING 
	(
		SELECT Id,d_ExaminDiseaseId,d_ExaminationId,d_DisaeseId,tid
		FROM @tblDiseaseN TT LEFT JOIN sExamination.tExaminDiseaseDetail T ON TT.d_DisaeseId = T.DiseaseId
		and TT.d_ExaminDiseaseId = T.ExaminDiseaseId
	) AS Source ON Target.ExaminDiseaseId = Source.d_ExaminDiseaseId and Target.DiseaseId = Source.d_DisaeseId	
	WHEN NOT MATCHED THEN
		INSERT
		(
			ExaminDiseaseId,DiseaseId,Remark,OrgId,IsObsolete
		)
		VALUES
		(
			d_ExaminDiseaseId,d_DisaeseId,'',@rOrgId,0
		);
	
			
	
	END TRY
	BEGIN CATCH
		insert into tbl_ImportExaminationErrorLog
		select @rstrExaminationXML,1,'Error ' + ERROR_MESSAGE(),sCommon.fGetDate(),@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 @rOrgId,'DBError',5000,@exceptiondetail,sCommon.fGetDate(),@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_OPDNumber varchar(200),t_TestDetailId int,t_Result varchar(300),t_ExaminationDate varchar(200),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('@OPDNumber','varchar(200)') as OPDNumber,
		T.c.value('@TestDetailId','int') as TestDetailId,
		T.c.value('@Result','varchar(300)') as Result,
		T.c.value('@ExaminationDate','varchar(200)') as ExaminationDate,
		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'
		            AND object_id = OBJECT_ID('sExamination.tTestRequestDetail'))
		BEGIN
			DROP INDEX IX_tTestRequestDetail ON sExamination.tTestRequestDetail
		END
		CREATE INDEX IX_tTestRequestDetail ON sExamination.tTestRequestDetail (Id,TestRequestId,TestDetailId)

		select * from #tbltmpTests

		update #tbltmpTests set t_ExaminationId = (Case When ( t_ParticipantSourceId =0) then (select  Id from sExamination.tExamination  where OrgId = @rOrgId and StoreLocationId = @rStoreLocationId and ExaminationNumber = t_OPDNumber ) else (select e_examinationid from #tbltmpExamination where e_ParticipantSourceId = t_ParticipantSourceId and e_ExaminationDate = t_ExaminationDate )END) ,
		t_OrgId = (Case When ( t_ParticipantSourceId = 0) then (Select OrgId from sExamination.tExamination  where OrgId = @rOrgId and StoreLocationId = @rStoreLocationId and ExaminationNumber = t_OPDNumber) else (select top 1 e_orgid from #tbltmpExamination where e_ParticipantSourceId = t_ParticipantSourceId) END) 

		
		
		update #tbltmpTests set t_TestDetailIdMain = sCommon.fGetIntIdForOrg(t_TestDetailId,t_OrgId)
		
		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
		
		select * from #tbltmpTests
		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 @rOrgId, '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
			(
				@rOrgId,@lFromNextNumber + tid,1002,ExId,0,t_TestId
			);
			
		select @lCount = COUNT(1) FROM @tbl
		SET @lNextNumber  = @lCount + @lFromNextNumber	
		--select @lCount
		exec sCommon.pTableRowIdModify @rOrgId, @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
		
		select * from #tbltmpTests	
		--exec sCommon.pTableRowIdGet @rOrgId, '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
			(
				@rOrgId,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 @rOrgId, @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)
		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,@rOrgId),sCommon.fGetIntIdForOrg(33,@rOrgId),sCommon.fGetIntIdForOrg(31,@rOrgId)
		,sCommon.fGetIntIdForOrg(32,@rOrgId))		
				

		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
		--if(@rstrExaminationXML != '')	
		--BEGIN
		--update w set w.n_StoreLocationId = e.e_StoreLocationId from #tbltmpRatioN w inner join #tbltmpExamination e on w.n_ExaminationId = e.e_examinationid
		--END
		--Else
		--BEGIN

		update w set w.n_StoreLocationId = EE.StoreLocationId from #tbltmpRatioN w inner join sExamination.tExamination EE on w.n_ExaminationId = EE.Id
		--END
		declare @lRatioCnt int,@lRationIncr int,@lConfValueAuto int
		select @lRationIncr = 1,@lRatioCnt = count(*) from #tbltmpRatioN
		
		
		
		
		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',@rOrgId,@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,@rOrgId)
			
			select @lHDLVal = r_Res,@lTestRequestId = r_TestRequestId,@lTestId = r_TestId from #tbltmpRatio
			where r_ExaminationId = @lExaminationId and r_ParameterId = sCommon.fGetIntIdForOrg(33,@rOrgId)
			
			select @lCHOLEVal = r_Res,@lTestRequestId = r_TestRequestId,@lTestId = r_TestId from #tbltmpRatio
			where r_ExaminationId = @lExaminationId and r_ParameterId = sCommon.fGetIntIdForOrg(31,@rOrgId)
			
			select @lTryVal = r_Res,@lTestRequestId = r_TestRequestId,@lTestId = r_TestId from #tbltmpRatio
			where r_ExaminationId = @lExaminationId and r_ParameterId = sCommon.fGetIntIdForOrg(32,@rOrgId)
			
			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,@rOrgId)
			select @lTestDetail2Id = Id from sOrderEntry.tTestDetail where TestParameterId = sCommon.fGetIntIdForOrg(37,@rOrgId)
			select @lTestDetail3Id = Id from sOrderEntry.tTestDetail where TestParameterId = sCommon.fGetIntIdForOrg(35,@rOrgId)
			select @lTestDetail4Id = Id from sOrderEntry.tTestDetail where TestParameterId = sCommon.fGetIntIdForOrg(34,@rOrgId)
			
			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)
				where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail1Id
			end
			else
			begin
				--exec sCommon.pTableRowIdGet @rOrgId, '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,@rOrgId
				
				update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue)
				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)
				where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail2Id
			end
			else
			begin
				--exec sCommon.pTableRowIdGet @rOrgId, '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,@rOrgId
				
				update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue)
				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)
					where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail3Id
				end
				else
				begin
					--exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
					
					insert into sExamination.tTestRequestDetail
					(
						TestRequestId,TestDetailId,ServiceValue,OrgId
					)
					select @lTestRequestId,@lTestDetail3Id,@lVLDL,@rOrgId
					
					update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue)
					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)
					where TestRequestId = @lTestRequestId and TestDetailId = @lTestDetail4Id
				end
				else
				begin
					--exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tTestRequestDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
					
					insert into sExamination.tTestRequestDetail
					(
						TestRequestId,TestDetailId,ServiceValue,OrgId
					)
					select @lTestRequestId,@lTestDetail4Id,@lLDL,@rOrgId
					
					update sExamination.tTestRequestDetail set IsAbnormal = [sExamination].[fGetAbnormalValueForTestN](Id,ServiceValue)
					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)
		from sExamination.tTestRequestDetail inner join #tbltmpRatio on r_TestRequestDetailId = Id


	declare @tblExaminationOPD table
	(
		tid int identity(1,1),e_ParticipantSourceId bigint,e_ParticipantSourceTypeId int,
		e_Name varchar(300),e_ExaminationId bigint
	)
	insert into @tblExaminationOPD
	select e_ParticipantSourceId,e_ParticipantSourceTypeId,e_Name,e_ExaminationId from #tbltmpExamination --where e_ParticipantSourceTypeId = 1009
	
	MERGE sExamination.tOPD AS Target USING 
	(
		SELECT e_Name,e_ExaminationId,tid
		FROM @tblExaminationOPD TT LEFT JOIN sExamination.tOPD T ON TT.e_examinationid = T.ExaminationId
	) AS Source ON Target.ExaminationId = Source.e_examinationid	
	WHEN NOT MATCHED THEN
		INSERT
		(
			ExaminationId,OtherName,OPDTime,OPDOutTime
		)
		VALUES
		(
			e_examinationid,e_Name,LTRIM(RIGHT(CONVERT(VARCHAR(50), GETDATE(), 100), 7)),LTRIM(RIGHT(CONVERT(VARCHAR(50), GETDATE(), 100), 7))
		);	

		select * from @tblExaminationOPD
		
			
	END TRY
	BEGIN CATCH
		insert into tbl_ImportExaminationErrorLog
		select @rXML,7,'Error ' + ERROR_MESSAGE(),sCommon.fGetDate(),@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 @rOrgId,'DBError',5000,@exceptiondetail,sCommon.fGetDate(),@rUserId
	END CATCH
	
END
GO
PRINT N'Altering Procedure [sExamination].[pOPDConsolidatedcostDashboard]...';


GO

ALTER PROCEDURE [sExamination].[pOPDConsolidatedcostDashboard]
(
	@rStoreLocationId int,
	@rParticipantTypeId int,
	@rCaseCauseId int,
	@rLocationId int,
	@rFunctionId int,
	@rDepartmentGroupId int,
	@rDepartmentId int,
	@rGradeId int,
	@rDesignationId int,
	@rJobTitleId int=0,
	@rEmployeeTypeId int=0,
	@rCompanyId int=0,
	@rContractorId int,
	@rGenderId smallint,
	@rStatusId smallint,
	@rAgeFrom int,
	@rAgeTo int=100,
	@rFromDate datetime = null,
	@rToDate datetime = null,
	@rOrgId int,
	@rEmployeeCode nvarchar(50)='',
	@rUserId bigint
)
AS
BEGIN
SET NOCOUNT ON;

DECLARE @CurrentDate DATETIME = GETDATE();

SELECT
	ED.Id AS ExaminationId,
	ED.StoreLocationId AS LocationId,
	
	CASE ED.ParticipantSourceTypeId
		WHEN 95 THEN 'Employee'
		WHEN 1001 THEN 'Dep'
		WHEN 1009 THEN 'Oth'
	END AS EMPType,

	CASE ED.ParticipantSourceTypeId
		WHEN 95 THEN ETM.Code
		WHEN 1001 THEN 'Dep'
		WHEN 1009 THEN BTM.Code
	END AS ParticipantType

INTO #BaseData

FROM sExamination.tExamination ED

LEFT JOIN sHrm.tEmployeeMaster EM ON ED.ParticipantSourceId = EM.Id AND ED.ParticipantSourceTypeId = 95
LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON ED.ParticipantSourceId = EFD.Id AND ED.ParticipantSourceTypeId = 1001
LEFT JOIN sHrm.tCsrBenefiterMaster BM ON BM.Id = ED.ParticipantSourceId AND ED.ParticipantSourceTypeId = 1009
LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
LEFT JOIN sHrm.tEmployeePersonalDetail PD ON EM.Id = PD.EmployeeId
LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
LEFT JOIN sHrm.tEmployeeJobDetail EJD2 ON EFD.EmployeeId = EJD2.EmployeeId

LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM ON BM.CSRBenefiterTypeId = BTM.Id

LEFT JOIN sCommon.tOrganizationDepartmentMaster OD ON ED.OrganizationDepartmentId = OD.Id
LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON OD.DepartmentGroupId = DGM.Id
LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId = FM.Id

LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = ED.CauseId
LEFT JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = ED.StoreLocationId

INNER JOIN sExamination.tSetupMaster SSM ON ED.SetupId = SSM.Id
INNER JOIN sExamination.tSubTypeMaster ST ON SSM.SubTypeId = ST.Id

WHERE 
	ST.MainTypeId = 8
	AND ISNULL(ED.IsCancel,0) = 0
	AND ED.OrgId = @rOrgId
	AND
	(
		(EM.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 95)
		OR (EM2.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 1001)
		OR (BM.Code = @rEmployeeCode AND ED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeCode = ''
	)
	AND
	(
		(EJD.EmployeeJobTitleId = @rJobTitleId AND ED.ParticipantSourceTypeId = 95)
		OR (EJD2.EmployeeJobTitleId = @rJobTitleId AND ED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND ED.ParticipantSourceTypeId = 1009)
		OR @rJobTitleId = 0
	)
	AND
	(
		(EJD.EmployeeTypeId = @rEmployeeTypeId and ED.ParticipantSourceTypeId = 95)
		OR (EJD2.ContractorId = @rEmployeeTypeId and ED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND ED.ParticipantSourceTypeId = 1009)
		OR @rEmployeeTypeId = 0
	)	
	AND
	(
		(EJD.ContractorId = @rContractorId and ED.ParticipantSourceTypeId = 95)
		OR (EJD2.ContractorId = @rContractorId and ED.ParticipantSourceTypeId = 1001)
		OR (0 = 0 AND ED.ParticipantSourceTypeId = 1009)
		OR @rContractorId = 0
	)	
	AND (ED.EmployeeCompanyId=@rCompanyId OR @rCompanyId=0)
	AND
	(
		(PD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 95)
		OR (EFD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1001)
		OR (BM.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1009)
		OR @rGenderId = 0
	)
	AND (EM.StatusId=@rStatusId OR @rStatusId=0)
	AND (@rStoreLocationId = 0 OR ED.StoreLocationId = @rStoreLocationId)
	AND (@rDepartmentId = 0 OR ED.OrganizationDepartmentId = @rDepartmentId)
	AND (@rGradeId = 0 OR ED.GradeId = @rGradeId)
	AND (@rDesignationId = 0 OR ED.EmployeeDesignationId = @rDesignationId)
	AND (@rCaseCauseId = 0 OR ED.CauseId = @rCaseCauseId)
	AND (@rParticipantTypeId = 0 OR ED.ParticipantSourceTypeId = @rParticipantTypeId)
	AND (@rFunctionId = 0 OR FM.Id = @rFunctionId)
	AND (@rDepartmentGroupId = 0 OR DGM.Id = @rDepartmentGroupId)

	AND (@rFromDate IS NULL OR ED.ExaminationDate >= @rFromDate)
	AND (@rToDate IS NULL OR ED.ExaminationDate <= @rToDate)
	AND (
		@rAgeTo = 0 OR
		(
			(ED.ParticipantSourceTypeId = 95 AND PD.DateOfBirth >= DATEADD(YEAR, -@rAgeTo, @CurrentDate))
			OR (ED.ParticipantSourceTypeId = 1001 AND EFD.DateOfBirth >= DATEADD(YEAR, -@rAgeTo, @CurrentDate))
			OR (ED.ParticipantSourceTypeId = 1009 AND BM.DateOfBirth >= DATEADD(YEAR, -@rAgeTo, @CurrentDate))
		)
	)

	AND (
		@rAgeFrom = 0 OR
		(
			(ED.ParticipantSourceTypeId = 95 AND PD.DateOfBirth <= DATEADD(YEAR, -@rAgeFrom, @CurrentDate))
			OR (ED.ParticipantSourceTypeId = 1001 AND EFD.DateOfBirth <= DATEADD(YEAR, -@rAgeFrom, @CurrentDate))
			OR (ED.ParticipantSourceTypeId = 1009 AND BM.DateOfBirth <= DATEADD(YEAR, -@rAgeFrom, @CurrentDate))
		)
	)

	AND UL.UserId = @rUserId;

SELECT
	SUM(CASE WHEN EMPType = 'Oth' THEN 1 ELSE 0 END) AS Oth,
	SUM(CASE WHEN EMPType = 'Employee' THEN 1 ELSE 0 END) AS Employee,
	SUM(CASE WHEN EMPType = 'Dep' THEN 1 ELSE 0 END) AS Dep
FROM #BaseData B
INNER JOIN sIp.tStoreLocationMaster SLM ON B.LocationId = SLM.Id
WHERE 
	SLM.IsActiveHealth = 1
	AND SLM.IsOPDSetup = 1;

DROP TABLE #BaseData;

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


GO

ALTER PROCEDURE [sExamination].[pHealthIndexValueAdd]  
@rSetupId bigint,  
@rSourceId bigint = null,  
@rFromDate Datetime = null,  
@rToDate Datetime = null  
WITH EXECUTE AS CALLER  
AS  
BEGIN  
  
 SET @rFromDate = ISNULL (@rFromDate, '2000-01-01 00:00:00')  
 SET @rToDate = ISNULL (@rToDate, '2090-02-28 00:00:00')  
  
 DECLARE @lExaminationId bigint,  
 @lEarnedPoINTs int,  
 @lTotalPoINTs int,  
 @lParameterId int,  
 @FieldName nvarchar(50),  
 @lFROMValue nvarchar(50),  
 @lToValue nvarchar(50),  
 @lPoINTs int,  
 @lCount int,  
 @lParameterTypeId int,  
 @lQueryString1 nvarchar(max),  
 @lTestParameterId int,  
 @lPercentage decimal(6, 2),  
 @lGenderId tinyint,  
 @lCountIndicator int,  
 @lIndicatorExaminationId bigint,  
 @roundgroupid int,  
 @rOrgId int,
 @lDiagnosisRemark nvarchar(250)
   
 select @rSourceId = case when @rSourceId is null then 0 else @rSourceId end  
 --added by MS for Roundgroup  
 select @roundgroupid = SetupGroupId,@rOrgId=OrgId from sExamination.tsetupmaster where id = @rSetupId  
   
 UPDATE DS SET DS.TotalHealthPoints = 0,DS.EarnedHealthPoints = 0,  
 DS.HealthIndicatorId = 0,DS.AgeGroupId = 0,DS.HealthIndex = 0  
 FROM sExamination.tDiagnosis AS DS  
 INNER JOIN sExamination.tExamination AS EX ON EX.Id = DS.SourceId  
 WHERE EX.SetupId = @rSetupId and (EX.Id = @rSourceId or isnull(@rSourceId,0) = 0)  
 AND ((EX.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((EX.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND EX.OrgId=@rOrgId  
  
 DELETE HI FROM sExamination.tDiagnosisPartial AS HI  
 INNER JOIN sExamination.tExamination AS EX ON Ex.Id = HI.ExaminationId  
 WHERE ex.SetupId = @rSetupId and (EX.Id = @rSourceId or isnull(@rSourceId,0) = 0)  
 AND ((EX.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((EX.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND EX.OrgId=@rOrgId  
  
 DELETE HI FROM sExamination.tHealthIndex AS HI  
 INNER JOIN sExamination.tExamination AS EX ON Ex.Id = HI.ExaminationId  
 WHERE ex.SetupId = @rSetupId and (EX.Id = @rSourceId or isnull(@rSourceId,0) = 0)  
 AND ((EX.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((EX.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND EX.OrgId=@rOrgId  
  
 IF OBJECT_ID('tempdb..#tmpServiceValue') IS NOT NULL begin drop table #tmpServiceValue end  
 IF OBJECT_ID('tempdb..#tHealthIndex') IS NOT NULL begin drop table #tHealthIndex end  
 IF OBJECT_ID('tempdb..#tTable1') IS NOT NULL begin drop table #tTable1 end  
  
 CREATE TABLE #tmpServiceValue  
 (  
  Id int IDENTITY(1,1),TestParameterId int,SourceId bigint,ServiceValue float,ParameterName nvarchar(50),  
  Remark nvarchar(200),GenderId tinyint  
 )  
 CREATE TABLE #tHealthIndex  
 (  
  Id int IDENTITY(1,1),ExaminationId bigint,HealthIndexParameterId int,EarnedPoINTs int,TotalPoINTs int  
 )  
 CREATE TABLE #tTable1  
 (  
  Id bigint IDENTITY,HealthIndexParameterId int,ParameterTypeId int,FieldName nvarchar(50),  
  FROMValue nvarchar(50),ToValue nvarchar(50),PoINTs int,GenderId tinyint,DiagnosisRemark nvarchar(250)  
 )  
 DECLARE @ExaminationTable TABLE  
 (  
  tId int IDENTITY (1, 1),ExaminationId bigint  
 )  
 DECLARE @TempTable1 TABLE  
 (  
  tId int IDENTITY(1,1),TempTableId int,ExaminationId bigint  
 )  
 DECLARE @TempTable2 TABLE  
 (  
  tId int IDENTITY(1,1),TempTableId int,ExaminationId bigint  
 )  
   
 INSERT INTO #tmpServiceValue  
 SELECT TPM.Id,E.Id,ServiceValue,STPM.UCode,TRD.Remark,PD.GenderId  
 FROM sExamination.tExamination E  
 INNER JOIN sHrm.tEmployeePersonalDetail PD ON E.ParticipantSourceId = PD.EmployeeId  
 INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.Id  
 INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id   
 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 AND TPM.ParameterValueTypeId = 1  
 INNER JOIN SOrderEntry.tStaticTestParameterMaster STPM ON TPM.StaticTestParameterId = STPM.Id  
 WHERE ISNUMERIC(TRD.ServiceValue) = 1 AND TRD.ServiceValue <> '+' AND (ISNULL(TRD.ServiceValue, '') != '')  
 AND E.SetupId = @rSetupId and (E.Id = @rSourceId or isnull(@rSourceId,0) = 0)  
 AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND E.OrgId=@rOrgId  
     
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  
 if(@configval='Priority' or @configval='Priority Abnormal')  
  begin  
   -- changes as per mentis issue no:12021 - 2020-07-08 (Rahul,Raju sir,das sir) discussion  
   INSERT INTO #tTable1  
   SELECT HealthIndexParameterId,HealthIndexParameterTypeId,FieldName,FROMValue,ToValue,PoINTs,GenderId,DiagnosisRemark  
   FROM sExamination.tHealthIndexParameterDetail HD  
   INNER JOIN sExamination.tHealthIndexParameterMaster HIM ON HIM.Id = HD.HealthIndexParameterId   
   WHERE HIM.IsObsolete = 0 AND HD.OrgId=@rOrgId AND HIM.OrgId=@rOrgId and HIM.StaticHealthIndexParameterId in(  
    select distinct HealthIndexParameterId from sExamination.tHealthIndexGroupParameter 
	where roundgroupid=@roundgroupid  
   ) OR 
	(        
        HIM.StaticHealthIndexParameterId IN (18,19,21)
        AND EXISTS (
            SELECT 1 
            FROM sExamination.tHealthIndexGroupParameter 
            WHERE RoundGroupId = @roundgroupid
            AND HealthIndexParameterId = 2
        )
    )
   --union  
   --select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','4.00','5.60',10,1,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','4.00','5.60',10,2,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','5.61','6.40',6,1,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','5.61','6.40',6,2,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','6.41','200',3,1,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','6.41','200',3,2,''
   --union  
   --select [sCommon].[fGetIntIdForOrg](18,@rOrgId),2,'DIABETIC_PPBS','0','140.00',10,1,''
   --union  
   --select [sCommon].[fGetIntIdForOrg](18,@rOrgId),2,'DIABETIC_PPBS','0','140.00',10,2,''
   --union  
   --select [sCommon].[fGetIntIdForOrg](18,@rOrgId),2,'DIABETIC_PPBS','140.01','199.00',6,1,''
   --union  
   --select [sCommon].[fGetIntIdForOrg](18,@rOrgId),2,'DIABETIC_PPBS','140.01','199.00',6,2,''
   --union  
   --select [sCommon].[fGetIntIdForOrg](18,@rOrgId),2,'DIABETIC_PPBS','199.01','1000',3,1,''
   --union  
   --select [sCommon].[fGetIntIdForOrg](18,@rOrgId),2,'DIABETIC_PPBS','199.01','1000',3,2,''
   --union  
   --select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','0','120.50',10,1,''
   --union  
   --select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','0','120.50',10,2,''
   --union  
   --select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','120.51','159.50',6,1,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','120.51','159.50',6,2,''
   --union  
   --select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','159.51','1000',3,1,''
   --union  
   --select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','159.51','1000',3,2,'' 
 end  
 else  
 begin  
   INSERT INTO #tTable1  
   SELECT HealthIndexParameterId,HealthIndexParameterTypeId,FieldName,FROMValue,ToValue,PoINTs,GenderId,DiagnosisRemark  
   FROM sExamination.tHealthIndexParameterDetail HD  
   INNER JOIN sExamination.tHealthIndexParameterMaster HIM ON HIM.Id = HD.HealthIndexParameterId   
   WHERE HIM.IsObsolete = 0 AND HD.OrgId=@rOrgId AND HIM.OrgId=@rOrgId and HIM.StaticHealthIndexParameterId in(  
   select distinct HealthIndexParameterId from sExamination.tHealthIndexGroupParameter where roundgroupid=@roundgroupid  
   )  
 end  
  
 --select * from #tTable1 
 --select * from #tmpServiceValue

 SELECT @lCount = COUNT(Id) FROM #tTable1  
   
 WHILE @lCount > 0  
 BEGIN  
  SELECT @lParameterId = 0,@FieldName = '',@lParameterTypeId = 0,@lFROMValue = 0,@lToValue = 0,  
  @lPoINTs = 0,@lGenderId = 0,@lTestParameterId = 0,@lDiagnosisRemark = ''
    
  SELECT @lParameterId = HealthIndexParameterId,@FieldName = FieldName,@lParameterTypeId = ParameterTypeId,  
  @lFROMValue = FROMValue, @lToValue = ToValue, @lPoINTs = PoINTs, @lGenderId = GenderId, @lDiagnosisRemark = DiagnosisRemark  
  FROM #tTable1 WHERE Id = @lCount  
    
  IF (@lParameterTypeId = 1)  
  BEGIN  
   --Vital  
   SET @lQueryString1 = '  SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
   FROM sExamination.tExamination E  
   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
   INNER JOIN sExamination.tVital V ON V.SourceId=E.Id  
   WHERE  (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ')  
   AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
   AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
   AND (' + CAST(@lFROMValue AS nvarchar(30)) + '<=' + CAST(@FieldName AS nvarchar(30)) + ')  
   AND (' + CAST(@FieldName AS nvarchar(30)) + '<=' + CAST(@lToValue AS nvarchar(30)) + ')  
   AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
   AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'  
   --0<=bmi and bmi<=20     
  END  
  ELSE IF (@lParameterTypeId = 2)  
  BEGIN  
   --Numeric Test  
   SELECT @lTestParameterId = TestParameterId  
   FROM #tmpServiceValue WHERE ParameterName LIKE (Case WHEN @FieldName = 'DIABETIC' THEN 'DIABETIC_FBS' ELSE @FieldName END)
     
   --select @FieldName,@lTestParameterId  
     
   SET @lQueryString1 = 'SELECT SourceId,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
   FROM #tmpServiceValue WHERE TestParameterId = (' + CAST(@lTestParameterId AS nvarchar(30)) + ')' + '  
   AND (' + CAST(@lFROMValue AS nvarchar(30)) + ' <= ServiceValue' + ')  
   AND (GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ')  OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
   AND ( ServiceValue <=' + CAST(@lToValue AS nvarchar(30)) + ')'  
  END  
  ELSE IF (@lParameterTypeId = 3)  
  BEGIN  
   --List Test     
   SELECT @lTestParameterId = TestParameterId  
   FROM sExamination.tExamination E  
   INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.id  
   INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id  
   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 AND TPM.ParameterValueTypeId = 2  
   WHERE TPM.Title LIKE @FieldName  
     
   SET @lQueryString1 = 'SELECT SourceId,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
   FROM sExamination.tExamination E  
   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
   INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.id  
   INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id  
   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 AND TPM.ParameterValueTypeId = 2  
   WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' AND E.ParticipantSourceTypeId = 95  
   AND (E.Id=' + CAST(@rSourceId AS nvarchar(30)) + ' OR ' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0)  
   AND (EPD.GenderId=' + CAST(@lGenderId AS nvarchar(30)) + ' OR ' + CAST(@lGenderId AS nvarchar(30)) + ' = 0)  
   AND TestParameterId = ' + CAST(@lTestParameterId AS nvarchar(30)) + '  
   AND ServiceValue = ''' + CAST(@lFROMValue AS nvarchar(30)) + '''' + 'AND ServiceValue <> ''''  
   AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
   AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'  
  END  
  ELSE IF (@lParameterTypeId = 4)  
  BEGIN  
   IF (CAST(@FieldName AS int) = 2)  
   BEGIN  
    --Habit  
    SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    INNER JOIN sExamination.tHabitHygine H ON H.SourceId=E.Id  
    LEFT JOIN sExamination.tHabitHygineDetail HD ON HD.HabitHygineId=H.Id AND HD.IsObsolete=0  
    WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
    AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
    AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
   AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))  
    Group by E.Id,HD.HabitHygineId having (COUNT(HD.HabitHygineId) >=' + CAST(@FieldName AS nvarchar(30)) + ')'  
   END  
   ELSE IF (CAST(@FieldName AS int) = 1)  
   BEGIN  
    SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    INNER JOIN sExamination.tHabitHygine H ON H.SourceId=E.Id  
    LEFT JOIN sExamination.tHabitHygineDetail HD ON HD.HabitHygineId=H.Id AND HD.IsObsolete=0  
    WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
    AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
    AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
   AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))  
    Group by E.Id,HD.HabitHygineId having (COUNT(HD.HabitHygineId) =' + CAST(@FieldName AS nvarchar(30)) + ')'  
   END  
   ELSE IF (CAST(@FieldName AS int) = 0)  
   BEGIN  
    SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    LEFT JOIN sExamination.tHabitHygine H ON H.SourceId=E.Id  
    LEFT JOIN sExamination.tHabitHygineDetail HD ON HD.HabitHygineId=H.Id AND HD.IsObsolete=0  
    WHERE HD.Id is null AND  E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
    AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
    AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
    AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'  
   END  
  END  
  ELSE IF (@lParameterTypeId = 5)  
  BEGIN  
   IF (CAST(@FieldName AS int) = 2)  
   BEGIN  
    --Life Style Disease  
    SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    INNER JOIN sExamination.tExistingDisease ED ON ED.SourceId=E.Id  
    inner JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId=ED.Id AND EDD.IsObsolete=0  
    WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
    AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
    AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
    AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))  
    Group by E.Id,EDD.ExistingDiseaseId having (COUNT(EDD.ExistingDiseaseId) >=' + CAST(@FieldName AS nvarchar(30)) + ')'  
   END  
   ELSE IF (CAST(@FieldName AS int) = 1)  
   BEGIN  
    SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    INNER JOIN sExamination.tExistingDisease ED ON ED.SourceId=E.Id  
    inner JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId=ED.Id AND EDD.IsObsolete=0  
    WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
    AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
    AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
    AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))  
    Group by E.Id,EDD.ExistingDiseaseId having (COUNT(EDD.ExistingDiseaseId) =' + CAST(@FieldName AS nvarchar(30)) + ')'  
   END  
   ELSE IF (CAST(@FieldName AS int) = 0)  
   BEGIN  
    SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    LEFT JOIN sExamination.tExistingDisease ED ON ED.SourceId=E.Id  
    WHERE ED.Id IS NULL and E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
    AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
    AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))  
    UNION SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    INNER JOIN sExamination.tExistingDisease ED ON ED.SourceId=E.Id  
    LEFT JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId=ED.Id AND EDD.IsObsolete=0  
    WHERE EDD.Id IS NULL  AND  E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
    AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
    AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
    AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'  
    --and ISNULL(ED.Remark,'''') <> ''''  
   END  
  END  
  ELSE IF (@lParameterTypeId = 11)  
  BEGIN  
   --Shift Duty  
   SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',0  
   FROM sExamination.tExamination E  
   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=E.ParticipantSourceId  
   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
   WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
   AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
   AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
   AND EJD.IsWorkingInShift = 1  
   AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
   AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'  
  END  
  ELSE  
  IF (@lParameterTypeId = 12)  
  BEGIN  
   --Hazard Process  
   SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',0  
   FROM sExamination.tExamination E  
   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
   WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
   AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
   AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0)) AND E.ProcessTypeId = 1  
   AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
   AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'  
  END 
  IF (@lParameterTypeId = 13)  
  BEGIN  
   --Audiometry  
   SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
   FROM sExamination.tExamination E
   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
   INNER JOIN sExamination.tAudiometry AUD ON AUD.SourceId=E.Id
   INNER JOIN sExamination.tAudiometryResultMaster ARM ON ARM.Id = CASE WHEN AUD.AudiometryAcResultLeftId > AUD.AudiometryAcResultRightId 
																   THEN AUD.AudiometryAcResultLeftId ELSE AUD.AudiometryAcResultRightId END
   WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
   AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
   AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
   AND UPPER(LTRIM(RTRIM(ARM.Title))) = UPPER(''' + @lDiagnosisRemark + ''')
   AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
   AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'  
  END
  IF (@lParameterTypeId = 14)  
  BEGIN  
   --Pulmonary  
   SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
   FROM sExamination.tExamination E
   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
   INNER JOIN sExamination.tPulmonary PUL ON PUL.SourceId=E.Id
   WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '  
   AND (E.Id=(' + CAST(@rSourceId AS nvarchar(30)) + ') OR (' + CAST(isnull(@rSourceId,0) AS nvarchar(30)) + ' = 0))  
   AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
   AND UPPER(LTRIM(RTRIM(ISNULL(PUL.PulmonaryResulIntensity,'''') + '' '' + ISNULL(PUL.PulmonaryResult,'''')))) = UPPER(''' + @lDiagnosisRemark + ''')
   AND (E.ExaminationDate >=(''' + Convert(nvarchar(30),@rFromDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rFromDate,''''),102) + ''' = ''''))  
   AND (E.ExaminationDate <=(''' + Convert(nvarchar(30),@rToDate,102) + ''') OR (''' + Convert(nvarchar(30),isnull(@rToDate,''''),102) + ''' = ''''))'  
  END
  
    
  print @lQueryString1     
  INSERT INTO #tHealthIndex  
  EXECUTE sp_executesql @lQueryString1  
  SET @lCount = @lCount - 1  
  
    
 END  
   
 --select * from #tHealthIndex  
 --return
 print @configval  
 if(@configval='Priority')  
  begin  
   -- changes as per mentis issue no:12021 - 2020-07-08 (Rahul,Raju sir,das sir) discussion  
   -- new changes as per mentis issue no:32667 - Nidhi Pandey - 10/04/2024  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](19,@rOrgId)  
   )   
   and HealthIndexParameterId   
   --in ([sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](2,@rOrgId)  
   ) and HealthIndexParameterId   
   in ([sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   --in ([sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId)  
   ) and HealthIndexParameterId in ([sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   --select * from #tHealthIndex  
   --update #tHealthIndex set HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](2,@rOrgId)  
   --where (HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](19,@rOrgId)   
   --or HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](18,@rOrgId)   
   --or HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   --select * from #tHealthIndex  
   -- new changes end as per mentis issue no:32667 - Nidhi Pandey - 10/04/2024  
  end  
 else if(@configval='Priority Abnormal')  
  begin  
     
   -- changes as per mentis issue no:12372 - 2020-07-08 (Rahul,Raju sir,das sir) discussion  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](19,@rOrgId) and isnull(EarnedPoINTs,0)=3  
   )   
   and HealthIndexParameterId   
   --in ([sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](2,@rOrgId) and isnull(EarnedPoINTs,0)=3  
   ) and HealthIndexParameterId   
   --in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   in ([sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId) and isnull(EarnedPoINTs,0)=3  
   ) and HealthIndexParameterId   
   --in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](21,@rOrgId) and isnull(EarnedPoINTs,0)=3  
   ) and HealthIndexParameterId   
   --in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](19,@rOrgId) and isnull(EarnedPoINTs,0)=6  
   )   
   and HealthIndexParameterId   
   --in ([sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](2,@rOrgId) and isnull(EarnedPoINTs,0)=6  
   ) and HealthIndexParameterId   
   --in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   in ([sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId) and isnull(EarnedPoINTs,0)=6  
   ) and HealthIndexParameterId   
   --in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](21,@rOrgId) and isnull(EarnedPoINTs,0)=6  
   ) and HealthIndexParameterId   
   --in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](19,@rOrgId) and isnull(EarnedPoINTs,0)=10  
   )   
   and HealthIndexParameterId   
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   --in ([sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](2,@rOrgId) and isnull(EarnedPoINTs,0)=10  
   ) and HealthIndexParameterId   
   --in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   in ([sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId) and isnull(EarnedPoINTs,0)=10  
   ) and HealthIndexParameterId   
   --in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](21,@rOrgId) and isnull(EarnedPoINTs,0)=10  
   ) and HealthIndexParameterId   
   --in ([sCommon].[fGetIntIdForOrg](20,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId))  
     
   --update #tHealthIndex set HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](2,@rOrgId)  
   --where (HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](19,@rOrgId)   
   --or HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](18,@rOrgId)   
   --or HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
  end  
  
  --select * from #tHealthIndex  
  --return  
  
 if @rSourceId > 0  
 begin   
  delete from #tHealthIndex where ExaminationId <> @rSourceId  
 end  
   
 insert into @TempTable1  
 SELECT h.Id,h.ExaminationId FROM #tHealthIndex as h  
 inner join sExamination.tExamination as exm on exm.Id=h.ExaminationId  
 INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = h.HealthIndexParameterId AND pm.OrgId=@rOrgId  
 inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @roundgroupid  
 where exm.SetupId=@rSetupId and (exm.Id = @rSourceId or isnull(@rSourceId,0) = 0) AND pm.StaticHealthIndexParameterId IN (12)  
 AND ((exm.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((exm.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND exm.OrgId=@rOrgId  
 --AND exm.GradeId   IN (300100120, 300100121, 300100122, 300100123, 300100124, 300100125, 300100126)  
    
 insert into @TempTable2  
 SELECT h.Id,h.ExaminationId FROM #tHealthIndex as h  
 inner join sExamination.tExamination as exm on exm.Id=h.ExaminationId  
 INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = h.HealthIndexParameterId AND pm.OrgId=@rOrgId  
 inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @roundgroupid  
 where exm.SetupId=@rSetupId and (exm.Id = @rSourceId or isnull(@rSourceId,0) = 0)  
 AND pm.StaticHealthIndexParameterId IN (14)  
 AND ((exm.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((exm.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND exm.OrgId=@rOrgId  
 --AND exm.GradeId   IN (300100120, 300100121, 300100122, 300100123, 300100124, 300100125, 300100126)  
   
 DELETE FROM #tHealthIndex WHERE Id IN  
 (  
  SELECT h.id FROM #tHealthIndex AS h  
  INNER JOIN sExamination.tExamination AS exm ON exm.Id = h.ExaminationId  
  INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = h.HealthIndexParameterId AND pm.OrgId=@rOrgId  
  inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @roundgroupid  
  WHERE exm.SetupId = @rSetupId and (exm.Id = @rSourceId or isnull(@rSourceId,0) = 0) 
  AND pm.StaticHealthIndexParameterId NOT IN   
  (  
   select HealthIndexParameterId from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @roundgroupid  
  )
  AND NOT
  (
    pm.StaticHealthIndexParameterId IN (18,19,21)
    AND EXISTS (
        SELECT 1 
        FROM sExamination.tHealthIndexGroupParameter 
        WHERE RoundGroupId = @roundgroupid
        AND HealthIndexParameterId = 2
    )
  )
  AND ((exm.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
  AND ((exm.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
  
  UNION ALL  
  
  SELECT t2.TempTableId FROM @TempTable1 AS t  
  INNER JOIN @TempTable2 AS t2 ON t.ExaminationId = t2.ExaminationId  
 )  
   
 declare @ParameterCountNonExcutive int = 0, @MaleParameterCountNonExcutive int = 0, @FemaleParameterCountNonExcutive int = 0;
 declare @ParameterCountExcutive int = 0;
 select @ParameterCountNonExcutive=count(1) from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=2  and ISNULL(RoundGroupId,0) = @roundgroupid  
 select @ParameterCountExcutive=count(1) from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=1  and ISNULL(RoundGroupId,0) = @roundgroupid  
   
 select @MaleParameterCountNonExcutive = (select Count(0) from (
	 select GenderId, HIPM.Title from sExamination.tHealthIndexGroupParameter HIGP
	 INNER JOIN sExamination.tStaticHealthIndexParameterDetail HIPD ON HIPD.StaticHealthIndexParameterId = HIGP.HealthIndexParameterId
	 INNER JOIN sExamination.tStaticHealthIndexParameterMaster HIPM ON HIPM.Id = HIPD.StaticHealthIndexParameterId
	 where HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @roundgroupid and GenderId = 1
	 Group BY GenderId,HIPM.Title
 ) male)

 select @FemaleParameterCountNonExcutive = (select Count(0) from (
	 select GenderId, HIPM.Title from sExamination.tHealthIndexGroupParameter HIGP
	 INNER JOIN sExamination.tStaticHealthIndexParameterDetail HIPD ON HIPD.StaticHealthIndexParameterId = HIGP.HealthIndexParameterId
	 INNER JOIN sExamination.tStaticHealthIndexParameterMaster HIPM ON HIPM.Id = HIPD.StaticHealthIndexParameterId
	 where HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @roundgroupid and GenderId = 2
	 Group BY GenderId,HIPM.Title
 ) female)

 INSERT INTO sExamination.tHealthIndex  
 SELECT  T.ExaminationId,T.HealthIndexParameterId,MAX(T.EarnedPoINTs),Max(T.TotalPoINTs)   
 FROM #tHealthIndex T  
 Group by T.ExaminationId,T.HealthIndexParameterId  
 --left join sExamination.tHealthIndex H On H.examinationid=T.ExaminationId and H.Healthindexparameterid=T.HealthIndexParameterId  
 --where T.examinationid is null and T.HealthIndexParameterId is null  
     
 INSERT INTO @ExaminationTable  
 SELECT exm.Id  
 FROM sExamination.tExamination AS exm  
 INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = exm.ParticipantSourceId
 INNER JOIN sExamination.tSetupMaster AS stp ON stp.Id = exm.SetupId  
 INNER JOIN sExamination.tDiagnosis AS dis ON dis.SourceId = exm.Id  
 INNER JOIN sExamination.tHealthIndex AS hei ON hei.ExaminationId = exm.Id  
 INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = hei.HealthIndexParameterId  
 inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @roundgroupid  
 --inner join sExamination.tHealthIndexGroupParameter as gpm on gpm.HealthIndexParameterId=pm.StaticHealthIndexParameterId and gpm.HealthIndexGroupId=2 and ISNULL(gpm.RoundGroupId,0) = @roundgroupid  
 WHERE exm.SetupId = @rSetupId and (exm.Id = @rSourceId or isnull(@rSourceId,0) = 0)   
 AND ((exm.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((exm.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND EXM.OrgId=@rOrgId
 AND (pm.StaticHealthIndexParameterId IN (select HealthIndexParameterId from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @roundgroupid)
     OR (pm.StaticHealthIndexParameterId in (18,19,21) AND EXISTS (SELECT 1 FROM sExamination.tHealthIndexGroupParameter 
             WHERE RoundGroupId = @roundgroupid AND HealthIndexParameterId = 2)))
 GROUP BY exm.Id, EPD.GenderId HAVING COUNT(0) >= CASE 
                     WHEN EPD.GenderId = 1 THEN @MaleParameterCountNonExcutive
                     WHEN EPD.GenderId = 2 THEN @FemaleParameterCountNonExcutive
                   END

 UNION ALL  
  
 SELECT exm.Id  
 FROM sExamination.tExamination AS exm  
 INNER JOIN sExamination.tSetupMaster AS stp ON stp.Id = exm.SetupId  
 INNER JOIN sExamination.tDiagnosis AS dis ON dis.SourceId = exm.Id  
 INNER JOIN sExamination.tHealthIndex AS hei ON hei.ExaminationId = exm.Id  
 INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = hei.HealthIndexParameterId  
 inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @roundgroupid  
 WHERE exm.SetupId = @rSetupId and (exm.Id = @rSourceId or isnull(@rSourceId,0) = 0)   
 AND pm.StaticHealthIndexParameterId IN (12, 14)   
 AND ((exm.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((exm.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND EXM.OrgId=@rOrgId  

 UNION ALL 
 
 SELECT exm.Id  
 FROM sExamination.tExamination AS exm  
 INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = exm.ParticipantSourceId
 INNER JOIN sExamination.tSetupMaster AS stp ON stp.Id = exm.SetupId  
 INNER JOIN sExamination.tDiagnosis AS dis ON dis.SourceId = exm.Id  
 INNER JOIN sExamination.tHealthIndex AS hei ON hei.ExaminationId = exm.Id  
 INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = hei.HealthIndexParameterId AND pm.OrgId=@rOrgId  
 inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @roundgroupid   
 --inner join sExamination.tHealthIndexGroupParameter as gpm on gpm.HealthIndexParameterId=pm.StaticHealthIndexParameterId and gpm.HealthIndexGroupId=1 and ISNULL(gpm.RoundGroupId,0) = @roundgroupid  
 WHERE exm.SetupId = @rSetupId and (exm.Id = @rSourceId or isnull(@rSourceId,0) = 0) AND pm.StaticHealthIndexParameterId not IN (12, 14)  
 AND ((exm.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((exm.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND EXM.OrgId=@rOrgId
 AND (pm.StaticHealthIndexParameterId IN (select HealthIndexParameterId from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @roundgroupid)
     OR (pm.StaticHealthIndexParameterId in (18,19,21) AND EXISTS (SELECT 1 FROM sExamination.tHealthIndexGroupParameter 
             WHERE RoundGroupId = @roundgroupid AND HealthIndexParameterId = 2)))
 GROUP BY exm.Id, EPD.GenderId HAVING COUNT(0) >= CASE 
                     WHEN EPD.GenderId = 1 THEN @MaleParameterCountNonExcutive
                     WHEN EPD.GenderId = 2 THEN @FemaleParameterCountNonExcutive
                   END
 --GROUP BY exm.Id HAVING COUNT(0) >= @ParameterCountNonExcutive  
   
 INSERT INTO sExamination.tDiagnosisPartial  
 (  
  ExaminationId,TotalHealthPoints,EarnedHealthPoints,HealthIndicatorId,AgeGroupId,HealthIndex  
 )  
 SELECT Distinct EX.ExaminationId,EX.TotalPoints,EX.EarnedPoints,EX.HealthIndicatorId,EX.AgeGroupId,  
 CONVERT(decimal(6, 2),(CONVERT(decimal(6, 2),ISNULL(EX.EarnedPoints, 0)) * 100) / CONVERT(decimal(6, 2),  
 ISNULL(EX.TotalPoints, 0)))  
 FROM sExamination.tDiagnosis AS DS  
 INNER JOIN  
 (  
  SELECT a.ExaminationId,a.EarnedPoints,a.TotalPoints,a.Percentage,  
  (  
   SELECT ID  
   FROM [sExamination].[tHealthIndicatorMaster]  
   WHERE RangeTo >= a.Percentage  
   AND a.Percentage > RangeFrom  
  )  
  HealthIndicatorId,[dbo].[fGetAgeGroupId](ISNULL(DATEDIFF(yy, EPD.DateOfBirth, sCommon.fGetDate()), 0),EPD.OrgId) AgeGroupId  
  FROM  
  (  
   SELECT ExaminationId,SUM(EarnedPoints) EarnedPoints,SUM(TotalPoints) TotalPoints,  
   ISNULL(CONVERT(decimal(18, 2), ((CONVERT(decimal(6, 2), SUM(EarnedPoints)) * 100) / CONVERT(decimal(6, 2),  
   SUM(TotalPoints)))), 0) Percentage  
   FROM sExamination.tHealthIndex  
   GROUP BY ExaminationId  
   HAVING SUM(TotalPoINTs) > 0  
  ) AS a  
  INNER JOIN sExamination.tExamination E ON e.id = a.ExaminationId AND E.SetupId = @rSetupId AND e.OrgId=@rOrgId  
  and (E.Id = @rSourceId or isnull(@rSourceId,0) = 0)  
  AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
  AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
  LEFT JOIN sHrm.tEmployeePersonalDetail AS EPD ON EPD.EmployeeId = e.ParticipantSourceId  
 ) AS EX ON EX.ExaminationId = DS.SourceId  
 left join @ExaminationTable e2 on e2.ExaminationId=ds.SourceId  
 where e2.ExaminationId is null   
  
 UPDATE DS SET DS.TotalHealthPoints = EX.TotalPoints,  
 DS.EarnedHealthPoints = EX.EarnedPoints,DS.HealthIndicatorId = EX.HealthIndicatorId,  
 DS.AgeGroupId = EX.AgeGroupId,  
 DS.HealthIndex = CONVERT(decimal(6, 2), (CONVERT(decimal(6, 2), ISNULL(EX.EarnedPoints, 0)) * 100) / CONVERT(decimal(6, 2), ISNULL(EX.TotalPoints, 0)))  
 FROM sExamination.tDiagnosis AS DS  
 INNER JOIN  
 (  
  SELECT a.ExaminationId,a.EarnedPoints,a.TotalPoints,a.Percentage,  
  (  
   SELECT ID FROM [sExamination].[tHealthIndicatorMaster]  
   WHERE RangeTo >= a.Percentage AND a.Percentage > RangeFrom  
  )  
  HealthIndicatorId,[dbo].[fGetAgeGroupId](ISNULL(DATEDIFF(yy, EPD.DateOfBirth, sCommon.fGetDate()), 0), EPD.OrgId) AgeGroupId  
  FROM  
  (  
   SELECT ExaminationId,SUM(EarnedPoints) EarnedPoints,SUM(TotalPoints) TotalPoints,  
   ISNULL(CONVERT(decimal(18, 2), ((CONVERT(decimal(6, 2), SUM(EarnedPoints)) * 100) / CONVERT(decimal(6, 2), SUM(TotalPoints)))), 0) Percentage  
   FROM sExamination.tHealthIndex GROUP BY ExaminationId HAVING SUM(TotalPoINTs) > 0  
  ) AS a INNER JOIN sExamination.tExamination E  
  ON e.id = a.ExaminationId AND E.SetupId = @rSetupId and (E.Id = @rSourceId or isnull(@rSourceId,0) = 0) AND e.OrgId=@rOrgId  
  AND ((E.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
  AND ((E.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
  LEFT JOIN sHrm.tEmployeePersonalDetail AS EPD ON EPD.EmployeeId = e.ParticipantSourceId  
 ) AS EX ON EX.ExaminationId = DS.SourceId  
 left join @ExaminationTable as e2 on e2.ExaminationId=ds.SourceId  
 where e2.ExaminationId is not null   
  
 DELETE HI FROM sExamination.tHealthIndexPartial AS HI  
 INNER JOIN sExamination.tExamination AS EX ON Ex.Id = HI.ExaminationId  
 left join @ExaminationTable as e2 on e2.ExaminationId=hi.ExaminationId  
 WHERE ex.SetupId = @rSetupId and (ex.Id = @rSourceId or isnull(@rSourceId,0) = 0) and e2.ExaminationId is null  
 AND ((EX.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((EX.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND ex.OrgId=@rOrgId  
  
 INSERT INTO sExamination.tHealthIndexPartial  
 (  
  ExaminationId,HealthIndexParameterId,EarnedPoints,TotalPoints  
 )  
 SELECT HI.ExaminationId,HI.HealthIndexParameterId,HI.EarnedPoints,HI.TotalPoints  
 FROM sExamination.tHealthIndex AS HI  
 INNER JOIN sExamination.tExamination AS EX ON Ex.Id = HI.ExaminationId  
 LEFT JOIN @ExaminationTable as e2 on e2.ExaminationId=hi.ExaminationId  
 WHERE ex.SetupId = @rSetupId and (ex.Id = @rSourceId or isnull(@rSourceId,0) = 0) and e2.ExaminationId is null  
 AND ((EX.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((EX.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND ex.OrgId=@rOrgId
  
 DELETE HI FROM sExamination.tHealthIndex AS HI  
 INNER JOIN sExamination.tExamination AS EX ON Ex.Id = HI.ExaminationId  
 LEFT JOIN @ExaminationTable as e2 on e2.ExaminationId=hi.ExaminationId  
 WHERE ex.SetupId = @rSetupId and (ex.Id = @rSourceId or isnull(@rSourceId,0) = 0) and e2.ExaminationId is null  
 AND ((EX.ExaminationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((EX.ExaminationDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND ex.OrgId=@rOrgId  
  
 update sExamination.tSetupMaster set IsHealthIndexUpdated =1 where Id=@rSetupId   
   
   
 SELECT 1 AS Result  
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].[pBulkOperationHealthIndexValue]...';


GO

ALTER PROCEDURE [sExamination].[pBulkOperationHealthIndexValue]  
@rSetupGroupId int = 0,  
@rSetupId int = 0  
WITH EXECUTE AS CALLER  
AS  
BEGIN  
  
 DECLARE @lExaminationId bigint,  
 @lEarnedPoINTs int,  
 @lTotalPoINTs int,  
 @lParameterId int,  
 @FieldName nvarchar(50),  
 @lFROMValue nvarchar(50),  
 @lToValue nvarchar(50),  
 @lPoINTs int,  
 @lCount int,  
 @lParameterTypeId int,  
 @lQueryString1 nvarchar(max),  
 @lTestParameterId int,  
 @lPercentage decimal(6, 2),  
 @lGenderId tinyint,  
 @lCountIndicator int,  
 @lIndicatorExaminationId bigint,   
 @rOrgId int,
 @lDiagnosisRemark nvarchar(250)
   
  
 SELECT @rOrgId = OrgId FROM sExamination.tSetupGroupMaster WHERE Id = @rSetupGroupId  
   
 UPDATE DS SET DS.TotalHealthPoints = 0,DS.EarnedHealthPoints = 0,  
 DS.HealthIndicatorId = 0,DS.AgeGroupId = 0,DS.HealthIndex = 0  
 FROM sExamination.tDiagnosis AS DS  
 INNER JOIN sExamination.tExamination AS EX ON EX.Id = DS.SourceId  
 INNER JOIN sExamination.tSetupMaster SM ON EX.SetupId = SM.Id  
 WHERE SM.SetupGroupId = @rSetupGroupId  
 AND (EX.SetupId = @rSetupId OR @rSetupId = 0)  
 AND EX.OrgId = @rOrgId  
  
 DELETE HI FROM sExamination.tDiagnosisPartial AS HI  
 INNER JOIN sExamination.tExamination AS EX ON Ex.Id = HI.ExaminationId  
 INNER JOIN sExamination.tSetupMaster SM ON EX.SetupId = SM.Id  
 WHERE SM.SetupGroupId = @rSetupGroupId  
 AND (EX.SetupId = @rSetupId OR @rSetupId = 0)  
 AND EX.OrgId = @rOrgId  
  
 DELETE HI FROM sExamination.tHealthIndex AS HI  
 INNER JOIN sExamination.tExamination AS EX ON Ex.Id = HI.ExaminationId  
 INNER JOIN sExamination.tSetupMaster SM ON EX.SetupId = SM.Id  
 WHERE SM.SetupGroupId = @rSetupGroupId  
 AND (EX.SetupId = @rSetupId OR @rSetupId = 0)  
 AND EX.OrgId = @rOrgId  
  
 IF OBJECT_ID('tempdb..#tmpServiceValue') IS NOT NULL begin drop table #tmpServiceValue end  
 IF OBJECT_ID('tempdb..#tHealthIndex') IS NOT NULL begin drop table #tHealthIndex end  
 IF OBJECT_ID('tempdb..#tTable1') IS NOT NULL begin drop table #tTable1 end  
  
 CREATE TABLE #tmpServiceValue  
 (  
  Id int IDENTITY(1,1),TestParameterId int,SourceId bigint,ServiceValue float,ParameterName nvarchar(50),  
  Remark nvarchar(200),GenderId tinyint  
 )  
 CREATE TABLE #tHealthIndex  
 (  
  Id int IDENTITY(1,1),ExaminationId bigint,HealthIndexParameterId int,EarnedPoINTs int,TotalPoINTs int  
 )  
 CREATE TABLE #tTable1  
 (  
  Id bigint IDENTITY,HealthIndexParameterId int,ParameterTypeId int,FieldName nvarchar(50),  
  FROMValue nvarchar(50),ToValue nvarchar(50),PoINTs int,GenderId tinyint,DiagnosisRemark nvarchar(250)  
 )  
 DECLARE @ExaminationTable TABLE  
 (  
  tId int IDENTITY (1, 1),ExaminationId bigint  
 )  
 DECLARE @TempTable1 TABLE  
 (  
  tId int IDENTITY(1,1),TempTableId int,ExaminationId bigint  
 )  
 DECLARE @TempTable2 TABLE  
 (  
  tId int IDENTITY(1,1),TempTableId int,ExaminationId bigint  
 )  
   
 INSERT INTO #tmpServiceValue  
 SELECT TPM.Id,E.Id,ServiceValue,STPM.UCode,TRD.Remark,PD.GenderId  
 FROM sExamination.tExamination E  
 INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
 INNER JOIN sHrm.tEmployeePersonalDetail PD ON E.ParticipantSourceId = PD.EmployeeId  
 INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.Id  
 INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id   
 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 AND TPM.ParameterValueTypeId = 1  
 INNER JOIN SOrderEntry.tStaticTestParameterMaster STPM ON TPM.StaticTestParameterId = STPM.Id  
 WHERE ISNUMERIC(TRD.ServiceValue) = 1 AND TRD.ServiceValue <> '+' AND (ISNULL(TRD.ServiceValue, '') != '')  
 AND SM.SetupGroupId = @rSetupGroupId  
 AND (E.SetupId = @rSetupId OR @rSetupId = 0)  
 AND E.OrgId = @rOrgId  
     
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  
   
 if(@configval='Priority' or @configval='Priority Abnormal')  
  begin  
   -- changes as per mentis issue no:12021 - 2020-07-08 (Rahul,Raju sir,das sir) discussion  
   INSERT INTO #tTable1  
   SELECT HealthIndexParameterId,HealthIndexParameterTypeId,FieldName,FROMValue,ToValue,PoINTs,GenderId,DiagnosisRemark  
   FROM sExamination.tHealthIndexParameterDetail HD  
   INNER JOIN sExamination.tHealthIndexParameterMaster HIM ON HIM.Id = HD.HealthIndexParameterId   
   WHERE HIM.IsObsolete = 0 AND HD.OrgId=@rOrgId AND HIM.OrgId=@rOrgId and HIM.StaticHealthIndexParameterId in(  
   select distinct HealthIndexParameterId from sExamination.tHealthIndexGroupParameter 
   where RoundGroupId = @rSetupGroupId  
   ) OR 
	(        
		HIM.StaticHealthIndexParameterId IN (18,19,21)
		AND EXISTS (
			SELECT 1 
			FROM sExamination.tHealthIndexGroupParameter 
			WHERE RoundGroupId = @rSetupGroupId
			AND HealthIndexParameterId = 2
		)
	)
   --UNION  
   --select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','4.00','5.60',10,1,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','4.00','5.60',10,2,'' 
   --union  
   --select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','5.70','6.40',6,1,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','5.70','6.40',6,2,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','6.50','200',3,1,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](19,@rOrgId),2,'DIABETIC_HBA1C','6.50','200',3,2,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','0','120.50',10,1,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','0','120.50',10,2,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','120.51','159.50',6,1,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','120.51','159.50',6,2,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','159.51','1000',3,1,''  
   --union  
   --select [sCommon].[fGetIntIdForOrg](21,@rOrgId),2,'DIABETIC_RBS','159.51','1000',3,2,''  
 end  
 else  
 begin  
   INSERT INTO #tTable1  
   SELECT HealthIndexParameterId,HealthIndexParameterTypeId,FieldName,FROMValue,ToValue,PoINTs,GenderId,DiagnosisRemark  
   FROM sExamination.tHealthIndexParameterDetail HD  
   INNER JOIN sExamination.tHealthIndexParameterMaster HIM ON HIM.Id = HD.HealthIndexParameterId   
   WHERE HIM.IsObsolete = 0 AND HD.OrgId=@rOrgId AND HIM.OrgId=@rOrgId and HIM.StaticHealthIndexParameterId IN(  
   SELECT DISTINCT HealthIndexParameterId FROM sExamination.tHealthIndexGroupParameter WHERE RoundGroupId = @rSetupGroupId)  
 end  
     
 SELECT @lCount = COUNT(Id) FROM #tTable1  
   
 WHILE @lCount > 0  
 BEGIN  
  SELECT @lParameterId = 0,@FieldName = '',@lParameterTypeId = 0,@lFROMValue = 0,@lToValue = 0,  
  @lPoINTs = 0,@lGenderId = 0,@lTestParameterId = 0,@lDiagnosisRemark = ''
    
  SELECT @lParameterId = HealthIndexParameterId,@FieldName = FieldName,@lParameterTypeId = ParameterTypeId,  
  @lFROMValue = FROMValue, @lToValue = ToValue, @lPoINTs = PoINTs, @lGenderId = GenderId, @lDiagnosisRemark = DiagnosisRemark  
  FROM #tTable1 WHERE Id = @lCount  
    
  IF (@lParameterTypeId = 1)  
  BEGIN  
   --Vital  
   SET @lQueryString1 = '  SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
   FROM sExamination.tExamination E  
   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
   INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
   INNER JOIN sExamination.tVital V ON V.SourceId=E.Id  
   WHERE SM.SetupGroupId =' + CAST(@rSetupGroupId AS nvarchar(30)) + ' ' +'  
   AND (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' OR ' + CAST(@rSetupId AS nvarchar(30)) + ' = 0)  
   AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
   AND (' + CAST(@lFROMValue AS nvarchar(30)) + '<=' + CAST(@FieldName AS nvarchar(30)) + ')  
   AND (' + CAST(@FieldName AS nvarchar(30)) + '<=' + CAST(@lToValue AS nvarchar(30)) + ')'   
        
  END  
  ELSE IF (@lParameterTypeId = 2)  
  BEGIN  
   --Numeric Test  
   SELECT @lTestParameterId = TestParameterId  
   FROM #tmpServiceValue WHERE ParameterName LIKE @FieldName  
     
   --select @FieldName,@lTestParameterId  
     
   SET @lQueryString1 = 'SELECT SourceId,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
   FROM #tmpServiceValue WHERE TestParameterId = (' + CAST(@lTestParameterId AS nvarchar(30)) + ')' + '  
   AND (' + CAST(@lFROMValue AS nvarchar(30)) + ' <= ServiceValue' + ')  
   AND (GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ')  OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
   AND ( ServiceValue <=' + CAST(@lToValue AS nvarchar(30)) + ')'  
  END  
  ELSE IF (@lParameterTypeId = 3)  
  BEGIN  
   --List Test     
   SELECT @lTestParameterId = TestParameterId  
   FROM sExamination.tExamination E  
   INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.id  
   INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id  
   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 AND TPM.ParameterValueTypeId = 2  
   WHERE TPM.Title LIKE @FieldName  
     
   SET @lQueryString1 = 'SELECT SourceId,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
   FROM sExamination.tExamination E  
   INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
   INNER JOIN sExamination.tTestRequest TR ON TR.SourceId = E.id  
   INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id  
   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 AND TPM.ParameterValueTypeId = 2  
   WHERE SM.SetupGroupId =' + CAST(@rSetupGroupId AS nvarchar(30)) + ' ' +'  
   AND (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' OR ' + CAST(@rSetupId AS nvarchar(30)) + ' = 0)  
   AND E.ParticipantSourceTypeId = 95  
   AND (EPD.GenderId=' + CAST(@lGenderId AS nvarchar(30)) + ' OR ' + CAST(@lGenderId AS nvarchar(30)) + ' = 0)  
   AND TestParameterId = ' + CAST(@lTestParameterId AS nvarchar(30)) + '  
   AND ServiceValue = ''' + CAST(@lFROMValue AS nvarchar(30)) + '''' + 'AND ServiceValue <> '''''  
  END  
  ELSE IF (@lParameterTypeId = 4)  
  BEGIN  
   IF (CAST(@FieldName AS int) = 2)  
   BEGIN  
    --Habit  
    SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    INNER JOIN sExamination.tHabitHygine H ON H.SourceId=E.Id  
    LEFT JOIN sExamination.tHabitHygineDetail HD ON HD.HabitHygineId=H.Id AND HD.IsObsolete=0  
    WHERE SM.SetupGroupId =' + CAST(@rSetupGroupId AS nvarchar(30)) + ' ' + '  
    AND (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' OR ' + CAST(@rSetupId AS nvarchar(30)) + ' = 0)  
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
    Group by E.Id,HD.HabitHygineId having (COUNT(HD.HabitHygineId) >=' + CAST(@FieldName AS nvarchar(30)) + ')'  
   END  
   ELSE IF (CAST(@FieldName AS int) = 1)  
   BEGIN  
    SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    INNER JOIN sExamination.tHabitHygine H ON H.SourceId=E.Id  
    LEFT JOIN sExamination.tHabitHygineDetail HD ON HD.HabitHygineId=H.Id AND HD.IsObsolete=0  
    WHERE SM.SetupGroupId =' + CAST(@rSetupGroupId AS nvarchar(30)) + ' ' + '  
    AND (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' OR ' + CAST(@rSetupId AS nvarchar(30)) + ' = 0)   
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))      
    Group by E.Id,HD.HabitHygineId having (COUNT(HD.HabitHygineId) =' + CAST(@FieldName AS nvarchar(30)) + ')'  
   END  
   ELSE IF (CAST(@FieldName AS int) = 0)  
   BEGIN  
    SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    LEFT JOIN sExamination.tHabitHygine H ON H.SourceId=E.Id  
    LEFT JOIN sExamination.tHabitHygineDetail HD ON HD.HabitHygineId=H.Id AND HD.IsObsolete=0  
    WHERE HD.Id is null  
    AND SM.SetupGroupId =' + CAST(@rSetupGroupId AS nvarchar(30)) + ' ' + '  
    AND (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' OR ' + CAST(@rSetupId AS nvarchar(30)) + ' = 0)   
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))'  
   END  
  END  
  ELSE IF (@lParameterTypeId = 5)  
  BEGIN  
   IF (CAST(@FieldName AS int) = 2)  
   BEGIN  
    --Life Style Disease  
    SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    INNER JOIN sExamination.tExistingDisease ED ON ED.SourceId=E.Id  
    inner JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId=ED.Id AND EDD.IsObsolete=0  
    WHERE SM.SetupGroupId =' + CAST(@rSetupGroupId AS nvarchar(30)) + ' ' + '  
    AND (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' OR ' + CAST(@rSetupId AS nvarchar(30)) + ' = 0)   
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
    Group by E.Id,EDD.ExistingDiseaseId having (COUNT(EDD.ExistingDiseaseId) >=' + CAST(@FieldName AS nvarchar(30)) + ')'  
   END  
   ELSE IF (CAST(@FieldName AS int) = 1)  
   BEGIN  
    SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    INNER JOIN sExamination.tExistingDisease ED ON ED.SourceId=E.Id  
    inner JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId=ED.Id AND EDD.IsObsolete=0  
    WHERE SM.SetupGroupId =' + CAST(@rSetupGroupId AS nvarchar(30)) + ' ' + '  
    AND (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' OR ' + CAST(@rSetupId AS nvarchar(30)) + ' = 0)   
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
    Group by E.Id,EDD.ExistingDiseaseId having (COUNT(EDD.ExistingDiseaseId) =' + CAST(@FieldName AS nvarchar(30)) + ')'  
   END  
   ELSE IF (CAST(@FieldName AS int) = 0)  
   BEGIN  
    SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    LEFT JOIN sExamination.tExistingDisease ED ON ED.SourceId=E.Id  
    WHERE ED.Id IS NULL   
    AND SM.SetupGroupId =' + CAST(@rSetupGroupId AS nvarchar(30)) + ' ' + '  
    AND (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' OR ' + CAST(@rSetupId AS nvarchar(30)) + ' = 0)   
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
    UNION SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
    FROM sExamination.tExamination E  
    INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
    INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
    INNER JOIN sExamination.tExistingDisease ED ON ED.SourceId=E.Id  
    LEFT JOIN sExamination.tExistingDiseaseDetail EDD ON EDD.ExistingDiseaseId=ED.Id AND EDD.IsObsolete=0  
    WHERE EDD.Id IS NULL   
    AND SM.SetupGroupId =' + CAST(@rSetupGroupId AS nvarchar(30)) + ' ' + '  
    AND (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' OR ' + CAST(@rSetupId AS nvarchar(30)) + ' = 0)   
    AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
    --and ISNULL(ED.Remark,'''') <> '''''  
   END  
  END  
  ELSE IF (@lParameterTypeId = 11)  
  BEGIN  
   --Shift Duty  
   SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',0  
   FROM sExamination.tExamination E  
   INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=E.ParticipantSourceId  
   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
   WHERE SM.SetupGroupId =' + CAST(@rSetupGroupId AS nvarchar(30)) + ' ' + '  
   AND (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' OR ' + CAST(@rSetupId AS nvarchar(30)) + ' = 0)   
   AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))  
   AND EJD.IsWorkingInShift = 1'  
  END  
  ELSE  
  IF (@lParameterTypeId = 12)  
  BEGIN  
   --Hazard Process  
   SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',0  
   FROM sExamination.tExamination E  
   INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId  
   WHERE SM.SetupGroupId =' + CAST(@rSetupGroupId AS nvarchar(30)) + ' ' + '  
   AND (E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' OR ' + CAST(@rSetupId AS nvarchar(30)) + ' = 0)  
   AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0)) AND E.ProcessTypeId = 1'  
  END 
  IF (@lParameterTypeId = 13)  
  BEGIN  
   --Audiometry  
   SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
   FROM sExamination.tExamination E
   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
   INNER JOIN sExamination.tAudiometry AUD ON AUD.SourceId=E.Id
   INNER JOIN sExamination.tAudiometryResultMaster ARM ON ARM.Id = CASE WHEN AUD.AudiometryAcResultLeftId > AUD.AudiometryAcResultRightId 
																   THEN AUD.AudiometryAcResultLeftId ELSE AUD.AudiometryAcResultRightId END
   WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + ' 
   AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
   AND UPPER(LTRIM(RTRIM(ARM.Title))) = UPPER(''' + @lDiagnosisRemark + ''')'  
  END
  IF (@lParameterTypeId = 14)  
  BEGIN  
   --Pulmonary  
   SET @lQueryString1 = 'SELECT E.Id,''' + CAST(@lParameterId AS nvarchar(100)) + ''',''' + CAST(@lPoINTs AS nvarchar(100)) + ''',10  
   FROM sExamination.tExamination E
   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=E.ParticipantSourceId
   INNER JOIN sExamination.tPulmonary PUL ON PUL.SourceId=E.Id
   WHERE E.SetupId=' + CAST(@rSetupId AS nvarchar(30)) + '
   AND (EPD.GenderId=(' + CAST(@lGenderId AS nvarchar(30)) + ') OR (' + CAST(@lGenderId AS nvarchar(30)) + ' = 0))
   AND UPPER(LTRIM(RTRIM(ISNULL(PUL.PulmonaryResulIntensity,'''') + '' '' + ISNULL(PUL.PulmonaryResult,'''')))) = UPPER(''' + @lDiagnosisRemark + ''')'  
  END
   
  print @lQueryString1     
  INSERT INTO #tHealthIndex  
  EXECUTE sp_executesql @lQueryString1  
  SET @lCount = @lCount - 1  
  
    
 END  
   
 --select * from #tHealthIndex  
 --return  
 print @configval  
 if(@configval='Priority')  
  begin  
   -- changes as per mentis issue no:12021 - 2020-07-08 (Rahul,Raju sir,das sir) discussion 
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](19,@rOrgId)  
   )   
   and HealthIndexParameterId   
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](2,@rOrgId)  
   )   
   and HealthIndexParameterId   
   in ([sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId)  
   ) and HealthIndexParameterId   
   in ([sCommon].[fGetIntIdForOrg](21,@rOrgId))
   
   --update #tHealthIndex set HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](2,@rOrgId)  
   --where (HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](19,@rOrgId)   
   --or HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  end  
 else if(@configval='Priority Abnormal')  
  begin 
   -- changes as per mentis issue no:12372 - 2020-07-08 (Rahul,Raju sir,das sir) discussion  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](19,@rOrgId) and isnull(EarnedPoINTs,0)=3  
   )   
   and HealthIndexParameterId   
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
   
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](2,@rOrgId) and isnull(EarnedPoINTs,0)=3  
   ) and HealthIndexParameterId   
   in ([sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId) and isnull(EarnedPoINTs,0)=3  
   ) and HealthIndexParameterId
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](21,@rOrgId) and isnull(EarnedPoINTs,0)=3  
   ) and HealthIndexParameterId
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](19,@rOrgId) and isnull(EarnedPoINTs,0)=6  
   )   
   and HealthIndexParameterId
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](2,@rOrgId) and isnull(EarnedPoINTs,0)=6  
   ) and HealthIndexParameterId
   in ([sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId) and isnull(EarnedPoINTs,0)=6  
   ) and HealthIndexParameterId
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](21,@rOrgId) and isnull(EarnedPoINTs,0)=6  
   ) and HealthIndexParameterId
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](19,@rOrgId) and isnull(EarnedPoINTs,0)=10  
   )   
   and HealthIndexParameterId   
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](2,@rOrgId) and isnull(EarnedPoINTs,0)=10  
   ) and HealthIndexParameterId
   in ([sCommon].[fGetIntIdForOrg](18,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](18,@rOrgId) and isnull(EarnedPoINTs,0)=10  
   ) and HealthIndexParameterId
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](21,@rOrgId))  
  
   delete from #tHealthIndex  
   where ExaminationId in (  
   Select ExaminationId  
   From #tHealthIndex  
   Where HealthIndexParameterId=[sCommon].[fGetIntIdForOrg](21,@rOrgId) and isnull(EarnedPoINTs,0)=10  
   ) and HealthIndexParameterId
   in ([sCommon].[fGetIntIdForOrg](2,@rOrgId),[sCommon].[fGetIntIdForOrg](19,@rOrgId),[sCommon].[fGetIntIdForOrg](18,@rOrgId)) 
     
   --update #tHealthIndex set HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](2,@rOrgId)  
   --where (HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](19,@rOrgId)   
   --or HealthIndexParameterId = [sCommon].[fGetIntIdForOrg](21,@rOrgId))
  
  end  
   
   
 insert into @TempTable1  
 SELECT h.Id,h.ExaminationId FROM #tHealthIndex as h  
 inner join sExamination.tExamination as exm on exm.Id = h.ExaminationId  
 INNER JOIN sExamination.tSetupMaster SM ON exm.SetupId = SM.Id   
 INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = h.HealthIndexParameterId AND pm.OrgId=@rOrgId  
 inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=1 AND ISNULL(RoundGroupId,0) = @rSetupGroupId  
 where SM.SetupGroupId = @rSetupGroupId   
 AND (exm.SetupId = @rSetupId OR @rSetupId = 0)  
 AND pm.StaticHealthIndexParameterId IN (12)  
 AND exm.OrgId=@rOrgId  
    
 insert into @TempTable2  
 SELECT h.Id,h.ExaminationId FROM #tHealthIndex as h  
 inner join sExamination.tExamination as exm on exm.Id=h.ExaminationId  
 INNER JOIN sExamination.tSetupMaster SM ON exm.SetupId = SM.Id   
 INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = h.HealthIndexParameterId AND pm.OrgId=@rOrgId  
 inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @rSetupGroupId  
 where SM.SetupGroupId = @rSetupGroupId   
 AND (exm.SetupId = @rSetupId OR @rSetupId = 0)  
 AND pm.StaticHealthIndexParameterId IN (14)  
 AND exm.OrgId=@rOrgId  
   
 DELETE FROM #tHealthIndex WHERE Id IN  
 (  
  SELECT h.id FROM #tHealthIndex AS h  
  INNER JOIN sExamination.tExamination AS exm ON exm.Id = h.ExaminationId  
  INNER JOIN sExamination.tSetupMaster SM ON exm.SetupId = SM.Id   
  INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = h.HealthIndexParameterId AND pm.OrgId=@rOrgId  
  inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @rSetupGroupId  
  WHERE SM.SetupGroupId = @rSetupGroupId   
  AND (exm.SetupId = @rSetupId OR @rSetupId = 0)   
  AND pm.StaticHealthIndexParameterId NOT IN   
  (  
   select HealthIndexParameterId from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @rSetupGroupId  
  )
  AND NOT
  (
    pm.StaticHealthIndexParameterId IN (18,19,21)
    AND EXISTS (
        SELECT 1 
        FROM sExamination.tHealthIndexGroupParameter 
        WHERE RoundGroupId = @rSetupGroupId
        AND HealthIndexParameterId = 2
    )
  )
  UNION ALL  
  
  SELECT t2.TempTableId FROM @TempTable1 AS t  
  INNER JOIN @TempTable2 AS t2 ON t.ExaminationId = t2.ExaminationId  
 )  
   
 declare @ParameterCountNonExcutive int = 0, @MaleParameterCountNonExcutive int = 0, @FemaleParameterCountNonExcutive int = 0;  
 declare @ParameterCountExcutive int = 0  
 select @ParameterCountNonExcutive=count(1) from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=2  and ISNULL(RoundGroupId,0) = @rSetupGroupId  
 select @ParameterCountExcutive=count(1) from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=1  and ISNULL(RoundGroupId,0) = @rSetupGroupId  
  
 select @MaleParameterCountNonExcutive = (select Count(0) from (
 	 select GenderId, HIPM.Title from sExamination.tHealthIndexGroupParameter HIGP
 	 INNER JOIN sExamination.tStaticHealthIndexParameterDetail HIPD ON HIPD.StaticHealthIndexParameterId = HIGP.HealthIndexParameterId
 	 INNER JOIN sExamination.tStaticHealthIndexParameterMaster HIPM ON HIPM.Id = HIPD.StaticHealthIndexParameterId
 	 where HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @rSetupGroupId and GenderId = 1
 	 Group BY GenderId,HIPM.Title
  ) male)
 
 select @FemaleParameterCountNonExcutive = (select Count(0) from (
  select GenderId, HIPM.Title from sExamination.tHealthIndexGroupParameter HIGP
  INNER JOIN sExamination.tStaticHealthIndexParameterDetail HIPD ON HIPD.StaticHealthIndexParameterId = HIGP.HealthIndexParameterId
  INNER JOIN sExamination.tStaticHealthIndexParameterMaster HIPM ON HIPM.Id = HIPD.StaticHealthIndexParameterId
  where HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @rSetupGroupId and GenderId = 2
  Group BY GenderId,HIPM.Title
 ) female)

 INSERT INTO sExamination.tHealthIndex  
 SELECT  T.ExaminationId,T.HealthIndexParameterId,MAX(T.EarnedPoINTs),Max(T.TotalPoINTs)   
 FROM #tHealthIndex T  
 Group by T.ExaminationId,T.HealthIndexParameterId  
     
 INSERT INTO @ExaminationTable  
 SELECT exm.Id  
 FROM sExamination.tExamination AS exm
 INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = exm.ParticipantSourceId
 INNER JOIN sExamination.tSetupMaster AS stp ON stp.Id = exm.SetupId  
 INNER JOIN sExamination.tDiagnosis AS dis ON dis.SourceId = exm.Id  
 INNER JOIN sExamination.tHealthIndex AS hei ON hei.ExaminationId = exm.Id  
 INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = hei.HealthIndexParameterId  
 INNER JOIN sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @rSetupGroupId  
 --INNER JOIN sExamination.tHealthIndexGroupParameter as gpm on gpm.HealthIndexParameterId=pm.StaticHealthIndexParameterId and gpm.HealthIndexGroupId=2 and ISNULL(gpm.RoundGroupId,0) = @rSetupGroupId  
 WHERE (stp.SetupGroupId = @rSetupGroupId)   
 AND (exm.SetupId = @rSetupId or @rSetupId = 0)  
 AND EXM.OrgId=@rOrgId
 AND (pm.StaticHealthIndexParameterId IN (select HealthIndexParameterId from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=2 and ISNULL(RoundGroupId,0) = @rSetupGroupId)
     OR (pm.StaticHealthIndexParameterId in (18,19,21) AND EXISTS (SELECT 1 FROM sExamination.tHealthIndexGroupParameter 
             WHERE RoundGroupId = @rSetupGroupId AND HealthIndexParameterId = 2)))
 GROUP BY exm.Id, EPD.GenderId HAVING COUNT(0) >= CASE 
                     WHEN EPD.GenderId = 1 THEN @MaleParameterCountNonExcutive
                     WHEN EPD.GenderId = 2 THEN @FemaleParameterCountNonExcutive
                   END
  
 UNION ALL  
  
 SELECT exm.Id  
 FROM sExamination.tExamination AS exm  
 INNER JOIN sExamination.tSetupMaster AS stp ON stp.Id = exm.SetupId  
 INNER JOIN sExamination.tDiagnosis AS dis ON dis.SourceId = exm.Id  
 INNER JOIN sExamination.tHealthIndex AS hei ON hei.ExaminationId = exm.Id  
 INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = hei.HealthIndexParameterId  
 inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @rSetupGroupId  
 WHERE stp.SetupGroupId = @rSetupGroupId   
 AND (exm.SetupId = @rSetupId or @rSetupId = 0)  
 AND pm.StaticHealthIndexParameterId IN (12, 14)   
 AND EXM.OrgId=@rOrgId  
   
 UNION ALL  
 SELECT exm.Id  
 FROM sExamination.tExamination AS exm 
 INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = exm.ParticipantSourceId
 INNER JOIN sExamination.tSetupMaster AS stp ON stp.Id = exm.SetupId  
 INNER JOIN sExamination.tDiagnosis AS dis ON dis.SourceId = exm.Id  
 INNER JOIN sExamination.tHealthIndex AS hei ON hei.ExaminationId = exm.Id  
 INNER JOIN sExamination.tHealthIndexParameterMaster pm ON pm.Id = hei.HealthIndexParameterId AND pm.OrgId=@rOrgId  
 inner join sExamination.tHealthIndexGroupGrade as hgm on hgm.GradeId=exm.GradeId and hgm.HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @rSetupGroupId   
 --inner join sExamination.tHealthIndexGroupParameter as gpm on gpm.HealthIndexParameterId=pm.StaticHealthIndexParameterId and gpm.HealthIndexGroupId=1 and ISNULL(gpm.RoundGroupId,0) = @rSetupGroupId  
 WHERE stp.SetupGroupId = @rSetupGroupId AND pm.StaticHealthIndexParameterId not IN (12, 14)  
 AND (exm.SetupId = @rSetupId or @rSetupId = 0)  
 AND EXM.OrgId = @rOrgId  
 AND (pm.StaticHealthIndexParameterId IN (select HealthIndexParameterId from sExamination.tHealthIndexGroupParameter where HealthIndexGroupId=1 and ISNULL(RoundGroupId,0) = @rSetupGroupId)
     OR (pm.StaticHealthIndexParameterId in (18,19,21) AND EXISTS (SELECT 1 FROM sExamination.tHealthIndexGroupParameter
             WHERE RoundGroupId = @rSetupGroupId AND HealthIndexParameterId = 2)))
 GROUP BY exm.Id, EPD.GenderId HAVING COUNT(0) >= CASE 
                     WHEN EPD.GenderId = 1 THEN @MaleParameterCountNonExcutive
                     WHEN EPD.GenderId = 2 THEN @FemaleParameterCountNonExcutive
                   END
 --GROUP BY exm.Id HAVING COUNT(0) >= @ParameterCountNonExcutive  
   
 INSERT INTO sExamination.tDiagnosisPartial  
 (  
  ExaminationId,TotalHealthPoints,EarnedHealthPoints,HealthIndicatorId,AgeGroupId,HealthIndex  
 )  
 SELECT Distinct EX.ExaminationId,EX.TotalPoints,EX.EarnedPoints,EX.HealthIndicatorId,EX.AgeGroupId,  
 CONVERT(decimal(6, 2),(CONVERT(decimal(6, 2),ISNULL(EX.EarnedPoints, 0)) * 100) / CONVERT(decimal(6, 2),  
 ISNULL(EX.TotalPoints, 0)))  
 FROM sExamination.tDiagnosis AS DS  
 INNER JOIN  
 (  
  SELECT a.ExaminationId,a.EarnedPoints,a.TotalPoints,a.Percentage,  
  (  
   SELECT ID  
   FROM [sExamination].[tHealthIndicatorMaster]  
   WHERE RangeTo >= a.Percentage  
   AND a.Percentage > RangeFrom  
  )  
  HealthIndicatorId,[dbo].[fGetAgeGroupId](ISNULL(DATEDIFF(yy, EPD.DateOfBirth, sCommon.fGetDate()), 0),EPD.OrgId) AgeGroupId  
  FROM  
  (  
   SELECT ExaminationId,SUM(EarnedPoints) EarnedPoints,SUM(TotalPoints) TotalPoints,  
   ISNULL(CONVERT(decimal(18, 2), ((CONVERT(decimal(6, 2), SUM(EarnedPoints)) * 100) / CONVERT(decimal(6, 2),  
   SUM(TotalPoints)))), 0) Percentage  
   FROM sExamination.tHealthIndex  
   GROUP BY ExaminationId  
   HAVING SUM(TotalPoINTs) > 0  
  ) AS a  
  INNER JOIN sExamination.tExamination E ON e.id = a.ExaminationId
  INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
  LEFT JOIN sHrm.tEmployeePersonalDetail AS EPD ON EPD.EmployeeId = e.ParticipantSourceId 
  WHERE SM.SetupGroupId = @rSetupGroupId
  AND (E.SetupId = @rSetupId OR @rSetupId = 0)  
  AND e.OrgId=@rOrgId    
 ) AS EX ON EX.ExaminationId = DS.SourceId  
 left join @ExaminationTable e2 on e2.ExaminationId=ds.SourceId  
 where e2.ExaminationId is null   
  
 UPDATE DS SET DS.TotalHealthPoints = EX.TotalPoints,  
 DS.EarnedHealthPoints = EX.EarnedPoints,DS.HealthIndicatorId = EX.HealthIndicatorId,  
 DS.AgeGroupId = EX.AgeGroupId,  
 DS.HealthIndex = CONVERT(decimal(6, 2), (CONVERT(decimal(6, 2), ISNULL(EX.EarnedPoints, 0)) * 100) / CONVERT(decimal(6, 2), ISNULL(EX.TotalPoints, 0)))  
 FROM sExamination.tDiagnosis AS DS  
 INNER JOIN  
 (  
  SELECT a.ExaminationId,a.EarnedPoints,a.TotalPoints,a.Percentage,  
  (  
   SELECT ID FROM [sExamination].[tHealthIndicatorMaster]  
   WHERE RangeTo >= a.Percentage AND a.Percentage > RangeFrom  
  )  
  HealthIndicatorId,[dbo].[fGetAgeGroupId](ISNULL(DATEDIFF(yy, EPD.DateOfBirth, sCommon.fGetDate()), 0), EPD.OrgId) AgeGroupId  
  FROM  
  (  
   SELECT ExaminationId,SUM(EarnedPoints) EarnedPoints,SUM(TotalPoints) TotalPoints,  
   ISNULL(CONVERT(decimal(18, 2), ((CONVERT(decimal(6, 2), SUM(EarnedPoints)) * 100) / CONVERT(decimal(6, 2), SUM(TotalPoints)))), 0) Percentage  
   FROM sExamination.tHealthIndex GROUP BY ExaminationId HAVING SUM(TotalPoINTs) > 0  
  ) AS a
  INNER JOIN sExamination.tExamination E ON e.id = a.ExaminationId    
  INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id  
  LEFT JOIN sHrm.tEmployeePersonalDetail AS EPD ON EPD.EmployeeId = e.ParticipantSourceId  
  WHERE SM.SetupGroupId = @rSetupGroupId
  AND (E.SetupId = @rSetupId OR @rSetupId = 0)  
  AND e.OrgId=@rOrgId    
 ) AS EX ON EX.ExaminationId = DS.SourceId  
 left join @ExaminationTable as e2 on e2.ExaminationId=ds.SourceId  
 where e2.ExaminationId is not null   
  
 DELETE HI FROM sExamination.tHealthIndexPartial AS HI  
 INNER JOIN sExamination.tExamination AS EX ON Ex.Id = HI.ExaminationId  
 INNER JOIN sExamination.tSetupMaster SM ON EX.SetupId = SM.Id  
 left join @ExaminationTable as e2 on e2.ExaminationId=hi.ExaminationId  
 WHERE SM.SetupGroupId = @rSetupGroupId   
 AND (ex.SetupId = @rSetupId OR @rSetupId = 0) and e2.ExaminationId is null  
 AND ex.OrgId=@rOrgId  
  
 INSERT INTO sExamination.tHealthIndexPartial  
 (  
  ExaminationId,HealthIndexParameterId,EarnedPoints,TotalPoints  
 )  
 SELECT HI.ExaminationId,HI.HealthIndexParameterId,HI.EarnedPoints,HI.TotalPoints  
 FROM sExamination.tHealthIndex AS HI  
 INNER JOIN sExamination.tExamination AS EX ON Ex.Id = HI.ExaminationId  
 INNER JOIN sExamination.tSetupMaster SM ON EX.SetupId = SM.Id  
 LEFT JOIN @ExaminationTable as e2 on e2.ExaminationId=hi.ExaminationId  
 WHERE SM.SetupGroupId = @rSetupGroupId   
 AND (ex.SetupId = @rSetupId OR @rSetupId = 0) and e2.ExaminationId is null  
 AND ex.OrgId=@rOrgId
  
 DELETE HI FROM sExamination.tHealthIndex AS HI  
 INNER JOIN sExamination.tExamination AS EX ON Ex.Id = HI.ExaminationId  
 INNER JOIN sExamination.tSetupMaster SM ON EX.SetupId = SM.Id  
 LEFT JOIN @ExaminationTable as e2 on e2.ExaminationId=hi.ExaminationId  
 WHERE  SM.SetupGroupId = @rSetupGroupId   
 AND (ex.SetupId = @rSetupId OR @rSetupId = 0) and e2.ExaminationId is null  
 AND ex.OrgId=@rOrgId  
  
 UPDATE SM set IsHealthIndexUpdated = 1 FROM   
 sExamination.tSetupGroupMaster SGM INNER JOIN sExamination.tSetupMaster SM   
 ON SGM.Id = SM.SetupGroupId WHERE SGM.Id = @rSetupGroupId    
   
 SELECT 1 AS Result  
END
GO
PRINT N'Altering Procedure [sExamination].[pDiagnosisAnalysisSearch]...';


GO

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, [Morbidly Obese] smallint, [Vitamin D3 Toxicity Risk] 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],  
 (  
  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 = 'Morbidly Obese'  
 ) [Morbidly 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.VitaminD3 = 'Vitamin D3 Toxicity Risk' 
) [Vitamin D3 Toxicity Risk]

 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].[pExaminationAdd]...';


GO

ALTER PROCEDURE [sExamination].[pExaminationAdd]
@rId bigint,
@rOrgId smallint,
@rParticipantSourceTypeId smallint,
@rParticipantSourceId bigint,
@rOrganizationDepartmentId int,
@rSetupId bigint,
@rMainTypeId int,
@rRoundNumber int = 0,
@rStatusId int,
@rExaminationDate date,
@rDoctorEmployeeId bigint  = NULL,
@rCreatedUserId bigint,
@rUpdatedUserId bigint = 0,
@rParentExaminationId bigint = Null,
@rStoreLocationId bigint,
@rCauseId int = null,
@rProcessTypeId int,
@rImportId bigint = null,
@rCriteriaGroupId int = null,
@rEmployeeStatusId int,
@rTargetGroupId int = null,
@rDoctorFlag int = null,
@rPastHistorySelf nvarchar(2000) = '',
@rHistoryMother nvarchar(2000) = '',
@rHistoryFather nvarchar(2000) = '',
@rDataEntryTemplateId bigint = 0,
@rMedicalAgencyId int = 0
AS
SET NOCOUNT ON
BEGIN
declare @trancount int;


	BEGIN TRY		
        begin transaction
	set @trancount = @@trancount;        

		declare @exceptiondetail nvarchar(max)
		if @rCreatedUserId = 0
		begin
			SELECT -101 AS RESULT
			return
		end
		if @rParticipantSourceId = 0
		begin
			SELECT -102 AS RESULT
			return
		end
		if @rParticipantSourceTypeId = 0
		begin
			SELECT -103 AS RESULT
			return
		end
		Declare @rExistingId  bigint = 0
		--Declare @lFromDate datetime
		--Declare @lToDate datetime
		--SET @lFromDate=(select FromDate from sExamination.tSetupMaster WHERE Id=@rSetupId AND StoreLocationId=@rStoreLocationId AND OrgId=@rOrgId)
		--SET @lToDate=(select ToDate from sExamination.tSetupMaster WHERE Id=@rSetupId AND StoreLocationId=@rStoreLocationId AND OrgId=@rOrgId)
		
		--IF(@rMainTypeId = 1 OR @rMainTypeId=6 OR @rMainTypeId=7)
		--BEGIN
		--	IF(@rExaminationDate < @lFromDate OR @rExaminationDate >@lToDate)
		--	BEGIN
		--		SELECT -2 AS RESULT
		--		RETURN
		--	END
		--END
		
	     SELECT @rExistingId = ID  FROM [sExamination].[tExamination] WHERE ParticipantSourceTypeId = @rParticipantSourceTypeId AND ParticipantSourceId = @rParticipantSourceId AND SetupId = @rSetupId
		 
		 IF(@rMainTypeId = 1 OR @rMainTypeId = 2 OR @rMainTypeId = 4 OR @rMainTypeId = 6 OR @rMainTypeId = 7)
		  SET @rId = @rExistingId		  
		  
		IF(@rDoctorEmployeeId <= 0)
			SET @rDoctorEmployeeId = NULL
			
		if isnull(@rOrganizationDepartmentId,0) = 0 and @rParticipantSourceTypeId = 95
		begin
			select @rOrganizationDepartmentId = OrganizationDepartmentId from sHrm.tEmployeeJobDetail where EmployeeId = @rParticipantSourceId
		end
		
		DECLARE @lNextNumber bigint,@lEmployeeCompanyId int,@lTargetGroupId int,@lEmployeeDesignationId int,@lGradeId int,@lLegalEntityId int,@lIsTargetGroupRestrictInHR bit
		DECLARE @lRawMaterialUsed nvarchar(50), @lDangerousProcess nvarchar(50), @lHazardousProcess nvarchar(50),@lEmployeeContractorId int;

		select @lEmployeeCompanyId = EmployeeCompanyId,@lEmployeeDesignationId=EmployeeDesignationId,@lLegalEntityId=LegalEntityId ,
		@lRawMaterialUsed = RawMaterialUsed,@lDangerousProcess = DangerousProcess, @lHazardousProcess = HazardousProcess, @lEmployeeContractorId = ContractorId
		from sHrm.tEmployeeJobDetail where employeeId = @rParticipantSourceId and (@rParticipantSourceTypeId = 95 or @rParticipantSourceTypeId = 1001)

		select @lGradeId = GradeId from sHrm.vEmployeeCommonDetail where EmployeeId = @rParticipantSourceId and (@rParticipantSourceTypeId = 95 or @rParticipantSourceTypeId = 1001)

		select @lIsTargetGroupRestrictInHR=isnull(IsTargetGroupRestrictInHR,0) from sExamination.tSetupmaster where id=@rSetupId
		
		if @rProcessTypeId > 0
		begin
			update sHrm.tEmployeeJobDetail set ProcessTypeId = @rProcessTypeId where EmployeeId = @rParticipantSourceId
		end
		
		if Isnull(@rOrganizationDepartmentId,0) > 0 and @rParticipantSourceTypeId = 95
		begin
			update sHrm.tEmployeeJobDetail set OrganizationDepartmentId = Isnull(@rOrganizationDepartmentId,0) where EmployeeId = @rParticipantSourceId
		end

		if (@rTargetGroupId > 0 and Isnull(@lIsTargetGroupRestrictInHR,0)=0)
		begin
			--if not exists(select * from sHrm.tEmployeeMaster where Id = @rParticipantSourceId and isnull(TargetGroupId,0) = 0)
			--begin
				update sHrm.tEmployeeMaster set TargetGroupId = @rTargetGroupId where Id = @rParticipantSourceId
			--end
		end
		
		select @lTargetGroupId = @rTargetGroupId
		
		
		IF (@rId = 0)
		--IF EXISTS (SELECT 1 FROM [sExamination].[tExamination] WHERE ParticipantSourceTypeId = @rParticipantSourceTypeId
		--AND ParticipantSourceId = @rParticipantSourceId AND SetupId = @rSetupId)
		BEGIN
			--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sExamination.tExamination', 0, 1, 1,@outNextNumber = @lNextNumber output
			
			INSERT INTO [sExamination].[tExamination] 
			(
				OrgId,ParticipantSourceTypeId,ParticipantSourceId,OrganizationDepartmentId,SetupId,
				RoundNumber,StatusId,ExaminationDate,DoctorEmployeeId,CreatedUserId,CreatedDateTime,
				UpdatedUserId,UpdatedDateTime,ParentExaminationId,StoreLocationId,CauseId,ProcessTypeId,
				EmployeeCompanyId,TargetGroupId,EmployeeDesignationId,MedicalAgencyId,CriteiraGroupId,EmployeeStatusId,GradeId,LegalEntityId,
				HazardousProcess, DangerousProcess,RawMaterialUsed,PastHistorySelf,HistoryMother,HistoryFather,
				DataEntryTemplateId,ContractorId
			)
			VALUES
			(
				@rOrgId,@rParticipantSourceTypeId,@rParticipantSourceId,@rOrganizationDepartmentId,
				@rSetupId,@rRoundNumber,1,@rExaminationDate,@rDoctorEmployeeId,@rCreatedUserId,sCommon.fGetDate(),
				@rUpdatedUserId,sCommon.fGetDate(),@rParentExaminationId,@rStoreLocationId,@rCauseId,@rProcessTypeId,
				@lEmployeeCompanyId,@lTargetGroupId,@lEmployeeDesignationId,@rMedicalAgencyId,
				CASE WHEN @rCriteriaGroupId = -1 then NULL else @rCriteriaGroupId end,@rEmployeeStatusId,@lGradeId,@lLegalEntityId,
				@lHazardousProcess,@lDangerousProcess,@lRawMaterialUsed,@rPastHistorySelf,@rHistoryMother,@rHistoryFather,
				@rDataEntryTemplateId,@lEmployeeContractorId
			)
			
			select @lNextNumber = SCOPE_IDENTITY()

			declare @cnt bigint = 0,@prefix varchar(100),@Title varchar(100),@cn varchar(300)
			select @Title = Title from sExamination.tSetupMaster where Id = @rSetupId
			--select @cnt = count(1) from sExamination.tExamination where isnull(Examinationnumber,'') <> ''
			--and DATEDIFF(day,CONVERT(date, CreatedDateTime, 105),CONVERT(date, sCommon.fGetDate(), 105))>=0 and SetupId = @rSetupId
			--and StoreLocationId = @rStoreLocationId
			select @cnt = Max(Right(ISNULL(Examinationnumber,00000),13)) from sExamination.tExamination where isnull(Examinationnumber,'') <> ''
			and DATEDIFF(day,CONVERT(date, CreatedDateTime, 105),CONVERT(date, sCommon.fGetDate(), 105))>=0 and SetupId = @rSetupId
			and StoreLocationId = @rStoreLocationId

			if len(@cnt)=12
			begin
			select @cnt = Right(isnull(@cnt,00000),4)
			end
			else if(len(@cnt)=13)
			begin
			select @cnt = Right(isnull(@cnt,00000),5)
			end
			else
			begin
			select @cnt = Right(isnull(@cnt,00000),4)
			end
			
			if(@cnt=9999)
			begin
				select @cnt = @cnt + 1 +(select count(*) from sExamination.tExamination 
				where isnull(Examinationnumber,'') <> '' and 
				DATEDIFF(day,CONVERT(date, CreatedDateTime, 105),CONVERT(date, sCommon.fGetDate(), 105))>=0 
				and SetupId = @rSetupId	and StoreLocationId = @rStoreLocationId)
			end
			else
			begin
			select @cnt = @cnt + 1
			end

			--select @prefix = case when sCommon.fGetIntIdForOrg(8,@rOrgId) = @rSetupId then
			--'OPD-' + convert(varchar,sCommon.fGetDate(),112)  + RIGHT(100000 + (@cnt) ,5) else '' end

			--- mantis : 0036445, Nidhi Pandey; DT - 13/09/2024
			--DECLARE @dateValue DATETIME = sCommon.fGetDate()  -- Replace with your sCommon.fGetDate() if needed
			--DECLARE @updateddateValue VARCHAR(20);
			--SET @updateddateValue = 
			--CONVERT(VARCHAR(8), @dateValue, 112) +  -- yyyyMMdd format
			--REPLACE(CONVERT(VARCHAR(8), @dateValue, 114), ':', '') +  -- HHmmss format
			--RIGHT('000' + CAST(DATEPART(MILLISECOND, @dateValue) AS VARCHAR(3)), 3)

			select @prefix = case when sCommon.fGetIntIdForOrg(8,@rOrgId) = @rSetupId then
			'OPD-' + sCommon.fGetFormattedDate()  + RIGHT(100000 + (@cnt) ,5) else '' end

			update sExamination.tExamination set Examinationnumber = @prefix where Id = @lNextNumber
		END
		ELSE
		BEGIN
			SET @lNextNumber = @rId
			UPDATE [sExamination].[tExamination] SET OrgId = @rOrgId,ParticipantSourceTypeId  = @rParticipantSourceTypeId,
			ParticipantSourceId  = @rParticipantSourceId,OrganizationDepartmentId = @rOrganizationDepartmentId,
			ExaminationDate = @rExaminationDate,DoctorEmployeeId = case when isnull(@rDoctorFlag,0) = 1 then DoctorEmployeeId else @rDoctorEmployeeId end,
			RoundNumber =  @rRoundNumber,StatusId =  1,ParentExaminationId = @rParentExaminationId,CauseId = @rCauseId,UpdatedUserId =  case when @rUpdatedUserId>0 then @rUpdatedUserId else @rCreatedUserId end,
			UpdatedDateTime = sCommon.fGetDate(),ProcessTypeId=@rProcessTypeId,EmployeeCompanyId=@lEmployeeCompanyId,
			CriteiraGroupId = CASE WHEN @rCriteriaGroupId = -1 then NULL else @rCriteriaGroupId end,
			EmployeeStatusId=@rEmployeeStatusId,GradeId=@lGradeId,TargetGroupId=@lTargetGroupId,LegalEntityId=@lLegalEntityId,
			PastHistorySelf=@rPastHistorySelf,HistoryMother=@rHistoryMother,HistoryFather=@rHistoryFather,DataEntryTemplateId=@rDataEntryTemplateId,MedicalAgencyId=@rMedicalAgencyId
			WHERE Id = @rId
		END
		SELECT @lNextNumber AS Result		
		
      commit tran;
	END TRY
	BEGIN CATCH
	declare @error int, @message varchar(4000), @xstate int,@username nvarchar(200);
		select @error = ERROR_NUMBER(),
               @message = ERROR_MESSAGE(), 
               @xstate = XACT_STATE();
		set @username =(select Top 1 ISNULL(LoginTitle,'') from sSecurity.tUser where id=ISNULL(CreatedUserId,0))
		--if @xstate = -1
  --          rollback;
  --      if @xstate = 1 and @trancount = 0
  --          rollback
  --      if @xstate = 1 and @trancount > 0
            rollback transaction;

		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 @rOrgId,'OPD_Main_DBError',5000,@exceptiondetail,sCommon.fGetDate(),@rCreatedUserId	
		SELECT -1 AS RESULT
		return
	END CATCH	
	
END
GO
PRINT N'Altering Procedure [sExamination].[pGetAHCAutomationDataForMHI]...';


GO


ALTER PROCEDURE [sExamination].[pGetAHCAutomationDataForMHI] 
(
	@rSetupGroupId INT,
	@rSetupId INT,
	@rStoreLocationId INT,
	@rOrgId SMALLINT,
	@rUserId BIGINT
)
AS
BEGIN

	WITH ExamCTE AS
	(
		SELECT 
			Exam.Id,
			Exam.ParticipantSourceTypeId,
			Exam.ParticipantSourceId,
			Exam.StoreLocationId
		FROM 
			[sExamination].[tSetupGroupMaster] SGM
		INNER JOIN 
			[sExamination].[tSetupMaster] SM ON SM.SetupGroupId = SGM.Id 
		INNER JOIN 
			[sExamination].[tExamination] Exam ON Exam.SetupId = SM.Id AND Exam.ParticipantSourceTypeId = 95 AND Exam.StatusId = 4
		WHERE
			SGM.Id = @rSetupGroupId 
		AND 
			((@rSetupId = 0) OR (@rSetupId = SM.Id)) AND Exam.IsPublish = 1
		AND
			((@rStoreLocationId = 0) OR (@rStoreLocationId = SM.StoreLocationId))
		AND
			SGM.OrgId =  @rOrgId
	),

	ExamFiltered AS
	(
		SELECT 
			E.*
		FROM 
			ExamCTE E
		INNER JOIN 
			[sSecurity].[tUserLocation] USR
		ON 
			USR.StoreLocationId = E.StoreLocationId
		WHERE 
			USR.UserId = @rUserId
	),

	LabData AS
	(
		SELECT 
			TR.SourceId,
			MAX(CASE WHEN TPM.StaticTestParameterId = 25 THEN CASE WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' AND TRD.ServiceValue <> '' THEN CAST(TRD.ServiceValue AS NUMERIC(10,2)) END END) AS HBA1C,
			MAX(CASE WHEN TPM.StaticTestParameterId = 34 THEN CASE WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' AND TRD.ServiceValue <> '' THEN CAST(TRD.ServiceValue AS NUMERIC(10,2)) END END) AS LDL
		FROM 
			[sExamination].[tTestRequest] TR
		INNER JOIN 
			[sExamination].[tTestRequestDetail] TRD 
		ON 
			TRD.TestRequestId = TR.Id
		INNER JOIN 
			[sOrderEntry].[tTestDetail] TD 
		ON 
			TD.Id = TRD.TestDetailId
		INNER JOIN 
			[sOrderEntry].[tTestParameterMaster] TPM 
		ON 
			TPM.Id = TD.TestParameterId
		INNER JOIN 
			ExamFiltered E 
		ON 
			E.Id = TR.SourceId 
		WHERE 
			TPM.StaticTestParameterId IN (25, 34) AND  TRD.ServiceValue <> '' AND  TRD.ServiceValue NOT LIKE '%[^0-9.]%'
		GROUP BY 
			TR.SourceId
	)

	SELECT 
		E.ParticipantSourceTypeId,
		E.ParticipantSourceId,
		EM.Code AS EmployeeCode,
		Vital.BloodPressureSystolic AS SystolicBP,
		Vital.BloodPressureDiastolic AS DiastolicBP,
		Vital.BMI AS BMI,
		L.HBA1C AS HBA1C,
		L.LDL AS LDL,
		MHI.Stress AS Stress,
		MHI.Lifestyle AS LifeStyle
	FROM 
		[ExamFiltered] E
	LEFT JOIN 
		[sExamination].[tVital] Vital
	ON 
		Vital.SourceId = E.Id
	LEFT JOIN 
		[sWellness].[tMHIScoreUpdation] MHI
	ON 
		MHI.ParticipantSourceId = E.ParticipantSourceId
	LEFT JOIN 
		[LabData] L	
	ON 
		L.SourceId = E.Id
	INNER JOIN
		[sHRM].[tEmployeeMaster] EM
	ON
		EM.Id = E.ParticipantSourceId
END
GO
PRINT N'Altering Procedure [sExamination].[pGetAHCAutomationSchedulerDataForMHI]...';


GO


ALTER PROCEDURE [sExamination].[pGetAHCAutomationSchedulerDataForMHI] 
(
	@rSetupGroupId INT,
	@rSetupId INT,
	@rStoreLocationId INT,
	@rOrgId SMALLINT,
	@rUserId BIGINT
)
AS
BEGIN

	WITH ExamCTE AS
	(
		SELECT 
			Exam.Id,
			Exam.ParticipantSourceTypeId,
			Exam.ParticipantSourceId,
			Exam.StoreLocationId
		FROM 
			[sExamination].[tSetupGroupMaster] SGM
		INNER JOIN 
			[sExamination].[tSetupMaster] SM ON SM.SetupGroupId = SGM.Id 
		INNER JOIN 
			[sExamination].[tExamination] Exam ON Exam.SetupId = SM.Id AND Exam.ParticipantSourceTypeId = 95 AND Exam.StatusId = 4
		WHERE
			SGM.Id = @rSetupGroupId 
		AND 
			((@rSetupId = 0) OR (@rSetupId = SM.Id)) AND Exam.IsPublish = 1
		AND
			((@rStoreLocationId = 0) OR (@rStoreLocationId = SM.StoreLocationId))
		AND
			SGM.OrgId =  @rOrgId
	),

	ExamFiltered AS
	(
		SELECT 
			E.*
		FROM 
			ExamCTE E
		INNER JOIN 
			[sSecurity].[tUserLocation] USR
		ON 
			USR.StoreLocationId = E.StoreLocationId
		WHERE 
			((@rUserId = 0) OR (USR.UserId = @rUserId))
	),

	LabData AS
	(
		SELECT 
			TR.SourceId,
			MAX(CASE WHEN TPM.StaticTestParameterId = 25 THEN CASE WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' AND TRD.ServiceValue <> '' THEN CAST(TRD.ServiceValue AS NUMERIC(10,2)) END END) AS HBA1C,
			MAX(CASE WHEN TPM.StaticTestParameterId = 34 THEN CASE WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' AND TRD.ServiceValue <> '' THEN CAST(TRD.ServiceValue AS NUMERIC(10,2)) END END) AS LDL
		FROM 
			[sExamination].[tTestRequest] TR
		INNER JOIN 
			[sExamination].[tTestRequestDetail] TRD 
		ON 
			TRD.TestRequestId = TR.Id
		INNER JOIN 
			[sOrderEntry].[tTestDetail] TD 
		ON 
			TD.Id = TRD.TestDetailId
		INNER JOIN 
			[sOrderEntry].[tTestParameterMaster] TPM 
		ON 
			TPM.Id = TD.TestParameterId
		INNER JOIN 
			ExamFiltered E 
		ON 
			E.Id = TR.SourceId 
		WHERE 
			TPM.StaticTestParameterId IN (25, 34) AND  TRD.ServiceValue <> '' AND  TRD.ServiceValue NOT LIKE '%[^0-9.]%'
		GROUP BY 
			TR.SourceId
	)

	SELECT DISTINCT
		E.ParticipantSourceTypeId,
		E.ParticipantSourceId,
		EM.Code AS EmployeeCode,
		Vital.BloodPressureSystolic AS SystolicBP,
		Vital.BloodPressureDiastolic AS DiastolicBP,
		Vital.BMI AS BMI,
		L.HBA1C AS HBA1C,
		L.LDL AS LDL,
		MHI.Stress AS Stress,
		MHI.Lifestyle AS LifeStyle
	FROM 
		[ExamFiltered] E
	LEFT JOIN 
		[sExamination].[tVital] Vital
	ON 
		Vital.SourceId = E.Id
	LEFT JOIN 
		[sWellness].[tMHIScoreUpdation] MHI
	ON 
		MHI.ParticipantSourceId = E.ParticipantSourceId
	LEFT JOIN 
		[LabData] L	
	ON 
		L.SourceId = E.Id
	INNER JOIN
		[sHRM].[tEmployeeMaster] EM
	ON
		EM.Id = E.ParticipantSourceId
END
GO
PRINT N'Altering Procedure [sExamination].[pGetDiagnosisUpdateDataForMHI]...';


GO
ALTER PROCEDURE [sExamination].[pGetDiagnosisUpdateDataForMHI]
(
	@ExaminationIds VARCHAR(MAX),
	@rOrgId SMALLINT
)
AS
BEGIN

	;WITH ExamIds AS
	(
		SELECT CAST(value AS BIGINT) AS ExaminationId
		FROM [dbo].[SplitString](@ExaminationIds, ',')
	)

	SELECT
		E.ParticipantSourceTypeId,
		E.ParticipantSourceId,
		EM.Code AS EmployeeCode,
		V.BloodPressureSystolic AS SystolicBP,
		V.BloodPressureDiastolic AS DiastolicBP,
		V.BMI AS BMI,
		H.HBA1C AS HBA1C,
		L.LDL AS LDL,
		MHI.Stress AS Stress,
		MHI.Lifestyle AS LifeStyle
	FROM ExamIds EI
	INNER JOIN sExamination.tExamination E ON E.Id = EI.ExaminationId AND E.ParticipantSourceTypeId = 95 AND E.StatusId = 4 AND E.IsPublish = 1
	INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id = E.ParticipantSourceId AND EM.OrgID = @rOrgId
	LEFT JOIN sWellness.tMHIScore MHI ON MHI.EmployeeId = EM.Id 
	LEFT JOIN sExamination.tVital V ON V.SourceId = E.Id

	OUTER APPLY
	(
		SELECT TOP 1
			CAST(ISNULL(TRD.ServiceValue,0) AS NUMERIC(10,2)) AS HBA1C
		FROM sExamination.tTestRequest TR
		INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id
		INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = TRD.TestDetailId
		INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
		WHERE TR.SourceId = E.Id
		  AND TPM.StaticTestParameterId = 25
		  AND (CASE 
			  WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' 
			  		AND TRD.ServiceValue <> ''
			  THEN CAST(TRD.ServiceValue AS FLOAT)
			  ELSE 0
		 END) > 0
		ORDER BY TRD.Id DESC
	) H

	OUTER APPLY
	(
		SELECT TOP 1
			CAST(ISNULL(TRD.ServiceValue,0) AS NUMERIC(10,2)) AS LDL
		FROM sExamination.tTestRequest TR
		INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestRequestId = TR.Id
		INNER JOIN sOrderEntry.tTestDetail TD ON TD.Id = TRD.TestDetailId
		INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.Id = TD.TestParameterId
		WHERE TR.SourceId = E.Id
		  AND TPM.StaticTestParameterId = 34
		  AND (CASE 
			  WHEN TRD.ServiceValue NOT LIKE '%[^0-9.]%' 
			  		AND TRD.ServiceValue <> ''
			  THEN CAST(TRD.ServiceValue AS FLOAT)
			  ELSE 0
		 END) > 0
		ORDER BY TRD.Id DESC
	) L;
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 [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='Morbidly 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 = 'Morbidly 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
 ELSE IF (@rColumnName='Vitamin D3 Toxicity 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.VitaminD3 = 'Vitamin D3 Toxicity Risk'
  )  
 END

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


GO



ALTER PROCEDURE [sExamination].[pGetRoundGroupStatusDataForMHI] 
(
    @rMainTypeId INT,
    @rSetupGroupId INT,
    @rSetupIds NVARCHAR(MAX),
    @rUserId BIGINT,
    @rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;
 
	-- STEP 1: Split SetupIds once

	SELECT TRY_CAST(value AS BIGINT) AS SetupId
	INTO #SetupIds
	FROM dbo.SplitString(@rSetupIds, ',')
	WHERE @rSetupIds IS NOT NULL;

	CREATE INDEX IX_#SetupIds ON #SetupIds(SetupId);
 
	-- STEP 2: Filter base data early (very important)

	SELECT 
		STP.Id AS SetupId,
		STP.Title,
		EXM.Id AS ExaminationId,
		EXM.ParticipantSourceId,
		EXM.ParticipantSourceTypeId,
		EXM.StoreLocationId
	INTO 
		#ExamBase
	FROM 
		sExamination.tSetupMaster STP
	INNER JOIN 
		sExamination.tExamination EXM ON EXM.SetupId = STP.Id AND EXM.ParticipantSourceTypeId = 95 AND EXM.StatusId = 4 AND EXM.IsPublish = 1
	INNER JOIN 
		sExamination.tSubTypeMaster STM ON STM.Id = STP.SubTypeId
	INNER JOIN 
		sSecurity.tUserLocation USR ON USR.StoreLocationId = EXM.StoreLocationId
	WHERE 
			STP.OrgId = @rOrgId
		AND STP.IsObsolete = 0 AND (STM.MainTypeId = @rMainTypeId OR @rMainTypeId = 0)
		AND STP.SetupGroupId = @rSetupGroupId AND USR.UserId = @rUserId
		AND (@rSetupIds IS NULL OR STP.Id IN (SELECT SetupId FROM #SetupIds));
 
	CREATE CLUSTERED INDEX IX_#ExamBase ON #ExamBase(ExaminationId);

	SELECT 
		TR.SourceId AS ExaminationId,
		MAX(CASE WHEN TPM.StaticTestParameterId = 25 THEN CAST(TRD.ServiceValue AS NUMERIC(10,2)) END) AS HBA1C,
		MAX(CASE WHEN TPM.StaticTestParameterId = 34 THEN CAST(TRD.ServiceValue AS NUMERIC(10,2)) END) AS LDL
	INTO 
		#LabData
	FROM
		[sExamination].[tTestRequest] TR
	INNER JOIN 
		[sExamination].[tTestRequestDetail] TRD ON TRD.TestRequestId = TR.Id
	INNER JOIN 
		[sOrderEntry].[tTestDetail] TD ON TD.Id = TRD.TestDetailId
	INNER JOIN 
		[sOrderEntry].[tTestParameterMaster] TPM ON TPM.Id = TD.TestParameterId
	INNER JOIN 
		#ExamBase EB ON EB.ExaminationId = TR.SourceId 
	WHERE 
		TPM.StaticTestParameterId IN (25,34) AND CAST(TRD.ServiceValue AS FLOAT) > 0
	GROUP BY
		TR.SourceId;
 
	CREATE CLUSTERED INDEX IX_#LabData ON #LabData(ExaminationId);
 
	-- STEP 4: Final select

	SELECT 
		EB.ParticipantSourceTypeId,
		EB.ParticipantSourceId,
		EM.Code AS EmployeeCode,
		Vital.BloodPressureSystolic AS SystolicBP,
		Vital.BloodPressureDiastolic AS DiastolicBP,
		Vital.BMI AS BMI,
		LD.HBA1C AS HBA1C,
		LD.LDL AS LDL,
		MHI.Stress AS Stress,
		MHI.Lifestyle AS LifeStyle
	FROM 
		#ExamBase EB
	INNER JOIN 
		[sIp].[tStoreLocationMaster] SLM ON SLM.Id = EB.StoreLocationId
	LEFT JOIN 
		[sExamination].[tVital] Vital ON Vital.SourceId = EB.ExaminationId
	LEFT JOIN 
		[sWellness].[tMHIScoreUpdation] MHI ON MHI.ParticipantSourceId = EB.ParticipantSourceId AND EXISTS ( SELECT 1 FROM [sExamination].[tExamination] E WHERE E.Id = EB.ExaminationId)
	LEFT JOIN 
		#LabData LD ON LD.ExaminationId = EB.ExaminationId
	INNER JOIN
		[sHrm].[tEmployeeMaster] EM ON EM.Id = EB.ParticipantSourceId
	--WHERE
	--	MHI.Stress > 0 OR MHI.Lifestyle > 0

	DROP TABLE #SetupIds
	DROP TABLE #LabData
	DROP TABLE #ExamBase

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


GO

ALTER PROCEDURE [sExamination].[pHealthAnalysisEmployeeParameterGetWithPagination]
	@rMaINTypeId INT,
	@rOrgId INT,
	@rSetupGroupId INT,
	@rSetupId INT,
	@rHealthIndicatorId 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,
	@PageSize int = 20,
	@GlobalSearch NVARCHAR(MAX)= ''
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SET @rEmployeeFname = sCommon.fSearchStringGet(@rEmployeeFname)
	SET @rEmployeeLname = sCommon.fSearchStringGet(@rEmployeeLname)

	IF(@rToDate='')
	BEGIN
		SET @rToDate='01/06/2050'
	END
	select @rFromDate = CONVERT(VARCHAR(10), CONVERT(date, @rFromDate, 105), 23)
	select @rToDate = CONVERT(VARCHAR(10), CONVERT(date, @rToDate, 105), 23)

	DECLARE @EmployeeCode nVarchar(100)=''
	 
	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=@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 ((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 ((EMP.FirstName LIKE @rEmployeeFname)  OR  (@rEmployeeFname = ''))
	AND ((EMP.LastName  LIKE @rEmployeeLname)  OR  (@rEmployeeLname = ''))
	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 (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='')
	AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0) -- Nidhi Pandey; Mantis id = 22911, DT - 16/01/2023
	--select * from #tmp
	select TR.ID As TestRequestId,TR.TestId,T.ID As ExaminationId
	into #tmp1
	From sExamination.tTestRequest TR
	    inner join #tmp as T On T.ID = TR.SourceID 		
		
	--mantis id 0047676
	select Distinct TRD.ServiceValue,T1.ExaminationId,   CASE 
        WHEN STPM.UCode = 'DIABETIC_FBS' THEN 'DIABETIC'
        ELSE STPM.UCode
    END AS UCode,TRD.Diagnosis
	into #tmp2
	from sExamination.tTestRequestDetail TRD
	inner join #tmp1 T1 On T1.TestRequestId=TRD.TestRequestId
	inner join sOrderEntry.tTestMaster TM on T1.TestId = TM.Id
	inner join sOrderEntry.tTestDetail TD on TM.Id = TD.TestId and TRD.TestDetailId = TD.Id
	inner join sOrderEntry.tTestParameterMaster TPM on TD.TestParameterId = TPM.Id
	inner join sOrderEntry.tStaticTestParameterMaster STPM on TPM.StaticTestParameterId = STPM.Id

	UNION ALL

	-- Mantis:51206, Dummy record if DIABETIC / DIABETIC_FBS not present
	SELECT 
    '' AS ServiceValue,
    X.ExaminationId,
    'DIABETIC' AS UCode,
    '' AS Diagnosis
	FROM (
		SELECT DISTINCT ExaminationId
		FROM #tmp1
	) X
	WHERE NOT EXISTS (
		SELECT 1
		FROM sExamination.tTestRequestDetail TRD
		INNER JOIN sExamination.tTestRequest TR 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
		INNER JOIN sOrderEntry.tStaticTestParameterMaster STPM ON TPM.StaticTestParameterId = STPM.Id
		WHERE TR.SourceId = X.ExaminationId
		  AND STPM.UCode IN ('DIABETIC_FBS','DIABETIC')
	);

	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
	-- changes as per mentis issue no:12021 - 2020-07-08 (Rahul,Raju sir,das sir) discussion
	if(@configval='Priority')
		begin
			update t set t.ServiceValue=(case when Isnull(t2.ServiceValue,'')!='' 
											--and Isnull(t3.ServiceValue,'')='' 
											then t2.ServiceValue
											when Isnull(t.ServiceValue,'')!='' then t.ServiceValue
											when Isnull(t3.ServiceValue,'')!='' then t3.ServiceValue
											 else t1.ServiceValue end)
			From #tmp2 as t
			left join #tmp2 as t1 on t1.ExaminationId=t.ExaminationId and t1.UCode='DIABETIC_RBS'
			left join #tmp2 as t2 on t2.ExaminationId=t.ExaminationId and t2.UCode='DIABETIC_HBA1C'
			left join #tmp2 as t3 on t3.ExaminationId=t.ExaminationId and t3.UCode='DIABETIC_PPBS'
			Where t.UCode='DIABETIC' --rand Isnull(t.ServiceValue,'')=''
		end
	else if(@configval='Priority Abnormal')
		begin
			update t set t.ServiceValue=(case when Isnull(t2.Diagnosis,'')='Diabetic' 											
											then t2.ServiceValue
											when Isnull(t.Diagnosis,'')='Diabetic' 
											then t.ServiceValue
											when Isnull(t3.Diagnosis,'')='Diabetic' 
											then t3.ServiceValue 
											when Isnull(t1.Diagnosis,'')='Diabetic' 
											then t1.ServiceValue
											
											when Isnull(t2.Diagnosis,'')='Pre Diabetic' 											
											then t2.ServiceValue
											when Isnull(t.Diagnosis,'')='Pre Diabetic' 
											then t.ServiceValue
											when Isnull(t3.Diagnosis,'')='Pre Diabetic' 
											then t3.ServiceValue
											when Isnull(t1.Diagnosis,'')='Pre Diabetic' 
											then t1.ServiceValue											
											 else t.ServiceValue end)
			From #tmp2 as t
			left join #tmp2 as t1 on t1.ExaminationId=t.ExaminationId and t1.UCode='DIABETIC_RBS'
			left join #tmp2 as t2 on t2.ExaminationId=t.ExaminationId and t2.UCode='DIABETIC_HBA1C'
			left join #tmp2 as t3 on t3.ExaminationId=t.ExaminationId and t3.UCode='DIABETIC_PPBS'
			Where t.UCode='DIABETIC' 

		end
	--select * from #tmp2 order by UCode

	DECLARE @TableOne TABLE
	(
		tid int identity(1,1),EmployeeCode NVARCHAR(250),EmployeeName NVARCHAR(250),TotalPoints NVARCHAR(100),
		EarnedPoints NVARCHAR(100),Percentage NVARCHAR(100),IndicatorName NVARCHAR(250),SetupName varchar(100),
		SubLocation varchar(50),HealthIndexParameter varchar(50),FromValue varchar(50),ToValue varchar(50),
		EarnedValue varchar(50),ParamterTypeId int,GradeTitle varchar(300),StorelocationId int, ColorCode nvarchar(50)
	)
	INSERT INTO @TableOne
	SELECT isnull(EMP.Code,''),
	UPPER(ISNULL(EMP.FirstName,'')+' '+ISNULL(EMP.LastName,'')),
	TotalPoints,
	EarnedPoints,
	CONVERT(DECIMAL(18,2),((CONVERT(DECIMAL(18,2),HI.EarnedPoints)* 100) /CONVERT(DECIMAL(18,2),HI.TotalPoints))) AS Percentage,
	(SELECT (CASE WHEN ISNULL(HealthIndicatorLabel, '') != '' and IsObsolete = 0 THEN HealthIndicatorLabel ELSE Title END) 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) AS IndicatorName,
	STM.Title,
	SLM.Title,
	CASE WHEN HIP.Title IN ('DIABETIC_HBA1C','DIABETIC_PPBS','DIABETIC_RBS') THEN 'DIABETIC' ELSE HIP.Title END,
	(select top 1 FromValue from [sExamination].[tHealthIndexParameterDetail] where HealthIndexParameterId = HIP.Id and EarnedPoints = HI.EarnedPoints
	and GenderId = EPD.GenderId and Points=10),
	(select top 1 ToValue from [sExamination].[tHealthIndexParameterDetail] where HealthIndexParameterId = HIP.Id and EarnedPoints = HI.EarnedPoints
	and GenderId = EPD.GenderId and Points=10),
	CASE WHEN HIP.HealthIndexParameterTypeId = 1 and HIP.Title = 'BMI' then
	(select convert(varchar,BMI) from sExamination.tVital where SourceId = EXM.Id)
	WHEN HIP.HealthIndexParameterTypeId = 1 and HIP.Title = 'Blood Pressure Systolic' then
	(select convert(varchar,BloodPressureSystolic) from sExamination.tVital where SourceId = EXM.Id)
	WHEN HIP.HealthIndexParameterTypeId = 1 and HIP.Title = 'Blood Pressure Diastolic' then
	(select convert(varchar,BloodPressureDiastolic) from sExamination.tVital where SourceId = EXM.Id)
	--WHEN HIP.HealthIndexParameterTypeId = 2 or HIP.HealthIndexParameterTypeId = 3 then (Select ISNULL(TRD.ServiceValue,'') From #tmp2 as TRD Where TRD.ExaminationId=EXM.Id and TRD.UCode=(Case WHEN HIP.Title = 'DIABETIC' THEN 'DIABETIC_FBS' ELSE HIP.Title END))
    WHEN HIP.HealthIndexParameterTypeId IN (2, 3) THEN     ISNULL(TRD.ServiceValue,'')
	WHEN HIP.HealthIndexParameterTypeId = 13 and HIP.Title = 'Audiometry' then
	(select convert(varchar,ARM.Title) from sExamination.tAudiometry AUD
	INNER JOIN sExamination.tAudiometryResultMaster ARM ON ARM.Id = CASE WHEN AUD.AudiometryAcResultLeftId > AUD.AudiometryAcResultRightId 
																   THEN AUD.AudiometryAcResultLeftId ELSE AUD.AudiometryAcResultRightId END
	where SourceId = EXM.Id)
	WHEN HIP.HealthIndexParameterTypeId = 14 and HIP.Title = 'Pulmonary' then
	(select LTRIM(RTRIM(ISNULL(PulmonaryResulIntensity,'') + ' ' + ISNULL(PulmonaryResult,''))) from sExamination.tPulmonary where SourceId = EXM.Id)
	else '' end,
	HIP.HealthIndexParameterTypeId,isnull(GRD.Title,''),
	SLM.Id,
	(SELECT ColorCode 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) AS ColorCode
	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
	LEFT JOIN #tmp2 TRD ON TRD.ExaminationId = EXM.Id AND TRD.UCode = HIP.Title
	INNER JOIN sSecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	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 ((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 ((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 ((EMP.FirstName LIKE @rEmployeeFname)  OR  (@rEmployeeFname = ''))
	AND ((EMP.LastName  LIKE @rEmployeeLname)  OR  (@rEmployeeLname = ''))
	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 ((EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)) -- Nidhi Pandey; Mantis id = 22911, DT - 16/01/2023
	AND UL.UserId = @rUserId
	--AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0 or @rFromDate = '')
	--AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 or @rToDate ='') 
	ORDER BY EMP.ID,HI.HealthIndexParameterId
	OPTION(RECOMPILE)


  
	
	;WITH PageNumbers AS(
	select 
	 ROW_NUMBER() OVER(
			ORDER BY CASE WHEN @SortColumnName = 'SrNo' AND @IsAscendingOrder = 0 THEN isnull(CONVERT(varchar,tid),'') END DESC,
					 CASE WHEN @SortColumnName = 'SrNo' AND @IsAscendingOrder = 1 THEN isnull(CONVERT(varchar,tid),'') END,
					 CASE WHEN @SortColumnName = 'Code' AND @IsAscendingOrder = 0 THEN isnull(EmployeeCode,'') END DESC,
					 CASE WHEN @SortColumnName = 'Code' AND @IsAscendingOrder = 1 THEN isnull(EmployeeCode,'') END,
					 CASE WHEN @SortColumnName = 'Employee' AND @IsAscendingOrder = 0 THEN isnull(EmployeeName,'') END DESC,
					 CASE WHEN @SortColumnName = 'Employee' AND @IsAscendingOrder = 1 THEN isnull(EmployeeName,'') END,
					 CASE WHEN @SortColumnName = 'Grade' AND @IsAscendingOrder = 0 THEN isnull(GradeTitle,'') END DESC,
					 CASE WHEN @SortColumnName = 'Grade' AND @IsAscendingOrder = 1 THEN isnull(GradeTitle,'') END,
					 CASE WHEN @SortColumnName = 'SetupName' AND @IsAscendingOrder = 0 THEN isnull(SetupName,'') END DESC,
					 CASE WHEN @SortColumnName = 'SetupName' AND @IsAscendingOrder = 1 THEN isnull(SetupName,'') END,
					 CASE WHEN @SortColumnName = 'SubLocation' AND @IsAscendingOrder = 0 THEN isnull(SubLocation,'') END DESC,
					 CASE WHEN @SortColumnName = 'SubLocation' AND @IsAscendingOrder = 1 THEN isnull(SubLocation,'') END,
					 CASE WHEN @SortColumnName = 'HealthIndexParameter' AND @IsAscendingOrder = 0 THEN isnull(HealthIndexParameter,'') END DESC,
					 CASE WHEN @SortColumnName = 'HealthIndexParameter' AND @IsAscendingOrder = 1 THEN isnull(HealthIndexParameter,'') END,
					 CASE WHEN @SortColumnName = 'TotalPoints' AND @IsAscendingOrder = 0 THEN ISNULL(TotalPoints,'') END DESC,
					 CASE WHEN @SortColumnName = 'TotalPoints' AND @IsAscendingOrder = 1 THEN ISNULL(TotalPoints,'') END,
					 CASE WHEN @SortColumnName = 'EarnedPoints' AND @IsAscendingOrder = 0 THEN ISNULL(EarnedPoints,'') END DESC,
					 CASE WHEN @SortColumnName = 'EarnedPoints' AND @IsAscendingOrder = 1 THEN ISNULL(EarnedPoints,'') END,
					 CASE WHEN @SortColumnName = 'Value' AND @IsAscendingOrder = 0 THEN ISNULL(EarnedValue,'') END DESC,
					 CASE WHEN @SortColumnName = 'Value' AND @IsAscendingOrder = 1 THEN ISNULL(EarnedValue,'') END,
					 CASE WHEN @SortColumnName = 'Range' AND @IsAscendingOrder = 0 THEN '(' + FromValue + ' - ' + ToValue + ')' END DESC,
					 CASE WHEN @SortColumnName = 'Range' AND @IsAscendingOrder = 1 THEN '(' + FromValue + ' - ' + ToValue + ')' END,
					 CASE WHEN @SortColumnName = 'Percentage' AND @IsAscendingOrder = 0 THEN ISNULL(Percentage,'') END DESC,
					 CASE WHEN @SortColumnName = 'Percentage' AND @IsAscendingOrder = 1 THEN ISNULL(Percentage,'') END,
					 CASE WHEN @SortColumnName = 'Indicator' AND @IsAscendingOrder = 0 THEN ISNULL(IndicatorName,'') END DESC,
					 CASE WHEN @SortColumnName = 'Indicator' AND @IsAscendingOrder = 1 THEN ISNULL(IndicatorName,'') END,
					 CASE WHEN @SortColumnName = '' THEN tid END
	  ) ID,
	 COUNT(*) OVER() 'RecordCount',
	 isnull(CONVERT(varchar,tid),'') 'SrNo',
	 isnull(EmployeeCode,'') 'Code',
	 isnull(EmployeeName,'') 'Employee',
	 isnull(GradeTitle,'') 'Grade',
	 isnull(SetupName,'') 'SetupName',
	 isnull(SubLocation,'') 'SubLocation',
	 isnull(HealthIndexParameter,'') 'HealthIndexParameter',
	 isnull(TotalPoints ,'') 'TotalPoints',
	 isnull(EarnedPoints,'') 'EarnedPoints',
	 isnull(EarnedValue,'') 'EarnedValue',
	 '(' + FromValue + ' - ' + ToValue + ')' 'Range',
	 isnull(Percentage,'') 'Percentage',
	 isnull(IndicatorName ,'') 'Indicator',
	 isnull(ColorCode, '') ColorCode
	from @TableOne 
	WHERE (ISNULL(@GlobalSearch,'') = '' OR isnull(CONVERT(varchar,tid),'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(EmployeeCode,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(EmployeeName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(GradeTitle,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(SetupName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(SubLocation,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(HealthIndexParameter,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(TotalPoints,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(EarnedPoints,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(EarnedValue,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR '(' + FromValue + ' - ' + ToValue + ')' LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(Percentage,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										 OR ISNULL(IndicatorName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%')
	)
	SELECT  *
	FROM    PageNumbers
	WHERE  (@PageSize = -1 OR ID  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize)) 
	OPTION(RECOMPILE)
	
	-------------------------

	Drop Table #tmp
	Drop Table #tmp1
	Drop Table #tmp2
END
GO
PRINT N'Altering Procedure [sExamination].[pInjuryReferEmployeeDetail]...';


GO

ALTER PROCEDURE [sExamination].[pInjuryReferEmployeeDetail]
    @rExaminationId BIGINT = 0
AS
BEGIN
    BEGIN TRY
        DECLARE 
            @StoreLocationid INT,
            @orgid INT,
            @html VARCHAR(MAX),
            @rowstart VARCHAR(20),
            @rowend VARCHAR(20),
            @mainhtml NVARCHAR(MAX),
            @rowmid VARCHAR(20),
            @emailid VARCHAR(500) = '',
            @rEmployeeCodes NVARCHAR(MAX) = '',
            @lFieldResponse NVARCHAR(MAX) = '';

        -- placeholders variables
        DECLARE
            @IncidentDate VARCHAR(50),
            @IncidentTime VARCHAR(50),
            @ReportingDate VARCHAR(50),
            @ReportingTime VARCHAR(50),
            @Unit VARCHAR(200),
            @PlaceofIncident VARCHAR(500),
            @IncidentRemark VARCHAR(MAX),
            @NatureAndExtentOfInjury VARCHAR(MAX),
            @ActivityWhileAccident VARCHAR(MAX),
            @PPEUsed VARCHAR(200),
            @TransportationToOHC VARCHAR(200),
            @TransportationFromOHC VARCHAR(200),
            @Code VARCHAR(200),
            @Name VARCHAR(500),
            @Age VARCHAR(50),
            @Company VARCHAR(200),
            @Department VARCHAR(200),
            @Designation VARCHAR(200),
            @BodyPart VARCHAR(200),
            @BodySide VARCHAR(200),
			@IncidentType VARCHAR(200),
			@Cause VARCHAR(200),
            @Shift VARCHAR(200),
            @FurtherAction VARCHAR(200),
            @TreatmentType VARCHAR(200),
            @TreatmentGivenRemark VARCHAR(MAX),
            @Storelocation VARCHAR(200),
            @LegalPoint VARCHAR(200),
            @DoctorName VARCHAR(300);

        -- get storelocation and orgid
        SELECT @StoreLocationid = Storelocationid, @orgid = orgid
        FROM sExamination.tExamination
        WHERE id = @rExaminationId;

        -- build emailid if present in company (top 1)
        SELECT TOP 1 
            @emailid = CASE WHEN LEN(ISNULL(C.EmailIds, '')) > 0 THEN ',' + ISNULL(C.EmailIds, '') ELSE '' END
        FROM sExamination.tAccidentLog A
        INNER JOIN sHrm.tEmployeeCompanyMaster C ON C.id = A.EmployeeCompanyId
        WHERE A.ExaminationId = @rExaminationId;

        SET @html = '<table width="100%" border="1" cellspacing="0" cellpadding="0">';
        SET @rowstart = '<tr><td> ';
        SET @rowmid = ' </td><td>';
        SET @rowend = ' </td></tr>';

        IF NOT EXISTS(
            SELECT 1 
            FROM sAlert.tAssociateRecipient 
            WHERE StoreLocationId = @StoreLocationid 
              AND EventId = 27 
              AND ExaminationID = @rExaminationId
        )
        BEGIN
			   select OrgId,EventId,AlertModeId,IsAutoSend,MailSubject from sAlert.tEventTemplate where eventid=27 and orgid=@orgid and AlertModeId=1

               DECLARE @Template NVARCHAR(MAX);
               DECLARE @MailSubject NVARCHAR(MAX);
               DECLARE @StorelocationName NVARCHAR(MAX);
               

               SELECT @StorelocationName = ISNULL(SLM.Title, '')
               FROM sExamination.tExamination E
               INNER JOIN sIp.tStoreLocationMaster SLM ON E.StoreLocationId = SLM.Id
               WHERE E.Id = @rExaminationId;
               

               SELECT 
                   @Template = Template,
                   @MailSubject = MailSubject
               FROM sAlert.tEventTemplate  
               WHERE eventid = 27 
                 AND orgid = @orgid 
                 AND AlertModeId = 1;
               

               SET @MailSubject = REPLACE(ISNULL(@MailSubject, ''), '[Sublocation]', @StorelocationName);
               

               

			     -- build field response (concatenate)
            --SELECT @lFieldResponse = ISNULL(@lFieldResponse, '') + @rowstart + ISNULL(INS.FieldRemark,'') + @rowmid + ISNULL(AFF.AccidentLogFieldResponse,'') + @rowend
            --FROM sExamination.tAccidentLog AL
            --LEFT JOIN sExamination.tAccidentLogField AFF ON AFF.AccidentLogId = AL.Id
            --LEFT JOIN sSafety.tIncidentSetup INS ON INS.Id = AFF.IncidentSetupId
            --WHERE AL.ExaminationId = @rExaminationId;
			SELECT 
    @lFieldResponse = ISNULL(@lFieldResponse, '') 
        + @rowstart 
        + ISNULL(INS.FieldRemark, '') 
        + @rowmid 
        + CASE 
              WHEN ISDATE(REPLACE(LEFT(AFF.AccidentLogFieldResponse,16),'T',' ')) = 1 
                  THEN CONVERT(VARCHAR(20), CONVERT(DATETIME, REPLACE(LEFT(AFF.AccidentLogFieldResponse,16),'T',' '), 120), 103)  
            + ' ' + RIGHT(CONVERT(VARCHAR(20), CONVERT(DATETIME, REPLACE(LEFT(AFF.AccidentLogFieldResponse,16),'T',' '), 120), 100), 7)
				  --FORMAT(CAST(AFF.AccidentLogFieldResponse AS DATETIME), 'dd/MM/yyyy hh:mm tt')
              ELSE ISNULL(AFF.AccidentLogFieldResponse, '')
          END
        + @rowend
FROM sExamination.tAccidentLog AL
LEFT JOIN sExamination.tAccidentLogField AFF ON AFF.AccidentLogId = AL.Id
LEFT JOIN sSafety.tIncidentSetup INS ON INS.Id = AFF.IncidentSetupId
WHERE AL.ExaminationId = @rExaminationId;


			--print @lFieldResponse
            SET @lFieldResponse = ISNULL(@lFieldResponse, '');

            -- 2. fetch all fields into variables in one select (joins same as original)
            SELECT TOP 1
                @IncidentDate = ISNULL(CONVERT(VARCHAR(50), AL.IncidentDate, 103), ''),
                @IncidentTime = ISNULL(CONVERT(VARCHAR(50), AL.IncidentTime, 108), ''),
                @ReportingDate = ISNULL(CONVERT(VARCHAR(50), AL.ReportingDate, 103), ''),
                @ReportingTime = ISNULL(AL.ReportingTime, ''),
                @Unit = ISNULL(ECM.Title, ''),
                @PlaceofIncident = ISNULL(AL.PlaceofIncident, ''),
                @IncidentRemark = ISNULL(AL.IncidentRemark, ''),
                @NatureAndExtentOfInjury = ISNULL(AL.NatureAndExtant, ''),
                @ActivityWhileAccident = ISNULL(AL.ActivityWAccident, ''),
                @PPEUsed =  CASE ISNULL(AL.IsPPEUsed, 0) WHEN 1 THEN 'Yes' ELSE 'No' END,
                @TransportationToOHC = ISNULL(STRA.Title, ''),
                @TransportationFromOHC = ISNULL(STRA1.Title, ''),
                @Code = ISNULL(
                            CASE E.ParticipantSourceTypeId 
                                WHEN 95 THEN EM.Code 
                                WHEN 1001 THEN EM2.Code 
                                WHEN 1009 THEN BM.Code 
                            END, ''
                        ),
                @Name = ISNULL(
                            CASE E.ParticipantSourceTypeId 
                                WHEN 95 THEN EM.FirstName + ' ' + ISNULL(EM.LastName,'') 
                                WHEN 1001 THEN EFD.Name 
                                WHEN 1009 THEN CASE WHEN ISNULL(O.OtherName,'')<>'' THEN O.OtherName ELSE BM.FirstName + ' ' + ISNULL(BM.LastName,'') END 
                            END, ''
                        ),
                @Age = ISNULL(
                            CASE E.ParticipantSourceTypeId
                                WHEN 95 THEN ISNULL(DATEDIFF(YY, EPD.DateOfBirth, GETDATE()),0)
                                WHEN 1001 THEN ISNULL(DATEDIFF(YY, EFD.DateOfBirth, GETDATE()),0)
                                WHEN 1009 THEN ISNULL(O.Age, ISNULL(DATEDIFF(YY, BM.DateOfBirth, GETDATE()),0))
                            END, ''
                        ),
                @Company = ISNULL(
                            CASE E.ParticipantSourceTypeId
                                WHEN 95 THEN ISNULL(ECM.Title,'')
                                WHEN 1001 THEN ISNULL(ECM.Title,'')
                                WHEN 1009 THEN ''
                            END, ''
                        ),
                @Department = ISNULL(
                            CASE E.ParticipantSourceTypeId 
                                WHEN 95 THEN ISNULL(ODM.Title,'')
                                WHEN 1001 THEN ISNULL(ODM.Title,'')
                                WHEN 1009 THEN ''
                            END, ''
                        ),
                @Designation = ISNULL(
                            CASE E.ParticipantSourceTypeId
                                WHEN 95 THEN ISNULL(EDM.Title,'')
                                WHEN 1001 THEN ISNULL(EDM.Title,'')
                                WHEN 1009 THEN ''
                            END, ''
                        ),
                --@BodyPart = ISNULL(BPM.Title, ''),
                   @BodyPart = STUFF(
                       (
                           SELECT ',' + ISNULL(BPM.Title, '')
                           FROM sSafety.tBodyPartMaster BPM
                           WHERE ',' + AL.BodyPartIds + ',' LIKE '%,' + CAST(BPM.Id AS NVARCHAR(10)) + ',%'
                           FOR XML PATH(''), TYPE
                       ).value('.', 'NVARCHAR(MAX)')
                   ,1,1,''),


                @BodySide = ISNULL(BSTE.Title, ''),
				@IncidentType = ISNULL(ITE.Title, ''),
			    @Cause   = ISNULL(CM.Title, ''),
                @Shift = ISNULL(SSTE.Title, ''),
                @FurtherAction = ISNULL(SFTE.Title, ''),
                @TreatmentType = ISNULL(SFTY.Title, ''),
                @TreatmentGivenRemark = ISNULL(AL.TreatmentRemark, ''),
                @Storelocation = ISNULL(SLM.Title, ''),
                @LegalPoint = ISNULL(ILTE.Title, ''),
                @DoctorName = ISNULL(
                                CASE 
                                    WHEN D.EmployeeId IS NOT NULL THEN EM3.FirstName + ' ' + EM3.LastName 
                                    WHEN VD.Id IS NOT NULL THEN VD.FirstName + ' ' + VD.LastName 
                                    ELSE ISNULL(U.DisplayTitle,'') 
                                END, ''
                            )
            FROM sExamination.tAccidentLog AL
            INNER JOIN sExamination.tExamination E ON E.id = AL.ExaminationID
            INNER JOIN sExamination.tCauseMaster CM ON CM.id = E.CauseId
            INNER JOIN sIp.tStoreLocationMaster SLM ON E.StoreLocationId = SLM.Id
            LEFT JOIN sSafety.tIncidentTypeMaster ITE ON ITE.Id = AL.IncidentTypeId
            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.tEmployeeMaster EM2 ON EFD.EmployeeId = EM2.Id
            LEFT JOIN sHrm.tCsrBenefiterMaster BM ON E.ParticipantSourceId = BM.Id AND E.ParticipantSourceTypeId = 1009
            LEFT JOIN sExamination.tOPD O ON O.ExaminationId = E.Id
            LEFT JOIN sCwb.tDoctorMaster D ON E.DoctorEmployeeId = D.EmployeeId
            LEFT JOIN sHrm.tEmployeeMaster EM3 ON D.EmployeeId = EM3.Id
            LEFT JOIN sAppointment.tVisitingDoctorMaster VD ON E.DoctorEmployeeId = VD.Id
            LEFT JOIN sSecurity.tUser U ON U.id = E.CreatedUserid
            LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = E.OrganizationDepartmentId
            LEFT JOIN sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = E.EmployeeCompanyId
            LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = E.EmployeeDesignationId
            LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId
            LEFT JOIN sSafety.tBodyPartMaster BPM ON BPM.Id = AL.BodyPartId
            LEFT JOIN sSafety.tBodySideMaster BSTE ON BSTE.Id = AL.bodySideId
            LEFT JOIN sSafety.tShiftMaster SSTE ON SSTE.Id = AL.ShiftId
            LEFT JOIN sSafety.tFurtherActionMaster SFTE ON SFTE.Id = AL.FurtherActionId
            LEFT JOIN sSafety.tLegalPointMaster ILTE ON ILTE.Id = AL.LegalPointId
            LEFT JOIN sSafety.tTreatmentTypeMaster SFTY ON SFTY.Id = AL.TreatmentTypeId
            LEFT JOIN sSafety.tTransportationMaster STRA ON STRA.Id = AL.TransportationToOhcId
            LEFT JOIN sSafety.tTransportationMaster STRA1 ON STRA1.Id = AL.TransportationFromOhcId
            WHERE AL.ExaminationId = @rExaminationId;

            -- initialize main template
            SET @mainhtml = ISNULL(@Template, '');

            -- perform replacements (one by one - easier to maintain)
            SET @mainhtml = REPLACE(@mainhtml, '[IncidentDate]', ISNULL(@IncidentDate, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[IncidentTime]', ISNULL(@IncidentTime, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[ReportingDate]', ISNULL(@ReportingDate, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[ReportingTime]', ISNULL(@ReportingTime, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[Unit]', ISNULL(@Unit, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[PlaceofIncident]', ISNULL(@PlaceofIncident, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[IncidentRemark]', ISNULL(@IncidentRemark, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[NatureAndExtentOfInjury]', ISNULL(@NatureAndExtentOfInjury, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[ActivityWhileAccident]', ISNULL(@ActivityWhileAccident, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[PPEUsed]', ISNULL(@PPEUsed, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[TransportationToOHC]', ISNULL(@TransportationToOHC, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[TransportationFromOHC]', ISNULL(@TransportationFromOHC, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[Code]', ISNULL(@Code, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[Name]', ISNULL(@Name, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[Age]', ISNULL(@Age, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[Company]', ISNULL(@Company, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[Department]', ISNULL(@Department, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[Designation]', ISNULL(@Designation, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[BodyPart]', ISNULL(@BodyPart, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[BodySide]', ISNULL(@BodySide, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[Cause]', ISNULL(@BodySide, ''));
			SET @mainhtml = REPLACE(@mainhtml, '[IncidentType]', ISNULL(@IncidentType, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[Shift]', ISNULL(@Shift, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[FurtherAction]', ISNULL(@FurtherAction, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[TreatmentType]', ISNULL(@TreatmentType, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[TreatmentGivenRemark]', ISNULL(@TreatmentGivenRemark, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[Sublocation]', ISNULL(@Storelocation, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[LegalPoint]', ISNULL(@LegalPoint, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[DoctorName]', ISNULL(@DoctorName, ''));
            SET @mainhtml = REPLACE(@mainhtml, '[DynamicFields]', @lFieldResponse);





            -- return recipients (same logic as you had)
            SELECT 
                AutoId,
                EventId,
                CASE WHEN LEN(ISNULL(EmailIds, '')) > 2 THEN ISNULL(EmailIds, '') + @emailid ELSE @emailid END AS EmailIds,
                ISNULL(MobileIds, '') AS MobileIds,
                StoreLocationId
            FROM sAlert.tAssociateRecipient
            WHERE StoreLocationId = @StoreLocationid AND EventId = 27;

         
		 
SELECT @mainhtml AS Result;
            -- get employee codes from recipients and then find employee ids
            SELECT @rEmployeeCodes = ISNULL(EmployeeCodes, '') FROM sAlert.tAssociateRecipient WHERE StoreLocationId = @StoreLocationid AND EventId = 27;
            PRINT @rEmployeeCodes;

            SELECT Id AS EmployeeId 
            FROM sHrm.tEmployeeMaster 
            WHERE ISNULL(Code,'') IN (SELECT item FROM sCommon.fnsplit(ISNULL(@rEmployeeCodes,''), ','));

		--subject this will pick form index 4
		SELECT 
    REPLACE(ISNULL(MailSubject, ''), '[Sublocation]', @StorelocationName) AS MailSubject FROM sAlert.tEventTemplate WHERE OrgId = @orgid AND EventId = 27 AND AlertModeId = 1;
        END; -- end IF not exists

    END TRY
    BEGIN CATCH
        SELECT ERROR_MESSAGE() AS result;
    END CATCH
END;
GO
PRINT N'Altering Procedure [sExamination].[pLSDDashboardGraphListGet]...';


GO
ALTER PROCEDURE [sExamination].[pLSDDashboardGraphListGet]
@rOrgId int,
@rStoreLocationId int,
@rUserId bigint,
@rTypeId int,
@rFromDate varchar(100),
@rToDate varchar(100)
AS
BEGIN

	--select @rFromDate,@rToDate

    DECLARE @FromDate DATETIME, @ToDate DATETIME;

    IF (@rTypeId != 5)
	select @rToDate=convert(varchar,sCommon.fGetDate(),102)

   if(@rTypeId=1)
	begin
		select @rFromDate = convert(varchar,dateadd(mm,-1,sCommon.fGetDate()),102)
	end
	else if(@rTypeId=2)
	begin
		select @rFromDate = convert(varchar,dateadd(mm,-3,sCommon.fGetDate()),102)
	end
	else if(@rTypeId=3)
	begin
		select @rFromDate = convert(varchar,dateadd(mm,-6,sCommon.fGetDate()),102)
	end
	else if(@rTypeId=4)
	begin
		select @rFromDate = convert(varchar,dateadd(mm,-12,sCommon.fGetDate()),102)
	end
	else
	begin 
		SET @rFromDate = (SELECT FORMAT(CONVERT(DATE, @rFromDate, 103), 'yyyy.MM.dd'));
		SET @rToDate = (SELECT FORMAT(CONVERT(DATE, @rToDate, 103), 'yyyy.MM.dd'));
	end
	
	--select @rFromDate,@rToDate

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

	Create TABLE #tbltmpGraphList
	(tid int identity(1,1),Parameter varchar(30),MName varchar(30),Cnt int)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)
	From
	(Select Distinct 'Diabetic' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.FBS='Diabetic'	
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList	
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID) 
	From
	(Select Distinct 'Pre Diabetic' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.FBS='Pre Diabetic'
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)  
	From
	(Select Distinct 'Hypertension' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.BloodPressure ='Hypertension'
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID) 
	From
	(Select Distinct 'PreHypertension' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.BloodPressure ='PreHypertension'
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)	
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList	
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID) 
	From
	(Select Distinct 'Diabetic Existing' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.DiabeticExisting ='Diabetic Existing'
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)		
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList	
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)  
	From
	(Select Distinct 'Hypertension Existing' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.HypertensionExisting ='Hypertension Existing'
	) as final	
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)	
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)  
	From
	(Select Distinct 'New PreDiabetic' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.IsNewDiabeticStatus=1
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)	
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)
	From
	(Select Distinct 'New Diabetic' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.IsNewDiabeticStatus=2
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)
	From
	(Select Distinct 'New PreHypertension' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.IsNewHypertensionStatus=1
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)
	From
	(Select Distinct 'New Hypertension' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.IsNewHypertensionStatus=2
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)
	From
	(Select Distinct 'Tobacco' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.Tobacco=1
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)
	From
	(Select Distinct 'Smoker' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.Smoker=1
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)
	From
	(Select Distinct 'Alcohol' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.Alcohol=1
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)
	From
	(Select Distinct 'Underweight' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.BMI='Underweight'
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)
	From
	(Select Distinct 'Overweight' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.BMI='Overweight'
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)
	order by Month(ExaminationDate),Year(ExaminationDate)

	insert into #tbltmpGraphList
	select Parameter,DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate) as MName,Count(ID)
	From
	(Select Distinct 'Obese' as Parameter ,EXM.ExaminationDate,EMP.Id
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = @rOrgId
	AND UL.UserId = @rUserId
	AND (datediff(day,@rFromDate,EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,@rToDate)>=0 )
	AND dte.BMI='Obese'
	) as final
	Group BY DateName(mm,ExaminationDate) + '-' +DateName(yy,ExaminationDate),Parameter,Month(ExaminationDate),Year(ExaminationDate)
	order by Month(ExaminationDate),Year(ExaminationDate)

	--select * from #tbltmpGraphList

	declare @tmpdate table(tid int identity,MName date)
	insert into @tmpdate
	select Convert(date,MName)MName from (select distinct '01/'+ Replace(MName,'-','/') as Mname from #tbltmpGraphList)tmp order by Convert(date,MName)

	declare @columns NVARCHAR(MAX) = '',@columnsDisplay NVARCHAR(MAX) = '',@column NVARCHAR(MAX) = '',@HeaderDisplay NVARCHAR(MAX) = '', @sql     NVARCHAR(MAX) = '',@result nvarchar(max)
	
	
	select @columns = @columns +  QUOTENAME(DateName(mm,MName)+'-' + DateName(yy,MName)) + ',' 
	From 
	(
		select MName From @tmpdate
	)as final
	print @columns

	select @columnsDisplay = @columnsDisplay +  'Isnull(' + QUOTENAME(DateName(mm,MName)+'-' + DateName(yy,MName)) + ',0)' + ' as '+ QUOTENAME(Left(DateName(mm,MName),3)+'-' + Right(DateName(yy,MName),2)) +',' 
	From 
	(
	select MName From @tmpdate
	)as final

	-- remove the last comma
	--SET @columns = LEFT(@columns, LEN(@columns) - 1);
	--SET @columnsDisplay = LEFT(@columnsDisplay, LEN(@columnsDisplay) - 1);
	IF ISNULL(@columns,'') <> ''
BEGIN
	SET @columns = LEFT(@columns, LEN(@columns) - 1);
END

IF ISNULL(@columnsDisplay,'') <> ''
BEGIN
	SET @columnsDisplay = LEFT(@columnsDisplay, LEN(@columnsDisplay) - 1);
END


	SET @sql =' Select Parameter, '+@columnsDisplay+' into #tbltmpPivot From (select Parameter,MName,Cnt From #tbltmpGraphList)t 
	PIVOT(Min(Cnt) 
		FOR MName IN ('+ @columns +')
	) AS pivot_table; select * from #tbltmpPivot' 
	
	-- execute the dynamic SQL
	--print @sql;
	EXECUTE sp_executesql @sql;

	--select @HeaderDisplay=@HeaderDisplay + '<tbody><tr><th>Parameter</th>'
	--select @HeaderDisplay = @HeaderDisplay + '<th>' +  QUOTENAME(MName) + '</th>' 
	--From 
	--(
	--select distinct MName
	--from #tbltmpGraphList
	--)as final
	--select @HeaderDisplay=@HeaderDisplay + '</tr></tbody>'
	--Print @HeaderDisplay
	
	
END
GO
PRINT N'Altering Procedure [sExamination].[pMISExaminationDashboardDiagnosisTracker]...';


GO

ALTER PROC [sExamination].[pMISExaminationDashboardDiagnosisTracker]
@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
    )

    INSERT INTO @tExamination (Id, StoreLocationId)

        SELECT EXM.Id, EXM.StoreLocationId
        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 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




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

    CREATE TABLE ##tempTable (
			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,
			[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,
			[Morbidly Obese] smallint, 
			[Vitamin D3 Toxicity Risk] 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 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], (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.MetabolicSyndrome = 1)
        [Metabolic Syndrome], (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.CVDMajorRisk = 1)
        [CVD Major RISK], (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.CVDMinorRisk = 1)
        [CVD Minor RISK], (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.NCDsRisk = 1)
        [NCD`s RISK],
		 (  
         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.T3 = 'Elevated T3'  
         )[Elevated T3],
         (  
        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.T4 = 'Elevated T4'  
         )[Elevated T4],
         (  
        	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.TSH = 'Elevated TSH'  
         )[Elevated TSH],
         (  
        	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.PSA = 'High PSA'  
         )[High PSA],
         (  
        	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.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 EXM.StoreLocationId = 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 EXM.StoreLocationId = 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 EXM.StoreLocationId = 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 EXM.StoreLocationId = 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 EXM.StoreLocationId = 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 EXM.StoreLocationId = 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 EXM.StoreLocationId = 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 EXM.StoreLocationId = t.GroupId
                AND DTE.VitaminD3 = 'Vitamin D3 deficiency'  
        ) [Vitamin D3 deficiency], (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 = 'Morbidly Obese')
        [Morbidly 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.VitaminD3 = 'Vitamin D3 Toxicity Risk'
        ) [Vitamin D3 Toxicity Risk]
        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
        DROP TABLE #tblTmp

    CREATE TABLE #tblTmp (
        tid int IDENTITY (1, 1),
        id int,
        title varchar(200),
        cnt int
    )

   INSERT INTO #tblTmp
        SELECT M.Id, '[' + M.Title + ']', 0
        FROM sExamination.tDiagnosisTrackerMaster M
        --INNER JOIN sExamination.tDiagnosisTrackerUser O ON M.Id = O.DiagnosisTrackerId
		Inner join sExamination.tDiagnosisTrackerOrg T on M.Id = T.DiagnosisTrackerId and OrgId = @rOrgId
        WHERE 
		--O.UserId = @rUserId AND 
		m.IsObsolete = 0
		and m.id not in (49,50,51)
		ORDER BY T.OrderIndex ASC

    INSERT INTO @TableHeader
        SELECT M.Id, M.Title
        FROM sExamination.tDiagnosisTrackerMaster M
        --INNER JOIN sExamination.tDiagnosisTrackerUser O ON M.Id = O.DiagnosisTrackerId
		Inner join sExamination.tDiagnosisTrackerOrg T on M.Id = T.DiagnosisTrackerId and OrgId = @rOrgId
        WHERE 
		--O.UserId = @rUserId AND 
		m.IsObsolete = 0
		and m.id not in (49,50,51)
		ORDER BY T.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.tDiagnosisTrackerUser O ON M.Id = O.DiagnosisTrackerId
	Inner join sExamination.tDiagnosisTrackerOrg T on M.Id = T.DiagnosisTrackerId and OrgId = @rOrgId
    WHERE 
	--O.UserId = @rUserId AND 
	m.IsObsolete = 0
	and m.id not in (49,50,51)
	ORDER BY T.OrderIndex ASC


    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(50), ' + SUBSTRING(@columns, 2, LEN(@columns)) + ' )'
    END
    ELSE
    BEGIN
        SET @columns = 'CREATE TABLE ##temp007(tId int identity (1,1), GroupId	int, GroupName varchar(50))'
    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)

    --SELECT * FROM ##temp007
	

    DECLARE @DiagnosHeader varchar(max) = '',
    @ColCnt int,
    @ColIncr int,
    @result varchar(max) = '',
    @RowCnt int,
    @RowIncr int


    SELECT @DiagnosHeader = '<table class="table table-bordered table-striped"  cellspacing="0" rules="all" border="1" style="width: 100%; border-collapse: collapse;"><thead><tr><td>Sub Location</td>'


    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 + '<td>' + @ColName + '</td>'
        SELECT @ColIncr = @ColIncr + 1
    END

    SELECT @DiagnosHeader = @DiagnosHeader + '</tr></thead>'

    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>' + 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)

            --print @SqlStatement1
            EXECUTE (@SqlStatement1)
			

            DECLARE @Val int = 0

            SELECT @Val = Value
            FROM ##temp001

            SELECT @result = @result + '<td style="text-align:center;padding:5pt 5pt 5pt 5pt;">' + CONVERT(varchar, @Val) +'</td>'
            SELECT @RowIncr = @RowIncr + 1
        END


        SELECT @result = @result + '</tr>'
        SELECT @ColIncr = @ColIncr + 1

    END
    

    SELECT @ColCnt = COUNT(0), @ColIncr = 1
    FROM #tblTmp


    DECLARE @colscnt int
    SELECT @colscnt = COUNT(0)
    FROM ##tempTable


    IF (@colscnt > 0)
    BEGIN
        SELECT @result = @result + '<tr><td style="font-weight: 700;">Total</td>'
        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 + +'<td style="text-align:center;padding:5pt 5pt 5pt 5pt; font-weight: 700;"> ' + CONVERT(varchar, @sum1) + ' </td>'

            SELECT @ColIncr = @ColIncr + 1
        END
        SELECT @result = @result + '</tr></table>'
    END

    DECLARE @h int
    SELECT @h = COUNT(0)
    FROM @TableHeader

    SELECT @result =
                    CASE
                        WHEN ISNULL(@colscnt, 0) = 0 THEN '<tr><td style="font-weight: 700;" colspan="' + CONVERT(varchar, @h + 1) + '">No Records found in this selected criteria !</td></tr></table>'
                        ELSE @result
                    END
    SELECT @DiagnosHeader + @result AS ResultGrid, LEN(@DiagnosHeader + @result)
    
   IF OBJECT_ID('tempdb..##tempTable') IS NOT NULL  
   BEGIN  
        DROP TABLE ##tempTable  
   END
END
GO
PRINT N'Altering Procedure [sExamination].[pMobAllDiagnosisCountGet]...';


GO
        
ALTER proc [sExamination].[pMobAllDiagnosisCountGet]          
@rOrgId INT,          
@rSetupGroupId INT,          
@rSectorId nvarchar(max)= '',          
@rVerticalId nvarchar(max)= '',          
@rCompanyGroupId nvarchar(max)= '',          
@rCompanyId nvarchar(max)= '',          
@rGradeId nvarchar(max)= '',          
@rFunctionId nvarchar(max)= '',          
@rStoreLocationId nvarchar(max)= '',          
@rEmployeeTypeGroupid int=0,          
@rIsCurrent int          
as        
begin      
 set @riscurrent = 0;        
 declare @tbltmp table        
 (      
  tid int identity(1,1),t_OrgId bigint,t_OrganizationName varchar(200),t_ExaminationId bigint,t_BMI varchar(200),        
  t_BloodPressure varchar(200),t_FBS varchar(200),t_SGPT varchar(200),t_TB varchar(200),t_DiabeticExisting  varchar(200),t_HypertensionExisting  varchar(200),t_Hypertriglyceridemia  varchar(200)     
  ,t_Hypercholesterolemia  varchar(200),t_Elevated_LDL varchar(200), t_PSA varchar(200), t_SerumCreatinine varchar(200),
  t_TSH varchar(200),t_VitaminB12 varchar(200),t_VitaminD3 varchar(200)
 )      
 insert into @tbltmp      
 SELECT SCT.Id,SCT.Title,EXM.Id,DTE.BMI,DTE.BloodPressure,DTE.FBS,DTE.SGPT,DTE.TB,DTE.DiabeticExisting,
 DTE.HypertensionExisting, DTE.Triglyceride,DTE.Cholesterol,DTE.LDL,DTE.PSA,DTE.SerumCreatinine,DTE.TSH,
 DTE.VitaminB12,DTE.VitaminD3
 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 SSM ON SSM.Id = STM.SubTypeId          
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId and EXM.ParticipantSourceTypeId=95          
 INNER JOIN [sHrm].[tEmployeeJobDetail]  AS EJD ON EJD.EmployeeId=EMP.ID          
 INNER JOIN [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId            
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=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.tOrganizationDepartmentMaster ODM on ODM.Id=(case when @rIsCurrent=0 then EXM.OrganizationDepartmentId else EJD.OrganizationDepartmentId end )          
 INNER JOIN sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id          
 INNER JOIN sExamination.tDiagnosisTrackerEmployee DTE on EXM.Id = DTE.ExaminationId          
           
 WHERE EXM.ParticipantSourceTypeId=95 AND SCT.OrgId=@rOrgId          
 --AND DIA.TotalHealthPoints>0           
 AND (STM.SetupGroupId=@rSetupGroupId OR @rSetupGroupId=0)           
 AND (ISNULL(SCT.Id,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rSectorId,''),','))OR ISNULL(@rSectorId,'')='')          
 AND (ISNULL(VTM.Id,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 AND (ISNULL(ECM.CompanyGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rCompanyGroupId,''),','))OR ISNULL(@rCompanyGroupId,'')='')          
 AND (ISNULL(EXM.EmployeeCompanyId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rCompanyId,''),','))OR ISNULL(@rCompanyId,'')='')          
 AND (ISNULL(EXM.GradeId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rGradeId,''),','))OR ISNULL(@rGradeId,'')='')          
 AND (ISNULL(DGM.FunctionId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rFunctionId,''),','))OR ISNULL(@rFunctionId,'')='')          
 AND (ISNULL(EXM.StoreLocationId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rStoreLocationId,''),','))OR ISNULL(@rStoreLocationId,'')='')            
 AND (ETM.EmployeeTypeGroupId=@rEmployeeTypeGroupid OR @rEmployeeTypeGroupid=0)          
           
 declare @lOverWeight int,@lPreHypertension int,@lHypertension int,@lPreDiabetic int,@lDiabetic int,@lHighSGPT int,
 @lHypertriglyceridemia int,@lHypercholesterolemia int,@lElevated_LDL int,@lObese int,@lMorbidlyObese int,
 @lHighPSA int,@lHighSerumCreatinine int,@lLowTSH int,@lHighTSH int,@lVitaminB12deficiency int, 
 @lVitaminD3deficiency int, @lVitaminD3ToxicityRisk int
  
 select @lOverWeight = COUNT(0) FROM @tbltmp WHERE (t_BMI = 'Overweight')         
      
 select @lPreHypertension = COUNT(0)          
 FROM @tbltmp WHERE (t_BloodPressure = 'PreHypertension'  AND Isnull(t_HypertensionExisting,'')<>'Hypertension Existing') -- CHANGE BY MS  MENTIS ISSUE:0024494 2023-04-07       
           
 select @lHypertension = COUNT(0)          
 FROM @tbltmp WHERE (t_BloodPressure in ('Hypertension','High Blood Pressure','Hypertension stage 2','Hypertension Existing') or t_HypertensionExisting='Hypertension Existing')         
      
 select @lPreDiabetic = COUNT(0) FROM @tbltmp WHERE (t_FBS = 'Pre Diabetic' AND Isnull(t_DiabeticExisting,'') <> 'Diabetic Existing') -- CHANGE BY MS  MENTIS ISSUE:0024494 2023-04-07        
      
 select @lDiabetic = COUNT(0) FROM @tbltmp WHERE (t_FBS in ('Diabetic','Diabetic Existing')  or t_DiabeticExisting ='Diabetic Existing')       
      
 select @lHighSGPT = COUNT(0) FROM @tbltmp WHERE t_SGPT = 'Elevated  SGPT' 
 
  select @lHypertriglyceridemia = COUNT(0) FROM @tbltmp WHERE t_Hypertriglyceridemia = 'Hypertriglyceridemia' 
  
  select @lHypercholesterolemia = COUNT(0) FROM @tbltmp WHERE t_Hypercholesterolemia = 'Hypercholesterolemia' 

  select @lElevated_LDL = COUNT(0) FROM @tbltmp WHERE t_Elevated_LDL = 'Elevated  LDL'
  
  select @lObese = COUNT(0) FROM @tbltmp WHERE (t_BMI = 'Obese')

  select @lMorbidlyObese = COUNT(0) FROM @tbltmp WHERE (t_BMI = 'Morbidly Obese')

  select @lHighPSA = COUNT(0) FROM @tbltmp WHERE (t_PSA = 'High PSA')

  select @lHighSerumCreatinine = COUNT(0) FROM @tbltmp WHERE (t_SerumCreatinine = 'High Serum Creatinine')

  select @lLowTSH = COUNT(0) FROM @tbltmp WHERE (t_TSH = 'Low TSH')

  select @lHighTSH = COUNT(0) FROM @tbltmp WHERE (t_TSH = 'Elevated TSH')

  select @lVitaminB12deficiency = COUNT(0) FROM @tbltmp WHERE (t_VitaminB12 = 'Vitamin B12 deficiency')

  select @lVitaminD3deficiency = COUNT(0) FROM @tbltmp WHERE (t_VitaminD3 = 'Vitamin D3 deficiency')

  select @lVitaminD3ToxicityRisk = COUNT(0) FROM @tbltmp WHERE (t_VitaminD3 = 'Vitamin D3 Toxicity Risk')
           
 select @lOverWeight as Overweight,@lPreHypertension as Prehypertension,@lHypertension as Hypertension,          
 @lPreDiabetic as Prediabetic,@lDiabetic as Diabetic,@lHighSGPT as HighSGPT , 
 @lHypertriglyceridemia as Hypertriglyceridemia,@lHypercholesterolemia as Hypercholesterolemia, 
 @lElevated_LDL as Elevated_LDL,@lObese as Obese,@lMorbidlyObese as MorbidObesity,@lHighPSA as HighPSA,
 @lHighSerumCreatinine as HighSerumCreatinine,@lLowTSH as LowTSH,@lHighTSH as HighTSH,
 @lVitaminB12deficiency as VitaminB12deficiency,@lVitaminD3deficiency as VitaminD3deficiency,
 @lVitaminD3ToxicityRisk as VitaminD3ToxicityRisk

end
GO
PRINT N'Altering Procedure [sExamination].[pMobEmployeeWiseDiagnosisGet]...';


GO
           
ALTER proc [sExamination].[pMobEmployeeWiseDiagnosisGet]              
@rOrgId INT,              
@rSetupGroupId INT,              
@rSectorId nvarchar(max)= '',              
@rVerticalId nvarchar(max)= '',              
@rCompanyGroupId nvarchar(max)= '',              
@rCompanyId nvarchar(max)= '',              
@rGradeId nvarchar(max)= '',              
@rFunctionId nvarchar(max)= '',              
@rStoreLocationId nvarchar(max)= '',              
@rFlag int=1,              
@rDiseaseId int=0,              
@rEmployeeTypeGroupid int=0,              
@rIsCurrent int              
as              
begin      
set @rIsCurrent =0;      
 declare @tbltmp table              
 (              
  tid int identity(1,1),t_OrgId bigint,t_OrganizationName varchar(200),t_ExaminationId bigint,t_SectorId int,              
  t_VerticalId int,t_BMI varchar(200),t_BloodPressure varchar(200),t_FBS varchar(200),t_SGPT varchar(200),t_TB varchar(200),              
  t_EmployeeName varchar(300),t_EmployeeId bigint,t_SetupId bigint,t_EmployeeCode varchar(300),t_DiabeticExisting  varchar(200),t_HypertensionExisting  varchar(200) 
  ,t_Hypertriglyceridemia  varchar(200),t_Elevated_LDL  varchar(200),t_Hypercholesterolemia varchar(200),
  t_PSA varchar(200), t_SerumCreatinine varchar(200), t_TSH varchar(200),t_VitaminB12 varchar(200),t_VitaminD3 varchar(200)
 )        
               
 if (@rFlag=1 or @rFlag=4) -- Location wise              
 begin               
 INSERT INTO @tbltmp              
 SELECT SLM.Id ,              
 SLM.Title,          
 EXM.Id,SCT.Id,VTM.Id,DTE.BMI,DTE.BloodPressure,DTE.FBS,DTE.SGPT,DTE.TB,EM.FirstName + ' ' + EM.LastName            
 ,EM.Id,STM.Id, EM.Code,DTE.DiabeticExisting,DTE.HypertensionExisting, DTE.Triglyceride,DTE.LDL ,
 DTE.Cholesterol,DTE.PSA,DTE.SerumCreatinine,DTE.TSH,DTE.VitaminB12,DTE.VitaminD3         
 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 SSM ON SSM.Id = STM.SubTypeId              
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId and EXM.ParticipantSourceTypeId=95              
 INNER JOIN [sHrm].[tEmployeeJobDetail]  AS EJD ON EJD.EmployeeId=EMP.ID              
 INNER JOIN [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId                 
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=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.tOrganizationDepartmentMaster ODM on ODM.Id=(case when @rIsCurrent=0 then EXM.OrganizationDepartmentId else EJD.OrganizationDepartmentId end )                 
 INNER JOIN sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id              
 INNER JOIN sExamination.tDiagnosisTrackerEmployee DTE on EXM.Id = DTE.ExaminationId              
 INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id=EXM.StoreLocationId              
 INNER JOIN sCommon.tLocationMaster LM on LM.Id=SLM.LocationId              
 --INNER JOIN sCommon.tStateMaster SM on SM.Id=LM.StateId              
 INNER JOIN sHrm.tEmployeeMaster EM on EM.Id = EXM.ParticipantSourceId              
               
 WHERE EXM.ParticipantSourceTypeId=95     
 --AND DIA.TotalHealthPoints>0     
 AND VTM.OrgId=@rOrgId              
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))              
 AND (ISNULL(SCT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rSectorId,''),','))OR ISNULL(@rSectorId,'')='')              
 AND (ISNULL(VTM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')              
 AND (ISNULL(ECM.CompanyGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyGroupId,''),','))OR ISNULL(@rCompanyGroupId,'')='')              
 AND (ISNULL(EXM.EmployeeCompanyId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyId,''),','))OR ISNULL(@rCompanyId,'')='')              
 AND (ISNULL(EXM.GradeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rGradeId,''),','))OR ISNULL(@rGradeId,'')='')              
 AND (ISNULL(DGM.FunctionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rFunctionId,''),','))OR ISNULL(@rFunctionId,'')='')              
 AND (ISNULL(EXM.StoreLocationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rStoreLocationId,''),','))OR ISNULL(@rStoreLocationId,'')='')              
 AND (ETM.EmployeeTypeGroupId=@rEmployeeTypeGroupid OR @rEmployeeTypeGroupid=0)
            
    end              
                  
 else if(@rFlag=2) -- State wise              
 begin              
 INSERT INTO @tbltmp              
 SELECT SM.Id ,              
 SM.Title,              
 EXM.Id,SCT.Id,VTM.Id,DTE.BMI,DTE.BloodPressure,DTE.FBS,DTE.SGPT,DTE.TB,EM.FirstName + ' ' + EM.LastName            
 ,EM.Id ,STM.Id, EM.Code,DTE.DiabeticExisting,DTE.HypertensionExisting , DTE.Triglyceride,DTE.LDL,
 DTE.Cholesterol,DTE.PSA,DTE.SerumCreatinine,DTE.TSH,DTE.VitaminB12,DTE.VitaminD3            
 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 SSM ON SSM.Id = STM.SubTypeId              
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId and EXM.ParticipantSourceTypeId=95              
 INNER JOIN [sHrm].[tEmployeeJobDetail]  AS EJD ON EJD.EmployeeId=EMP.ID              
 INNER JOIN [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId                 
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=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.tOrganizationDepartmentMaster ODM on ODM.Id=EXM.OrganizationDepartmentId              
 INNER JOIN sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id              
 INNER JOIN sExamination.tDiagnosisTrackerEmployee DTE on EXM.Id = DTE.ExaminationId              
 INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id=EXM.StoreLocationId              
 INNER JOIN sCommon.tLocationMaster LM on LM.Id=SLM.LocationId              
 INNER JOIN sCommon.tStateMaster SM on SM.Id=LM.StateId              
 INNER JOIN sHrm.tEmployeeMaster EM on EM.Id = EXM.ParticipantSourceId              
               
 WHERE EXM.ParticipantSourceTypeId=95 --AND DIA.TotalHealthPoints>0 
 AND VTM.OrgId=@rOrgId              
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))              
 AND (ISNULL(SCT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rSectorId,''),','))OR ISNULL(@rSectorId,'')='')              
 AND (ISNULL(VTM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')              
 AND (ISNULL(ECM.CompanyGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyGroupId,''),','))OR ISNULL(@rCompanyGroupId,'')='')              
 AND (ISNULL(EXM.EmployeeCompanyId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyId,''),','))OR ISNULL(@rCompanyId,'')='')              
 AND (ISNULL(EXM.GradeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rGradeId,''),','))OR ISNULL(@rGradeId,'')='')         
 AND (ISNULL(DGM.FunctionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rFunctionId,''),','))OR ISNULL(@rFunctionId,'')='')              
 AND (ISNULL(SM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rStoreLocationId,''),','))OR ISNULL(@rStoreLocationId,'')='')              
 AND (ETM.EmployeeTypeGroupId=@rEmployeeTypeGroupid OR @rEmployeeTypeGroupid=0)              
    end              
                  
 else if (@rFlag=3) -- Location Sub Group wise (Cluster Wise)              
 begin               
 INSERT INTO @tbltmp              
 SELECT LSM.Id ,              
 LSM.Title,              
 EXM.Id,SCT.Id,VTM.Id,DTE.BMI,DTE.BloodPressure,DTE.FBS,DTE.SGPT,DTE.TB,EM.FirstName + ' ' + EM.LastName            
 ,EM.Id ,STM.Id, EM.Code,DTE.DiabeticExisting,DTE.HypertensionExisting , DTE.Triglyceride,DTE.LDL,
 DTE.Cholesterol,DTE.PSA,DTE.SerumCreatinine,DTE.TSH,DTE.VitaminB12,DTE.VitaminD3           
 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 SSM ON SSM.Id = STM.SubTypeId              
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId and EXM.ParticipantSourceTypeId=95              
 INNER JOIN [sHrm].[tEmployeeJobDetail]  AS EJD ON EJD.EmployeeId=EMP.ID              
 INNER JOIN [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId                 
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=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.tOrganizationDepartmentMaster ODM on ODM.Id=EXM.OrganizationDepartmentId              
 INNER JOIN sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id              
 INNER JOIN sExamination.tDiagnosisTrackerEmployee DTE on EXM.Id = DTE.ExaminationId              
 INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id=EXM.StoreLocationId              
 INNER JOIN sCommon.tLocationMaster LM on LM.Id=SLM.LocationId              
 inner join sCommon.tLocationSubGroupMaster LSM on LSM.id=LM.LocationSubGroupId              
 --INNER JOIN sCommon.tStateMaster SM on SM.Id=LM.StateId              
 INNER JOIN sHrm.tEmployeeMaster EM on EM.Id = EXM.ParticipantSourceId              
               
 WHERE EXM.ParticipantSourceTypeId=95 AND DIA.TotalHealthPoints>0 AND VTM.OrgId=@rOrgId              
 AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))              
 AND (ISNULL(SCT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rSectorId,''),','))OR ISNULL(@rSectorId,'')='')              
 AND (ISNULL(VTM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')              
 AND (ISNULL(ECM.CompanyGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyGroupId,''),','))OR ISNULL(@rCompanyGroupId,'')='')              
 AND (ISNULL(EXM.EmployeeCompanyId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyId,''),','))OR ISNULL(@rCompanyId,'')='')              
 AND (ISNULL(EXM.GradeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rGradeId,''),','))OR ISNULL(@rGradeId,'')='')              
 AND (ISNULL(DGM.FunctionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rFunctionId,''),','))OR ISNULL(@rFunctionId,'')='')              
 AND (ISNULL(LSM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rStoreLocationId,''),','))OR ISNULL(@rStoreLocationId,'')='')              
 AND (ETM.EmployeeTypeGroupId=@rEmployeeTypeGroupid OR @rEmployeeTypeGroupid=0)              
    end              
  --  select * from @tbltmp              
               
 if (@rDiseaseId = 5)  -- Overweight              
 begin              
  select 1 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode   from @tbltmp where (t_BMI = 'Overweight')              
 end         
 else if (@rDiseaseId = 6)  -- Obese        
 begin
 select 2 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode   from @tbltmp where (t_BMI = 'Obese')
 end
 else if (@rDiseaseId = 75)  -- Morbidly Obese        
 begin
 select 3 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode   from @tbltmp where (t_BMI = 'Morbidly Obese')
 end            
 else if (@rDiseaseId = 9)  -- Prehypertension              
 begin              
  select 4 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where (t_BloodPressure = 'PreHypertension' AND Isnull(t_HypertensionExisting,'') <> 'Hypertension Existing')  -- CHANGE BY MS  MENTIS ISSUE:0024494 2023-04-07            
 end        
 else if (@rDiseaseId = 10)  -- Hypertension              
 begin              
  select 5 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where (t_BloodPressure in ('Hypertension','High Blood Pressure','Hypertension stage 2','Hypertension Existing') or t_HypertensionExisting='Hypertension Existing')              
 end          
 else if (@rDiseaseId = 11)  -- Prediabetic              
 begin              
  select 6 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where (t_FBS = 'Pre Diabetic'  AND Isnull(t_DiabeticExisting,'') <> 'Diabetic Existing')  -- CHANGE BY MS  MENTIS ISSUE:0024494 2023-04-07           
 end     
 else if (@rDiseaseId = 12)  -- Diabetic              
 begin              
  select 7 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where (t_FBS in ('Diabetic','Diabetic Existing')  or t_DiabeticExisting ='Diabetic Existing')             
 end    
 else if (@rDiseaseId = 35)-- HighSGPT              
 begin              
  select 8 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where t_SGPT = 'Elevated  SGPT'              
 end                
 else if (@rDiseaseId = 30)-- Hypertriglyceridemia        
 begin        
 select 9 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where t_Hypertriglyceridemia = 'Hypertriglyceridemia' 
 end
 else if (@rDiseaseId = 28)-- Hypercholesterolemia        
 begin        
 select 10 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where t_Hypercholesterolemia = 'Hypercholesterolemia'       
 end
 else if (@rDiseaseId = 32)-- Elevated_LDL        
 begin        
 select 11 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where t_Elevated_LDL = 'Elevated  LDL'       
 end
 else if (@rDiseaseId = 36)-- HighSerumCreatinine        
 begin
 select 12 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where t_SerumCreatinine = 'High Serum Creatinine'
 end
 else if (@rDiseaseId = 58)-- HighTSH        
 begin
 select 13 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where t_TSH = 'Elevated TSH'
 end
 else if (@rDiseaseId = 59)-- HighPSA        
 begin        
 select 14 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where t_PSA = 'High PSA'
 end
 else if (@rDiseaseId = 67)-- LowTSH        
 begin        
 select 15 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where t_TSH = 'Low TSH'
 end
 else if (@rDiseaseId = 69)-- VitaminB12deficiency        
 begin        
 select 16 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where t_VitaminB12 = 'Vitamin B12 deficiency'
 end
 else if (@rDiseaseId = 70)-- VitaminD3deficiency        
 begin        
 select 17 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where t_VitaminD3 = 'Vitamin D3 deficiency'
 end
 else if (@rDiseaseId = 76)-- VitaminD3ToxicityRisk        
 begin        
 select 18 as Id,t_EmployeeName as EmployeeName,'#FFFFFF' as ColorCode,t_EmployeeId as EmployeeId,        
  T_SetupId as SetupId,t_EmployeeCode as EmployeeCode from @tbltmp where t_VitaminD3 = 'Vitamin D3 Toxicity Risk'
 end
 
end
GO
PRINT N'Altering Procedure [sExamination].[pMobImproveDeteriorateCountGet]...';


GO

ALTER proc [sExamination].[pMobImproveDeteriorateCountGet]
@rSectorId nvarchar(max)= '',    
@rVerticalId nvarchar(max)= '',  
@rStateId nvarchar(max) = '',   
@rSetup1Id int,  
@rSetup2Id int,  
@rFlag int = 0,   -- Flag 0 for up down count, 1 for up employee list, 2 for down employee list
@rIsCurrent int = 1
as
begin  
 declare @tbl1Setup table
 (
  tid int identity(1,1),t_ParticipantSourceId bigint,t_HealthIndex decimal(12,2),t_ParticipantName varchar(300)  
 )
 insert into @tbl1Setup  
 select E.ParticipantSourceId,D.HealthIndex,EM.FirstName + ' ' + EM.LastName  
 from sExamination.tExamination E
 inner join shrm.temployeejobdetail ejd on ejd.employeeid=E.participantSourceid    
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=0 then E.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 [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId    
 INNER join sCommon.tOrganizationDepartmentMaster ODM on ODM.Id=(case when @rIsCurrent=0 then E.OrganizationDepartmentId else EJD.OrganizationDepartmentId end)   
 INNER join sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id    
 inner join sCommon.tFunctionMaster FM on FM.id=FunctionId    
 INNER join sCommon.tLocationMaster LM on Ejd.EmployeeLocationId=LM.Id  
 inner join sCommon.tStateMaster tSM on tSM.Id=LM.StateId   
 inner join sExamination.tDiagnosis D on E.Id = D.SourceId  
 inner join sHrm.tEmployeeMaster EM on EM.Id = E.ParticipantSourceId 
  
 where E.SetupId = @rSetup1Id and E.ParticipantSourceTypeId = 95
 AND (ISNULL(SCT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rSectorId,''),','))OR ISNULL(@rSectorId,'')='')    
 AND (ISNULL(VTM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')       
 AND (ISNULL(tSM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rStateId,''),','))OR ISNULL(@rStateId,'')='')    
 and D.HealthIndex > 0  
   
 declare @tbl2Setup table  
 (  
  tid int identity(1,1),t_ParticipantSourceId bigint,t_HealthIndex decimal(12,2)  
 )  
 insert into @tbl2Setup  
 select E.ParticipantSourceId,D.HealthIndex 
 from sExamination.tExamination E  
 inner join shrm.temployeejobdetail ejd on ejd.employeeid=E.participantSourceid    
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=0 then E.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 [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId    
 INNER join sCommon.tOrganizationDepartmentMaster ODM on ODM.Id=(case when @rIsCurrent=0 then E.OrganizationDepartmentId else EJD.OrganizationDepartmentId end)
 INNER join sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id    
 inner join sCommon.tFunctionMaster FM on FM.id=FunctionId    
 INNER join sCommon.tLocationMaster LM on Ejd.EmployeeLocationId=LM.Id  
 inner join sCommon.tStateMaster tSM on tSM.Id=LM.StateId   
 inner join sExamination.tDiagnosis D on E.Id = D.SourceId  
 inner join sHrm.tEmployeeMaster EM on EM.Id = E.ParticipantSourceId  
 where E.SetupId = @rSetup2Id and E.ParticipantSourceTypeId = 95    
 and D.HealthIndex > 0  
   
 declare @lImporoved int,@lDeteriorate int  
   
 select @lImporoved = count(1) from @tbl2Setup t2,@tbl1Setup t1 where t2.t_ParticipantSourceId = t1.t_ParticipantSourceId  
 and t2.t_HealthIndex > t1.t_HealthIndex  
   
 select @lDeteriorate = count(1) from @tbl2Setup t2,@tbl1Setup t1 where t2.t_ParticipantSourceId = t1.t_ParticipantSourceId  
 and t2.t_HealthIndex < t1.t_HealthIndex  
   
 if @rFlag = 0  
 begin  
  select @lImporoved as UP,@lDeteriorate as Down  
 end  
   
 if @rFlag = 1  
 begin   
  select t1.t_ParticipantSourceId as EmployeeId,t1.t_ParticipantName as EmployeeName,t1.t_HealthIndex as Setup1,t2.t_HealthIndex as Setup2  
  from @tbl2Setup t2,@tbl1Setup t1 where t2.t_ParticipantSourceId = t1.t_ParticipantSourceId  
  and t2.t_HealthIndex > t1.t_HealthIndex  
 end  
 else if @rFlag = 2  
 begin  
  select t1.t_ParticipantSourceId as EmployeeId,t1.t_ParticipantName as EmployeeName,t1.t_HealthIndex as Setup1,t2.t_HealthIndex as Setup2  
  from @tbl2Setup t2,@tbl1Setup t1 where t2.t_ParticipantSourceId = t1.t_ParticipantSourceId  
  and t2.t_HealthIndex < t1.t_HealthIndex  
 end
end
GO
PRINT N'Altering Procedure [sExamination].[pMobLocationWiseDiagnosisCountGet]...';


GO
         
ALTER proc [sExamination].[pMobLocationWiseDiagnosisCountGet]          
@rOrgId INT,          
@rSetupGroupId INT,          
@rSectorId nvarchar(max)= '',          
@rVerticalId nvarchar(max)= '',          
@rCompanyGroupId nvarchar(max)= '',          
@rCompanyId nvarchar(max)= '',          
@rGradeId nvarchar(max)= '',          
@rFunctionId nvarchar(max)= '',          
@rStoreLocationId nvarchar(max)= '',          
@rFlag int=1,          
@rDiseaseId int=0,          
@rEmployeeTypeGroupid int=0,          
@rIsCurrent int          
as          
begin          
set @riscurrent = 0;           
 declare @tbltmp table          
 (          
  tid int identity(1,1),t_OrgId bigint,t_OrganizationName varchar(200),t_ExaminationId bigint,t_SectorId int,          
  t_VerticalId int,t_BMI varchar(200),t_BloodPressure varchar(200),t_FBS varchar(200),t_SGPT varchar(200),
  t_TB varchar(200),t_DiabeticExisting  varchar(200),t_HypertensionExisting  varchar(200),
  t_Hypertriglyceridemia  varchar(200),t_Elevated_LDL  varchar(200),t_Hypercholesterolemia varchar(200), 
  t_PSA varchar(200), t_SerumCreatinine varchar(200), t_TSH varchar(200),t_VitaminB12 varchar(200),t_VitaminD3 varchar(200)  
 )          
 if (@rFlag=1 or @rFlag=4 ) -- Location wise          
 begin          
 INSERT INTO @tbltmp          
 SELECT SLM.Id,          
 SLM.Title,          
 EXM.Id,SCT.Id,VTM.Id,DTE.BMI,DTE.BloodPressure,DTE.FBS,DTE.SGPT,DTE.TB,DTE.DiabeticExisting,DTE.HypertensionExisting, DTE.Triglyceride,DTE.LDL,
 DTE.Cholesterol,DTE.PSA,DTE.SerumCreatinine,DTE.TSH,DTE.VitaminB12,DTE.VitaminD3        
 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 SSM ON SSM.Id = STM.SubTypeId          
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId and EXM.ParticipantSourceTypeId=95          
 INNER JOIN [sHrm].[tEmployeeJobDetail]  AS EJD ON EJD.EmployeeId=EMP.ID          
 INNER JOIN [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId            
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=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.tOrganizationDepartmentMaster ODM on ODM.Id=(case when @rIsCurrent=0 then EXM.OrganizationDepartmentId else EJD.OrganizationDepartmentId end )          
 INNER JOIN sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id          
 INNER JOIN sExamination.tDiagnosisTrackerEmployee DTE on EXM.Id = DTE.ExaminationId          
 INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id=EXM.StoreLocationId          
 INNER JOIN sCommon.tLocationMaster LM on LM.Id=SLM.LocationId          
 --INNER JOIN sCommon.tStateMaster SM on SM.Id=LM.StateId          
           
 WHERE EXM.ParticipantSourceTypeId=95       
 --AND DIA.TotalHealthPoints>0       
 AND VTM.OrgId=@rOrgId          
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))          
  AND (ISNULL(SCT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rSectorId,''),','))OR ISNULL(@rSectorId,'')='')          
  AND (ISNULL(VTM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
  AND (ISNULL(ECM.CompanyGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyGroupId,''),','))OR ISNULL(@rCompanyGroupId,'')='')          
  AND (ISNULL(EXM.EmployeeCompanyId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyId,''),','))OR ISNULL(@rCompanyId,'')='')          
  AND (ISNULL(EXM.GradeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rGradeId,''),','))OR ISNULL(@rGradeId,'')='')          
  AND (ISNULL(DGM.FunctionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rFunctionId,''),','))OR ISNULL(@rFunctionId,'')='')          
  AND (ISNULL(EXM.StoreLocationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rStoreLocationId,''),','))OR ISNULL(@rStoreLocationId,'')='')       
  AND (ETM.EmployeeTypeGroupId=@rEmployeeTypeGroupid OR @rEmployeeTypeGroupid=0)          
  end          
          
 else if(@rFlag=2) -- State wise          
 begin          
           
 INSERT INTO @tbltmp          
 SELECT SM.Id,          
 SM.Title,          
 EXM.Id,SCT.Id,VTM.Id,DTE.BMI,DTE.BloodPressure,DTE.FBS,DTE.SGPT,DTE.TB,DTE.DiabeticExisting,DTE.HypertensionExisting, DTE.Triglyceride,DTE.LDL,
 DTE.Cholesterol,DTE.PSA,DTE.SerumCreatinine,DTE.TSH,DTE.VitaminB12,DTE.VitaminD3           
 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 SSM ON SSM.Id = STM.SubTypeId            
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId and EXM.ParticipantSourceTypeId=95          
 INNER JOIN [sHrm].[tEmployeeJobDetail]  AS EJD ON EJD.EmployeeId=EMP.ID          
 INNER JOIN [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId           
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=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.tOrganizationDepartmentMaster ODM on ODM.Id=(case when @rIsCurrent=0 then EXM.OrganizationDepartmentId else EJD.OrganizationDepartmentId end )               
 INNER JOIN sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id          
 INNER JOIN sExamination.tDiagnosisTrackerEmployee DTE on EXM.Id = DTE.ExaminationId          
 INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id=EXM.StoreLocationId          
 INNER JOIN sCommon.tLocationMaster LM on LM.Id=SLM.LocationId          
 INNER JOIN sCommon.tStateMaster SM on SM.Id=LM.StateId          
           
 WHERE EXM.ParticipantSourceTypeId=95     
 --AND DIA.TotalHealthPoints>0     
 AND VTM.OrgId=@rOrgId          
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))          
  AND (ISNULL(SCT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rSectorId,''),','))OR ISNULL(@rSectorId,'')='')          
  AND (ISNULL(VTM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
  AND (ISNULL(ECM.CompanyGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyGroupId,''),','))OR ISNULL(@rCompanyGroupId,'')='')          
  AND (ISNULL(EXM.EmployeeCompanyId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyId,''),','))OR ISNULL(@rCompanyId,'')='')          
  AND (ISNULL(EXM.GradeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rGradeId,''),','))OR ISNULL(@rGradeId,'')='')          
  AND (ISNULL(DGM.FunctionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rFunctionId,''),','))OR ISNULL(@rFunctionId,'')='')          
  AND (ISNULL(EXM.StoreLocationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rStoreLocationId,''),','))OR ISNULL(@rStoreLocationId,'')='')          
  AND (ETM.EmployeeTypeGroupId=@rEmployeeTypeGroupid OR @rEmployeeTypeGroupid=0)          
 end          
          
 else if (@rFlag=3) -- Location Sub Group wise (Cluster Wise)          
 begin          
 INSERT INTO @tbltmp          
 SELECT LSM.Id,          
 LSM.Title,          
 EXM.Id,SCT.Id,VTM.Id,DTE.BMI,DTE.BloodPressure,DTE.FBS,DTE.SGPT,DTE.TB,DTE.DiabeticExisting,DTE.HypertensionExisting, DTE.Triglyceride,DTE.LDL,
 DTE.Cholesterol,DTE.PSA,DTE.SerumCreatinine,DTE.TSH,DTE.VitaminB12,DTE.VitaminD3          
 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 SSM ON SSM.Id = STM.SubTypeId          
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId and EXM.ParticipantSourceTypeId=95          
 INNER JOIN [sHrm].[tEmployeeJobDetail]  AS EJD ON EJD.EmployeeId=EMP.ID          
 INNER JOIN [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId            
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=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.tOrganizationDepartmentMaster ODM on ODM.Id=(case when @rIsCurrent=0 then EXM.OrganizationDepartmentId else EJD.OrganizationDepartmentId end )                 
 INNER JOIN sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id          
 INNER JOIN sExamination.tDiagnosisTrackerEmployee DTE on EXM.Id = DTE.ExaminationId          
 INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id=EXM.StoreLocationId          
 INNER JOIN sCommon.tLocationMaster LM on LM.Id=SLM.LocationId          
 inner join sCommon.tLocationSubGroupMaster LSM on LSM.id=LM.LocationSubGroupId          
 --INNER JOIN sCommon.tStateMaster SM on SM.Id=LM.StateId          
           
 WHERE EXM.ParticipantSourceTypeId=95     
 --AND DIA.TotalHealthPoints>0     
 AND VTM.OrgId=@rOrgId          
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))          
  AND (ISNULL(SCT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rSectorId,''),','))OR ISNULL(@rSectorId,'')='')          
  AND (ISNULL(VTM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
  AND (ISNULL(ECM.CompanyGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyGroupId,''),','))OR ISNULL(@rCompanyGroupId,'')='')          
  AND (ISNULL(EXM.EmployeeCompanyId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyId,''),','))OR ISNULL(@rCompanyId,'')='')          
  AND (ISNULL(EXM.GradeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rGradeId,''),','))OR ISNULL(@rGradeId,'')='')          
  AND (ISNULL(DGM.FunctionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rFunctionId,''),','))OR ISNULL(@rFunctionId,'')='')          
  AND (ISNULL(EXM.StoreLocationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rStoreLocationId,''),','))OR ISNULL(@rStoreLocationId,'')='')          
  AND (ETM.EmployeeTypeGroupId=@rEmployeeTypeGroupid OR @rEmployeeTypeGroupid=0)          
  end           
          
  declare @tempTable table          
 (          
  tId int IDENTITY(1,1),[OverWeight] smallint,[Obese] smallint,[Morbidly Obese] smallint,[PreHypertension] smallint,[Hypertension] smallint,          
  [Pre Diabetic] smallint,[Diabetic] smallint,[High SGPT] smallint,Hypertriglyceridemia  smallint,[Elevated  LDL]  smallint,Hypercholesterolemia smallint,
  HighSerumCreatinine smallint,HighTSH smallint,HighPSA smallint,LowTSH smallint,VitaminB12deficiency smallint,
  VitaminD3deficiency smallint, VitaminD3ToxicityRisk smallint,
  OrgId bigint,OrgName varchar(300),SectorId int,VerticalId int          
 )          
 INSERT INTO @tempTable          
 SELECT          
 (          
  SELECT COUNT(0)          
  FROM @tbltmp WHERE (t_BMI = 'Overweight')          
  and t_OrgId = EXM.t_OrgId          
 ),
 (      
  SELECT COUNT(0)      
  FROM @tbltmp WHERE (t_BMI = 'Obese')      
  and t_OrgId = EXM.t_OrgId      
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE (t_BMI = 'Morbidly Obese')        
  and t_OrgId = EXM.t_OrgId
 ),
 (          
  SELECT COUNT(0)          
  FROM @tbltmp WHERE (t_BloodPressure = 'PreHypertension' AND ISNULL(t_HypertensionExisting,'') <> 'Hypertension Existing') -- CHANGE BY MS  MENTIS ISSUE:0024494 2023-04-07        
  and t_OrgId = EXM.t_OrgId          
 ),          
 (          
  SELECT COUNT(0)          
  FROM @tbltmp WHERE (t_BloodPressure in ('Hypertension','High Blood Pressure','Hypertension stage 2','Hypertension Existing') or t_HypertensionExisting='Hypertension Existing')           
  and t_OrgId = EXM.t_OrgId          
 ),          
 (          
  SELECT COUNT(0)          
  FROM @tbltmp WHERE (t_FBS = 'Pre Diabetic' AND ISNULL(t_DiabeticExisting,'') <> 'Diabetic Existing')  -- CHANGE BY MS  MENTIS ISSUE:0024494 2023-04-07       
  and t_OrgId = EXM.t_OrgId    
 ),          
 (          
  SELECT COUNT(0)          
  FROM @tbltmp WHERE (t_FBS in ('Diabetic','Diabetic Existing')  or t_DiabeticExisting ='Diabetic Existing')          
  and t_OrgId = EXM.t_OrgId          
 ),          
 (          
  SELECT COUNT(0)          
  FROM @tbltmp WHERE t_SGPT = 'Elevated  SGPT'          
  and t_OrgId = EXM.t_OrgId          
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_Hypertriglyceridemia = 'Hypertriglyceridemia'        
  and t_OrgId = EXM.t_OrgId        
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_Elevated_LDL = 'Elevated  LDL'        
  and t_OrgId = EXM.t_OrgId        
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_Hypercholesterolemia = 'Hypercholesterolemia'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_SerumCreatinine = 'High Serum Creatinine'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_TSH = 'Elevated TSH'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_PSA = 'High PSA'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_TSH = 'Low TSH'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_VitaminB12 = 'Vitamin B12 deficiency'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_VitaminD3 = 'Vitamin D3 deficiency'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_VitaminD3 = 'Vitamin D3 Toxicity Risk'        
  and t_OrgId = EXM.t_OrgId        
 ),
 EXM.t_OrgId,EXM.t_OrganizationName,t_SectorId,t_VerticalId          
 FROM @tbltmp EXM           
 group by t_SectorId,t_VerticalId,t_OrgId,t_OrganizationName          
 ORDER BY 1          
           
 --select OrgId as StoreLocationId,OrgName as StoreLocationName,SectorId,VerticalId,[OverWeight] as Overweight,[PreHypertension] as Prehypertension,          
 --[Hypertension] as Hypertension,[Pre Diabetic] as Prediabetic,[Diabetic] as Diabetic,[High SGPT] as HighSGPT from @tempTable          
 if (@rFlag=4) -- Cluster Location wise          
 begin          
 if (@rDiseaseId = 5)  -- Overweight          
 begin          
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[OverWeight] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014          
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[OverWeight] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,SUM(t.[OverWeight]) as DiseaseCount,Max(isnull(e.EntityColor,'#000000')) as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[OverWeight] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )          
 --Group By e.EntityColor          
 order by MVL.OrderIndex          
 end
 else if (@rDiseaseId = 6)  -- Obese        
 begin
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Obese] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014          
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[Obese] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,SUM(t.[Obese]) as DiseaseCount,Max(isnull(e.EntityColor,'#000000')) as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[Obese] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )          
 order by MVL.OrderIndex
 end

 else if (@rDiseaseId = 75)  -- Morbidly Obese        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Morbidly Obese] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014          
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[Morbidly Obese] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,SUM(t.[Morbidly Obese]) as DiseaseCount,Max(isnull(e.EntityColor,'#000000')) as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[Morbidly Obese] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )          
 order by MVL.OrderIndex
 end
           
 else if (@rDiseaseId = 9)  -- Prehypertension          
 begin          
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[PreHypertension] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[PreHypertension] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,SUM(t.[PreHypertension]) as DiseaseCount,Max(isnull(e.EntityColor,'#000000')) as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[PreHypertension] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )          
 --Group By e.EntityColor          
 order by MVL.OrderIndex          
 end          
           
 else if (@rDiseaseId = 10)  -- Hypertension          
 begin          
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Hypertension] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014          
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[Hypertension] > 0           
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,SUM(t.[Hypertension]) as DiseaseCount,Max(isnull(e.EntityColor,'#000000')) as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[Hypertension] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )          
 --Group By e.EntityColor          
 order by MVL.OrderIndex          
 end          
           
 else if (@rDiseaseId = 11)  -- Prediabetic          
 begin          
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Pre Diabetic] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[Pre Diabetic] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,SUM(t.[Pre Diabetic]) as DiseaseCount,Max(isnull(e.EntityColor,'#000000')) as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[Pre Diabetic] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )          
 --Group By e.EntityColor          
 order by MVL.OrderIndex          
 end          
           
 else if (@rDiseaseId = 12)  -- Diabetic          
 begin          
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Diabetic] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[Diabetic] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,SUM(t.[Diabetic]) as DiseaseCount,Max(isnull(e.EntityColor,'#000000')) as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[Diabetic] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )          
 --Group By e.EntityColor          
 order by MVL.OrderIndex          
 end          
           
 else if (@rDiseaseId = 35)-- HighSGPT          
 begin          
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[High SGPT] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable as  t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[High SGPT] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,ISNULL(SUM(t.[High SGPT]),0) as DiseaseCount,isnull(Max(e.EntityColor),'#000000') as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[High SGPT] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )          
 --Group By e.EntityColor          
 order by MVL.OrderIndex          
 end
 else if (@rDiseaseId = 30)-- Hypertriglyceridemia        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Hypertriglyceridemia] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable as  t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[Hypertriglyceridemia] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,ISNULL(SUM(t.[Hypertriglyceridemia]),0) as DiseaseCount,isnull(Max(e.EntityColor),'#000000') as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[Hypertriglyceridemia] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )         
 order by MVL.OrderIndex
 end 
 else if (@rDiseaseId = 28)-- Hypercholesterolemia        
 begin        
 --select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[Hypercholesterolemia] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 --from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[Hypercholesterolemia] > 0
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Hypercholesterolemia] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable as  t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[Hypercholesterolemia] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,ISNULL(SUM(t.[Hypercholesterolemia]),0) as DiseaseCount,isnull(Max(e.EntityColor),'#000000') as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[Hypercholesterolemia] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )         
 order by MVL.OrderIndex
 end
 else if (@rDiseaseId = 32)-- Elevated_LDL        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Elevated  LDL] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable as  t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[Elevated  LDL] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,ISNULL(SUM(t.[Elevated  LDL]),0) as DiseaseCount,isnull(Max(e.EntityColor),'#000000') as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[Elevated  LDL] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )         
 order by MVL.OrderIndex
 end
 else if (@rDiseaseId = 36)-- HighSerumCreatinine 
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[HighSerumCreatinine] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable as  t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[HighSerumCreatinine] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,ISNULL(SUM(t.[HighSerumCreatinine]),0) as DiseaseCount,isnull(Max(e.EntityColor),'#000000') as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[HighSerumCreatinine] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )         
 order by MVL.OrderIndex
 end
 else if (@rDiseaseId = 58)-- HighTSH        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[HighTSH] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable as  t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[HighTSH] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,ISNULL(SUM(t.[HighTSH]),0) as DiseaseCount,isnull(Max(e.EntityColor),'#000000') as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[HighTSH] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )         
 order by MVL.OrderIndex
 end
 else if (@rDiseaseId = 59)-- HighPSA        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[HighPSA] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable as  t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[HighPSA] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,ISNULL(SUM(t.[HighPSA]),0) as DiseaseCount,isnull(Max(e.EntityColor),'#000000') as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[HighPSA] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )         
 order by MVL.OrderIndex
 end
 else if (@rDiseaseId = 67)-- LowTSH        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[LowTSH] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable as  t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[LowTSH] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,ISNULL(SUM(t.[LowTSH]),0) as DiseaseCount,isnull(Max(e.EntityColor),'#000000') as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[LowTSH] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )         
 order by MVL.OrderIndex
 end
 else if (@rDiseaseId = 69)-- VitaminB12deficiency        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[VitaminB12deficiency] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable as  t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[VitaminB12deficiency] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,ISNULL(SUM(t.[VitaminB12deficiency]),0) as DiseaseCount,isnull(Max(e.EntityColor),'#000000') as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[VitaminB12deficiency] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )         
 order by MVL.OrderIndex
 end
 else if (@rDiseaseId = 70)-- VitaminD3deficiency        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[VitaminD3deficiency] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable as  t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[VitaminD3deficiency] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,ISNULL(SUM(t.[VitaminD3deficiency]),0) as DiseaseCount,isnull(Max(e.EntityColor),'#000000') as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[VitaminD3deficiency] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )         
 order by MVL.OrderIndex
 end
 else if (@rDiseaseId = 76)-- VitaminD3ToxicityRisk        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[VitaminD3ToxicityRisk] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode,MVL.OrderIndex          
 from @tempTable as  t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 inner join  sIp.tStoreLocationMaster LM on LM.Id=t.OrgId          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On MVl.verticalId=t.VerticalId and Mvl.locationid=LM.LocationId           
 where t.[VitaminD3ToxicityRisk] > 0          
 union all          
 select 0 as StoreLocationId,'Other' as StoreLocationName,0 as SectorId,0 as VerticalId,ISNULL(SUM(t.[VitaminD3ToxicityRisk]),0) as DiseaseCount,isnull(Max(e.EntityColor),'#000000') as ColorCode,'100' as OrderIndex          
 from @tempTable t           
 left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 1014           
 where t.[VitaminD3ToxicityRisk] > 0 and t.OrgId not in           
 (Select SLM.id           
 from sIp.tStoreLocationMaster SLM          
 inner join [SCommon].[tMobVerticalLocationLink] MVL On  Mvl.locationid=SLM.LocationId          
 where (ISNULL(MVL.VerticalId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')          
 )         
 order by MVL.OrderIndex
 end
 end          
          
 else          
 begin          
 if (@rDiseaseId = 5)  -- Overweight          
 begin       select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[OverWeight] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end          
 where t.[OverWeight] > 0          
 order by t.OrgName          
 end          
 else if (@rDiseaseId = 6)  -- Obese        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Obese] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end          
 where t.[Obese] > 0          
 order by t.OrgName
 end
 else if (@rDiseaseId = 75)  -- Morbidly Obese        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Morbidly Obese] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end          
 where t.[Morbidly Obese] > 0          
 order by t.OrgName
 end       
 else if (@rDiseaseId = 9)  -- Prehypertension          
 begin          
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[PreHypertension] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end          
 where t.[PreHypertension] > 0          
 order by t.OrgName          
 end 
 else if (@rDiseaseId = 10)  -- Hypertension          
 begin          
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Hypertension] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end          
 where t.[Hypertension] > 0           
 order by t.OrgName
 end
 else if (@rDiseaseId = 11)  -- Prediabetic          
 begin          
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Pre Diabetic] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.[Pre Diabetic] > 0          
 order by t.OrgName          
 end      
 else if (@rDiseaseId = 12)  -- Diabetic          
 begin          
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Diabetic] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.[Diabetic] > 0          
 order by t.OrgName          
 end
 else if (@rDiseaseId = 35)-- HighSGPT          
 begin          
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[High SGPT] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.[High SGPT] > 0          
 order by t.OrgName          
 end
 else if (@rDiseaseId = 30)-- Hypertriglyceridemia        
 begin        
  select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Hypertriglyceridemia] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.[Hypertriglyceridemia] > 0          
 order by t.OrgName      
 end
 else if (@rDiseaseId = 28)-- Hypercholesterolemia        
 begin        
   select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.Hypercholesterolemia as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.Hypercholesterolemia > 0          
 order by t.OrgName        
 end
 else if (@rDiseaseId = 32)-- Elevated_LDL        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[Elevated  LDL] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.[Elevated  LDL] > 0          
 order by t.OrgName        
 end
 else if (@rDiseaseId = 36)-- HighSerumCreatinine        
 begin
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[HighSerumCreatinine] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.[HighSerumCreatinine] > 0          
 order by t.OrgName
 end
 else if (@rDiseaseId = 58)-- HighTSH        
 begin
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[HighTSH] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.[HighTSH] > 0          
 order by t.OrgName
 end
 else if (@rDiseaseId = 59)-- HighPSA        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[HighPSA] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.[HighPSA] > 0          
 order by t.OrgName
 end
 else if (@rDiseaseId = 67)-- LowTSH        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[LowTSH] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.[LowTSH] > 0          
 order by t.OrgName
 end
 else if (@rDiseaseId = 69)-- VitaminB12deficiency        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[VitaminB12deficiency] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.[VitaminB12deficiency] > 0          
 order by t.OrgName
 end
 else if (@rDiseaseId = 70)-- VitaminD3deficiency        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[VitaminD3deficiency] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.[VitaminD3deficiency] > 0          
 order by t.OrgName
 end
 else if (@rDiseaseId = 76)-- VitaminD3ToxicityRisk        
 begin        
 select t.OrgId as StoreLocationId,t.OrgName as StoreLocationName,t.SectorId,t.VerticalId,t.[VitaminD3ToxicityRisk] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode          
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = case when @rFlag=3 then 2020 when @rFlag=2 then 2021 else 1014 end           
 where t.[VitaminD3ToxicityRisk] > 0          
 order by t.OrgName
 end
          
 end          
end
GO
PRINT N'Altering Procedure [sExamination].[pMobSectorWiseDiagnosisCountGet]...';


GO

ALTER proc [sExamination].[pMobSectorWiseDiagnosisCountGet]        
@rOrgId INT,        
@rSetupGroupId INT,        
@rSectorId nvarchar(max)= '',        
@rVerticalId nvarchar(max)= '',        
@rCompanyGroupId nvarchar(max)= '',        
@rCompanyId nvarchar(max)= '',        
@rGradeId nvarchar(max)= '',        
@rFunctionId nvarchar(max)= '',        
@rStoreLocationId nvarchar(max)= '',        
@rDiseaseId int=0,        
@rEmployeeTypeGroupid int=0,        
@rIsCurrent int        
as        
begin    
set @rIsCurrent = 0        
 declare @tbltmp table        
 (        
  tid int identity(1,1),t_OrgId bigint,t_OrganizationName varchar(200),t_ExaminationId bigint,t_BMI varchar(200),        
  t_BloodPressure varchar(200),t_FBS varchar(200),t_SGPT varchar(200),t_TB varchar(200),
  t_DiabeticExisting  varchar(200),t_HypertensionExisting  varchar(200),t_Hypertriglyceridemia  varchar(200),
  t_Elevated_LDL  varchar(200),t_Hypercholesterolemia varchar(200), t_PSA varchar(200), t_SerumCreatinine varchar(200),
  t_TSH varchar(200),t_VitaminB12 varchar(200),t_VitaminD3 varchar(200)       
 )        
 insert into @tbltmp        
 SELECT SCT.Id,SCT.Title,EXM.Id,DTE.BMI,DTE.BloodPressure,DTE.FBS,DTE.SGPT,DTE.TB,DTE.DiabeticExisting,
 DTE.HypertensionExisting, DTE.Triglyceride,DTE.LDL ,DTE.Cholesterol,DTE.PSA,DTE.SerumCreatinine,DTE.TSH,
 DTE.VitaminB12,DTE.VitaminD3      
 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 SSM ON SSM.Id = STM.SubTypeId        
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId and EXM.ParticipantSourceTypeId=95        
 INNER JOIN [sHrm].[tEmployeeJobDetail]  AS EJD ON EJD.EmployeeId=EMP.ID        
 INNER JOIN [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId            
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=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.tOrganizationDepartmentMaster ODM on ODM.Id =(case when @rIsCurrent=0 then EXM.OrganizationDepartmentId else EJD.OrganizationDepartmentId end )       
 INNER JOIN sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id        
 INNER JOIN sExamination.tDiagnosisTrackerEmployee DTE on EXM.Id = DTE.ExaminationId        
         
 WHERE EXM.ParticipantSourceTypeId=95 AND SCT.OrgId=@rOrgId        
 --DIA.TotalHealthPoints>0 AND       
 AND (STM.SetupGroupId=@rSetupGroupId OR @rSetupGroupId=0)         
 AND (ISNULL(SCT.Id,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rSectorId,''),','))OR ISNULL(@rSectorId,'')='')        
 AND (ISNULL(VTM.Id,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')        
 AND (ISNULL(ECM.CompanyGroupId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rCompanyGroupId,''),','))OR ISNULL(@rCompanyGroupId,'')='')        
 AND (ISNULL(EXM.EmployeeCompanyId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rCompanyId,''),','))OR ISNULL(@rCompanyId,'')='')        
 AND (ISNULL(EXM.GradeId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rGradeId,''),','))OR ISNULL(@rGradeId,'')='')        
 AND (ISNULL(DGM.FunctionId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rFunctionId,''),','))OR ISNULL(@rFunctionId,'')='')        
 AND (ISNULL(EXM.StoreLocationId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(ISNULL(@rStoreLocationId,''),','))OR ISNULL(@rStoreLocationId,'')='')        
 AND (ETM.EmployeeTypeGroupId=@rEmployeeTypeGroupid OR @rEmployeeTypeGroupid=0)        
 declare @tempTable table        
 (        
  tId int IDENTITY(1,1),[OverWeight] smallint,[Obese] smallint,[Morbidly Obese] smallint,
  [PreHypertension] smallint,[Hypertension] smallint,[Pre Diabetic] smallint,[Diabetic] smallint,
  [High SGPT] smallint,Hypertriglyceridemia  smallint,Elevated_LDL  smallint,Hypercholesterolemia smallint,
  HighSerumCreatinine smallint,HighTSH smallint,HighPSA smallint,LowTSH smallint,VitaminB12deficiency smallint,
  VitaminD3deficiency smallint, VitaminD3ToxicityRisk smallint,
  OrgId bigint,OrgName varchar(300)        
 )        
 INSERT INTO @tempTable        
 SELECT        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE (t_BMI = 'Overweight')        
  and t_OrgId = EXM.t_OrgId        
 ),      
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE (t_BMI = 'Obese')        
  and t_OrgId = EXM.t_OrgId        
 ),      
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE (t_BMI = 'Morbidly Obese')        
  and t_OrgId = EXM.t_OrgId
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE (t_BloodPressure = 'PreHypertension' AND Isnull(t_HypertensionExisting,'') <> 'Hypertension Existing') -- CHANGE BY MS  MENTIS ISSUE:0024494 2023-04-07      
  and t_OrgId = EXM.t_OrgId        
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE (t_BloodPressure in ('Hypertension','High Blood Pressure','Hypertension stage 2','Hypertension Existing') or t_HypertensionExisting='Hypertension Existing')        
  and t_OrgId = EXM.t_OrgId        
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE (t_FBS = 'Pre Diabetic' AND Isnull(t_DiabeticExisting,'') <> 'Diabetic Existing') -- CHANGE BY MS  MENTIS ISSUE:0024494 2023-04-07      
  and t_OrgId = EXM.t_OrgId        
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE (t_FBS in ('Diabetic','Diabetic Existing')  or t_DiabeticExisting ='Diabetic Existing')        
  and t_OrgId = EXM.t_OrgId        
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_SGPT = 'Elevated  SGPT'        
  and t_OrgId = EXM.t_OrgId        
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_Hypertriglyceridemia = 'Hypertriglyceridemia'        
  and t_OrgId = EXM.t_OrgId        
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_Elevated_LDL = 'Elevated  LDL'        
  and t_OrgId = EXM.t_OrgId        
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_Hypercholesterolemia = 'Hypercholesterolemia'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_SerumCreatinine = 'High Serum Creatinine'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_TSH = 'Elevated TSH'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_PSA = 'High PSA'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_TSH = 'Low TSH'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_VitaminB12 = 'Vitamin B12 deficiency'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_VitaminD3 = 'Vitamin D3 deficiency'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_VitaminD3 = 'Vitamin D3 Toxicity Risk'        
  and t_OrgId = EXM.t_OrgId        
 ),
 EXM.t_OrgId,EXM.t_OrganizationName         
 FROM @tbltmp EXM group by t_OrgId,t_OrganizationName        
 ORDER BY 1        
         
 --select OrgId as SectorId,OrgName as SectorName,[OverWeight] as Overweight,[PreHypertension] as Prehypertension,[Hypertension] as Hypertension,        
 --[Pre Diabetic] as Prediabetic,[Diabetic] as Diabetic,[High SGPT] as HighSGPT from @tempTable        
         
 if (@rDiseaseId = 5)  -- Overweight        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[OverWeight] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end        
 else if (@rDiseaseId = 6)  -- Obese        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[Obese] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end
 else if (@rDiseaseId = 75)  -- Morbidly Obese        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[Morbidly Obese] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end
 else if (@rDiseaseId = 9)  -- Prehypertension        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[PreHypertension] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end 
 else if (@rDiseaseId = 10)  -- Hypertension        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[Hypertension] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end        
         
 else if (@rDiseaseId = 11)  -- Prediabetic        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[Pre Diabetic] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end        
         
 else if (@rDiseaseId = 12)  -- Diabetic        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[Diabetic] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end 
 else if (@rDiseaseId = 35)-- HighSGPT        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[High SGPT] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end 
 else if (@rDiseaseId = 30)-- Hypertriglyceridemia        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[Hypertriglyceridemia] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end 
 else if (@rDiseaseId = 28)-- Hypercholesterolemia        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[Hypercholesterolemia] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end
 else if (@rDiseaseId = 32)-- Elevated_LDL        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[Elevated_LDL] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end
 else if (@rDiseaseId = 36)-- HighSerumCreatinine        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[HighSerumCreatinine] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end
 else if (@rDiseaseId = 58)-- HighTSH        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[HighTSH] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end
 else if (@rDiseaseId = 59)-- HighPSA        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[HighPSA] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end
 else if (@rDiseaseId = 67)-- LowTSH        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[LowTSH] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end
 else if (@rDiseaseId = 69)-- VitaminB12deficiency        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[VitaminB12deficiency] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end
 else if (@rDiseaseId = 70)-- VitaminD3deficiency        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[VitaminD3deficiency] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end
 else if (@rDiseaseId = 76)-- VitaminD3ToxicityRisk        
 begin        
 select t.OrgId as SectorId,t.OrgName as SectorName,t.[VitaminD3ToxicityRisk] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2012        
 end
end
GO
PRINT N'Altering Procedure [sExamination].[pMobVerticalWiseDiagnosisCountGet]...';


GO

ALTER proc [sExamination].[pMobVerticalWiseDiagnosisCountGet]      
@rOrgId INT,      
@rSetupGroupId INT,  
@rSectorId nvarchar(max)= '',      
@rVerticalId nvarchar(max)= '',      
@rCompanyGroupId nvarchar(max)= '',      
@rCompanyId nvarchar(max)= '',      
@rGradeId nvarchar(max)= '',      
@rFunctionId nvarchar(max)= '',      
@rStoreLocationId nvarchar(max)= '',      
@rDiseaseId int=0,      
@rEmployeeTypeGroupid int=0,      
@rIsCurrent int      
as      
begin      
set @riscurrent = 0;      
 declare @tbltmp table      
 (      
  tid int identity(1,1),t_OrgId bigint,t_OrganizationName varchar(200),t_ExaminationId bigint,t_SectorId int,      
  t_BMI varchar(200),t_BloodPressure varchar(200),t_FBS varchar(200),t_SGPT varchar(200),t_TB varchar(200),
  t_DiabeticExisting  varchar(200),t_HypertensionExisting  varchar(200),t_Hypertriglyceridemia varchar(200),
  t_Elevated_LDL  varchar(200),t_Hypercholesterolemia varchar(200), t_PSA varchar(200), t_SerumCreatinine varchar(200),
  t_TSH varchar(200),t_VitaminB12 varchar(200),t_VitaminD3 varchar(200)        
 )      
 INSERT INTO @tbltmp      
 SELECT VTM.Id,VTM.Title,EXM.Id,SCT.Id,DTE.BMI,DTE.BloodPressure,DTE.FBS,DTE.SGPT,DTE.TB,DTE.DiabeticExisting,
 DTE.HypertensionExisting, DTE.Triglyceride,DTE.LDL ,DTE.Cholesterol,DTE.PSA,DTE.SerumCreatinine,DTE.TSH,
 DTE.VitaminB12,DTE.VitaminD3    
 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 SSM ON SSM.Id = STM.SubTypeId      
 INNER JOIN [sHrm].[tEmployeeMaster] AS EMP ON EMP.ID= EXM.ParticipantSourceId and EXM.ParticipantSourceTypeId=95      
 INNER JOIN [sHrm].[tEmployeeJobDetail]  AS EJD ON EJD.EmployeeId=EMP.ID      
 INNER JOIN [sHrm].[tEmployeeTypeMaster] AS ETM ON ETM.id=EJD.EmployeeTypeId        
 INNER JOIN [sHrm].[tEmployeeCompanyMaster] AS ECM ON ECM.Id=(case when @rIsCurrent=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.tOrganizationDepartmentMaster ODM on ODM.Id=(case when @rIsCurrent=0 then EXM.OrganizationDepartmentId else EJD.OrganizationDepartmentId end )    
 INNER JOIN sCommon.tDepartmentGroupMaster DGM on ODM.DepartmentGroupId = DGM.Id      
 INNER JOIN sExamination.tDiagnosisTrackerEmployee DTE on EXM.Id = DTE.ExaminationId      
    
 WHERE EXM.ParticipantSourceTypeId=95     
 --AND DIA.TotalHealthPoints>0     
 AND VTM.OrgId=@rOrgId      
  AND ((STM.SetupGroupId=@rSetupGroupId) OR (@rSetupGroupId=0))      
  AND (ISNULL(SCT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rSectorId,''),','))OR ISNULL(@rSectorId,'')='')      
  AND (ISNULL(VTM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rVerticalId,''),','))OR ISNULL(@rVerticalId,'')='')      
  AND (ISNULL(ECM.CompanyGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyGroupId,''),','))OR ISNULL(@rCompanyGroupId,'')='')      
  AND (ISNULL(EXM.EmployeeCompanyId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rCompanyId,''),','))OR ISNULL(@rCompanyId,'')='')      
  AND (ISNULL(EXM.GradeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rGradeId,''),','))OR ISNULL(@rGradeId,'')='')      
  AND (ISNULL(DGM.FunctionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rFunctionId,''),','))OR ISNULL(@rFunctionId,'')='')      
  AND (ISNULL(EXM.StoreLocationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(ISNULL(@rStoreLocationId,''),','))OR ISNULL(@rStoreLocationId,'')='')      
  AND (ETM.EmployeeTypeGroupId=@rEmployeeTypeGroupid OR @rEmployeeTypeGroupid=0)      
  declare @tempTable table      
 (      
  tId int IDENTITY(1,1),[OverWeight] smallint,[Obese] smallint,[Morbidly Obese] smallint,
  [PreHypertension] smallint,[Hypertension] smallint,[Pre Diabetic] smallint,[Diabetic] smallint,
  [High SGPT] smallint,Hypertriglyceridemia  smallint,Elevated_LDL  smallint,Hypercholesterolemia smallint,
  HighSerumCreatinine smallint,HighTSH smallint,HighPSA smallint,LowTSH smallint,VitaminB12deficiency smallint,
  VitaminD3deficiency smallint, VitaminD3ToxicityRisk smallint,
  OrgId bigint,OrgName varchar(300),SectorId int    
 )      
 INSERT INTO @tempTable      
 SELECT      
 (      
  SELECT COUNT(0)      
  FROM @tbltmp WHERE (t_BMI = 'Overweight')      
  and t_OrgId = EXM.t_OrgId      
 ),
 (      
  SELECT COUNT(0)      
  FROM @tbltmp WHERE (t_BMI = 'Obese')      
  and t_OrgId = EXM.t_OrgId      
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE (t_BMI = 'Morbidly Obese')        
  and t_OrgId = EXM.t_OrgId
 ),
 (      
  SELECT COUNT(0)      
  FROM @tbltmp WHERE (t_BloodPressure = 'PreHypertension' AND Isnull(t_HypertensionExisting,'') <> 'Hypertension Existing')  -- CHANGE BY MS  MENTIS ISSUE:0024494 2023-04-07    
  and t_OrgId = EXM.t_OrgId      
 ),      
 (      
  SELECT COUNT(0)      
  FROM @tbltmp WHERE (t_BloodPressure in ('Hypertension','High Blood Pressure','Hypertension stage 2','Hypertension Existing') or t_HypertensionExisting='Hypertension Existing')      
  and t_OrgId = EXM.t_OrgId      
 ),      
 (      
  SELECT COUNT(0)      
  FROM @tbltmp WHERE (t_FBS = 'Pre Diabetic' AND Isnull(t_DiabeticExisting,'') <> 'Diabetic Existing') -- CHANGE BY MS  MENTIS ISSUE:0024494 2023-04-07    
  and t_OrgId = EXM.t_OrgId      
 ),      
 (      
  SELECT COUNT(0)      
  FROM @tbltmp WHERE (t_FBS in ('Diabetic','Diabetic Existing')  or t_DiabeticExisting ='Diabetic Existing')      
  and t_OrgId = EXM.t_OrgId      
 ),      
 (      
  SELECT COUNT(0)      
  FROM @tbltmp WHERE t_SGPT = 'Elevated  SGPT'      
  and t_OrgId = EXM.t_OrgId      
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_Hypertriglyceridemia = 'Hypertriglyceridemia'        
  and t_OrgId = EXM.t_OrgId        
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_Elevated_LDL = 'Elevated  LDL'        
  and t_OrgId = EXM.t_OrgId        
 ),        
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_Hypercholesterolemia = 'Hypercholesterolemia'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_SerumCreatinine = 'High Serum Creatinine'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_TSH = 'Elevated TSH'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_PSA = 'High PSA'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_TSH = 'Low TSH'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_VitaminB12 = 'Vitamin B12 deficiency'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_VitaminD3 = 'Vitamin D3 deficiency'        
  and t_OrgId = EXM.t_OrgId        
 ),
 (        
  SELECT COUNT(0)        
  FROM @tbltmp WHERE t_VitaminD3 = 'Vitamin D3 Toxicity Risk'        
  and t_OrgId = EXM.t_OrgId        
 ),
 EXM.t_OrgId,EXM.t_OrganizationName,t_SectorId      
 FROM @tbltmp EXM group by t_SectorId,t_OrgId,t_OrganizationName      
 ORDER BY 1      
       
 --select OrgId as VerticalId,OrgName as VerticalName,SectorId,[OverWeight] as Overweight,[PreHypertension] as Prehypertension,      
 --[Hypertension] as Hypertension,[Pre Diabetic] as Prediabetic,[Diabetic] as Diabetic,[High SGPT] as HighSGPT from @tempTable       
       
       
 if (@rDiseaseId = 5)  -- Overweight      
 begin      
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[OverWeight] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode      
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[OverWeight] > 0      
 end     
 else if (@rDiseaseId = 6)  -- Obese        
 begin        
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[Obese] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[Obese] > 0
 end
 else if (@rDiseaseId = 75)  -- Morbidly Obese        
 begin        
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[Morbidly Obese] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[Morbidly Obese] > 0
 end
 else if (@rDiseaseId = 9)  -- Prehypertension      
 begin      
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[PreHypertension] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode      
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[PreHypertension] > 0      
 end
 else if (@rDiseaseId = 10)  -- Hypertension      
 begin      
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[Hypertension] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode      
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[Hypertension] > 0      
 end    
 else if (@rDiseaseId = 11)  -- Prediabetic      
 begin      
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[Pre Diabetic] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode      
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[Pre Diabetic] > 0      
 end
 else if (@rDiseaseId = 12)  -- Diabetic      
 begin      
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[Diabetic] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode      
 from @tempTable t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[Diabetic] > 0      
 end
 else if (@rDiseaseId = 35)-- HighSGPT      
 begin      
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[High SGPT] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode      
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[High SGPT] > 0      
 end
 else if (@rDiseaseId = 30)-- Hypertriglyceridemia        
 begin        
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[Hypertriglyceridemia] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[Hypertriglyceridemia] > 0
 end 
 else if (@rDiseaseId = 28)-- Hypercholesterolemia        
 begin        
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[Hypercholesterolemia] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[Hypercholesterolemia] > 0
 end
 else if (@rDiseaseId = 32)-- Elevated_LDL        
 begin        
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[Elevated_LDL] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[Elevated_LDL] > 0
 end
 else if (@rDiseaseId = 36)-- HighSerumCreatinine        
 begin        
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[HighSerumCreatinine] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[HighSerumCreatinine] > 0
 end
 else if (@rDiseaseId = 58)-- HighTSH        
 begin        
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[HighTSH] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[HighTSH] > 0
 end
 else if (@rDiseaseId = 59)-- HighPSA        
 begin        
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[HighPSA] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[HighPSA] > 0
 end
 else if (@rDiseaseId = 67)-- LowTSH        
 begin        
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[LowTSH] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[LowTSH] > 0
 end
 else if (@rDiseaseId = 69)-- VitaminB12deficiency        
 begin        
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[VitaminB12deficiency] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[VitaminB12deficiency] > 0
 end
 else if (@rDiseaseId = 70)-- VitaminD3deficiency        
 begin        
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[VitaminD3deficiency] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[VitaminD3deficiency] > 0
 end
 else if (@rDiseaseId = 76)-- VitaminD3ToxicityRisk        
 begin        
 select t.OrgId as VerticalId,t.OrgName as VerticalName,t.SectorId,t.[VitaminD3ToxicityRisk] as DiseaseCount,isnull(e.EntityColor,'#000000') as ColorCode        
 from @tempTable as  t left join sHrm.tEntityColor E on e.EntitySourceId = t.OrgId AND e.EntitySourceTypeId = 2013 where t.[VitaminD3ToxicityRisk] > 0
 end
 
 
end
GO
PRINT N'Altering Procedure [sIncident].[pRptInjuryReport]...';


GO
ALTER PROCEDURE [sIncident].[pRptInjuryReport]
@FromDate datetime = null,
@ToDate datetime = null,
@ReportTypeId bigint = 0,
@SubLocationId bigint = 0,
@EmployeeCode nvarchar(50) = null,
@DepartmentId bigint = 0,
@BodyPartId bigint = 0,      
@DesignationId bigint =0,
@EmployeeTypeId bigint = 0,     	
@rBuilder1 nvarchar(max)='',
@rBuilder2 nvarchar(max)='',   
@orgid int,
@Company int=0,
@EmployeeName nvarchar(50) = null,
@CodeLike nvarchar(300) = null,
@UserId BIGINT,
@VisitPurpose int = 0
AS
SET NOCOUNT ON
BEGIN
	
	
SELECT ExaminationId,ExaminationDate,EmployeeName,EmployeeCode,DepartmentName,IncidentTime,IncidentDate,ReportingTime,ReportingDate,age,Gender,DoctorName,DoctorSignature,DoctorCode,
[TM Name (CAPS)] AS TMNameCAPS,
    [TM No] AS TMNo,
    [TKM Experience] AS TKMExperience,
    [Process Experience] AS ProcessExperience,
    [Shift] AS Shift,
    [Process/Line name] AS ProcessLineName,
    [TM/Apprentice/Contractor/ GAT/DAT] AS TMType,
    [Contract name (CAPS)] AS ContractNameCAPS,
    [Supervisor Name (CAPS)] AS SupervisorNameCAPS,
    [Supervisor mobile no] AS SupervisorMobileNo,
    [Member mobile No] AS MemberMobileNo,
    [Shop Manager Name] AS ShopManagerName,
    [Shop DGM Name] AS ShopDGMName,
    [How Accident occurred?] AS HowAccidentOccurred,
    [Injury details] AS InjuryDetails,
    [Injured part (in words)] AS InjuredPart,
    [Treatment detail] AS TreatmentDetail,
    [Outside hospital referred. ?] AS OutsideHospitalReferred,
    [Reason?] AS Reason,
    [Outside hospital detail: (Hospital Name / Contact Number)] AS OutsideHospitalDetail,
    [Treatment/Other update details from outside hospital, If any:] AS OutsideTreatmentDetails,
    [Details regarding post-accident conditions of the member:] AS PostAccidentCondition
FROM
(
SELECT Distinct IA.Id,IA.ExaminationId,
convert(varchar(10),EAED.ExaminationDate,103) as ExaminationDate,
	--case isnull(IA.ParticipantSourceTypeId,95) when 95 then isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')
	--else isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') end AS EmployeeName,

	CASE EAED.ParticipantSourceTypeId WHEN 1009 THEN
	CASE WHEN isnull(O.OtherName,'')='' THEN
	isnull(CS.FirstName,'') + ' ' + isnull(CS.LastName,'') ELSE O.OtherName END
	WHEN 95 THEN EM.FirstName + ' ' + EM.LastName WHEN 1001 THEN EFD.Name END  AS EmployeeName,

	case isnull(EAED.ParticipantSourceTypeId,95) when 95 then EM.Id else CS.Id end AS EmployeeId,
	case isnull(EAED.ParticipantSourceTypeId,95) when 95 then isnull(EM.Code,'') else isnull(CS.Code,'') end AS EmployeeCode,	
	IA.IncidentTime,
	convert(varchar(10),IA.IncidentDate,103) as IncidentDate,
	IA.PlaceofIncident,
	ITM.Title AS IncidentType,IA.IncidentTypeId
	,IA.ReportingTime,
	convert(varchar(10),IA.ReportingDate,103) as ReportingDate,
	IA.IncidentRemark,IA.TreatmentRemark,	
    case isnull(EAED.ParticipantSourceTypeId,95) when 95 then 'Employee' else 'Other' end AS EmployeeType,
	CM.Title AS Cause,
	
	ISNULL(ODM.Title,'') As DepartmentName,
	--case when IA.BodySideId =4 then '' Else Isnull(BSM.Title,'') End + ' ' + eb.Title As BodyPart,	

	D.DoctorSignature AS DoctorSignature,
	(EM2.FirstName + ' ' + EM2.LastName) as DoctorName,
	EM2.Code as DoctorCode,

		case when EAED.ParticipantSourceTypeId = 1009 then    
 case when CS.DateOfBirth = '1900-01-01' then 0 else datediff(yy,CS.DateOfBirth,getdate()) end    
 when EAED.ParticipantSourceTypeId = 1001 then    
 case when EFD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EFD.DateOfBirth,getdate()) end else    
 case when EPD.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EPD.DateOfBirth,getdate()) end end AS AGE,
	Gender = CASE EAED.ParticipantSourceTypeId
	WHEN 95 THEN GM1.Title
	WHEN 1001 THEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId),'')
	WHEN 1009 THEN CASE WHEN isnull(O.GenderId,0) = 0 THEN GM2.Title ELSE (select Title from sCommon.tGenderMaster where Id = O.GenderId) END END,
	
	InS.FieldRemark,
        ALF.AccidentLogFieldResponse
	From sExamination.tAccidentLog IA
	LEFT JOIN sExamination.tExamination EAED ON EAED.Id=IA.ExaminationId 
	LEFT JOIN sSafety.tIncidentTypeMaster ITM ON ITM.Id=IA.IncidentTypeId
	LEFT JOIN sHrm.tEmployeeMaster EM ON EAED.ParticipantSourceId =EM.Id AND isnull(EAED.ParticipantSourceTypeId,95) = 95
	LEFT JOIN sHrm.tCsrBenefiterMaster CS ON EAED.ParticipantSourceId=CS.Id AND EAED.ParticipantSourceTypeId = 1009	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
	Inner join sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id=EJD.OrganizationDepartmentId
	
	LEFT Join sHrm.tEmployeeCompanyMaster ECM On ECM.id=EJD.EmployeeCompanyId
	LEFT Join sHrm.tEmployeeCompanyMaster ECM1 On ECM1.id=EAED.EmployeeCompanyId
	 LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EM.Id = EPD.EmployeeId
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on EAED.ParticipantSourceId = EFD.Id and EAED.ParticipantSourceTypeId = 1001
	LEFT JOIN sCommon.tGenderMaster GM1 ON GM1.Id = EPD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = CS.GenderId
	LEFT JOIN sExamination.tCauseMaster CM ON CM.Id = EAED.CauseId
		LEFT JOIN sExamination.tOPD O ON O.ExaminationId = EAED.Id
	left JOIN sSecurity.tUser U ON U.Id = EAED.CreatedUserID		
	LEFT JOIN sCommon.tCompanyInformationDetail CID on EAED.OrgId = CID.orgid
	--LEFT join sSafety.tBodyPartMaster eb on eb.Id = IA.BodyPartId
	--left join sSafety.tBodySideMaster BSM On BSM.id=IA.BodySideId	
	left join sExamination.vExtEmployeeExaminationDetail EED ON EAED.Id = EED.ExaminationId
	--LEFT JOIN sExamination.tAccidentLog AL ON IA.SourceId=AL.Id	
	LEFT JOIN [sExamination].[tAccidentLogField] ALF ON ALF.ACCIDENTLOGID=IA.ID
	LEFT JOIN sSafety.tIncidentSetup InS ON  InS.Id= ALF.IncidentSetupId 
	LEFT JOIN sHrm.tEmployeeMaster EM2 ON EAED.DoctorEmployeeId=EM2.Id
    LEFT JOIN sCwb.tDoctorMaster D on d.EmployeeId = EM2.Id
   
	
		WHERE (EAED.StoreLocationId=@SubLocationId or (
			@SubLocationId = 0
			AND
			EAED.StoreLocationId IN (
				select LM.LocationId 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 isnull(EAED.iscancel,0) = 0
	and (EM.Code = @EmployeeCode or @EmployeeCode = '')
	and (EJD.OrganizationDepartmentId =@DepartmentId or @DepartmentId = 0)
	and (IA.BodyPartId =@BodyPartId or @BodyPartId = 0)
	and (EJD.EmployeeTypeId =@EmployeeTypeId or @EmployeeTypeId = 0)
	and ((IA.IncidentDate >= @FromDate) OR (ISNULL(@FromDate,'') = ''))
	and ((IA.IncidentDate <= @ToDate) OR (ISNULL(@ToDate,'') = ''))
	and (EJD.EmployeeDesignationId =@DesignationId or @DesignationId = 0)
	and (IA.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 EM.Code = LTRIM(RTRIM(SplitValues.item))
		)
		or ISNULL(@CodeLike, '') = ''
	)
	and ((EAED.CauseId = @VisitPurpose) OR @VisitPurpose = 0)
	
	
	) AS src
PIVOT
(
    MAX(AccidentLogFieldResponse)
    FOR FieldRemark IN (
        [TM Name (CAPS)],
		[TM No],
		[TKM Experience],
		[Process Experience],
		[Shift],
		[Process/Line name],
		[TM/Apprentice/Contractor/ GAT/DAT],
		[Contract name (CAPS)],
		[Supervisor Name (CAPS)],
		[Supervisor mobile no],
		[Member mobile No],
		[Shop Manager Name],
		[Shop DGM Name],
		[How Accident occurred?],
		[Injury details],
		[Injured part (in words)],
		[Treatment detail],
		[Outside hospital referred. ?],
		[Reason?],
		[Outside hospital detail: (Hospital Name / Contact Number)],
		[Treatment/Other update details from outside hospital, If any:],
		[Details regarding post-accident conditions of the member:]
    )
) AS pvt

	--ORDER BY IA.IncidentDate DESC
END
GO
PRINT N'Altering Procedure [sSupport].[pAssignEmployeeCustomSearchGet]...';


GO
ALTER PROCEDURE [sSupport].[pAssignEmployeeCustomSearchGet]
(
	@rOrgId smallint,
	@rAssignSurveyId int=0,
	@rCode [nvarchar](max) = '',
	@rDepartmentGroupId int = 0,	
	@rDepartmentId int = 0,	
	@rEmployeeTypeId int = 0,
	@rTargetGroupId int = 0,	
	@rBusinessId int = 0,	
	@rVerticalId int = 0,	
	@rCompanyGroupId int = 0,	
	@rCompanyId int = 0,	
	@rDesignationId int = 0,	
	@rGenderId int = 0,	
	@rProcessTypeId int = 0,
	@rLocationId int =0,
	@rIsShowExaminationEmployeeList bit,
    @rEmployeeId Bigint =0,
    @rSetupId int =0
 )
AS
SET NOCOUNT ON
BEGIN
IF(@rSetupId = 0) -- 0051189 -- For All Survey Type excluse Examination in which Round Id is 0
BEGIN
	SELECT EM.Id as EmployeeId,EM.Code AS EmployeeCode, ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS EmployeeName
		FROM sHrm.tEmployeeMaster EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id=EJD.EmployeeJobTitleId
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
		LEFT JOIN sHrm.tMedicalCoverageMaster MCM ON MCM.Id=EJD.MedicalCoverageId
		LEFT JOIN sCommon.tProcessTypeMaster PTM ON PTM.Id=EJD.ProcessTypeId
		LEFT JOIN sHrm.tSkillMaster SKM ON SKM.Id=EJD.SkillId
		LEFT JOIN sCommon.tLocationMaster ELM ON ELM.Id = EJD.EmployeeLocationId 
		left JOIN sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
		LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
		LEFT JOIN sHrm.tNationalityMaster NM ON NM.Id=EPD.NationalityId
		LEFT JOIN sHrm.tQualificationMaster QM ON QM.Id=EPD.HigestQualificationId
		LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
		LEFT JOIN sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = EJD.EmployeeCompanyId
		LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4 
		LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id = EJD.ContractorId
		INNER join sHrm.tEmployeeCommunications ECO On ECO.EmployeeId=Em.id
		left join sHrm.tEmployeeLegalEntitymaster LEM On LEM.id=EJD.LegalEntityId
		left join sHrm.tCompanyGroupMaster CGM on CGM.Id=ECM.CompanyGroupId
		left join sHrm.tVerticalMaster VRM on VRM.Id=CGM.VerticalId
		left join sHrm.tSectorMaster S on S.Id=VRM.SectorId
 LEFT join sCommon.tDepartmentGroupMaster DGM on DGM.Id=ODM.DepartmentGroupId
 where EM.IsObsolete=0
	AND EM.OrgId = @rOrgId 
		AND (EM.Code in (SELECT a.Item FROM dbo.fSplitStr(@rCode,',') AS a where a.Item!='') or ISNULL(@rCode,'')='')
		AND (DGM.Id = @rDepartmentGroupId or isnull(@rDepartmentGroupId,0) = 0)
		AND (EJD.OrganizationDepartmentId = @rDepartmentId or isnull(@rDepartmentId,0) = 0)
		AND (EJD.EmployeeTypeId = @rEmployeeTypeId or isnull(@rEmployeeTypeId,0) = 0)
		AND (EM.TargetGroupId = @rTargetGroupId or isnull(@rTargetGroupId,0) = 0)
		AND (S.Id = @rBusinessId or isnull(@rBusinessId,0) = 0)
		AND (VRM.Id = @rVerticalId or isnull(@rVerticalId,0) = 0)
		AND (CGM.Id = @rCompanyGroupId or isnull(@rCompanyGroupId,0) = 0)
		AND (EJD.EmployeeCompanyId = @rCompanyId or isnull(@rCompanyId,0) = 0)
		AND (EJD.EmployeeDesignationId = @rDesignationId or isnull(@rDesignationId,0) = 0)
		AND (EPD.GenderId = @rGenderId or isnull(@rGenderId,0) = 0)
		AND (EJD.ProcessTypeId = @rProcessTypeId or isnull(@rProcessTypeId,0) = 0)	
		AND (EM.Id = @rEmployeeId OR ISNULL(@rEmployeeId, 0) = 0)
		AND (EJD.EmployeeLocationId = @rLocationId)
END
ELSE
BEGIN
	if(@rIsShowExaminationEmployeeList = 'true')
	begin
		SELECT EM.Id as EmployeeId,EM.Code AS EmployeeCode, ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS EmployeeName
		FROM sExamination.tExamination E
		inner join sExamination.tSetupMaster SM1	on E.SetupId = SM1.Id
			inner join sExamination.tSubTypeMaster STM on SM1.SubTypeId = STM.Id
			inner join sHrm.tEmployeeMaster EM on EM.Id = E.ParticipantSourceId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id=EJD.EmployeeJobTitleId
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
			LEFT JOIN sHrm.tMedicalCoverageMaster MCM ON MCM.Id=EJD.MedicalCoverageId
			LEFT JOIN sCommon.tProcessTypeMaster PTM ON PTM.Id=EJD.ProcessTypeId
			LEFT JOIN sHrm.tSkillMaster SKM ON SKM.Id=EJD.SkillId
			INNER JOIN sCommon.tLocationMaster ELM ON ELM.Id = EJD.EmployeeLocationId 
			left JOIN sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
			LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
			LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
			LEFT JOIN sHrm.tNationalityMaster NM ON NM.Id=EPD.NationalityId
			LEFT JOIN sHrm.tQualificationMaster QM ON QM.Id=EPD.HigestQualificationId
			INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			LEFT JOIN sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = EJD.EmployeeCompanyId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4 
			LEFT JOIN sProcurement.tVendorMaster VM ON VM.Id = EJD.ContractorId
			left join sHrm.tEmployeeCommunications ECO On ECO.EmployeeId=Em.id
			left join sHrm.tEmployeeLegalEntitymaster LEM On LEM.id=EJD.LegalEntityId
			left join sHrm.tCompanyGroupMaster CGM on CGM.Id=ECM.CompanyGroupId
			left join sHrm.tVerticalMaster VRM on VRM.Id=CGM.VerticalId
			left join sHrm.tSectorMaster S on S.Id=VRM.SectorId
	 inner join sCommon.tDepartmentGroupMaster DGM on DGM.Id=ODM.DepartmentGroupId
	 where EM.IsObsolete=0
		AND EM.OrgId = @rOrgId 
		AND (EM.Code in (SELECT a.Item FROM dbo.fSplitStr(@rCode,',') AS a where a.Item!='') or ISNULL(@rCode,'')='')
		AND (DGM.Id = @rDepartmentGroupId or isnull(@rDepartmentGroupId,0) = 0)
		AND (EJD.OrganizationDepartmentId = @rDepartmentId or isnull(@rDepartmentId,0) = 0)
		AND (EJD.EmployeeTypeId = @rEmployeeTypeId or isnull(@rEmployeeTypeId,0) = 0)
		AND (EM.TargetGroupId = @rTargetGroupId or isnull(@rTargetGroupId,0) = 0)
		AND (S.Id = @rBusinessId or isnull(@rBusinessId,0) = 0)
		AND (VRM.Id = @rVerticalId or isnull(@rVerticalId,0) = 0)
		AND (CGM.Id = @rCompanyGroupId or isnull(@rCompanyGroupId,0) = 0)
		AND (EJD.EmployeeCompanyId = @rCompanyId or isnull(@rCompanyId,0) = 0)
		AND (EJD.EmployeeDesignationId = @rDesignationId or isnull(@rDesignationId,0) = 0)
		AND (EPD.GenderId = @rGenderId or isnull(@rGenderId,0) = 0)
		AND (EJD.ProcessTypeId = @rProcessTypeId or isnull(@rProcessTypeId,0) = 0)	
		AND (EM.Id = @rEmployeeId OR ISNULL(@rEmployeeId, 0) = 0)
		AND EM.Id not in(select distinct ASD.SourceId from sSupport.tAssignSurveyMaster ASM inner join sSupport.tAssignSurveyDetail ASD on ASM.Id=ASD.AssignSurveyId where ASM.Id=@rAssignSurveyId and ASM.OrgId=@rOrgId)
		and E.SetupId = @rSetupId
	end
		ELSE
	BEGIN
		SELECT DISTINCT
			SE.EmployeeId,
			EM.Code AS EmployeeCode,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName
		FROM sExamination.tSetupEmployee SE
		INNER JOIN sExamination.tSetupMaster SEM ON SEM.Id = SE.SetupId
		INNER JOIN sHrm.tEmployeeMaster EM ON SE.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
		LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON DGM.Id = ODM.DepartmentGroupId
		LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = EJD.EmployeeCompanyId
		LEFT JOIN sHrm.tCompanyGroupMaster CGM ON CGM.Id = ECM.CompanyGroupId
		LEFT JOIN sHrm.tVerticalMaster VRM ON VRM.Id = CGM.VerticalId
		LEFT JOIN sHrm.tSectorMaster S ON S.Id = VRM.SectorId
		LEFT JOIN sCommon.tLocationMaster LM ON LM.Id = EJD.EmployeeLocationId

		WHERE 
			EM.IsObsolete = 0
			AND EM.OrgId = @rOrgId
			AND SE.SetupId = @rSetupId  
			-- Code filter (supports single, CSV, LIKE)
			AND (
					EXISTS (
						SELECT 1
						FROM dbo.fSplitStr(@rCode, ',') s
						WHERE 
							(CHARINDEX(',', @rCode) = 0 AND EM.Code LIKE s.Item + '%')
							OR (CHARINDEX(',', @rCode) > 0 AND EM.Code = s.Item)
					)
					OR ISNULL(@rCode,'') = '' 
					OR ISNULL(@rCode,'') = '*'
				)

			-- Department Group
			AND (DGM.Id = @rDepartmentGroupId OR @rDepartmentGroupId = 0)

			-- Department (support CSV)
			AND (
					EJD.OrganizationDepartmentId IN (
						SELECT Item FROM dbo.fSplitStr(@rDepartmentId, ',')
					)
					OR ISNULL(@rDepartmentId,'') = ''
				)

			-- Employee Type
			AND (EJD.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0)

			-- Target Group
			AND (EM.TargetGroupId = @rTargetGroupId OR @rTargetGroupId = 0)

			-- Business / Sector
			AND (S.Id = @rBusinessId OR @rBusinessId = 0)

			-- Vertical
			AND (VRM.Id = @rVerticalId OR @rVerticalId = 0)

			-- Company Group
			AND (CGM.Id = @rCompanyGroupId OR @rCompanyGroupId = 0)

			-- Company
			AND (EJD.EmployeeCompanyId = @rCompanyId OR @rCompanyId = 0)

			-- Designation
			AND (EJD.EmployeeDesignationId = @rDesignationId OR @rDesignationId = 0)

			-- Gender
			AND (EPD.GenderId = @rGenderId OR @rGenderId = 0)

			-- Process Type
			AND (EJD.ProcessTypeId = @rProcessTypeId OR @rProcessTypeId = 0)

			-- Location
			--AND (EJD.EmployeeLocationId = @rLocationId OR @rLocationId = 0)

			-- Employee filter
			AND (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
			AND ISNULL(EM.IsObsolete,0)=0
			-- Exclude already assigned employees
			AND EM.Id NOT IN (
				SELECT ASD.SourceId
				FROM sSupport.tAssignSurveyMaster ASM
				INNER JOIN sSupport.tAssignSurveyDetail ASD 
					ON ASM.Id = ASD.AssignSurveyId
				WHERE ASM.Id = @rAssignSurveyId
				AND ASM.OrgId = @rOrgId
			)
	END
END
END
GO
PRINT N'Altering Procedure [sSupport].[pAssignEmployeeExaminationGet]...';


GO
ALTER proc [sSupport].[pAssignEmployeeExaminationGet]
@rSetupId [int] = 0,  
@rOrgId [int] = 0
as
begin
	SELECT EM.Id AS EmployeeId ,EM.Code AS EmployeeCode,  
 ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS EmployeeName
		FROM sExamination.tExamination E
		inner join sExamination.tSetupMaster SM1	on E.SetupId = SM1.Id
		inner join sExamination.tSubTypeMaster STM on SM1.SubTypeId = STM.Id
		inner join sHrm.tEmployeeMaster EM on EM.Id = E.ParticipantSourceId
		where e.setupid = @rSetupId
end
GO
PRINT N'Altering Procedure [sMro].[pExaminationCustomSearch]...';


GO
--exec [sMro].[pExaminationCustomSearch] 9999,9999000000003,0,0,'',0,0,'','0001-01-01','9999-12-31',999900147,0,0,0,0,'','','999900037,999901822,999900031','',''    
-- exec [sMro].[pExaminationCustomSearch]    
-- drop proc [sMro].[pExaminationCustomSearch]    
ALTER proc [sMro].[pExaminationCustomSearch]    
@rOrgId [int] = 0,    
@rUserId bigint = null,    
@rSetupId int=0,    
@rSetupGroupId int=0,    
@rEmployeeCompanyIds varchar(max)='',    
@rParticipantSourceId bigint = 0,    
--@rSourceTypeId int = 0,      
@rParticipantCode varchar(max)='',    
@rEmployeeName varchar(200)= '',    
@rFromDate date = '',    
@rToDate date = '',    
@rLocationId int,    
@rExaminationTypeId int = 0,    
@rStoreLocationId int = 0,    
@rExaminationStatusId int = 0,    
@rEmployeeTypeId int = 0,    
--@rParticipantSourceTypeId int = 0,    
@rTargetGroupIds varchar(max) ='',    
@rDepartmentGroupIds varchar(max) ='',    
@rDepartmentIds varchar(max) ='',    
@rDesignationIds varchar(max) ='',    
@rCompanyGroupIds varchar(max) ='',    
@rNationalId varchar(max) ='' ,  
@rBusinessIds nvarchar(max) = '', -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024  
@rSubBusinessIds nvarchar(max) = '',-- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024  
@rIsBusinessWise bit -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024  
as    
SET NOCOUNT ON    
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED    
BEGIN    
 IF(@rFromDate IS NULL)    
  SET @rFromDate='0001-01-01'    
     
 IF(@rToDate IS NULL)    
  SET @rToDate= convert(varchar, getdate(), 23)    
    
 Select distinct EED.ExaminationId,    
 EED.ParticipantCode as EmployeeCode,    
 EED.ParticipantName,    
 S.Title as StoreLocation,    
 SM.Title as Setup,    
 EED.ExaminationDate,    
 OD.Id as DepartmentId,    
 OD.Title as Department,    
 ECM.Title as CompanyName,    
 ESM.Title as Status  ,
 VII.Title as Contractor
 --ISNULL(EPD.NationalityId,0) NationalityId  
 --from sExamination.tExamination EED    
 from sExamination.vExtEmployeeExaminationDetail EED    
 LEFT JOIN sHrm.tEmployeePersonalDetail EPD on EED.EmployeeId = EPD.EmployeeId    
 --inner join sHrm.tEmployeeMaster EM on EED.ParticipantSourceId = EM.Id    
 inner join sExamination.tSetupMaster SM on SM.Id =EED.SetupId    
 inner join sIp.tStoreLocationMaster S on EED.StoreLocationId = S.Id    
 left join sHrm.tEmployeeJobDetail EJD on EED.EmployeeId = EJD.EmployeeId    
 left join sCommon.tOrganizationDepartmentMaster OD on EED.OrganizationDepartmentId = OD.Id    
 left join sHrm.tEmployeeCompanyMaster ECM on ECM.Id=(case when @rIsBusinessWise=0 then EED.EmployeeCompanyId else EJD.EmployeeCompanyId end)   -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024      
 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.tDepartmentGroupMaster DGM ON EED.DepartmentGroupId = DGM.Id AND DGM.IsObsolete=0     
 left join sExamination.tSetupGroupMaster SGM on SGM.Id=SM.SetupGroupId     
 --left join sSecurity.tUser Users on Users.Id = EED.CreatedUserId    
 left join sHrm.tEmployeeMaster EM1 on EM1.Id = EED.DoctorEmployeeId    
 LEFT JOIN sExamination.tStatusMaster ESM on ESM.Id = EED.StatusId     
 INNER JOIN sIp.tStoreLocationMaster SLM ON SLM.Id = EED.StoreLocationId    
 INNER JOIN sSecurity.tUserLocation UL on SLM.Id = UL.StoreLocationId    
 --INNER JOIN (SELECT Distinct SM.LocationId FROM sSecurity.tUserLocation UL INNER JOIN sIp.tStoreLocationMaster SM ON    
 --SM.Id = UL.StoreLocationId WHERE UL.UserId = @rUserId) UO ON UO.LocationId = EED.EmployeeLocationId    
 left JOIN  sProcurement.tVendorMaster VII on  VII.VendorCategoryId =EED.ContractorId
     
 where EED.OrgId = @rOrgId     
 and UL.UserId = @rUserId    
 AND ((EED.MainTypeId=@rExaminationTypeId) OR @rExaminationTypeId=0)    
 AND (EED.MainTypeId <> 8)    
 and (EED.ExaminationDate >= @rFromDate or isnull(@rFromDate,'') = '')    
 and (EED.ExaminationDate <= @rToDate or isnull(@rToDate,'') = '')     
 and ((EED.EmployeeId = @rParticipantSourceId) or (@rParticipantSourceId = 0))    
 --and (EED.ParticipantSourceTypeId = 95)    
 and ((EED.OrganizationDepartmentId IN (SELECT item FROM  sCommon.fnsplit(@rDepartmentIds,',')))  or @rDepartmentIds = '')    
 and (EED.SetupId = @rSetupId or isnull(@rSetupId,0) = 0)    
 and ((ISNULL(EED.ParticipantCode,'') IN (SELECT item FROM  sCommon.fnsplit(@rParticipantCode,','))) or (@rParticipantCode=''))    
 and ((EED.ParticipantName Like @rEmployeeName  + '%') or (@rEmployeeName = ''))    
 --and (EM.Code = @rParticipantCode or @rParticipantCode = '')    
 --and (EM.FirstName Like @rName  + '%' or @rName = '')    
 and ((EED.StoreLocationId = @rStoreLocationId) or @rStoreLocationId = 0)    
 --and (EED.StatusID = @rStatusId or  @rStatusId = 0)    
 and ((EED.EmployeecompanyId IN (SELECT item FROM  sCommon.fnsplit(@rEmployeeCompanyIds,','))) or  @rEmployeeCompanyIds = '')    
 and (SM.SetupGroupId = @rSetupGroupId or  @rSetupGroupId = 0)    
 and (ESM.Id = @rExaminationStatusId or  @rExaminationStatusId = 0)    
 and ((EED.EmployeeTargetGroupId IN (SELECT item FROM  sCommon.fnsplit(@rTargetGroupIds,',') )) or @rTargetGroupIds='')    
 AND ((EED.DepartmentGroupId IN (SELECT item FROM  sCommon.fnsplit(@rDepartmentGroupIds,',') ))  or (isnull(@rDepartmentGroupIds,'')=''))    
 AND ((EED.EmployeeDesignationId IN (SELECT item FROM  sCommon.fnsplit(@rDesignationIds,',') ))  or (isnull(@rDesignationIds,'')=''))    
 and (EED.EmployeeTypeId = @rEmployeeTypeId or  @rEmployeeTypeId = 0)    
 AND (ISNULL(@rCompanyGroupIds,'')='' OR ISNULL(ECM.CompanyGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCompanyGroupIds,',')))    
 AND ((EPD.NationalityId in (SELECT item FROM sCommon.fnsplit(@rNationalId,','))) OR (ISNULL(@rNationalId,'') = ''))    
 AND ((VTM.SectorId  IN(SELECT item FROM sCommon.fnsplit(@rBusinessIds,','))) OR (ISNULL(@rBusinessIds,'') = '')) -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024  
 AND ((CGM.VerticalId  IN(SELECT item FROM sCommon.fnsplit(@rSubBusinessIds,','))) OR (ISNULL(@rSubBusinessIds,'') = '')) -- mantis id - 0029440, Nidhi Pandey dt - 09/01/2024  
END
GO
PRINT N'Altering Procedure [dbo].[prc_GetJSON]...';


GO
-- exec prc_GetJSON '', '22/02/2023 12:00:00 AM'
-- drop proc prc_GetJSON
ALTER PROCEDURE [dbo].[prc_GetJSON]
@rFromDate varchar(30) = null,
@rToDate varchar(30) = null,
@rEmployeeCode nvarchar(40) = ''
as
begin

	
	Select distinct WIE.Id, 
	--Convert(nvarchar(max),replace(ISNULL(XMLString,''),',',', ')) as XMLString,
	'' as XMLString,
	CONVERT(varchar(5000),ISNULL(ValidationMessage,'')) as ValidationMessage,
	CONVERT(varchar(30),ISNULL(CreatedDate,''),113) as CreatedDate
	from [sHrm].[tWebApiImportEmployee] WIE
	where isnull(ValidationMessage,'') <> ''
	and ((convert(date,CreatedDate,103) >= convert(date,@rFromDate,103)) OR (ISNULL(@rFromDate,'') = ''))
	AND ((convert(date,CreatedDate,103) <= convert(date,@rToDate,103)) OR (ISNULL(@rToDate,'') = ''))
	AND ((WIE.ID in (select Distinct WebApiImportEmployeeId from sHrm.tWebApiImportMissingEmployee where PersonalNumber Like @rEmployeeCode + '%')) OR (@rEmployeeCode = ''))
	--order by CreatedDate desc
	
end
GO
PRINT N'Altering Procedure [sWellness].[pSaveAllConsultationDatas]...';


GO

ALTER PROCEDURE [sWellness].[pSaveAllConsultationDatas]   
@rId BIGINT,
@rSourceTypeId int = 10173,
@rParticipantSourceTypeId int = 95,
@rParticipantSourceId bigint,
@rOrgId smallint,
@rVitals nvarchar(max),                
@rTests nvarchar(max),              
@rWellnessAppointments nvarchar(max),                
@rTasks nvarchar(max),                
@rAdditionalFields nvarchar(max),
@rUserId bigint
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 @lNextNumber bigint,@lFromNextNumber bigint,@lCount int,@rStoreLocationId int               
 declare @lAppointmentid bigint,@rReferSourceId bigint,@i int,@lAppointmentType tinyint                
 declare @loNextNumber varchar(20),@lAppointmentDate varchar(50),@rConsultationDate varchar(50)               
                 
 declare @lxmlVital xml,@lxmlTests xml,@lxmlWellnessAppointment xml,@lxmlTasks xml,@lxmlAdditionalFields xml;
                 
 declare @exceptiondetail nvarchar(max),@username nvarchar(200);
 declare @cnt int;
 BEGIN TRY                       
 set @lxmlVital = CAST(@rVitals AS xml)           
 set @lxmlTests = CAST(@rTests AS xml) 
 set @lxmlWellnessAppointment = CAST(@rWellnessAppointments AS xml)                
 set @lxmlTasks = CAST(@rTasks AS xml)                
 set @lxmlAdditionalFields = CAST(@rAdditionalFields AS xml)
 
 set @username = (select Top 1 ISNULL(LoginTitle,'') from sSecurity.tUser where id=ISNULL(@rUserId,0));
 set @rConsultationDate = (select ConsultationDate from sWellness.tWellnessConsultation where Id = @rId);

BEGIN TRY
 declare @tblGeneralTemplates table(tid int identity(1,1),TestId int,ParamId int,
	GeneralTemplateConsultationId bigint,GeneralTemplateConsultationDetailId bigint,ServiceResult varchar(250),Remark varchar(250), GtgId smallint)
	insert into @tblGeneralTemplates
	select T.c.value('@GtId','Int') as TestId,
	T.c.value('@GtpId','Int') as ParamId,
	T.c.value('@GtExId','bigint') as GtExId,
	T.c.value('@GeneralTemplateConsultationDetailId','bigint') as GeneralTemplateConsultationDetailId,
	T.c.value('@ServiceResult','varchar(250)') as ServiceResult,
	T.c.value('@Remark','varchar(250)') as Remark,
	T.c.value('@GtgId','smallint') as GtgId
	from @lxmlVital.nodes('/GeneralTemplates/GeneralTemplate')T(c)

	select @cnt = count(*),@i = 1 from @tblGeneralTemplates

	delete w from sWellness.tGeneralTemplateConsultationDetail w
	inner join sWellness.tGeneralTemplateConsultation e
	on e.Id = w.GeneralTemplateConsultationId
	where e.GeneralTemplateId not in
	(
		select TestId from @tblGeneralTemplates
	)
	and w.GeneralTemplateParameterId not in
	(
		select ParamId from @tblGeneralTemplates
	) and e.SourceId = @rId and e.OrgId = @rOrgId
	and ((select distinct GtgId from @tblGeneralTemplates) = (select GeneralTemplateGroupId from sExamination.tGeneralTemplateMaster where Id = e.GeneralTemplateId))
		
	delete from sWellness.tGeneralTemplateConsultation where GeneralTemplateId not in
	(
		select TestId from @tblGeneralTemplates
	) and SourceId = @rId and OrgId = @rOrgId
	and ((select distinct GtgId from @tblGeneralTemplates) = (select GeneralTemplateGroupId from sExamination.tGeneralTemplateMaster where Id = GeneralTemplateId))

	while @i <= @cnt
	begin
		declare @TestId int,@ParamId int,@rServiceResult varchar(250)
		select @TestId = TestId,@ParamId = ParamId,@rServiceResult = ServiceResult from @tblGeneralTemplates where tid = @i
		select @TestId = isnull(@TestId,0),@ParamId = isnull(@ParamId,0),@rServiceResult = isnull(@rServiceResult,'')
		
		declare @detailid bigint
		select @detailid = GeneralTemplateConsultationDetailId from @tblGeneralTemplates where tid = @i
		
		declare @lParameterValueTypeId int,@lListValueTypeId int;
		select @lParameterValueTypeId = ParameterValueTypeId from sExamination.tGeneralTemplateParameter where Id = @ParamId
		
		if @TestId > 0
		begin
			if not exists(select * from sWellness.tGeneralTemplateConsultation where SourceId = @rId and SourceTypeId = @rSourceTypeId
			and GeneralTemplateId = @TestId and OrgId = @rOrgId)
			begin
				exec sCommon.pTableRowIdGet @rOrgId,'sWellness.tGeneralTemplateConsultation', 0, 1, 1,@outNextNumber = @lNextNumber output
				insert into sWellness.tGeneralTemplateConsultation
				(
					[Id],[SourceId],[GeneralTemplateId],[SourceTypeId],OrgId
				)
				values
				(
					@lNextNumber,@rId,@TestId,@rSourceTypeId,@rOrgId
				)
			end
			else
			begin
				select @lNextNumber = Id from sWellness.tGeneralTemplateConsultation where SourceId = @rId and SourceTypeId = @rSourceTypeId
				and GeneralTemplateId = @TestId and OrgId = @rOrgId
			end
			
			if @detailid > 0
			begin
				update sWellness.tGeneralTemplateConsultationDetail set ParameterValue = [sSetup].[fPortalXMLTagsReplaceReverse](@rServiceResult)
				where Id = @detailid
			end
			else if not exists(select * from sWellness.tGeneralTemplateConsultationDetail where GeneralTemplateConsultationId = @lNextNumber
			and GeneralTemplateParameterId = @ParamId)
			begin
				declare @GeneralTempExamiantionId bigint
				select @GeneralTempExamiantionId = @lNextNumber
				insert into sWellness.tGeneralTemplateConsultationDetail
				(
					[GeneralTemplateConsultationId],[GeneralTemplateParameterId],[ParameterValue],Remark,IsAbnormal
				)
				values
				(
					@GeneralTempExamiantionId,@ParamId,[sSetup].[fPortalXMLTagsReplaceReverse](@rServiceResult),'',0
				)
			end
			else
			begin
				update sWellness.tGeneralTemplateConsultationDetail set ParameterValue = [sSetup].[fPortalXMLTagsReplaceReverse](@rServiceResult)
				where [GeneralTemplateConsultationId] = @GeneralTempExamiantionId and [GeneralTemplateParameterId] = @ParamId
			end
		end
		select @i = @i + 1
	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 @rOrgId,'Consultation_Vital_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 1              
 END CATCH             
  
 declare @tblTests table(tid int identity(1,1),t_AreaId int,t_AreaTypeId int,t_ConsultationId 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('@ConsultationId','bigint') as ConsultationId,                 
 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 sWellness.tConsultationTestRequest p                
 on t.t_AreaId = p.TestId and t.t_ConsultationId = 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_ConsultationId bigint,tt_OrgId int,                
 tt_ParticipantAreaId bigint,tt_TestRequestId bigint,tt_IsPackageValue varchar(10))                
 insert into @tblTestsNew                
 select distinct t_AreaId,t_ConsultationId,t_OrgId,t_ParticipantAreaId,t_TestRequestId,t_IsPackageValue from @tblTests                
 BEGIN TRY          
         
 begin                
 exec sCommon.pTableRowIdGet @rOrgId, 'sWellness.tConsultationTestRequest', 0, 1, 1,@outNextNumber = @lNextNumber output                 
 SET @lFromNextNumber = @lNextNumber - 1                
 end                 
 MERGE sWellness.tConsultationTestRequest AS Target USING                 
 (                
  SELECT Id,tt_TestRequestId,tt_TestId,tt_OrgId,tt_ConsultationId,tid,tt_IsPackageValue                
  FROM @tblTestsNew TT LEFT JOIN sWellness.tConsultationTestRequest 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_ConsultationId,tt_TestId,@rSourceTypeId,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 @rOrgId, @rTableTitle = 'sWellness.tConsultationTestRequest', @rCurrentNumber = @lNextNumber                
 end             
                 
 update t set t.t_TestRequestId = p.Id from @tblTests t inner join sWellness.tConsultationTestRequest p                
 on t.t_AreaId = p.TestId and t.t_ConsultationId = p.SourceId                
                 
 update t set t.t_TestRequestDetailId = p.Id from @tblTests t inner join sWellness.tConsultationTestRequestDetail p                
 on t.t_TestDetailId = p.TestDetailId and t.t_TestRequestId = p.TestRequestId
                 
 declare @tblTestsM table(tid int identity(1,1),t_AreaId int,t_AreaTypeId int,t_ConsultationId 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_ConsultationId,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        
                
MERGE sWellness.tConsultationTestRequestDetail AS Target USING      
 (                
  SELECT Id,t_TestRequestId,t_TestDetailId,t_OrgId,t_ConsultationId,t_TestRequestDetailId,tid,t_ServiceValue,t_Remark      
  FROM @tblTestsM TT LEFT JOIN sWellness.tConsultationTestRequestDetail 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 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 @rOrgId,'Consultation_TestRequestDetail_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 2              
 END CATCH

 declare @tblWellnessAppointments 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)            
 insert into @tblWellnessAppointments                
 select T.c.value('@AppointmentId','bigint') as AppointmentId,                
 T.c.value('@ConsultationId','bigint') as ConsultationId,
 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,   
 [sSetup].[fPortalXMLTagsReplaceReverse](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           
 from @lxmlWellnessAppointment.nodes('/Appointments/Appointment')T(c)         
            
 update w set w.a_SubTypeId = s.SubTypeId from @tblWellnessAppointments w inner join sExamination.tSetupMaster s on s.Id = w.a_SetupId                
              
 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 @tblWellnessAppointments 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 @tblWellnessAppointments 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;            
  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) from @tblWellnessAppointments                    
            
  if(ISNULL(@lAppointmentid,0) > 0)            
  BEGIN
		update sWellness.tAppointment set ExaminationId = @lExamid where Id = ISNULL(@lAppointmentid,0)            
  END
                
  if(ISNULL(@lAppointmentid,0)>0)              
  begin               
  if exists (select 1 from  sWellness.tAppointment where Id = ISNULL(@lAppointmentid,0) and ISNULL(@lAppointmentType,0) <> 1 and ISNULL(@lExamid,0) <> ReferSourceId)                 
  begin   
  update sWellness.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 @tblWellnessAppointments 
       
 if @lAppointmentDate <> ''                
 begin                
   IF NOT EXISTS (SELECT 1 FROM sWellness.tAppointment WHERE ReferSourceId = @lExamid)
   BEGIN    
  exec sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId,@rPrefixFunctionalityId = 1022,@rStoreLocationId = 0,                
  @rNextNumber = @loNextNumber output         
                  
  update @tblWellnessAppointments set a_AppointNumber = @loNextNumber                
  begin try                
  --begin tran                
  begin                
                
  exec sCommon.pTableRowIdGet @rOrgId, 'sWellness.tAppointment', 0, 1, 1,@outNextNumber = @lNextNumber output                 
  SET @lFromNextNumber = @lNextNumber - 1                
  end                
    DECLARE @AppointmentFlag VARCHAR(50);
    SET @AppointmentFlag = 'Wellness Followup Appointment';

    INSERT INTO sWellness.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 @tblWellnessAppointments TT;     
  begin                
  select @lCount = COUNT(1) FROM @tblWellnessAppointments                 
  SET @lNextNumber  = @lCount + @lFromNextNumber                 
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sWellness.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 @rOrgId,'OPD_tAppointment_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 3          
 END CATCH     
 END
 end   
 
 DECLARE @tblTasks TABLE
(
    tid INT IDENTITY(1,1),
    r_ConsultationId BIGINT,
    r_Id BIGINT,
    r_WeekNoId INT,
    r_IsCustomActivityTask BIT,
    r_WellnessActivityCategoryId INT,
    r_WellnessActivityId INT,
    r_WellnessActivityTaskId INT,
    r_WellnessActivityCustomTask NVARCHAR(500),
    r_TargetValue NVARCHAR(100),
    r_UnitId INT,
    r_FrequencyTypeId INT,
    r_FrequencyCount INT,
    r_IsDelete BIT
)

INSERT INTO @tblTasks
SELECT
    T.c.value('@ConsultationId','bigint') AS ConsultationId,
    T.c.value('@Id','bigint') AS Id,
    T.c.value('@WeekNoId','int') AS WeekNoId,
    T.c.value('@IsCustomActivityTask','bit') AS IsCustomActivityTask,
    T.c.value('@WellnessActivityCategoryId','int') AS WellnessActivityCategoryId,
    T.c.value('@WellnessActivityId','int') AS WellnessActivityId,
    T.c.value('@WellnessActivityTaskId','int') AS WellnessActivityTaskId,
    T.c.value('@WellnessActivityCustomTask','nvarchar(500)') AS WellnessActivityCustomTask,
    T.c.value('@TargetValue','nvarchar(100)') AS TargetValue,
    T.c.value('@UnitId','int') AS UnitId,
    T.c.value('@FrequencyTypeId','int') AS FrequencyTypeId,
    T.c.value('@FrequencyCount','int') AS FrequencyCount,
    T.c.value('@IsDelete','bit') AS IsDelete
FROM @lxmlTasks.nodes('/WellnessTasks/Task') T(c)
         
 begin try
	DELETE A
	FROM sWellness.tAssignedActivity A
	INNER JOIN @tblTasks T 
		ON A.AssignedActivityId = T.r_Id
	WHERE T.r_IsDelete = 1

 DELETE FROM @tblTasks WHERE r_IsDelete = 1            
                 
 MERGE sWellness.tAssignedActivity AS Target
USING
(
 SELECT *
 FROM @tblTasks TT
 LEFT JOIN sWellness.tAssignedActivity T WITH(NOLOCK)
  ON TT.r_Id = T.AssignedActivityId
) AS Source
ON Target.AssignedActivityId = Source.r_Id
WHEN MATCHED THEN
 UPDATE SET
  WellnessActivityCategoryId = r_WellnessActivityCategoryId,
  WellnessActivityId = r_WellnessActivityId,
  WellnessActivityTaskId = r_WellnessActivityTaskId,
  IsCustomActivityTask = r_IsCustomActivityTask,
  WellnessActivityCustom = r_WellnessActivityCustomTask,
  TargetValue = r_TargetValue,
  UnitId = r_UnitId,
  FrequencyTypeId = r_FrequencyTypeId,
  FrequencyCount = r_FrequencyCount,
  WeekNo = r_WeekNoId,
  WeekStart = DATEADD(DAY, ((r_WeekNoId - 1) * 7) + 1, @rConsultationDate),
  WeekEnd = DATEADD(DAY, (r_WeekNoId * 7), @rConsultationDate),
  UpdatedUserId = @rUserId,
  UpdatedDateTime = sCommon.fGetDate()

WHEN NOT MATCHED THEN
 INSERT
 (
  ConsultationId,
  EmployeeId,
  WellnessActivityCategoryId,
  WellnessActivityId,
  WellnessActivityTaskId,
  IsCustomActivityTask,
  WellnessActivityCustom,
  TargetValue,
  UnitId,
  FrequencyTypeId,
  FrequencyCount,
  WeekNo,
  WeekStart,
  WeekEnd,
  CreatedUserId,
  CreatedDateTime
 )
 VALUES
 (
  @rId,
  @rParticipantSourceId,
  r_WellnessActivityCategoryId,
  r_WellnessActivityId,
  r_WellnessActivityTaskId,
  r_IsCustomActivityTask,
  r_WellnessActivityCustomTask,
  r_TargetValue,
  r_UnitId,
  r_FrequencyTypeId,
  r_FrequencyCount,
  r_WeekNoId,
  DATEADD(DAY, ((r_WeekNoId - 1) * 7) + 1, @rConsultationDate),
  DATEADD(DAY, (r_WeekNoId * 7), @rConsultationDate),
  @rUserId,
  sCommon.fGetDate()
 );  
                
 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 @rOrgId,'Consultation_Tasks_DBError',5000,@exceptiondetail,getdate()                
  Set @errorCount=-1                
  SET @errorLine = 4              
END CATCH 

BEGIN TRY
	IF NOT EXISTS (select * from sWellness.tConsultationAdditionalFieldMaster where ConsultationId = @rId)
	begin    
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sWellness.tConsultationAdditionalFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output 
		
	INSERT INTO sWellness.tConsultationAdditionalFieldMaster
	(
		Id,ConsultationId,
		OrgId, IsObsolete, CreatedUserId, CreatedDateTime,
		UpdatedUserId, UpdatedDateTime
	)
	VALUES
	(
		@lNextNumber,@rId,
		@rOrgId, 0, @rUserId, sCommon.fGetDate(), 
		@rUserId, sCommon.fGetDate()
	)
	end
	else
	begin
		UPDATE sWellness.tConsultationAdditionalFieldMaster SET
		UpdatedUserId = @rUserId, UpdatedDateTime = sCommon.fGetDate()
		WHERE ConsultationId = @rId

		select @lNextNumber = Id from sWellness.tConsultationAdditionalFieldMaster where ConsultationId = @rId
	end

	DECLARE @loDoc INT
	EXEC sp_xml_preparedocument @loDoc OUTPUT, @rAdditionalFields

	DELETE FROM sWellness.tConsultationAdditionalFieldDetails WHERE AdditionalFieldId=@lNextNumber
	
		INSERT INTO sWellness.tConsultationAdditionalFieldDetails
		(
			AdditionalFieldId,
			AdditionalFieldSetupId,
			AdditionalFieldResponse
		)
		SELECT
			@lNextNumber,AdditionalFieldSetupId,[sSetup].[fPortalXMLTagsReplaceReverse](AdditionalFieldResponse)
		FROM
			OPENXML (@loDoc, '/AdditionalFields/AdditionalField', 1)WITH
			(
				AdditionalFieldSetupId int,
				AdditionalFieldResponse nvarchar(1000)
			)
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 @rOrgId,'Consultation_QA_Error',5000,@exceptiondetail,getdate(),@rUserId                  
  Set @errorCount=-1                
  SET @errorLine = 5              
 END CATCH
                
              
 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 @rOrgId,'Consultation_DBError',5000,@exceptiondetail,getdate(),@rUserId                  
  Set @errorCount=-1                
  SET @errorLine = 6             
 END CATCH
 --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 [sWellness].[pAppointmentWellnessSchedulingAdd]...';


GO
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,
@rMobileNumber varchar(100)=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 != 17 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 != 17) 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 = 0, @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,MobileNumber      
  )      
  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 Wellness Appointment' ,@rMobileNumber    
  )      
  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'Altering Procedure [sWellness].[pAppointmentWellnessSchedulingModify]...';


GO
  
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,  
@rTimeslotId int = null ,
@rMobileNumber varchar(200)=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,TimeslotId = @rTimeslotId   ,MobileNumber=@rMobileNumber 
  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'Altering Procedure [sWellness].[pCoachCallRequestListGet]...';


GO
ALTER PROCEDURE [sWellness].[pCoachCallRequestListGet]   
(  
 @rEmployeeId BIGINT,  
 @rOrgId SMALLINT  
)  
AS  
SET NOCOUNT ON  
BEGIN  
     
  DECLARE @Today DATE = CAST(sCommon.fGetDate() AS DATE);  
  
  SELECT  
   DISTINCT  
   AP.Id,  
   AP.AppointmentNumber,  
   AP.DoctorEmployeeId,  
   CASE WHEN AP.PatientSourceTypeId = 95 THEN ED.Code WHEN AP.PatientSourceTypeId = 1009 THEN CSR.Code ELSE '-' END AS EmployeeCode,  
   AP.PatientSourceTypeId,  
   CASE WHEN AP.PatientSourceTypeId = 95 THEN ED.EmployeeName 
		WHEN AP.PatientSourceTypeId = 1009 THEN COALESCE(NULLIF(LTRIM(RTRIM(AP.OtherName)), ''),NULLIF(LTRIM(RTRIM(CONCAT(CSR.FirstName, ' ', CSR.LastName))), ''),'-' ) 
		ELSE COALESCE(NULLIF(LTRIM(RTRIM(CONCAT(CSR.FirstName, ' ', CSR.LastName))), ''),'-')END AS PatientName,
   CASE WHEN TRY_CAST(TM.FromTime AS TIME) IS NOT NULL AND TRY_CAST(TM.ToTime AS TIME) IS NOT NULL AND TRY_CAST(TM.FromTime AS TIME) <> '00:00:00' AND TRY_CAST(TM.ToTime AS TIME) <> '00:00:00'    THEN CONVERT(VARCHAR(8), TRY_CAST(TM.FromTime AS TIME), 100
) + ' to ' + CONVERT(VARCHAR(8), TRY_CAST(TM.ToTime AS TIME), 100) ELSE '-' END AS AppointmentTime,  
   CONVERT(VARCHAR,AP.AppointmentDate,103) AS AppointmentDateFormatted,  
   ISNULL(PM.Title, 'Not Assigned') AS ProgramName, AP.CauseId,  
   CASE WHEN AP.ExaminationId IS NOT NULL THEN 'Completed' ELSE 'Pending' END AS Status,  
   AP.ExaminationId as ConsultationId,  
   AP.MobileNumber,    ---all below one is getting for other master rest is picking from master data not from this table 95  
            AP.Age  as OtherAge,  
            AP.Months  as OtherMonth,  
            AP.GenderId  as OtherGenderId,  
   AP.OtherName  as OtherName  
  FROM   
   [sWellness].[tAppointment] AP  
  LEFT JOIN   
   [sHrm].[vEmployeeDetail] ED ON AP.PatientSourceId = ED.EmployeeId  
  LEFT JOIN   
   [sWellness].[tMHIScore] MH ON AP.PatientSourceId = MH.EmployeeId  
  LEFT JOIN   
   [sWellness].[tProgramMaster] PM ON MH.ProgramId = PM.Id  
  LEFT JOIN   
   [sAppointment].[tTimeSlotMaster] TM ON AP.TimeSlotId = TM.Id  
  LEFT JOIN   
   [sHrm].[tCsrBenefiterMaster] CSR ON AP.PatientSourceId = CSR.Id  
  WHERE   
   AP.DoctorEmployeeId = @rEmployeeId   
  AND   
   AP.OrgId = @rOrgId  
  AND   
   AP.AppointmentDate >= @Today   
  AND   
   AP.AppointmentDate < DATEADD(DAY,1,@Today)  
  ORDER BY   
   AP.Id   
  DESC;  
END
GO
PRINT N'Altering Procedure [sWellness].[pCoachScheduleListGet]...';


GO
ALTER PROCEDURE [sWellness].[pCoachScheduleListGet] 
(
	@rEmployeeId BIGINT,
	@rOrgId SMALLINT
)
AS
SET NOCOUNT ON
BEGIN
		 
		DECLARE @Today DATE = CAST(sCommon.fGetDate() AS DATE);

		SELECT
			DISTINCT
			AP.Id,
			AP.AppointmentNumber,
			AP.DoctorEmployeeId,
			CASE WHEN AP.PatientSourceTypeId = 95 THEN ED.Code WHEN AP.PatientSourceTypeId = 1009 THEN CSR.Code ELSE '-' END AS EmployeeCode,
			AP.PatientSourceTypeId,
			CASE WHEN AP.PatientSourceTypeId = 95 THEN ED.EmployeeName 
		WHEN AP.PatientSourceTypeId = 1009 THEN COALESCE(NULLIF(LTRIM(RTRIM(AP.OtherName)), ''),NULLIF(LTRIM(RTRIM(CONCAT(CSR.FirstName, ' ', CSR.LastName))), ''),'-' ) 
		ELSE COALESCE(NULLIF(LTRIM(RTRIM(CONCAT(CSR.FirstName, ' ', CSR.LastName))), ''),'-')END AS PatientName,
			CASE 
			WHEN TRY_CAST(TM.FromTime AS TIME) IS NOT NULL AND TRY_CAST(TM.ToTime AS TIME) IS NOT NULL AND TRY_CAST(TM.FromTime AS TIME) <> '00:00:00' AND TRY_CAST(TM.ToTime AS TIME) <> '00:00:00'
			THEN CONVERT(VARCHAR(8), TRY_CAST(TM.FromTime AS TIME), 100) + ' to ' + CONVERT(VARCHAR(8), TRY_CAST(TM.ToTime AS TIME), 100) ELSE '-' END AS AppointmentTime,
			CONVERT(VARCHAR,AP.AppointmentDate,103) AS AppointmentDateFormatted,
			ISNULL(PM.Title, 'Not Assigned') AS ProgramName, AP.CauseId
		FROM 
			[sWellness].[tAppointment] AP
		INNER JOIN 
			[sHrm].[vEmployeeDetail] ED ON AP.PatientSourceId = ED.EmployeeId
		LEFT JOIN 
			[sWellness].[tMHIScore] MH ON AP.PatientSourceId = MH.EmployeeId
		LEFT JOIN 
			[sWellness].[tProgramMaster] PM ON MH.ProgramId = PM.Id
		LEFT JOIN 
			[sAppointment].[tTimeSlotMaster] TM ON AP.TimeSlotId = TM.Id
		LEFT JOIN 
			[sHrm].[tCsrBenefiterMaster] CSR ON AP.PatientSourceId = CSR.Id
		WHERE 
			AP.DoctorEmployeeId = @rEmployeeId 
		AND 
			AP.OrgId = @rOrgId 
		AND 
			AP.AppointmentDate >= DATEADD(DAY,1,@Today)
		ORDER BY 
			AP.Id 
		DESC;
END
GO
PRINT N'Altering Procedure [sWellness].[pGetAllConsultationDetails]...';


GO
ALTER PROCEDURE [sWellness].[pGetAllConsultationDetails]     
@rConsultationId bigint,        
@rOrgId int,        
@rStoreLocationId int        
as        
SET NOCOUNT ON        
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED        
begin    
 select EE.Id, EE.Id as ConsultationId,    
 isnull(EE.ConsultationNumber,'') as ConsultationNumber,    
 EE.ConsultationDate,    
 ParticipantName = CASE WHEN EE.ParticipantSourceTypeId = 1009 THEN CBR.FirstName + ' ' + CBR.LastName     
      ELSE EM.FirstName + ' ' + EM.LastName END,    
 ParticipantCode = CASE WHEN EE.ParticipantSourceTypeId = 1009 THEN CBR.Code ELSE EM.Code END,    
 EE.ParticipantSourceTypeId,        
 EE.ParticipantSourceId,      
 EE.SetupId,      
 EE.DoctorEmployeeId,    
 isnull(C.Id,0) as CauseId,    
 isnull(EM.StatusId,0) as EmployeeStatusId,       
 isnull(convert(varchar,EE.ConsultationDate,103),'') as ExDate,    
-- isnull(G.Title,'') AS Gender,    
 isnull(CASE 
	WHEN EE.ParticipantSourceTypeId = 1009 then G2.Title
	WHEN EE.ParticipantSourceTypeId = 1001 then ''
	ELSE G.Title
 End,'') AS Gender,
-- Age = case when EP.DateOfBirth = '1900-01-01' then 0 else datediff(yy,EP.DateOfBirth,getdate()) end,       
Age = CASE 
        WHEN EE.ParticipantSourceTypeId = 95
             THEN CASE 
                    WHEN EP.DateOfBirth = '1900-01-01'
                         OR EP.DateOfBirth IS NULL
                    THEN 0
                    ELSE DATEDIFF(YY, EP.DateOfBirth, GETDATE())
                  END

        WHEN EE.ParticipantSourceTypeId = 1009
             THEN ISNULL(EE.Age,0)

        ELSE 0
      END,
 isnull(SA.Id,'') as WellnessAppointmentId,        
 isnull(convert(varchar,SA.AppointmentDate,103),'') as AppointmentDate,        
 isnull(SA.FollowupRemark,'') as FollowupRemark,    
 isnull(EE.ConsultationNotes,'') as ConsultationNotes,    
 isnull(EE.ConsultationRemarks,'') as ConsultationRemarks,      
 EM2.FirstName + ' ' + isnull(EM2.LastName,'') as DoctorName,     
 isnull(EE.ConsultationTime,'') as ConsultationTime,        
 isnull(EE.ConsultationOutTime,'') as ConsultationOutTime,    
 EJD.EmployeeLocationId as EmployeeLocationId,    
 ISNULL(EE.OtherName,'') as OtherName,  
 EE.Age as OtherAge,  
 EE.Months as OtherMonth,  
 EE.GenderId as OtherGenderId,    
 ISNULL(EE.EmailAddress,'') as EmailAddress,    
  ISNULL(EE.MobileNumber,'') as MobileNumber,    
 ISNULL(PM.Title,'') as ProgramName,    
 EE.CreatedDateTime,  
 DATEDIFF(SECOND, EE.CreatedDateTime, GETDATE()) / 3600.0 AS TotalConsultationHours    
 from sWellness.tWellnessConsultation EE        
 left join sHrm.tEmployeeMaster EM on EE.ParticipantSourceId = EM.Id and EE.ParticipantSourceTypeId = 95    
 left join sHrm.tCsrBenefiterMaster CBR on EE.ParticipantSourceId = CBR.Id and EE.ParticipantSourceTypeId = 1009    
 LEFT JOIN sWellness.tMHIScore MS ON MS.EmployeeId = EM.Id and MS.EmployeeSourceTypeId = 95    
 LEFT JOIN sWellness.tProgramMaster PM ON PM.Id = MS.ProgramId    
 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 sWellness.tWellnessVisitPurposeMaster C on C.Id = EE.CauseId    
 left join sHrm.tEmployeePersonalDetail PD on EE.ParticipantSourceId = PD.EmployeeId and EE.ParticipantSourceTypeId = 95    
 left join sWellness.tAppointment SA on EE.Id = SA.ReferSourceId         
 left join sHrm.tEmployeeMaster EM2 on EM2.Id = EE.DoctorEmployeeId    
 left join sCommon.tGenderMaster G ON EP.GenderId = G.Id    
 left join sCommon.tGenderMaster G2 ON CBR.GenderId = G2.Id   
 where EE.Id = @rConsultationId    
 OPTION (RECOMPILE)        
      
 select AA.AssignedActivityId as Id,     
 AA.WellnessActivityCategoryId,WAC.Title as WellnessActivityCategoryName,    
 AA.WellnessActivityId, WA.ActivityName as WellnessActivityName,    
 ISNULL(AA.WellnessActivityTaskId,0) as WellnessActivityTaskId,     
 CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN ISNULL(AA.WellnessActivityCustom,'')     
 ELSE ISNULL(WAT.[Name],'') END as WellnessActivityTask,    
 ISNULL(AA.IsCustomActivityTask,0) as IsCustomActivityTask,    
 CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN 2 ELSE 1 END AS TypeId,    
 CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN 'Custom' ELSE 'Pre Define' END AS TypeName,    
 ISNULL(AA.WellnessActivityCustom,'') as WellnessActivityCustomTask,    
 ISNULL(AA.TargetValue, 0) as TargetValue, AA.UnitId, AA.FrequencyTypeId, AA.FrequencyCount,    
 AA.WeekNo as WeekNoId,    
 CASE AA.WeekNo WHEN 1 THEN 'Week 1' WHEN 2 THEN 'Week 2' WHEN 3 THEN 'Week 3' WHEN 4 THEN 'Week 4' END AS WeekName,    
 CASE AA.UnitId WHEN 1 THEN 'Steps' WHEN 2 THEN 'Min' WHEN 3 THEN 'ML' WHEN 4 THEN 'Times' END AS UnitNo,    
 CASE AA.FrequencyTypeId WHEN 1 THEN 'Daily' WHEN 2 THEN 'Weekly' END AS FrequencyType,    
 CASE WHEN AA.WeekStart IS NULL THEN 'Assigned' WHEN GETDATE() < AA.WeekStart THEN 'Assigned'    WHEN GETDATE() BETWEEN AA.WeekStart AND AA.WeekEnd THEN 'Active'    WHEN GETDATE() > AA.WeekEnd THEN 'Expired' ELSE '-'   END AS [Status]    
 from sWellness.tAssignedActivity AA        
 INNER JOIN sWellness.tWellnessActivityCategoryMaster WAC on WAC.Id = AA.WellnessActivityCategoryId    
 INNER JOIN sWellness.tWellnessActivityMaster WA on WA.ActivityId = AA.WellnessActivityId    
 LEFT JOIN sWellness.tWellnessActivityTaskMaster WAT on WAT.Id = AA.WellnessActivityTaskId    
 where AA.ConsultationId = @rConsultationId    
 OPTION (RECOMPILE)    
    
 SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off        
end
GO
PRINT N'Altering Procedure [sWellness].[pGetWellnessAppointmentSchedulingList]...';


GO
    
ALTER PROCEDURE [sWellness].[pGetWellnessAppointmentSchedulingList]          
    @rOrgId INT,         
    @rId BIGINT = 0,    
    @rEmployeeCode NVARCHAR(20) = '',          
    @rPatientName NVARCHAR(500) = '',          
    @rStoreLocationId INT = 0,          
    @rLocationId INT = 0,          
    @rSetupId INT = 0,          
    @rDoctorEmployeeId BIGINT = 0,          
    @rEmployeeStoreLocationId INT = 0,    
    @rDescription nvarchar(4000)=''    
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,        
        ISNULL(A.Age,0) as Age,        
        ISNULL(A.Months,0) as Months,        
        A.GenderId,    
        A.ExaminationId,        
        A.Timeslot,    
  ISNULL(A.CompliantRemark, '') AS CompliantRemark ,  
 -- A.MobileNumber,
     A.MobileNumber,    ---all below one is getting for other master rest is picking from master data not from this table 95  
            A.Age  as OtherAge,  
            A.Months  as OtherMonth,  
            A.GenderId  as OtherGenderId,  
   A.OtherName  as OtherName  
    FROM    
  [sWellness].[vExtPatientWellnessAppointmentDetail] A    
    LEFT JOIN         
        sWellness.tWellnessConsultation E ON A.ExaminationId = E.Id        
        OR A.ReferSourceId = E.Id    
    WHERE         
        A.ApprovalStatusId = 548       
  AND A.AppointmentDate = CONVERT(DATE, 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 ((ISNULL(Relation, '')  Like @rDescription + '%') OR(@rDescription = ''))    
        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 ISNULL(A.ExaminationId, 0) = 0        
        AND ISNULL(E.IsCancel, 0) = 0    
 ORDER BY A.Id DESC;    
END
GO
PRINT N'Altering Procedure [sWellness].[pWellnessAppointmentListGetScheduling]...';


GO
    
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.TimeslotId,    
        A.Timeslot,    
  ISNULL(A.CompliantRemark, '') AS CompliantRemark,    
  A.AppointmentFlag,    
  CASE WHEN A.ApprovalStatusId = 550 THEN 1 ELSE 0 END AS IsConsultedFlag,    
  ISNULL(E.ConsultationNumber,'') AS ConsultationNumber ,  
  A.MobileNumber as MobileNumber  
    FROM         
        [sWellness].[vExtPatientWellnessAppointmentDetail] A      
    LEFT JOIN     
        sWellness.tWellnessConsultation E ON A.ExaminationId = E.Id        
        OR A.ReferSourceId = E.Id    
    WHERE         
        (A.ApprovalStatusId = 548 OR A.ApprovalStatusId = 550)    
        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);    
  order by A.id Desc
END
GO
PRINT N'Altering Procedure [sWellness].[pInsertMHIScoreHistoryIfChanged]...';


GO
ALTER   PROCEDURE [sWellness].[pInsertMHIScoreHistoryIfChanged]
(
    @rEmployeeId BIGINT,
    @rUserId BIGINT
)
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO sWellness.tMHIScore_History
    (
        Id,
        OrgId, ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,LocationId,

        BMI, BMIScore, BMICategory,
        HBA1C, HBA1CScore, HBA1CCategory,
        LDL, LDLScore, LDLCategory,
        BP, BPScore, BPCategory,
        Stress, StressScore, StressCategory,
        Lifestyle, LifestyleScore, LifestyleCategory,
        Biometrics, BiometricsCategory,
        SurveyCategory, MHICategory,MHICategoryId,ActionType,CreatedUserId,
        ActionDateTime
    )
    SELECT
        m.Id,
        m.OrgId, m.ProgramId, m.EmployeeId, m.EmployeeSourceTypeId, m.LastUpdateType,m.LocationId,

        m.BMI, m.BMIScore, m.BMICategory,
        m.HBA1C, m.HBA1CScore, m.HBA1CCategory,
        m.LDL, m.LDLScore, m.LDLCategory,
        m.BP, m.BPScore, m.BPCategory,
        m.Stress, m.StressScore, m.StressCategory,
        m.Lifestyle, m.LifestyleScore, m.LifestyleCategory,
        m.Biometrics, m.BiometricsCategory,
        m.SurveyCategory, m.MHICategory,m.MHICategoryId,'Update',m.CreatedUserId,
        sCommon.fGetDate()
    FROM sWellness.tMHIScore m
    WHERE m.EmployeeId = @rEmployeeId
      AND NOT EXISTS
      (
          SELECT 1
          FROM sWellness.tMHIScore_History h
          WHERE h.EmployeeId = m.EmployeeId
            AND h.ActionDateTime =
            (
                SELECT MAX(h2.ActionDateTime)
                FROM sWellness.tMHIScore_History h2
                WHERE h2.EmployeeId = m.EmployeeId
            )
            AND ISNULL(h.BMI,0)                  = ISNULL(m.BMI,0)
            AND ISNULL(h.BMIScore,0)             = ISNULL(m.BMIScore,0)
            AND ISNULL(h.BMICategory,'')         = ISNULL(m.BMICategory,'')

            AND ISNULL(h.HBA1C,0)                = ISNULL(m.HBA1C,0)
            AND ISNULL(h.HBA1CScore,0)           = ISNULL(m.HBA1CScore,0)
            AND ISNULL(h.HBA1CCategory,'')       = ISNULL(m.HBA1CCategory,'')

            AND ISNULL(h.LDL,0)                  = ISNULL(m.LDL,0)
            AND ISNULL(h.LDLScore,0)             = ISNULL(m.LDLScore,0)
            AND ISNULL(h.LDLCategory,'')         = ISNULL(m.LDLCategory,'')

            AND ISNULL(h.BP,'')                  = ISNULL(m.BP,'')
            AND ISNULL(h.BPScore,0)              = ISNULL(m.BPScore,0)
            AND ISNULL(h.BPCategory,'')          = ISNULL(m.BPCategory,'')

            AND ISNULL(h.Stress,0)               = ISNULL(m.Stress,0)
            AND ISNULL(h.StressScore,0)          = ISNULL(m.StressScore,0)
            AND ISNULL(h.StressCategory,'')      = ISNULL(m.StressCategory,'')

            AND ISNULL(h.Lifestyle,0)            = ISNULL(m.Lifestyle,0)
            AND ISNULL(h.LifestyleScore,0)       = ISNULL(m.LifestyleScore,0)
            AND ISNULL(h.LifestyleCategory,'')   = ISNULL(m.LifestyleCategory,'')

            AND ISNULL(h.Biometrics,0)           = ISNULL(m.Biometrics,0)
            AND ISNULL(h.BiometricsCategory,'')  = ISNULL(m.BiometricsCategory,'')

            AND ISNULL(h.SurveyCategory,'')      = ISNULL(m.SurveyCategory,'')
            AND ISNULL(h.MHICategory,'')         = ISNULL(m.MHICategory,'')
			AND ISNULL(h.MHICategoryId,0)        = ISNULL(m.MHICategoryId,0)
      );

    RETURN @@ROWCOUNT; -- 1 = inserted, 0 = skipped
END;
GO
PRINT N'Altering Procedure [sCommon].[pEmployeeSearchGet]...';


GO

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 EM.OrgID,EM.Id,EM.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,
			CASE WHEN DateOfBirth <> '1900-01-01' and ISNULL(DateOfBirth, '') <> ''
			     THEN ISNULL(DATEDIFF(yy,DateOfBirth,sCommon.fGetDate()),0) ELSE 0 END 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, ISNULL(PM.Title,'') as ProgramName
			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
			LEFT JOIN sWellness.tMHIScore MS ON MS.EmployeeId = EM.EmployeeId and MS.EmployeeSourceTypeId = 95
			LEFT JOIN sWellness.tProgramMaster PM ON PM.Id = MS.ProgramId
			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,
			CASE WHEN ECB.DateOfBirth <> '1900-01-01' and ISNULL(ECB.DateOfBirth, '') <> ''
			     THEN ISNULL(DATEDIFF(yy,ECB.DateOfBirth,sCommon.fGetDate()),0) ELSE 0 END 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,
			ISNULL(CB.EmailId,'') AS EmailId
			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,
			CASE WHEN ECB.DateOfBirth <> '1900-01-01' and ISNULL(ECB.DateOfBirth, '') <> '' 
				 THEN ISNULL(DATEDIFF(yy,ECB.DateOfBirth,sCommon.fGetDate()),0) ELSE 0 END 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,
			ISNULL(CB.EmailId,'') AS EmailId
			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 [sWellness].[pAddOrUpdateProgramMHIScoreNew]...';


GO

ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramMHIScoreNew]
(
	@rOrgId SMALLINT,	
    @rEmployeeId BIGINT,
	@rEmployeeSourceTypeId INT,
    @rInsertType SMALLINT,
    @rBMI NUMERIC(10,2) = NULL,
    @rSystolicBP NUMERIC(10,0)=NULL,
    @rDiastolicBP NUMERIC(10,0)=NULL,
    @rHBA1C NUMERIC(10,2)=NULL,
    @rLDL NUMERIC(10,2)=NULL,
    @rStress NUMERIC(10,2)=NULL,
    @rLifeStyle NUMERIC(10,2)=NULL,
	@rLocationId INT,
    @rUserId BIGINT
)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE @lNextNumber BIGINT = 0;
	BEGIN TRY
        BEGIN TRANSACTION
			CREATE TABLE #TempParameterRange
			(
				StaticHIPId INT, ParameterName VARCHAR(100), MinimumRange NUMERIC(10,5), MaximumRange NUMERIC(10,5), Score SMALLINT, Category NVARCHAR(100), GenderId SMALLINT
			)

			INSERT INTO #TempParameterRange 
			SELECT 
				HIPM.StaticHealthIndexParameterId, HIPM.Title, HIPD.FromValue, HIPD.ToValue, HIPD.Points, HIPD.DiagnosisRemark,HIPD.GenderId
			FROM 
				[sExamination].[tHealthIndexParameterMaster] HIPM
			INNER JOIN
				[sExamination].[tHealthIndexParameterDetail] HIPD
			ON
				HIPD.HealthIndexParameterId = HIPM.Id
			WHERE 
				StaticHealthIndexParameterId IN (1,2,5,17,23)

			DECLARE @TotalRecord INT = 0;
			SET @TotalRecord = (SELECT COUNT(StaticHIPId) FROM #TempParameterRange)
			IF(@TotalRecord > 0)
			BEGIN
				UPDATE #TempParameterRange SET Score = CASE WHEN Score = 10 THEN 1 WHEN Score = 6 THEN 2 WHEN Score = 3 THEN 3 ELSE Score END WHERE Score IS NOT NULL  AND Score > 0;
			END

			DECLARE @DepartmentId INT, @GenderId SMALLINT,
					@BMICategory NVARCHAR(30) = NULL, @BMIScore SMALLINT,
					@HBA1CCategory NVARCHAR(30) = NULL, @HBA1CScore SMALLINT,
					@LDLCategory NVARCHAR(30) = NULL, @LDLScore SMALLINT,
					@SystolicCategory NVARCHAR(30) = NULL, @SystolicScore SMALLINT,
					@DiastolicCategory NVARCHAR(30) = NULL, @DiastolicScore SMALLINT,
					@BPCategory NVARCHAR(30) = NULL, @BPScore SMALLINT = NULL,
					@BiometricsCategory VARCHAR(30) = NULL, @BiometricsCategoryIndex SMALLINT = NULL,
					@LifeStyleCategory VARCHAR(30) = NULL, @LifeStyleIndex SMALLINT = NULL,
					@StressCategory VARCHAR(30) = NULL, @StressIndex SMALLINT = NULL,
					@SurveyCategory VARCHAR(30) = NULL, @SurveyIndex SMALLINT = NULL,
					@MHICategory VARCHAR(30) = NULL, @MHICategoryId SMALLINT = NULL,
					@TotalBiometrics INT = NULL, @BiometricScore DECIMAL(10,2) = NULL,
					@AssignedMHIIndicatorId INT = 0, @AssignedProgramId INT = 0

			SET @DepartmentId = (SELECT TOP 1 DepartmentId FROM [sHrm].[vExtEmployeeMaster] WHERE EmployeeId = @rEmployeeId);
			SET @GenderId = (SELECT TOP 1 GenderId FROM [sHrm].[vExtEmployeeMaster] WHERE EmployeeId = @rEmployeeId);

			-- Add OR UPDATE Biometric parameter not included biometric category & survey & mhi category
			
				-- BMI
			IF(@rBMI IS NOT NULL AND @rBMI > 0 )
			BEGIN
				SELECT TOP 1 @BMICategory = Category, @BMIScore = Score FROM #TempParameterRange WHERE StaticHIPId = 1 AND @rBMI >= MinimumRange AND @rBMI <= MaximumRange AND GenderId = @GenderId
			END

			-- HBA1C
			IF(@rHBA1C IS NOT NULL AND @rHBA1C > 0 )
			BEGIN
				SELECT TOP 1 @HBA1CCategory = Category, @HBA1CScore = Score FROM #TempParameterRange WHERE StaticHIPId = 2 AND @rHBA1C >= MinimumRange AND @rHBA1C <= MaximumRange AND GenderId = @GenderId
			END
			-- LDL
			IF(@rLDL IS NOT NULL AND @rLDL > 0 )
			BEGIN
				SELECT TOP 1 @LDLCategory = Category, @LDLScore = Score FROM #TempParameterRange WHERE StaticHIPId = 5 AND @rLDL >= MinimumRange AND @rLDL <= MaximumRange AND GenderId = @GenderId
			END

			-- Systolic
			IF(@rSystolicBP IS NOT NULL AND @rSystolicBP > 0 )
			BEGIN
				SELECT TOP 1 @SystolicCategory = Category, @SystolicScore = Score FROM #TempParameterRange WHERE StaticHIPId = 23 AND @rSystolicBP >= MinimumRange AND @rSystolicBP <= MaximumRange AND GenderId = @GenderId
			END

			-- Diastolic
			IF(@rDiastolicBP IS NOT NULL AND @rDiastolicBP > 0 )
			BEGIN
				SELECT TOP 1 @DiastolicCategory = Category, @DiastolicScore = Score FROM #TempParameterRange WHERE StaticHIPId = 17 AND @rDiastolicBP >= MinimumRange AND @rDiastolicBP <= MaximumRange AND GenderId = @GenderId
			END

			IF(@rSystolicBP IS NOT NULL AND @rSystolicBP > 0 AND @rDiastolicBP IS NOT NULL AND @rDiastolicBP > 0 )
			BEGIN
				SET @BPScore = CASE WHEN @SystolicScore > @DiastolicScore THEN @SystolicScore ELSE @DiastolicScore END
				SET @BPCategory = CASE @BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END
			END

			IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId)
			BEGIN
					
				EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore', 0,1,1, @outNextNumber = @lNextNumber OUTPUT

				INSERT INTO [sWellness].[tMHIScore] 
				(
					Id,OrgId,ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,
					HBA1C,HBA1CScore, HBA1CCategory, LDL, LDLScore, LDLCategory, BMI, BMIScore, BMICategory,
					BP, BPScore, BPCategory, LocationId,
					CreatedUserId, CreatedDatetime
				) 
				VALUES
				(
					@lNextNumber, @rOrgId, 0, @rEmployeeId, @rEmployeeSourceTypeId, @rInsertType,
					@rHBA1C, @HBA1CScore, @HBA1CCategory, @rLDL, @LDLScore, @LDLCategory, @rBMI, @BMIScore, @BMICategory,
					CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)), @BPScore, @BPCategory,@rLocationId,
					@rUserId, sCommon.fGetDate()
				)
			END
			ELSE
			BEGIN
				UPDATE 
					[sWellness].[tMHIScore]
				SET
					HBA1C = @rHBA1C,
					HBA1CScore = @HBA1CScore,
					HBA1CCategory = @HBA1CCategory,
					LDL = @rLDL,
					LDLScore = @LDLScore,
					LDLCategory = @LDLCategory,
					BMI = @rBMI,
					BMIScore = @BMIScore,
					BMICategory = @BMICategory,
					BP = CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)),
					BPScore = @BPScore,
					BPCategory = @BPCategory,
					LastUpdateType = @rInsertType,
					LocationId = @rLocationId,
					UpdatedUserId = @rUserId,
					UpdatedDatetime = sCommon.fGetDate()
				WHERE
					EmployeeId = @rEmployeeId;

					SET @lNextNumber =@@ROWCOUNT;
			END
			
			-- Add OR UPDATE survey parameter not included bio metric category & biometric parameter & mhi category
			IF(@rStress IS NOT NULL)
			BEGIN
				--SET @StressIndex = CASE WHEN @rStress IS NULL THEN NULL WHEN @rStress <= 13 THEN 1 WHEN @rStress <= 26 THEN 2 ELSE 3 END;
				SET @StressIndex = CASE WHEN @rStress IS NULL THEN NULL WHEN @rStress >= 90 THEN 1 WHEN @rStress >= 75 THEN 2 ELSE 3 END;
				SET @StressCategory = CASE @StressIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
			END
			--IF(@rLifeStyle IS NOT NULL AND @rLifeStyle > 0 )
			IF(@rLifeStyle IS NOT NULL)
			BEGIN
				SET @LifestyleIndex = CASE WHEN @rLifeStyle IS NULL THEN NULL WHEN @rLifeStyle <= 49 THEN 3 WHEN @rLifeStyle <= 70 THEN 2 ELSE 1 END;
				SET @LifeStyleCategory = CASE @LifestyleIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
			END

			IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId)
			BEGIN		
				
				EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore', 0,1,1, @outNextNumber = @lNextNumber OUTPUT

				INSERT INTO [sWellness].[tMHIScore] 
				(
					Id,OrgId,ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,
					Stress, StressScore, StressCategory, Lifestyle, LifestyleScore, LifestyleCategory,
					CreatedUserId, CreatedDatetime
				) 
				VALUES
				(
					@lNextNumber, @rOrgId, 0, @rEmployeeId, @rEmployeeSourceTypeId, @rInsertType,
					@rStress, @StressIndex, @StressCategory, @rLifeStyle, @LifestyleIndex, @LifeStyleCategory,
					@rUserId, sCommon.fGetDate()
				)
			END
			ELSE
			BEGIN
				UPDATE 
					[sWellness].[tMHIScore]
				SET
					Stress = @rStress,
					StressScore = @StressIndex,
					StressCategory = @StressCategory,
					Lifestyle = @rLifeStyle,
					LifestyleScore = @LifestyleIndex,
					LifestyleCategory = @LifeStyleCategory,
					UpdatedUserId = @rUserId,
					UpdatedDatetime = sCommon.fGetDate()
				WHERE
					EmployeeId = @rEmployeeId;

					SET @lNextNumber = @@ROWCOUNT;

			END

			-- Calculate Biometric Score,  Biometric Category, Survey Category, MHI Category Start
			IF EXISTS(SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId AND BMIScore IS NOT NULL AND HBA1CScore IS NOT NULL AND LDLScore IS NOT NULL AND  BPScore IS NOT NULL)
			BEGIN
				SELECT @TotalBiometrics = ISNULL(BMIScore, 0) + ISNULL(HBA1CScore, 0) + ISNULL(LDLScore, 0) + ISNULL(BPScore, 0) FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId
				SET @BiometricScore = (100.0 * @TotalBiometrics) / NULLIF(4, 0);			
				SET @BiometricsCategoryIndex = CASE WHEN @BiometricScore IS NULL THEN NULL WHEN @BiometricScore <= 100 THEN 1 WHEN @BiometricScore < 150 THEN 2 ELSE 3 END;
				SET @BiometricsCategory = CASE @BiometricsCategoryIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END;
			END
			IF EXISTS(SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId AND StressScore IS NOT NULL AND LifestyleScore IS NOT NULL)
			BEGIN
				SELECT TOP 1 @SurveyCategory = CASE WHEN StressScore = 3 OR LifestyleScore = 3 THEN 'Alert' WHEN StressScore = 2 OR LifestyleScore = 2 THEN 'SubOptimal' ELSE 'Optimal' END FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId;
			END
			IF(@BiometricsCategory IS NOT NULL AND @SurveyCategory IS NOT NULL)
			BEGIN
				SET @MHICategory =  CASE WHEN @BiometricsCategory = 'Alert' OR @SurveyCategory = 'Alert' THEN 'Alert' 
									WHEN @BiometricsCategory = 'SubOptimal' OR @SurveyCategory = 'SubOptimal' THEN 'SubOptimal' 
									ELSE 'Optimal' END;

				SET @MHICategoryId = CASE  WHEN @MHICategory = 'Alert' THEN 3  WHEN @MHICategory = 'SubOptimal' THEN 2 WHEN @MHICategory = 'Optimal' THEN 1 ELSE 0 END;

				IF(@MHICategoryId > 0)
				BEGIN
					SET @AssignedMHIIndicatorId = (SELECT TOP 1 Id FROM [sWellness].[tStaticMHICategoryIndicator] WHERE Id = @MHICategoryId)
					IF(@AssignedMHIIndicatorId > 0)
					BEGIN
						SET @AssignedProgramId = (SELECT TOP 1 Id FROM [sWellness].[tProgramMaster] WHERE MHIIndicatorId = @AssignedMHIIndicatorId AND CategoryId = 1 AND IsObsolete = 0)
					END
				END
			END
			ELSE
			BEGIN
				SET @MHICategory = 'NotApplicable';
				SET @MHICategoryId = 0;
				SET @AssignedProgramId = 0;
			END

			UPDATE 
				[sWellness].[tMHIScore]
			SET
				ProgramId = @AssignedProgramId,
				Biometrics = @BiometricScore,
				BiometricsCategory = @BiometricsCategory,
				SurveyCategory = @SurveyCategory,
				MHICategory =  @MHICategory,
				MHICategoryId =  @MHICategoryId,
				UpdatedUserId = @rUserId,
				UpdatedDatetime = sCommon.fGetDate()
			WHERE
				EmployeeId = @rEmployeeId;

			SET @lNextNumber = @@ROWCOUNT;

			IF (@lNextNumber > 0)
			BEGIN
				 EXEC sWellness.pInsertMHIScoreHistoryIfChanged
						@rEmployeeId = @rEmployeeId,
						@rUserId     = @rUserId;
			END
 
		COMMIT TRANSACTION
        SELECT CAST(@lNextNumber AS NVARCHAR(20)) 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'Altering Procedure [sWellness].[pConsultationDashboard]...';


GO

ALTER PROCEDURE [sWellness].[pConsultationDashboard]
	@rStoreLocationId int,
	@rFromDate datetime = null,
	@rToDate datetime = null,
	@rCauseId int,
	@rDepartmentId int,
	@rEmployeeCode nvarchar(50)='',
	@rProgramId int = -1,
	@rDoctorId bigint,
	@rGenderId smallint,
	@rStatusId smallint,
	@rOrgId int,
	@rUserId bigint	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	CREATE TABLE #TempTable
	(
		ConsultationId bigint,DepartmentName nvarchar(200),OrganizationDepartmentId int,
		ParticipantCode nvarchar(50),ParticipantName nvarchar(300),GenderId tinyint,
		Gender nvarchar(20),CauseId int,CauseName nvarchar(100),ParticipantType nvarchar(100),
		ParticipantSourceTypeId smallint,EMPType nvarchar(100),LoginTitle nvarchar(100),
		UserId bigint,LocationId int, DoctorId bigint, DoctorName nvarchar(300),
		ProgramId int, ProgramName nvarchar(100)
	)

	INSERT INTO #TempTable
	(
		ConsultationId,DepartmentName,OrganizationDepartmentId,ParticipantCode,ParticipantName,
		GenderId,Gender,CauseId,CauseName,ParticipantType,ParticipantSourceTypeId,EMPType,
		LoginTitle,UserId,LocationId, DoctorId, DoctorName, ProgramId, ProgramName
	)
	SELECT ED.Id as ConsultationId,
	isnull(OD.Title,'N/A') AS DepartmentName,
	EJD.OrganizationDepartmentId,
	CASE
	    WHEN ED.ParticipantSourceTypeId = 95 THEN EM.Code
		ELSE BM.Code
	END AS ParticipantCode,
	CASE
	    WHEN ED.ParticipantSourceTypeId = 95 THEN EM.FirstName + ' ' + isnull(EM.LastName,'')
		ELSE BM.FirstName + ' ' + isnull(BM.LastName,'')
	END AS ParticipantName,
	--ParticipantCode = EM.Code,
	--ParticipantName = EM.FirstName + ' ' + isnull(EM.LastName,''),
	--GenderId = PD.GenderId,
	--Gender = ISNULL(GM.Title,'Not Known'),
	CASE 
		WHEN ED.ParticipantSourceTypeId = 95 THEN PD.GenderId
		ELSE BM.GenderId
	END AS GenderId,
	CASE 
		WHEN ED.ParticipantSourceTypeId = 95 THEN ISNULL(GM.Title,'Not Known')
		ELSE (CASE WHEN ED.GenderId > 0 THEN (select ISNULL(Title,'Not Known') from sCommon.tGenderMaster where Id = ED.GenderId) ELSE ISNULL(GM2.Title,'Not Known') END)
	END AS Gender,
	Isnull(CM.Id,0) As CauseId,
	isnull(CM.Title,'N/A') As CauseName,
	--ISNULL(ETM.Title,'NA') AS ParticipantType,
	CASE ED.ParticipantSourceTypeId
		WHEN 95 THEN ISNULL(ETM.Title,'NA')
		WHEN 1001 THEN 'Dependent'
		WHEN 1009 THEN ISNULL(BTM.Title,'NA')
	END AS ParticipantType,
	ED.ParticipantSourceTypeId,
	CASE ED.ParticipantSourceTypeId WHEN 95 THEN 'Employee'
	WHEN 1001 THEN 'Dependent' WHEN 1009 THEN 'Other' END AS EMPType,
	U.DisplayTitle as LoginTitle,
	UL.UserId,
	ED.StoreLocationId,
	DEM.Id as DoctorId,
	DEM.FirstName + ' ' + isnull(DEM.LastName,'') as DoctorName,
	CASE 
		WHEN ED.ParticipantSourceTypeId = 95 THEN PM.Id
		ELSE PMO.Id
	END AS ProgramId,
	CASE 
		WHEN ED.ParticipantSourceTypeId = 95 THEN ISNULL(PM.Title,'Not Applicable')
		ELSE ISNULL(PMO.Title,'Not Applicable')
	END AS ProgramName
	--PM.Id as ProgramId, ISNULL(PM.Title,'Not Applicable') as ProgramName

	FROM sWellness.tWellnessConsultation ED
	LEFT JOIN sHrm.tEmployeeMaster EM on ED.ParticipantSourceId = EM.Id and ED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tCsrBenefiterMaster BM ON BM.Id = ED.ParticipantSourceId AND ED.ParticipantSourceTypeId = 1009
	LEFT JOIN sWellness.tMHIScore MS ON MS.EmployeeId = EM.Id and MS.EmployeeSourceTypeId = 95
	LEFT JOIN sWellness.tMHIScore MSO ON MS.EmployeeId = BM.Id and MS.EmployeeSourceTypeId = 1009
	LEFT JOIN sWellness.tProgramMaster PM ON PM.Id = MS.ProgramId
	LEFT JOIN sWellness.tProgramMaster PMO ON PM.Id = MSO.ProgramId
	LEFT JOIN sHrm.tEmployeeMaster DEM on DEM.Id = ED.DoctorEmployeeId
	LEFT JOIN sHrm.tEmployeePersonalDetail PD on EM.Id = PD.EmployeeId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = PD.GenderId
	LEFT JOIN sCommon.tGenderMaster GM2 ON GM2.Id = BM.GenderId
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId  
	LEFT JOIN sHrm.tEmployeeTypeMaster ETM on ETM.Id = EJD.EmployeeTypeId
	LEFT JOIN sHrm.tCsrBenefiterTypeMaster BTM ON BM.CSRBenefiterTypeId = BTM.Id
	LEFT JOIN sCommon.tOrganizationDepartmentMaster OD on EJD.OrganizationDepartmentId = OD.Id
	LEFT JOIN sCommon.tDepartmentGroupMaster DGM ON OD.DepartmentGroupId = DGM.Id
	LEFT JOIN sCommon.tFunctionMaster FM ON DGM.FunctionId= FM.Id
	LEFT JOIN sWellness.tWellnessVisitPurposeMaster CM ON CM.Id = ED.CauseId
	INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = ED.StoreLocationId
	INNER JOIN sSecurity.tUser U ON U.Id = ED.CreatedUserId
	INNER JOIN sExamination.tSetupMaster SSM on ED.SetupId = SSM.Id
	INNER JOIN sExamination.tSubTypeMaster ST on SSM.SubTypeId = ST.Id
	INNER JOIN sIp.tStoreLocationMaster SLM on SLM.Id = ED.StoreLocationId
	WHERE ST.MainTypeId = 17 and isnull(IsCancel,0) = 0
	AND (
	((PM.Id = @rProgramId) OR (@rProgramId = -1) OR (@rProgramId = -2 AND ISNULL(PM.Id,0)=0) AND ED.ParticipantSourceTypeId = 95)
	OR
	((PMO.Id = @rProgramId) OR (@rProgramId = -1) OR (@rProgramId = -2 AND ISNULL(PMO.Id,0)=0) AND ED.ParticipantSourceTypeId = 1009)
	)
	AND ((ED.DoctorEmployeeId = @rDoctorId) OR (@rDoctorId = 0))
	AND ((CM.Id = @rCauseId) OR (@rCauseId = -1))
	AND ((ED.StoreLocationId = @rStoreLocationId)OR @rStoreLocationId=0)
	AND (
	@rEmployeeCode = '' OR
		(
			(ED.ParticipantSourceTypeId = 95 AND EM.Code = @rEmployeeCode)
			OR (ED.ParticipantSourceTypeId = 1009 AND BM.Code = @rEmployeeCode)
		)
	)
	AND (EJD.OrganizationDepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND
	(
		(PD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 95)
		OR (BM.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 1009)
		OR @rGenderId = 0
	)
	--AND
	--(
	--	(PD.GenderId = @rGenderId AND ED.ParticipantSourceTypeId = 95)
	--	OR @rGenderId = 0
	--)
	AND(EM.StatusId=@rStatusId OR @rStatusId=0)
	AND ((ED.ConsultationDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
	AND ((ED.ConsultationDate <= (@rToDate)) OR (ISNULL(@rToDate,'') = ''))
	AND ED.OrgId =  @rOrgId
	--AND ED.ParticipantSourceTypeId=95
	AND UL.UserId = @rUserId



	SELECT ISnull(CauseName,'N/A') AS CauseName,
	COUNT(Isnull(CauseId,0)) AS CauseCnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY CauseName
	ORDER BY CauseCnt desc

	SELECT ISnull(DoctorName,'N/A') AS DoctorName,
	COUNT(Isnull(DoctorId,0)) AS DoctorCnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY DoctorName
	ORDER BY DoctorCnt desc

	SELECT Isnull(ProgramName,'') AS ProgramName,
	COUNT(Isnull(ProgramId,0)) AS ProgramCnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY ProgramName
	ORDER BY ProgramCnt desc

	SELECT ISnull(DepartmentName,'') AS DepartmentName,
	COUNT(Isnull(OrganizationDepartmentId,0)) AS DepartmentCnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY OrganizationDepartmentId,DepartmentName
	ORDER BY DepartmentCnt desc

	SELECT ISnull(LoginTitle,'') AS LoginTitle,
	COUNT(Isnull(UserId,0)) AS UserCnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY UserId,LoginTitle
	ORDER BY UserCnt desc

	SELECT ISnull(Gender,'') AS Gender,
	COUNT(Isnull(Gender,'')) AS Gendercnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY Gender
	ORDER BY Gendercnt desc

	SELECT ISnull(EMPType,'') AS EmployeeType,
	COUNT(Isnull(EMPType,'')) AS EmployeeTypecnt
	FROM #TempTable TM
	inner join sIp.tStoreLocationMaster L on TM.LocationId = L.Id
	where L.IsActiveHealth=1
	GROUP BY EMPType
	ORDER BY EMPType desc
	--select * from #TempTable
	DROP TABLE #TempTable
END
GO
PRINT N'Altering Procedure [sWellness].[pGetMHIScoreUpdationList]...';


GO

ALTER   PROCEDURE [sWellness].[pGetMHIScoreUpdationList]
(
	@rOrgId SMALLINT = 0,
	@rProgramId INT = 0,
	@rDepartmentId INT = 0,
	@rLocationId INT = 0,
	@rInsertType SMALLINT = 1,
	@rUserId BIGINT
)
AS
BEGIN	

	;WITH BaseData AS
	(
		SELECT DISTINCT
			MHI.Id,
			MHI.ParticipantSourceTypeId,
			MHI.ParticipantSourceId,

			MHI.BMI,
			MHI.HBA1C,
			MHI.LDL,
			MHI.BPSystolic,
			MHI.BPDiastolic,
			MHI.Stress,
			MHI.LifeStyle,

			MHI.HBA1CCategory,
			MHI.LDLCategory,
			MHI.BMICategory,
			MHI.BPCategory,
			MHI.StressCategory,
			MHI.LifestyleCategory,

			ED.Code AS EmployeeCode,
			ED.EmployeeName,
			MHI.InsertType

		FROM [sWellness].[tMHIScoreUpdation] MHI

		INNER JOIN [sHrm].[vEmployeeDetail] ED 
			ON MHI.ParticipantSourceId = ED.EmployeeId

		LEFT JOIN [sWellness].[tMHIScore] MHS
			ON MHS.EmployeeId = ED.EmployeeId

		INNER JOIN [sIp].[tStoreLocationMaster] SLM 
			ON SLM.LocationId = ED.EmployeeLocationId

		INNER JOIN [sSecurity].[tUserLocation] UL 
			ON UL.StoreLocationId = SLM.Id

		LEFT JOIN [sWellness].[tProgramMaster] PM	
			ON PM.Id = MHS.ProgramId

		WHERE
			(@rProgramId = 0 
			 OR (@rProgramId = 999 AND (MHS.ProgramId = 0 OR MHS.ProgramId IS NULL))
			 OR (@rProgramId <> 0 AND @rProgramId <> 999 AND MHS.ProgramId = @rProgramId))
		AND (@rDepartmentId = 0 OR ED.DepartmentId = @rDepartmentId)
		AND (@rLocationId = 0 OR ED.EmployeeLocationId = @rLocationId)
		AND ED.OrgId = @rOrgId
		AND UL.UserId = @rUserId
	)

	SELECT
		Id,
		ParticipantSourceTypeId,
		ParticipantSourceId,

		-- =========================
		-- SCORE MODE
		-- =========================
		CASE WHEN @rInsertType = 1 THEN BMI END AS BMI,
		CASE WHEN @rInsertType = 1 THEN HBA1C END AS HBA1C,
		CASE WHEN @rInsertType = 1 THEN LDL END AS LDL,
		CASE WHEN @rInsertType = 1 THEN BPSystolic END AS BPSystolic,
		CASE WHEN @rInsertType = 1 THEN BPDiastolic END AS BPDiastolic,
		CASE WHEN @rInsertType = 1 THEN Stress END AS Stress,
		CASE WHEN @rInsertType = 1 THEN LifeStyle END AS LifeStyle,

		-- =========================
		-- CATEGORY MODE (NUMERIC)
		-- =========================
		CASE WHEN @rInsertType = 2 AND HBA1CCategory LIKE '[1-3]' THEN CAST(HBA1CCategory AS SMALLINT) ELSE 0 END AS HBA1CCategory,
		CASE WHEN @rInsertType = 2 AND LDLCategory LIKE '[1-3]' THEN CAST(LDLCategory AS SMALLINT) ELSE 0 END AS LDLCategory,
		CASE WHEN @rInsertType = 2 AND BMICategory LIKE '[1-3]' THEN CAST(BMICategory AS SMALLINT) ELSE 0 END AS BMICategory,
		CASE WHEN @rInsertType = 2 AND BPCategory LIKE '[1-3]' THEN CAST(BPCategory AS SMALLINT) ELSE 0 END AS BPCategory,
		CASE WHEN @rInsertType = 2 AND StressCategory LIKE '[1-3]' THEN CAST(StressCategory AS SMALLINT) ELSE 0 END AS StressCategory,
		CASE WHEN @rInsertType = 2 AND LifestyleCategory LIKE '[1-3]' THEN CAST(LifestyleCategory AS SMALLINT) ELSE 0 END AS LifestyleCategory,

		-- =========================
		-- CATEGORY MODE (NAME)
		-- =========================
		CASE 
			WHEN @rInsertType = 2 AND HBA1CCategory = '1' THEN 'Optimal'
			WHEN @rInsertType = 2 AND HBA1CCategory = '2' THEN 'SubOptimal'
			WHEN @rInsertType = 2 AND HBA1CCategory = '3' THEN 'Alert'
			ELSE NULL
		END AS HBA1CCategoryName,

		CASE 
			WHEN @rInsertType = 2 AND LDLCategory = '1' THEN 'Optimal'
			WHEN @rInsertType = 2 AND LDLCategory = '2' THEN 'SubOptimal'
			WHEN @rInsertType = 2 AND LDLCategory = '3' THEN 'Alert'
			ELSE NULL
		END AS LDLCategoryName,

		CASE 
			WHEN @rInsertType = 2 AND BMICategory = '1' THEN 'Optimal'
			WHEN @rInsertType = 2 AND BMICategory = '2' THEN 'SubOptimal'
			WHEN @rInsertType = 2 AND BMICategory = '3' THEN 'Alert'
			ELSE NULL
		END AS BMICategoryName,

		CASE 
			WHEN @rInsertType = 2 AND BPCategory = '1' THEN 'Optimal'
			WHEN @rInsertType = 2 AND BPCategory = '2' THEN 'SubOptimal'
			WHEN @rInsertType = 2 AND BPCategory = '3' THEN 'Alert'
			ELSE NULL
		END AS BPCategoryName,

		CASE 
			WHEN @rInsertType = 2 AND StressCategory = '1' THEN 'Optimal'
			WHEN @rInsertType = 2 AND StressCategory = '2' THEN 'SubOptimal'
			WHEN @rInsertType = 2 AND StressCategory = '3' THEN 'Alert'
			ELSE NULL
		END AS StressCategoryName,

		CASE 
			WHEN @rInsertType = 2 AND LifestyleCategory = '1' THEN 'Optimal'
			WHEN @rInsertType = 2 AND LifestyleCategory = '2' THEN 'SubOptimal'
			WHEN @rInsertType = 2 AND LifestyleCategory = '3' THEN 'Alert'
			ELSE NULL
		END AS LifeStyleCategoryName,

		EmployeeCode,
		EmployeeName

	FROM BaseData
	WHERE InsertType = @rInsertType
	ORDER BY Id DESC

END
GO
PRINT N'Altering Procedure [sWellness].[pAddOrUpdateMHIUpdationBulk]...';


GO
ALTER PROCEDURE [sWellness].[pAddOrUpdateMHIUpdationBulk]
( 
    @rUserId BIGINT,
	@rLocationId INT,
	@rInsertType SMALLINT,
	@rLastUpdateType SMALLINT,
    @rEmployeeMHIBulkList [sWellness].[udt_MHIScoreUpdation] READONLY,
    @Result INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ModifiedRows INT = 0;

    MERGE [sWellness].[tMHIScoreUpdation] AS T
    USING
    (
        SELECT 
            E.Id AS ParticipantSourceId,
            M.BMI,
            M.HBA1C,
            M.LDL,
            M.SystolicBP,
            M.DiastolicBP,
            M.Stress,
            M.LifeStyle
        FROM @rEmployeeMHIBulkList M
        INNER JOIN [sHrm].[tEmployeeMaster] E
            ON E.Code = M.EmployeeCode
    ) AS S
    ON T.ParticipantSourceId = S.ParticipantSourceId

    WHEN MATCHED THEN
        UPDATE SET
            T.BMI = S.BMI,
            T.HBA1C = S.HBA1C,
            T.LDL = S.LDL,
            T.BPSystolic = S.SystolicBP,
            T.BPDiastolic = S.DiastolicBP,
            T.Stress = S.Stress,
            T.LifeStyle = S.LifeStyle,
			T.LocationId = @rLocationId,
			T.InsertType = @rInsertType,
			T.LastUpdateType = @rLastUpdateType,
            T.UpdatedUserId = @rUserId,
            T.UpdatedDateTime = sCommon.fGetDate()

    WHEN NOT MATCHED THEN
        INSERT
        (
            ParticipantSourceTypeId,
            ParticipantSourceId,
            BMI,
            HBA1C,
            LDL,
            BPSystolic,
            BPDiastolic,
            Stress,
            LifeStyle,
			LocationId,
			InsertType,
			LastUpdateType,
            CreatedUserId,
            CreatedDateTime
        )
        VALUES
        (
            95,
            S.ParticipantSourceId,
            S.BMI,
            S.HBA1C,
            S.LDL,
            S.SystolicBP,
            S.DiastolicBP,
            S.Stress,
            S.LifeStyle,
			@rLocationId,
			@rInsertType,
			@rLastUpdateType,
            @rUserId,
            sCommon.fGetDate()
        );

    SET @ModifiedRows = @@ROWCOUNT;
    SET @Result = @ModifiedRows;
END
GO
PRINT N'Altering Procedure [sWellness].[pGetMHIScoreUpdation]...';


GO



ALTER   PROCEDURE [sWellness].[pGetMHIScoreUpdation]
(
	@rId INT
)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN		
	IF EXISTS (SELECT 1 FROM [sWellness].[tMHIScoreUpdation] WHERE Id = @rId)
	BEGIN	
		SELECT 
			MHI.Id,
			MHI.ParticipantSourceTypeId,
			MHI.ParticipantSourceId,
			BMI,
			HBA1C,
			LDL,
			BPSystolic,
			BPDiastolic,
			Stress,
			LifeStyle,
			InsertType,
			LocationId,
			CASE WHEN MHI.BMICategory LIKE '[1-3]' THEN CAST(MHI.BMICategory AS SMALLINT) ELSE 0 END AS BMICategory,
			CASE WHEN MHI.HBA1CCategory LIKE '[1-3]' THEN CAST(MHI.HBA1CCategory AS SMALLINT) ELSE 0 END AS HBA1CCategory,
			CASE WHEN MHI.LDLCategory LIKE '[1-3]' THEN CAST(MHI.LDLCategory AS SMALLINT) ELSE 0 END AS LDLCategory,
			CASE WHEN MHI.BPCategory LIKE '[1-3]' THEN CAST(MHI.BPCategory AS SMALLINT) ELSE 0 END AS BPCategory,
			CASE WHEN MHI.StressCategory LIKE '[1-3]' THEN CAST(MHI.StressCategory AS SMALLINT) ELSE 0 END AS StressCategory,
			CASE WHEN MHI.LifestyleCategory LIKE '[1-3]' THEN CAST(MHI.LifestyleCategory AS SMALLINT) ELSE 0 END AS LifestyleCategory,
			ED.Code AS EmployeeCode,
			ED.EmployeeName
		FROM 
			[sWellness].[tMHIScoreUpdation] mhi
		INNER JOIN 
			[sHrm].[vEmployeeDetail] ED 
		ON 
			mhi.ParticipantSourceId = ED.EmployeeId
		WHERE 
			MHI.Id=@rId	
		ORDER BY 
			MHI.Id DESC 
	END
	ELSE
	BEGIN
		SELECT -101 as Result
	end
END
GO
PRINT N'Altering Procedure [sWellness].[pMHIScoreUpdationAddUpdate]...';


GO

ALTER PROCEDURE [sWellness].[pMHIScoreUpdationAddUpdate]
	@rId bigint=0,
	@rParticipantSourceTypeId smallint,
	@rParticipantSourceId bigint,
	@rBMI decimal(10,2),
	@rHBA1C decimal(10,2),
	@rLDL decimal(10,2),
	@rBPSystolic decimal(10,2),
	@rBPDiastolic decimal(10,2),
	@rStress decimal(10,2),
	@rLifeStyle decimal(10,2),
	@rInsertType SMALLINT,
	@rLastUpdateType SMALLINT,
	@rLocationId INT,
	@rUserId bigint
 WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	BEGIN TRY

		--IF  EXISTS (SELECT 1 FROM [sWellness].[tMHIScoreUpdation] WHERE ParticipantSourceId = @rParticipantSourceId  and Id<>@rId)
		--BEGIN	 
		--	SELECT -102 AS RESULT
		--	return
		--END
		BEGIN TRAN
			DECLARE @lNextNumber BIGINT 
			IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScoreUpdation] WHERE ParticipantSourceId = @rParticipantSourceId and ParticipantSourceTypeId = @rParticipantSourceTypeId)
					BEGIN
					INSERT INTO [sWellness].[tMHIScoreUpdation]
							(
							ParticipantSourceTypeId,
							ParticipantSourceId,
							BMI,
							HBA1C,
							LDL,
							BPSystolic,
							BPDiastolic,
							Stress,
							LifeStyle,
							InsertType,
							LastUpdateType,
							LocationId,
							CreatedUserId,
							CreatedDateTime
							)
							values
							(
							@rParticipantSourceTypeId,
							@rParticipantSourceId,
							@rBMI,
							@rHBA1C,
							@rLDL,
							@rBPSystolic,
							@rBPDiastolic,
							@rStress,
							@rLifeStyle,
							@rInsertType,
							@rLastUpdateType,
							@rLocationId,
							@rUserId,
							sCommon.fGetDate()
							)
	                SET @lNextNumber = SCOPE_IDENTITY();
					END
			ELSE
				BEGIN
					--IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScoreUpdation] WHERE Id=@rId)
					--	BEGIN	 
					--		SELECT -101 AS RESULT
					--		return
					--	END
						Update [sWellness].[tMHIScoreUpdation]
							Set 
								BMI=@rBMI,
								HBA1C =@rHBA1C,
								LDL=@rLDL,
								BPSystolic=@rBPSystolic,
								BPDiastolic =@rBPDiastolic,
								Stress = @rStress,
								LifeStyle = @rLifeStyle,
								InsertType = @rInsertType,
								LastUpdateType = @rLastUpdateType,
								LocationId = @rLocationId,
								UpdatedUserId = @rUserId,
								UpdatedDateTime = sCommon.fGetDate()
							Where ParticipantSourceId=@rParticipantSourceId 
								  and ParticipantSourceTypeId = @rParticipantSourceTypeId

							SET @lNextNumber=1
				END
		COMMIT TRAN
		Select @lNextNumber as Result
	END TRY

	BEGIN CATCH
		ROLLBACK TRAN
		Select -105 as Result
		select ERROR_MESSAGE()
	END CATCH		
END
GO
PRINT N'Altering Procedure [sWellness].[pConsultationAdd]...';


GO
  
ALTER PROCEDURE [sWellness].[pConsultationAdd]  
@rId bigint,  
@rOrgId smallint,  
@rParticipantSourceTypeId smallint,  
@rParticipantSourceId bigint,  
@rSetupId bigint,  
@rMainTypeId int,  
@rConsultationDate date,  
@rDoctorFlag int = null,  
@rDoctorEmployeeId bigint  = NULL,  
@rStatusId int,  
@rStoreLocationId bigint,  
@rCauseId int = null,  
@rConsultationNotes nvarchar(2000) = '',  
@rConsultationRemarks nvarchar(2000) = '',  
@rConsultationTime nvarchar(50) = '',  
@rConsultationOutTime nvarchar(50) = '',  
@rOtherName nvarchar(250) = '',  
@rOtherAge tinyint,  
@rOtherMonth tinyint,  
@rOtherGenderId tinyint,  
@rEmailAddress nvarchar(100) = '',  
@rMobileNumber nvarchar(100) = null,  
@rCreatedUserId bigint,  
@rUpdatedUserId bigint = 0  
AS  
SET NOCOUNT ON  
BEGIN  
declare @trancount int;  
  
  
 BEGIN TRY    
        begin transaction  
 set @trancount = @@trancount;          
  
  declare @exceptiondetail nvarchar(max)  
  if @rCreatedUserId = 0  
  begin  
   SELECT -101 AS RESULT  
   return  
  end  
  if @rParticipantSourceId = 0  
  begin  
   SELECT -102 AS RESULT  
   return  
  end  
  if @rParticipantSourceTypeId = 0  
  begin  
   SELECT -103 AS RESULT  
   return  
  end     
      
  IF(@rDoctorEmployeeId <= 0)  
   SET @rDoctorEmployeeId = NULL  
     
  DECLARE @lNextNumber bigint,@lEmployeeDesignationId int  
  
  IF (@rId = 0)  
  BEGIN  
   INSERT INTO [sWellness].[tWellnessConsultation]   
   (  
    OrgId,ParticipantSourceTypeId,ParticipantSourceId,ConsultationDate,  
    DoctorEmployeeId,SetupId,CauseId,StatusId,StoreLocationId,ConsultationNotes,ConsultationRemarks,  
    ConsultationTime,ConsultationOutTime,CreatedUserId,CreatedDateTime,  
    UpdatedUserId,UpdatedDateTime,OtherName,Age,Months,GenderId,EmailAddress,MobileNumber  
   )  
   VALUES  
   (  
    @rOrgId,@rParticipantSourceTypeId,@rParticipantSourceId,@rConsultationDate,  
    @rDoctorEmployeeId,@rSetupId,@rCauseId,1,@rStoreLocationId,@rConsultationNotes,@rConsultationRemarks,  
    @rConsultationTime,@rConsultationOutTime,@rCreatedUserId,sCommon.fGetDate(),  
    @rUpdatedUserId,sCommon.fGetDate(),@rOtherName,@rOtherAge,@rOtherMonth,@rOtherGenderId,@rEmailAddress,@rMobileNumber  
   )  
     
   select @lNextNumber = SCOPE_IDENTITY()  
  
   declare @cnt bigint = 0,@prefix varchar(100),@Title varchar(100),@cn varchar(300)  
  
   select @Title = Title from sExamination.tSetupMaster where Id = @rSetupId  
  
   select @cnt = Max(Right(ISNULL(ConsultationNumber,00000),13)) from [sWellness].[tWellnessConsultation] where isnull(ConsultationNumber,'') <> ''  
   and DATEDIFF(day,CONVERT(date, CreatedDateTime, 105),CONVERT(date, sCommon.fGetDate(), 105))>=0 and SetupId = @rSetupId  
   and StoreLocationId = @rStoreLocationId  
  
   if len(@cnt)=12  
   begin  
   select @cnt = Right(isnull(@cnt,00000),4)  
   end  
   else if(len(@cnt)=13)  
   begin  
   select @cnt = Right(isnull(@cnt,00000),5)  
   end  
   else  
   begin  
   select @cnt = Right(isnull(@cnt,00000),4)  
   end  
     
   if(@cnt=9999)  
   begin  
    select @cnt = @cnt + 1 +(select count(*) from [sWellness].[tWellnessConsultation]   
    where isnull(ConsultationNumber,'') <> '' and   
    DATEDIFF(day,CONVERT(date, CreatedDateTime, 105),CONVERT(date, sCommon.fGetDate(), 105))>=0   
    and SetupId = @rSetupId and StoreLocationId = @rStoreLocationId)  
   end  
   else  
   begin  
   select @cnt = @cnt + 1  
   end  
  
   select @prefix = case when sCommon.fGetIntIdForOrg(17,@rOrgId) = @rSetupId then  
   'WC-' + sCommon.fGetFormattedDate()  + RIGHT(100000 + (@cnt) ,5) else '' end  
  
   update [sWellness].[tWellnessConsultation] set ConsultationNumber = @prefix where Id = @lNextNumber  
  END  
  ELSE  
  BEGIN  
   SET @lNextNumber = @rId  
   UPDATE [sWellness].[tWellnessConsultation] SET OrgId = @rOrgId,ParticipantSourceTypeId  = @rParticipantSourceTypeId,  
   ParticipantSourceId  = @rParticipantSourceId, ConsultationDate = @rConsultationDate,  
   DoctorEmployeeId = case when isnull(@rDoctorFlag,0) = 1 then DoctorEmployeeId else @rDoctorEmployeeId end,  
   CauseId = @rCauseId,ConsultationNotes=@rConsultationNotes,ConsultationRemarks=@rConsultationRemarks,  
   ConsultationTime=@rConsultationTime,ConsultationOutTime=@rConsultationOutTime,  
   UpdatedUserId =  case when @rUpdatedUserId>0 then @rUpdatedUserId else @rCreatedUserId end,  
   UpdatedDateTime = sCommon.fGetDate(),  
   OtherName=@rOtherName,Age=@rOtherAge,Months=@rOtherMonth,GenderId=@rOtherGenderId,  
   EmailAddress=@rEmailAddress  ,MobileNumber=@rMobileNumber
   WHERE Id = @rId  
  END  
  SELECT @lNextNumber AS Result    
    
      commit tran;  
 END TRY  
 BEGIN CATCH  
 declare @error int, @message varchar(4000), @xstate int,@username nvarchar(200);  
  select @error = ERROR_NUMBER(),  
               @message = ERROR_MESSAGE(),   
               @xstate = XACT_STATE();  
  set @username =(select Top 1 ISNULL(LoginTitle,'') from sSecurity.tUser where id=ISNULL(CreatedUserId,0))  
  --if @xstate = -1  
  --          rollback;  
  --      if @xstate = 1 and @trancount = 0  
  --          rollback  
  --      if @xstate = 1 and @trancount > 0  
            rollback transaction;  
  
  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 @rOrgId,'Consultation_Main_DBError',5000,@exceptiondetail,sCommon.fGetDate(),@rCreatedUserId   
  SELECT -1 AS RESULT  
  return  
 END CATCH   
   
END
GO
PRINT N'Altering Procedure [sWellness].[pGetConsultationFullViewDatas]...';


GO

ALTER PROCEDURE [sWellness].[pGetConsultationFullViewDatas]
@rConsultationId bigint
as
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	SELECT 
		CASE WHEN ParticipantSourceTypeId = 95 THEN EM.Code WHEN ParticipantSourceTypeId = 1009 THEN CSR.Code ELSE '-' END AS EmployeeCode,
		CASE WHEN ParticipantSourceTypeId = 95 THEN ISNULL(EM.FirstName, '') + '' + ISNULL(EM.LastName, '') WHEN ParticipantSourceTypeId = 1009 THEN ISNULL(CSR.FirstName, '') + '' + ISNULL(CSR.LastName, '') ELSE '-' END AS EmployeeName,
		WC.ConsultationNumber 
	from sWellness.tWellnessConsultation WC
	LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = WC.ParticipantSourceId and WC.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tCsrBenefiterMaster CSR ON CSR.Id = WC.ParticipantSourceId and WC.ParticipantSourceTypeId = 1009
	where WC.Id = @rConsultationId

	declare @tbltmpview table(tid int identity(1,1),col1 varchar(max),col2 varchar(max))	
	insert into @tbltmpview
	select 'Height',Convert(varchar(50),GTCD.ParameterValue) + ' Cm'	
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 502
	OPTION (RECOMPILE)

	insert into @tbltmpview
	select 'Weight',Convert(varchar(50),GTCD.ParameterValue) + ' Cm'	
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 501
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'BMI',Convert(varchar(50),GTCD.ParameterValue) + ' kg/m2'
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 503
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'BPSys',Convert(varchar(50),GTCD.ParameterValue) + ' mmHg'
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 506
	OPTION (RECOMPILE)

	insert into @tbltmpview
	select 'BPDia',Convert(varchar(50),GTCD.ParameterValue) + ' mmHg'
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 507
	OPTION (RECOMPILE)

	select col1 as Parameter, col2 as [Value] from @tbltmpview
	OPTION (RECOMPILE)

	SELECT TP.Title as Parameter,TRD.ServiceValue as Result,TRD.Remark as Remark
	FROM sWellness.tConsultationTestRequestDetail TRD
	INNER JOIN sWellness.tConsultationTestRequest 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 = @rConsultationId AND TP.IsObsolete = 0
	OPTION (RECOMPILE)

	SELECT CASE AA.WeekNo WHEN 1 THEN 'Week 1' WHEN 2 THEN 'Week 2' WHEN 3 THEN 'Week 3' WHEN 4 THEN 'Week 4' END AS [WeekNo],
	CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN 'Custom' ELSE 'Pre Define' END AS [Type],
	WAC.Title as [WellnessActivityCategory], WA.ActivityName as [WellnessActivity],
	CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN ISNULL(AA.WellnessActivityCustom,'') 
        ELSE ISNULL(WAT.[Name],'') END as [WellnessActivityTask],
		CAST(ISNULL(AA.TargetValue, 0) AS NVARCHAR(50)) AS [TargetValue],
 CASE AA.UnitId WHEN 1 THEN 'Steps' WHEN 2 THEN 'Min' WHEN 3 THEN 'ML' WHEN 4 THEN 'Times' END AS [UnitNo],
 CASE AA.FrequencyTypeId WHEN 1 THEN 'Daily' WHEN 2 THEN 'Weekly' END AS Frequency,
 CAST(AA.FrequencyCount AS NVARCHAR(50)) AS [FrequencyCount],
 CASE WHEN AA.WeekStart IS NULL THEN 'Assigned' WHEN GETDATE() < AA.WeekStart THEN 'Assigned'
			WHEN GETDATE() BETWEEN AA.WeekStart AND AA.WeekEnd THEN 'Active'
			WHEN GETDATE() > AA.WeekEnd THEN 'Expired' ELSE '-'
		END AS [Status]
	from sWellness.tAssignedActivity AA
	INNER JOIN sWellness.tWellnessActivityCategoryMaster WAC on WAC.Id = AA.WellnessActivityCategoryId
	INNER JOIN sWellness.tWellnessActivityMaster WA on WA.ActivityId = AA.WellnessActivityId
	LEFT JOIN sWellness.tWellnessActivityTaskMaster WAT on WAT.Id = AA.WellnessActivityTaskId
	where ConsultationId = @rConsultationId
	OPTION (RECOMPILE)

	SELECT Isnull(INS.FieldRemark,'') as Questions,
			convert(varchar,ISNULL(AFF.AdditionalFieldResponse,'')) as Answers 
	from sExamination.tAdditionalFieldSetup InS
	LEFT JOIN [sWellness].[tConsultationAdditionalFieldDetails] AFF ON InS.Id= AFF.AdditionalFieldSetupId --and (@rSourceId <> 0 OR (@rSourceId = 0 and Isnull([AdditionalFieldId],0)=0))
	Where ISNULL(InS.SourceTypeId, 0) = 3 and ISNULL(InS.ExaminationTypeId, 0) = 17
	AND (Isnull([AdditionalFieldId],0) = (Select Top 1 Id from [sWellness].[tConsultationAdditionalFieldMaster] where ConsultationId = @rConsultationId))
	ORDER BY FieldOrder
	OPTION (RECOMPILE)

	SELECT Isnull(WC.ConsultationNotes,'') as ConsultationNotes,
			Isnull(WC.ConsultationRemarks,'') as ConsultationRemarks 
	from sWellness.tWellnessConsultation WC
	Where WC.Id = @rConsultationId

	OPTION (RECOMPILE)
	SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
END
GO
PRINT N'Altering Procedure [sWellness].[pListEmployeeConsultionHistory]...';


GO
ALTER PROCEDURE [sWellness].[pListEmployeeConsultionHistory]    
(    
	@rEmployeeId BIGINT
)    
AS    
SET NOCOUNT ON    
BEGIN    
	SELECT
		WC.Id,
		WC.StatusId,
		WC.ConsultationNumber,
		CASE WHEN WC.ConsultationDate IS NULL THEN '-' ELSE CONVERT(VARCHAR(15),WC.ConsultationDate,103) END AS ConsultationDate,
		EEM.DepartmentName AS DepartmentName,
		ISNULL(EEM2.EmployeePrefix + ' ' + EEM2.FirstName + ' ' + EEM2.LastName,Users.DisplayTitle) AS ConsultedBy
	FROM 
		[sWellness].[tWellnessConsultation] WC
	LEFT JOIN
		[sHrm].[vExtEmployeeMaster] EEM
	ON
		EEM.Id = WC.ParticipantSourceId
	LEFT JOIN
		[sHrm].[tEmployeeMaster] EEM2
	ON
		EEM2.Id = WC.DoctorEmployeeId
	LEFT JOIN 
		sSecurity.tuser Users
	ON 
		Users.Id = wc.CreatedUserId
	WHERE
		ParticipantSourceId = @rEmployeeId
END
GO
PRINT N'Altering Procedure [sWellness].[pMobGetEmployeeConsultationViewDatas]...';


GO
ALTER PROCEDURE [sWellness].[pMobGetEmployeeConsultationViewDatas]
@rConsultationId bigint
as
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
begin
	declare @lOrgId int
	declare @lVitalRes varchar(max)='',@lTestRes varchar(max)='',@lTaskRes varchar(max)='',
			@lAdditionalFieldRes varchar(max)='',@lNotesRes varchar(max)=''
	declare @lVitalHead varchar(max)='',@lTestHead varchar(max)='',@lTaskHead varchar(max)='',
			@lAdditionalFieldHead varchar(max)='',@lNotesHead varchar(max)=''

	select @lOrgId = OrgId from sWellness.tWellnessConsultation where Id = @rConsultationId	

	declare @tbltmpview table(tid int identity(1,1),col1 varchar(max),col2 varchar(max))	
	insert into @tbltmpview
	select 'Height',Convert(varchar(50),GTCD.ParameterValue) + ' Cm'	
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 502
	OPTION (RECOMPILE)

	insert into @tbltmpview
	select 'Weight',Convert(varchar(50),GTCD.ParameterValue) + ' Cm'	
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 501
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'BMI',Convert(varchar(50),GTCD.ParameterValue) + ' kg/m2'
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 503
	OPTION (RECOMPILE)

	insert into @tbltmpview			
	select 'BPSys',Convert(varchar(50),GTCD.ParameterValue) + ' mmHg'
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 506
	OPTION (RECOMPILE)

	insert into @tbltmpview
	select 'BPDia',Convert(varchar(50),GTCD.ParameterValue) + ' mmHg'
	from sWellness.tGeneralTemplateConsultation GTC 
	INNER JOIN sWellness.tGeneralTemplateConsultationDetail GTCD ON GTCD.GeneralTemplateConsultationId = GTC.Id
	INNER JOIN sExamination.tGeneralTemplateParameter GTP ON GTP.Id = GTCD.GeneralTemplateParameterId
	where SourceId = @rConsultationId and GTP.StaticGeneralTemplateParameterId = 507
	OPTION (RECOMPILE)

	select @lVitalHead = @lVitalHead + '<div class="contentHolder box-body box-solid gridviewfont" style=" padding: 10px;background: #fff;border-radius: 5px;margin: 10px;">
	<div class="himsBoxHeader"><div class="leftdiv"> </div><div class="himsBoxTitle pTop5" style="padding: 10px 0px;">
    <div class="headerText"><div class="fLeft"> <span style="color:#7eacd3;font-weight:bold;font-size: 30px;">Vital</span> </div></div>
    <div class="fRight"></div></div></div><div class="himsBoxContent"><div>
    <table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse; border: 0px solid; font-size: 30px;">
    <tbody><tr><th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Parameter</span></th>
	<th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"><span>Value</span></th></tr>'
	OPTION (RECOMPILE)

	select @lVitalRes = @lVitalRes + '<tr>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col1,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><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 = @lVitalHead + @lVitalRes
	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 sWellness.tConsultationTestRequestDetail TRD
	INNER JOIN sWellness.tConsultationTestRequest 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 = @rConsultationId AND TP.IsObsolete = 0
	OPTION (RECOMPILE)

	select @lTestHead = @lTestHead + '<div class="contentHolder box-body box-solid gridviewfont" style=" padding: 10px;background: #fff;border-radius: 5px;margin: 10px;">
    <div class="himsBoxHeader"><div class="leftdiv"> </div><div class="himsBoxTitle pTop5" style="padding: 10px 0px;">
    <div class="headerText"><div class="fLeft"> <span style="color:#7eacd3;font-weight:bold;font-size: 30px;">Test</span></div>
    </div><div class="fRight"></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; border: 0px solid; font-size: 30px;">
	<tbody><tr><th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Parameter</span></th>
	<th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"><span>Result</span></th>
	<th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"><span>Remark</span></th></tr>'
	OPTION (RECOMPILE)

	select @lTestRes = @lTestRes + '<tr>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;">' + isnull(col1,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col2,'') + '" class="boxEllips" style="display:inline-block;">' + isnull(col2,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><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
	OPTION (RECOMPILE)

	declare @tbltmpTask table(tid int identity(1,1),col1 varchar(max),col2 varchar(max),col3 varchar(max)
									,col4 varchar(max),col5 varchar(max),col6 varchar(max),col7 varchar(max),col8 varchar(max)
									,col9 varchar(max),col10 varchar(max))
	insert into @tbltmpTask
	SELECT CASE AA.WeekNo WHEN 1 THEN 'Week 1' WHEN 2 THEN 'Week 2' WHEN 3 THEN 'Week 3' WHEN 4 THEN 'Week 4' END AS WeekName,
	CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN 'Custom' ELSE 'Pre Define' END AS TypeName,
	WAC.Title,WA.ActivityName,CASE WHEN ISNULL(AA.IsCustomActivityTask,0) = 1 THEN ISNULL(AA.WellnessActivityCustom,'') 
        ELSE ISNULL(WAT.[Name],'') END as WellnessActivityTask,
		ISNULL(AA.TargetValue, 0) as TargetValue,
 CASE AA.UnitId WHEN 1 THEN 'Steps' WHEN 2 THEN 'Min' WHEN 3 THEN 'ML' WHEN 4 THEN 'Times' END AS UnitNo,
 CASE AA.FrequencyTypeId WHEN 1 THEN 'Daily' WHEN 2 THEN 'Weekly' END AS FrequencyType,
 AA.FrequencyCount,
 CASE WHEN AA.WeekStart IS NULL THEN 'Assigned' WHEN GETDATE() < AA.WeekStart THEN 'Assigned'
			WHEN GETDATE() BETWEEN AA.WeekStart AND AA.WeekEnd THEN 'Active'
			WHEN GETDATE() > AA.WeekEnd THEN 'Expired' ELSE '-'
		END AS [Status]
	from sWellness.tAssignedActivity AA
	INNER JOIN sWellness.tWellnessActivityCategoryMaster WAC on WAC.Id = AA.WellnessActivityCategoryId
	INNER JOIN sWellness.tWellnessActivityMaster WA on WA.ActivityId = AA.WellnessActivityId
	LEFT JOIN sWellness.tWellnessActivityTaskMaster WAT on WAT.Id = AA.WellnessActivityTaskId
	where ConsultationId = @rConsultationId
	OPTION (RECOMPILE)

	select @lTaskHead = @lTaskHead + '<div class="contentHolder box-body box-solid gridviewfont" style=" padding: 10px;background: #fff;border-radius: 5px;margin: 10px;">
	<div class="himsBoxHeader"><div class="leftdiv"> </div><div class="himsBoxTitle pTop5" style="padding: 10px 0px;">
	<div class="headerText"><div class="fLeft"> <span style="color:#7eacd3;font-weight:bold;font-size: 30px;">Tasks</span> </div>
	</div><div class="fRight"></div></div></div><div class="himsBoxContent" style="margin-top: -4px"><div class="table-responsive mb-4">
   <table class="table table-bordered table-striped mb-0" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse; border: 0px solid; font-size: 30px;">
   <tbody><tr><th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Week No</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Type</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Wellness Activity Category</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Wellness Activity</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Wellness Activity Task</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Target Value</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Unit</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Frequency</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Frequency Count</span></th>
   <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Status</span></th></tr>'
	OPTION (RECOMPILE)

	select @lTaskRes = @lTaskRes + '<tr>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col1,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col1,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col2,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col2,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col3,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col3,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col4,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col4,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col5,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col5,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col6,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col6,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col7,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col7,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col8,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col8,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col9,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col9,'') + '</span> </td>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col10,'') + '" class="boxEllips" style="display:inline-block;width:300px;">' + isnull(col10,'') + '</span> </td>
	</tr>' from @tbltmpTask
	OPTION (RECOMPILE)

	select @lTaskRes = @lTaskRes + '</tbody></table></div></div></div>'
	select @lTaskRes = @lTaskHead + @lTaskRes
	OPTION (RECOMPILE)

	declare @tbltmpAdditionalField table(tid int identity(1,1),col1 varchar(max),col2 varchar(max))
	insert into @tbltmpAdditionalField
	SELECT Isnull(INS.FieldRemark,'') as FieldRemark,
			convert(varchar,ISNULL(AFF.AdditionalFieldResponse,'')) as AdditionalFieldResponse 
	from sExamination.tAdditionalFieldSetup InS
	LEFT JOIN [sWellness].[tConsultationAdditionalFieldDetails] AFF ON InS.Id= AFF.AdditionalFieldSetupId --and (@rSourceId <> 0 OR (@rSourceId = 0 and Isnull([AdditionalFieldId],0)=0))
	Where ISNULL(InS.SourceTypeId, 0) = 3 and ISNULL(InS.ExaminationTypeId, 0) = 17
	AND (Isnull([AdditionalFieldId],0) = (Select Top 1 Id from [sWellness].[tConsultationAdditionalFieldMaster] where ConsultationId = @rConsultationId))
	ORDER BY FieldOrder
	OPTION (RECOMPILE)

	select @lAdditionalFieldHead = @lAdditionalFieldHead + '<div class="contentHolder box-body box-solid gridviewfont" style=" padding: 10px;background: #fff;border-radius: 5px;margin: 10px;">
    <div class="himsBoxHeader"><div class="leftdiv"> </div><div class="himsBoxTitle pTop5" style="padding: 10px 0px;"><div class="headerText">
    <div class="fLeft"> <span style="color:#7eacd3;font-weight:bold;font-size: 30px;">Q & A</span> </div></div><div class="fRight"></div></div></div>
    <div class="himsBoxContent"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse; border: 0px solid; font-size: 30px;">
	<tbody><tr><th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Questions</span></th>
    <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Answers</span></th></tr>'
	OPTION (RECOMPILE)

	select @lAdditionalFieldRes = @lAdditionalFieldRes + '<tr>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col1,'') + '" class="boxEllips">' + isnull(col1,'') + '</span> </td>	
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col2,'') + '" class="boxEllips">' + isnull(col2,'') + '</span> </td>
	</tr>' from @tbltmpAdditionalField
	OPTION (RECOMPILE)

	select @lAdditionalFieldRes = @lAdditionalFieldRes + '</tbody></table></div></div></div>'
	select @lAdditionalFieldRes = @lAdditionalFieldHead + @lAdditionalFieldRes

	declare @tbltmpNotes table(tid int identity(1,1),col1 varchar(max),col2 varchar(max))
	insert into @tbltmpNotes
	SELECT Isnull(WC.ConsultationNotes,'') as ConsultationNotes,
			Isnull(WC.ConsultationRemarks,'') as ConsultationRemarks 
	from sWellness.tWellnessConsultation WC
	Where WC.Id = @rConsultationId
	OPTION (RECOMPILE)

	select @lNotesHead = @lNotesHead + '<div class="contentHolder box-body box-solid gridviewfont" style=" padding: 10px;background: #fff;border-radius: 5px;margin: 10px;">
    <div class="himsBoxHeader"><div class="leftdiv"> </div><div class="himsBoxTitle pTop5" style="padding: 10px 0px;"><div class="headerText">
    <div class="fLeft"> <span style="color:#7eacd3;font-weight:bold;font-size: 30px;">Notes</span> </div></div><div class="fRight"></div></div></div>
    <div class="himsBoxContent"><div>
	<table class="table table-bordered table-striped" cellspacing="0" rules="all" border="1" style="width:100%;border-collapse:collapse; border: 0px solid; font-size: 30px;">
	<tbody><tr><th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Consultation Notes</span></th>
    <th style="border-left: 0px solid !important;border-right: 0px solid !important;padding: 5px 0px;text-align: left;border: 2px solid;" scope="col"> <span>Consultation Remarks</span></th></tr>'
	OPTION (RECOMPILE)

	select @lNotesRes = @lNotesRes + '<tr>
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col1,'') + '" class="boxEllips">' + isnull(col1,'') + '</span> </td>	
	<td style="border: 0px solid;padding: 5px 0px;color: #787878;"><span title="' + isnull(col2,'') + '" class="boxEllips">' + isnull(col2,'') + '</span> </td>
	</tr>' from @tbltmpNotes
	OPTION (RECOMPILE)

	select @lNotesRes = @lNotesRes + '</tbody></table></div></div></div>'
	select @lNotesRes = @lNotesHead + @lNotesRes
	OPTION (RECOMPILE)

	select '<HTML>
   <HEAD>
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <STYLE>
         @media (max-width: 767px) {
         .himsBoxContent{
         overflow-x: auto;
         } 
         .table {
         font-size: 10px !important;
         }
         .fLeft span {
         font-size: 12px !important;
         }
         .boxEllips {
         width: unset !important;
         white-space: normal;
         }
         .table th,
         .table td {
         padding: 5px !important;
         }
         }
      </STYLE>
   </HEAD><body style="font-family: sans-serif;background-color: #e9e9e9;">' + isnull(@lVitalRes,'') + isnull(@lTestRes,'') 
   + isnull(@lTaskRes,'') + isnull(@lAdditionalFieldRes,'') + isnull(@lNotesRes,'') + '</body></HTML>'as Res

	OPTION (RECOMPILE)
	SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
end
GO
PRINT N'Altering Procedure [dbo].[prc_AutoImportEmployees_TKM]...';


GO
ALTER PROCEDURE [dbo].[prc_AutoImportEmployees_TKM]
@rOrgId int,                  
@rStrXML nvarchar(max),                  
@rCreatedUserId bigint,                  
@rTemplateId int                  
as                  
begin                  
 declare @loXML xml,@res varchar(50) ,@rEmployeeTypeId int,@rEmployeeSubTypeId int,@rEmployeeTypeGroupId int         
 BEGIN TRY            
  set @rStrXML = Replace(@rStrXML,'&nbsp;','')                  
  set @loXML = CAST(@rStrXML as xml)                  
 END TRY                  
 BEGIN CATCH                  
  update	[sHrm].[tWebApiImportEmployee]  set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
  select @res = 0                  
  return                  
 END CATCH                  
 DECLARE @tblinsertedlocationid TABLE(autoid int identity(1,1),Id int,Title nvarchar(200),Code nvarchar(50));                 
 BEGIN TRY                  
      
  declare @tblEmployee table                  
  (                  
   tid int identity(1,1),t_EmpCode varchar(300),t_UserName varchar(300),t_Status varchar(100),t_FirstName varchar(300),                  
   t_MiddleName varchar(300),t_LastName varchar(300),t_Business varchar(500),t_BusinessId int,                  
   t_SubBusiness varchar(500),t_VerticalId int,t_CompanyGroup varchar(500),t_CompanyGroupId int,t_CompanyName varchar(500),t_CompanyId int,                  
   t_DateOfBirth varchar(100),t_DateOfJoining varchar(100),t_Designation varchar(500),t_DesignationId int,                  
   t_Grade varchar(100),t_GradeId int,t_Location nvarchar(300),t_LocationId int,t_SubLocation nvarchar(300),t_SubLocationId int,
   t_Department varchar(500),t_DepartmentId int,                  
   t_BloodGroupId int,t_ReportingManager varchar(500),t_MaritalStatusId int,t_GenderId int,                  
   t_Address1 varchar(1000),t_Address2 varchar(1000),t_Address3 varchar(1000),t_City varchar(500),                  
   t_State varchar(500),t_Country varchar(500),t_CorporateMob varchar(100),t_CorporateEmail varchar(200),                  
   t_DateOfLeaving varchar(100),t_EmployeeId bigint,t_FunctionId int,                  
   t_DepartmentGroupId int,t_TargetGroupId int,t_StatusId int,t_ReportingManagerId bigint,t_CompanyIdNew int ,                
   --t_DateofMarriage varchar(100),t_GroupDateOfJoining varchar(100), t_LocationCode varchar(100),
   t_PanNo varchar(100), t_PFUANNo varchar(100),t_AdharNo varchar(100) ,t_EmployeeGroup varchar(500)    
   ,t_EmployeeTypeGroup varchar(500), t_EmployeeType varchar(500) ,t_EmployeeSubType varchar(500),t_ProcessTypeId int,t_ProcessType varchar(500),    
   t_EmployeeGroupId int ,t_EmployeeTypeId int ,t_EmployeeSubTypeId int, t_EmployeeTypeGroupId int,t_JobTitle varchar(500)
   ,t_JobTitleId int, t_CompanyHead varchar(500), t_CompanyHeadId bigint, t_CompanyGroupHead varchar(500), t_CompanyGroupHeadId bigint, 
   t_SubBussinesHead varchar(500), t_SubBussinesHeadId bigint, t_BussinesHead varchar(500), t_BussinesHeadId bigint,
   t_Coordinator varchar(500), t_CoordinatorId bigint, t_ExeCoordinator varchar(500), t_ExeCoordinatorId bigint, 
   t_Director varchar(500), t_DirectorId bigint, t_legalEntityTitle varchar(500),t_legalEntityId int, t_DepartmentGroupTitle varchar(500),t_FunctionTitle varchar(500),t_IsUserValid bit
  )                  
  insert into @tblEmployee                  
  select T.c.value('@EmpCode','varchar(300)') as EmpCode,
  T.c.value('@UserName','varchar(300)') as UserName,
  T.c.value('@EmployementStatus','varchar(100)') as EmployementStatus,                  
  T.c.value('@FirstName','varchar(300)') as FirstName,                  
  T.c.value('@MiddleName','varchar(300)') as MiddleName,                  
  T.c.value('@LastName','varchar(300)') as LastName,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Business','varchar(500)')) as Business,                  
  T.c.value('@BusinessId','int') as BusinessId,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@SubBusiness','varchar(500)')) as SubBusiness,                  
  T.c.value('@VerticalId','int') as VerticalId,    
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@CompanyGroup','varchar(500)')) as CompanyGroup,          
   T.c.value('@CompanyGroupId','int') as CompanyGroupId,                     
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@CompanyName','varchar(500)')) as CompanyName,                  
  T.c.value('@CompanyId','int') as CompanyId,                  
  T.c.value('@DateOfBirth','varchar(100)') as DateOfBirth,                  
  T.c.value('@DateOfJoining','varchar(100)') as DateOfJoining,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Designation','varchar(500)')) as Designation,                  
  T.c.value('@DesignationId','int') as DesignationId,              
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Grade','varchar(100)')) as Grade,         
  T.c.value('@GradeId','int') as GradeId,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Location','nvarchar(300)')) as Location,                  
  Isnull(T.c.value('@LocationId','int'),0) as LocationId,  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@SubLocation','nvarchar(300)')) as SubLocation,          
   Isnull(T.c.value('@SubLocationId','int'),0) as SubLocationId,                 
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Department','varchar(500)')) as Department,                  
  T.c.value('@DepartmentId','int') as DepartmentId,                  
  T.c.value('@BloodGroupId','int') as BloodGroupId,                  
  T.c.value('@ReportingManager','varchar(500)') as ReportingManager,                  
T.c.value('@MaritalStatusId','int') as MaritalStatusId,                  
  T.c.value('@GenderId','int') as GenderId,                  
[sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Address1','varchar(1000)')) as Address1,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Address2','varchar(1000)')) as Address2,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@Address3','varchar(1000)')) as Address3,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@City','varchar(500)')) as City,                  
  [sSetup].[fPortalXMLTagsReplaceReverse](T.c.value('@State','varchar(500)')) as State,                  
  T.c.value('@Country','varchar(500)') as Country,                  
  T.c.value('@CorporateMobile','varchar(100)') as CorporateMobile,                  
  T.c.value('@CorporateEmail','varchar(200)') as CorporateEmail,                  
  T.c.value('@LeavingDate','varchar(100)') as LeavingDate,                  
  null,null,null,null,null,null,null,                
  --T.c.value('@DateofMarriage','varchar(100)') as DateofMarriage,                  
  --T.c.value('@GroupDateOfJoining','varchar(100)') as GroupDateOfJoining,                 
  --T.c.value('@LocationCode','varchar(500)') as LocationCode,                
  T.c.value('@PanNo','varchar(500)') as PanNo,                
  T.c.value('@PFUANNo','varchar(500)') as PFUANNo,                
  T.c.value('@AdharNo','varchar(500)') as AdharNo,    
  T.c.value('@EmployeeGroup','varchar(500)') as EmployeeGroup,    
  T.c.value('@EmployeeTypeGroup','varchar(500)') as EmployeeTypeGroup, 
  T.c.value('@EmployeeType','varchar(500)') as EmployeeType,    
     
  T.c.value('@EmployeeSubType','varchar(500)') as EmployeeSubType,    
  null,    
  T.c.value('@ProcessType','varchar(500)') as ProcessType,null,null,null, null,  
  T.c.value('@JobTitle','varchar(500)') as JobTitle,null,
  T.c.value('@CompanyHead','varchar(500)') as CompanyHead,null,
  T.c.value('@CompanyGroupHead','varchar(500)') as CompanyGroupHead,null,
  T.c.value('@SubBussinesHead','varchar(500)') as SubBussinesHead,null,
  T.c.value('@BussinesHead','varchar(500)') as BussinesHead,null,
  T.c.value('@Coordinator','varchar(500)') as Coordinator,null,
  T.c.value('@ExeCoordinator','varchar(500)') as ExeCoordinator,null,
  T.c.value('@Director','varchar(500)') as Director,null,
  T.c.value('@LegalEntity','varchar(500)') as LegalEntityTitle,null,
  T.c.value('@DepartmentGroup','varchar(500)') as DepartmentGroupTitle,
  T.c.value('@Function','varchar(500)') as FunctionTitle,0
  

  from @loXML.nodes('/Employees/Employee')T(c) 

  ;WITH CTE AS
	(
		SELECT tid, t_EmpCode, 
			   ROW_NUMBER() OVER (PARTITION BY LTRIM(RTRIM(t_EmpCode)) ORDER BY tid) AS rn
			   FROM @tblEmployee
	)
	DELETE FROM CTE
	WHERE rn > 1;

  select * from @tblEmployee    
      
 --  DELETE FROM @tblEmployee    
 --WHERE t_EmpCode IN (    
 --   SELECT t_EmpCode    
 --   FROM @tblEmployee    
 --   GROUP BY t_EmpCode    
 --   HAVING COUNT(*) > 1    
 --)     
 --Limit 1;    
     
 --;WITH CTE AS (    
 --   SELECT *,    
 --          ROW_NUMBER() OVER (PARTITION BY t_EmpCode ORDER BY (SELECT NULL)) AS RowNum    
 --   FROM @tblEmployee    
 --)    
 --DELETE FROM CTE    
 --WHERE RowNum > 1;
               
  update @tblEmployee set t_EmployeeId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_EmpCode,0) = ISNULL(Code,0) and OrgId = @rOrgId                  
  update @tblEmployee set t_TargetGroupId = Id from sHrm.tTargetGroupMaster where Title = '-' and OrgId = @rOrgId                  
  update @tblEmployee set t_StatusId = case t_Status when 'Working' then 7 when 'Left' then 9 when 'Pre Join' then 10 else 7 end                  
  update @tblEmployee set t_ReportingManagerId = Id from sHrm.tEmployeeMaster where code = t_ReportingManager      
  update @tblEmployee set t_DepartmentId = Id from sCommon.tOrganizationDepartmentMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_Department,'')))) and OrgId = @rOrgId      
  update @tblEmployee set t_DepartmentGroupId = Id from sCommon.tDepartmentGroupMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_DepartmentGroupTitle,'')))) and OrgId = @rOrgId      
  update @tblEmployee set t_FunctionId = Id from sCommon.tFunctionMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_FunctionTitle,'')))) and OrgId = @rOrgId      
      
  update @tblEmployee set t_EmployeeGroup = '-' where ISNULL(t_EmployeeGroup,'') = ''    
  update @tblEmployee set t_EmployeeType = 'Regular' where ISNULL(t_EmployeeType,'') = ''    
  update @tblEmployee set t_EmployeeSubType = 'Regular' where ISNULL(t_EmployeeSubType,'') = ''    
  update @tblEmployee set t_ProcessType = 'Non Hazard' , t_ProcessTypeId = 2   where ISNULL(t_ProcessTypeId,0) = 0 
  update @tblEmployee set t_EmployeeTypeGroup = 'Regular' where ISNULL(t_EmployeeTypeGroup,'') = ''   
  
  update @tblEmployee set t_SubBusiness = t_Business where ISNULL(t_SubBusiness,'-') = '-' and t_Business != '-'
  update @tblEmployee set t_CompanyGroup = t_SubBusiness where ISNULL(t_CompanyGroup,'-') = '-' and ISNULL(t_SubBusiness,'-') != '-'
  update @tblEmployee set t_CompanyGroup = t_Business where ISNULL(t_CompanyGroup,'-') = '-' and ISNULL(t_SubBusiness,'-') = '-' 
  update @tblEmployee set t_CompanyName = t_CompanyGroup where ISNULL(t_CompanyName,'-') = '-' and ISNULL(t_CompanyGroup,'-') != '-' 
  update @tblEmployee set t_CompanyName = t_SubBusiness where ISNULL(t_CompanyName,'-') = '-' and ISNULL(t_CompanyGroup,'-') = '-' and ISNULL(t_SubBusiness,'-') != '-'    
  update @tblEmployee set t_CompanyName = t_Business where ISNULL(t_CompanyName,'-') = '-' and ISNULL(t_CompanyGroup,'-') = '-' and ISNULL(t_SubBusiness,'-') = '-'
  
  --select * from @tblEmployee
    
  update @tblEmployee set t_EmployeeGroupId = Id from sHrm.tEmployeeGroupMaster where UPPER(RTRIM(LTRIM(Title))) =  UPPER(RTRIM(LTRIM(t_EmployeeGroup))) and OrgId = @rOrgId    
      
  --SELECT Top 1 @rEmployeeTypeGroupId = Id FROM sHrm.tEmployeeTypeGroupMaster WHERE UPPER(RTRIM(LTRIM(Code))) = 'EMPLOYEE' and OrgId = @rOrgId    
      
  update @tblEmployee set t_EmployeeTypeGroupId = Id FROM sHrm.tEmployeeTypeGroupMaster WHERE UPPER(RTRIM(LTRIM(Title))) = UPPER(RTRIM(LTRIM(t_EmployeeTypeGroup)))  and OrgId = @rOrgId    
      
  update @tblEmployee set t_EmployeeTypeId = Id from sHrm.tEmployeeTypeMaster WHERE UPPER(RTRIM(LTRIM(Title))) = UPPER(RTRIM(LTRIM(t_EmployeeType))) and OrgId = @rOrgId and EmployeeTypeGroupId = t_EmployeeTypeGroupId    
      
  --SELECT Top 1 @rEmployeeTypeId = Id FROM sHrm.tEmployeeTypeMaster WHERE UPPER(RTRIM(LTRIM(Code))) = (Case when IsNULL(t_EmployeeType,'') = '' then 'REGULAR' else t_EmployeeType end) and OrgId = @rOrgId and EmployeeTypeGroupId = @rEmployeeTypeGroupId  
  
   update @tblEmployee set t_EmployeeSubTypeId =Id FROM sHrm.tEmployeeSubTypeMaster WHERE UPPER(RTRIM(LTRIM(Title))) = UPPER(RTRIM(LTRIM(t_EmployeeSubType))) and OrgId = @rOrgId and EmployeeTypeId = t_EmployeeTypeId                    
   
   update @tblEmployee set t_JobTitleId =Id FROM sHrm.tEmployeeJobTitleMaster WHERE UPPER(RTRIM(LTRIM(Title))) = UPPER(RTRIM(LTRIM(t_JobTitle))) and OrgId = @rOrgId  
   
   update @tblEmployee set t_legalEntityId =Id FROM sHrm.tEmployeeLegalEntitymaster WHERE UPPER(RTRIM(LTRIM(Title))) = UPPER(RTRIM(LTRIM(t_legalEntityTitle))) and OrgId = @rOrgId    
    
	-- update date format if it is not in "yyyy-mm-dd" format by MS - 2024-06-21 start changes
	UPDATE @tblEmployee
		SET
		  t_DateOfJoining = 
			CASE WHEN t_DateOfJoining LIKE '____-__-__' THEN t_DateOfJoining
				 ELSE CONVERT(varchar(10), CONVERT(date, t_DateOfJoining, 103), 23)
			END,
		  t_DateOfBirth = 
			CASE WHEN t_DateOfBirth LIKE '____-__-__' THEN t_DateOfBirth
				 ELSE CONVERT(varchar(10), CONVERT(date, t_DateOfBirth, 103), 23)
			END;

	-- changes end
	
	update @tblEmployee set t_CompanyHeadId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_CompanyHead,0) = ISNULL(Code,0) and OrgId = @rOrgId
	update @tblEmployee set t_CompanyGroupHeadId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_CompanyGroupHead,0) = ISNULL(Code,0) and OrgId = @rOrgId
	update @tblEmployee set t_SubBussinesHeadId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_SubBussinesHead,0) = ISNULL(Code,0) and OrgId = @rOrgId
	update @tblEmployee set t_BussinesHeadId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_BussinesHead,0) = ISNULL(Code,0) and OrgId = @rOrgId
	update @tblEmployee set t_CoordinatorId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_Coordinator,0) = ISNULL(Code,0) and OrgId = @rOrgId
	update @tblEmployee set t_ExeCoordinatorId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_ExeCoordinator,0) = ISNULL(Code,0) and OrgId = @rOrgId
	update @tblEmployee set t_DirectorId = ISNULL(Id,0) from sHrm.tEmployeeMaster where ISNULL(t_Director,0) = ISNULL(Code,0) and OrgId = @rOrgId

  select @res = 1
 END TRY     
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
  return                  
 END CATCH                  
                   
 declare @lNextNumber bigint,@lFromNextNumber bigint,@lCount int                  
                   
 BEGIN TRY                  
  update @tblEmployee set t_BusinessId = Id from sHrm.tSectorMaster where upper(Title) = RTrim(LTrim(upper(t_Business))) and OrgId = @rOrgId                  
  create table #tblTable                  
  (                  
   tid int identity(1,1),t_Title varchar(300),t_Id int,t_MainId int                  
  )                  
  insert into #tblTable                  
  select distinct t_Business,t_BusinessId,0 from @tblEmployee                  
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tSectorMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                     
  MERGE sHrm.tSectorMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title                  
   FROM #tblTable TT LEFT JOIN sHrm.tSectorMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id        
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tSectorMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_BusinessId = Id from sHrm.tSectorMaster where Title = t_Business and OrgId = @rOrgId                  
               
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
               
  select @res = 0                  
 END CATCH                  
                   
BEGIN TRY                  
  update @tblEmployee set t_VerticalId = Id from sHrm.tVerticalMaster where upper(Title) = Rtrim(LTrim(upper(t_SubBusiness)))  and OrgId = @rOrgId                  
  truncate table #tblTable                  
  insert into #tblTable 
           
select distinct t_SubBusiness,t_VerticalId,t_BusinessId from @tblEmployee                  
  -- select * from @tblEmployee
  --select * from #tblTable            
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tVerticalMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tVerticalMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId                  
   FROM #tblTable TT LEFT JOIN sHrm.tVerticalMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                    
  -- UPDATE SET SectorId = t_MainId,UpdatedUserId=@rCreatedUserId,UpdatedDateTime=getdate()                     
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,SectorId                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),t_MainId                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tVerticalMaster', @rCurrentNumber = @lNextNumber                  
                
                 
  update @tblEmployee set t_VerticalId = Id from sHrm.tVerticalMaster where Title = t_SubBusiness  and OrgId = @rOrgId                  
   --select * from @tblEmployee            
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 --BEGIN TRY                    
 -- truncate table #tblTable                  
 -- insert into #tblTable                  
 -- select distinct t_SubBusiness,t_VerticalId,t_VerticalId from @tblEmployee                  
                    
 -- exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tCompanyGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
 -- SET @lFromNextNumber = @lNextNumber - 1                  
                    
 -- MERGE sHrm.tCompanyGroupMaster AS Target USING                   
 -- (                  
 --  SELECT tid,Id,t_Id,t_Title,t_MainId                  
 --  FROM #tblTable TT LEFT JOIN sHrm.tCompanyGroupMaster T ON TT.t_Id = T.VerticalId                  
 -- ) AS Source ON Target.VerticalId = Source.t_Id                  
 -- --WHEN MATCHED THEN                    
 -- -- UPDATE SET VerticalId = t_MainId,UpdatedUserId=@rCreatedUserId,UpdatedDateTime=getdate()                   
 -- WHEN NOT MATCHED THEN                  
 --  INSERT                  
 --  (                  
 --   Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,VerticalId                  
 --  )                  
 --  VALUES                  
 --  (                  
 --   @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),t_MainId                  
 --  );                  
                    
 -- select @lCount = COUNT(1) FROM #tblTable                  
 -- SET @lNextNumber  = @lCount + @lFromNextNumber                   
 -- exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tCompanyGroupMaster', @rCurrentNumber = @lNextNumber                  
                    
 -- update @tblEmployee set t_CompanyGroupId = Id from sHrm.tCompanyGroupMaster where Title = t_SubBusiness and VerticalId = t_VerticalId and OrgId = @rOrgId                  
                    
 -- select @res = 1           
 --END TRY         
 --BEGIN CATCH                  
 -- update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
 -- where Id = @rTemplateId                  
                    
 -- select @res = 0                  
 --END CATCH  
 
 BEGIN TRY 
 
 update @tblEmployee set t_CompanyGroupId = Id from sHrm.tCompanyGroupMaster where upper(Title) = Rtrim(LTrim(upper(t_CompanyGroup))) and VerticalId = t_VerticalId and OrgId = @rOrgId                             
  truncate table #tblTable          
  insert into #tblTable          
  select distinct t_CompanyGroup,t_CompanyGroupId,t_VerticalId from @tblEmployee          
    
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tCompanyGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output           
  SET @lFromNextNumber = @lNextNumber - 1          
            
  MERGE sHrm.tCompanyGroupMaster AS Target USING           
  (          
   SELECT tid,Id,t_Id,t_Title,t_MainId          
   FROM #tblTable TT LEFT JOIN sHrm.tCompanyGroupMaster T ON TT.t_Id = T.Id          
  ) AS Source ON Target.Id = Source.t_Id                 
  WHEN NOT MATCHED THEN          
   INSERT          
   (          
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,VerticalId          
   )          
   VALUES          
   (          
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),t_MainId          
   );          
            
  select @lCount = COUNT(1) FROM #tblTable          
  SET @lNextNumber  = @lCount + @lFromNextNumber           
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tCompanyGroupMaster', @rCurrentNumber = @lNextNumber          
      
  update @tblEmployee set t_CompanyGroupId = Id from sHrm.tCompanyGroupMaster where Title = t_CompanyGroup and VerticalId = t_VerticalId and OrgId = @rOrgId          
         
  select @res = 1          
 END TRY          
 BEGIN CATCH          
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3          
  where Id = @rTemplateId          
            
  select @res = 0          
 END CATCH                   
                   
 BEGIN TRY                  
  update @tblEmployee set t_CompanyId = Id from sHrm.tEmployeeCompanyMaster where Upper(Title) = RTrim(LTrim(Upper(t_CompanyName))) and CompanyGroupId = t_CompanyGroupId and OrgId = @rOrgId                  
  truncate table #tblTable                  
  insert into #tblTable                  
  select distinct t_CompanyName,Isnull(t_CompanyId,0),t_CompanyGroupId from @tblEmployee                  
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCompanyMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeCompanyMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId                  
   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeCompanyMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                    
  -- UPDATE SET CompanyGroupId = t_MainId,UpdatedUserId=@rCreatedUserId,UpdatedDateTime=getdate()                   
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,CompanyGroupId                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),t_MainId                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeCompanyMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_CompanyId = Id from sHrm.tEmployeeCompanyMaster where Title = t_CompanyName and CompanyGroupId = t_CompanyGroupId and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 BEGIN TRY                  
  update @tblEmployee set t_legalEntityId = Id from sHrm.tEmployeeLegalEntitymaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_legalEntityTitle,'')))) and OrgId = @rOrgId                    
  truncate table #tblTable                  
  insert into #tblTable                  
  select distinct t_legalEntityTitle,Isnull(t_legalEntityId,0),0 from @tblEmployee                   
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeLegalEntitymaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeLegalEntitymaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId   
   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeLegalEntitymaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                    
  -- UPDATE SET CompanyGroupId = t_MainId,UpdatedUserId=@rCreatedUserId,UpdatedDateTime=getdate()                   
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeLegalEntitymaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_legalEntityId = Id from sHrm.tEmployeeLegalEntitymaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_legalEntityTitle,'')))) and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 BEGIN TRY                  
 update @tblEmployee set t_DesignationId = Id from sHrm.tEmployeeDesignationMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_Designation,'')))) and OrgId = @rOrgId                  
  truncate table #tblTable      
                  
  insert into #tblTable                  
  select distinct t_Designation,t_DesignationId,0 from @tblEmployee                  
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeDesignationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeDesignationMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title                  
   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeDesignationMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id               
 WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeDesignationMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_DesignationId = Id from sHrm.tEmployeeDesignationMaster where Title = t_Designation and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 BEGIN TRY                  
  truncate table #tblTable                  
  insert into #tblTable                  
  select distinct t_Grade,t_GradeId,0 from @tblEmployee                  
                 
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tGradeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tGradeMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title                  
   FROM #tblTable TT LEFT JOIN sHrm.tGradeMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                   
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,GradeNumber                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),1                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tGradeMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_GradeId = Id from sHrm.tGradeMaster where Title = t_Grade and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0               
 END CATCH                  
                   
 BEGIN TRY        
  truncate table #tblTable                  
  insert into #tblTable                  
  select distinct t_FunctionTitle,t_FunctionId,0 from @tblEmployee                  
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sCommon.tFunctionMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sCommon.tFunctionMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title                  
   FROM #tblTable TT LEFT JOIN sCommon.tFunctionMaster T ON TT.t_Title collate SQL_Latin1_General_CP1_CI_AS = T.Title                  
  ) AS Source ON upper(Target.Title) = upper(Source.t_Title) collate SQL_Latin1_General_CP1_CI_AS                   
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sCommon.tFunctionMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_FunctionId = Id from sCommon.tFunctionMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_FunctionTitle,'')))) and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 BEGIN TRY                  
  truncate table #tblTable                  
  insert into #tblTable                  
  select distinct t_DepartmentGroupTitle,t_DepartmentGroupId,ISNULL(t_FunctionId,0) from @tblEmployee                  
      
  exec sCommon.pTableRowIdGet @rOrgId, 'sCommon.tDepartmentGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sCommon.tDepartmentGroupMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId                  
   FROM #tblTable TT LEFT JOIN sCommon.tDepartmentGroupMaster T ON TT.t_Title collate SQL_Latin1_General_CP1_CI_AS = T.Title                  
  ) AS Source ON upper(Target.Title) = upper(Source.t_Title) collate SQL_Latin1_General_CP1_CI_AS                  
  --WHEN MATCHED THEN                  
  --UPDATE set FunctionId=t_MainId                  
                     
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,FunctionId       
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),t_MainId                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sCommon.tDepartmentGroupMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_DepartmentGroupId = Id from sCommon.tDepartmentGroupMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_DepartmentGroupTitle,'')))) and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 BEGIN TRY                  
  truncate table #tblTable                  
  insert into #tblTable                  
  select distinct t_Department,t_DepartmentId,ISNULL(t_DepartmentGroupId,0) from @tblEmployee                  
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sCommon.tOrganizationDepartmentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sCommon.tOrganizationDepartmentMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId                  
   FROM #tblTable TT LEFT JOIN sCommon.tOrganizationDepartmentMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                  
  --UPDATE set DepartmentGroupId=t_MainId                  
                       
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,DepartmentGroupId                  
   )                  
   VALUES                
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),t_MainId                  
   );                  
                    
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sCommon.tOrganizationDepartmentMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_DepartmentId = Id from sCommon.tOrganizationDepartmentMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_Department,'')))) and OrgId = @rOrgId                  
                    
                    
  select @res = 1                   
 END TRY  
 
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
 -- Location Auto Insert Starts here                  
 BEGIN TRY                  
  Declare @orgid int,@userid bigint,@maxcityid int                  
  set @orgid=@rOrgId                  
  set @userid=(select Top 1 CreatedUserid from scommon.tStatemaster where OrgId=@orgid)                  
   if not exists(Select 1 from scommon.tStatemaster where Title='-' and OrgId=@orgid)                  
    begin                  
     insert into scommon.tStatemaster                  
     select @orgid,[sCommon].[fGetIntIdForOrg](100,@orgid),'-',@userid,GetDate(),@userid,GetDate(),0,[sCommon].[fGetIntIdForOrg](1,@orgid),1              
     --print 'Insert State'                  
    end                  
                  
  --set @maxcityid=(select Right(Max(id),3)+100 from sCommon.tCityMaster where orgid=@orgid)      
  -- if not exists(Select 1 from scommon.tCitymaster where Title='-' and OrgId=@orgid)                  
  --  begin                  
  --   insert into scommon.tCitymaster                  
  --   select @orgid,[sCommon].[fGetIntIdForOrg](1,@orgid),'-',@userid,GetDate(),@userid,GetDate(),0,[sCommon].[fGetIntIdForOrg](@maxcityid,@orgid),1                  
  --   --print 'Insert City'                  
  --  end                  
                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                  
 --BEGIN TRY                  
 ---- change by MS 03/05/2022 for adani data issue            
 -- update @tblEmployee set t_LocationId = Id from sCommon.tLocationMaster where upper(Title) = Rtrim(LTrim(upper(t_Location))) and OrgId = @rOrgId             
 -- and upper(LocationCode) = Rtrim(LTrim(upper(t_LocationCode)))            
 -- and Isnull(t_LocationCode,'')<>''            
            
 -- update @tblEmployee set t_LocationId = Id from sCommon.tLocationMaster where upper(Title) = Rtrim(LTrim(upper(t_Location))) and OrgId = @rOrgId             
 -- --and upper(LocationCode) = Rtrim(LTrim(upper(t_LocationCode)))            
 -- and Isnull(t_LocationCode,'')=''            
                    
 -- truncate table #tblTable                    
 -- insert into #tblTable                  
 -- select distinct t_Location,t_LocationId,0 from @tblEmployee where Isnull(t_LocationId,0)=0             
                    
                    
 -- exec sCommon.pTableRowIdGet @rOrgId, 'sIp.tStoreLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
 -- SET @lFromNextNumber = @lNextNumber - 1               
            
            
                     
 -- MERGE sIp.tStoreLocationMaster AS Target USING                   
 -- (                  
 --  SELECT tid,Id,t_Id,t_Title                  
 --  FROM #tblTable TT LEFT JOIN sIp.tStoreLocationMaster T ON TT.t_Id = T.Id                  
 -- ) AS Source ON Target.Id = Source.t_Id                   
 -- WHEN NOT MATCHED THEN                  
 --  INSERT                  
 --  (                  
 --   Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
 --  )                  
 --  VALUES                  
 --  (                  
 --   @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
 --  )          
 --  OUTPUT          
 --  inserted.Id,inserted.Title,inserted.Code          
 --  into @tblinsertedlocationid;          
                  
 -- select @lCount = COUNT(1) FROM #tblTable                  
 -- SET @lNextNumber  = @lCount + @lFromNextNumber                   
 -- exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sIp.tStoreLocationMaster', @rCurrentNumber = @lNextNumber                    
            
 -- select @res = 1                  
 --END TRY                  
 --BEGIN CATCH                  
 -- update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
 -- where Id = @rTemplateId                  
                    
 -- select @res = 0                  
 --END CATCH                  
                  
 --BEGIN TRY                  
 -- truncate table #tblTable                  
 -- insert into #tblTable                  
 -- select distinct t_Location,t_LocationId,0 from @tblEmployee                  
                    
 -- exec sCommon.pTableRowIdGet @rOrgId, 'sCommon.tLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
 -- SET @lFromNextNumber = @lNextNumber - 1                  
                     
 -- MERGE sCommon.tLocationMaster AS Target USING                   
 -- (                  
 --  SELECT tid,Id,t_Id,t_Title                  
 --  FROM #tblTable TT LEFT JOIN sCommon.tLocationMaster T ON TT.t_Id = T.Id                  
 -- ) AS Source ON Target.Id = Source.t_Id                   
 -- WHEN NOT MATCHED THEN                  
 --  INSERT                  
 --  (                  
 --   Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,CountryId,StateId                  
 --  )                  
 --  VALUES                  
 --  (                  
 --   @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),[sCommon].[fGetIntIdForOrg](100,@orgid),[sCommon].[fGetIntIdForOrg](1,@orgid)                  
 --  );                  
                    
 -- select @lCount = COUNT(1) FROM #tblTable                  
 -- SET @lNextNumber  = @lCount + @lFromNextNumber                   
 -- exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sCommon.tLocationMaster', @rCurrentNumber = @lNextNumber                  
                    
 -- update @tblEmployee set t_LocationId = Id from sCommon.tLocationMaster where Upper(Title) = Upper(t_Location) and OrgId = @rOrgId                  
 -- update sCommon.tLocationMaster set LocationCode = t_LocationCode from @tblEmployee where t_LocationId = Id            
                    
 -- update SLM Set SLM.LocationId = LM.id From sIp.tStoreLocationMaster SLM                  
 -- inner join sCommon.tLocationMaster LM on Upper(LM.Title)=Upper(SLM.Title) and LM.OrgId = @rOrgId                  
 -- Where Isnull(SLM.LocationId,0) = 0          
            
 -- -- Mentis id (0021441 jignesh)           
 -- Declare @i int = 1;          
          
 -- while (@i <= (select count(*) from @tblinsertedlocationid))          
 -- begin          
 --Declare @Title_ nvarchar(200), @Code_ nvarchar(50),@LocationId_ int,@id_ int;          
 --select @Title_ = isnull(Title,''),@code_= isnull(code,''),@id_=Id from @tblinsertedlocationid where autoid = @i          
 --select @LocationId_ = SLM.LocationId from sIp.tStoreLocationMaster SLM where SLM.Id = @id_          
 --exec [sIp].[pStoreLocationMasterAdd_sap] @rTitle = @Title_,          
 --@rCreatedUserId = @rCreatedUserId,@rIsObsolete=0,@rCode=@code_,@rLocationId=@LocationId_,@rOrgId=@rOrgId,@rStartTime=null,          
 --@rEndTime=null,@rIsActiveHealth=1,@rIsOPDSetup=0          
          
 --set @i = @i+1;          
 -- end          
 -- ----------------------------------          
                    
                 
                  
 -- select @res = 1                  
 --END TRY                  
 --BEGIN CATCH                  
 -- update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
 -- where Id = @rTemplateId                  
                    
 -- select @res = 0                  
 --END CATCH    
 
 BEGIN TRY          
  update @tblEmployee set t_SubLocationId = 0, t_LocationId = 0  
  update @tblEmployee set t_SubLocationId = Id, t_LocationId = LocationId from sIp.tStoreLocationMaster     
 where upper(Title) = Rtrim(Ltrim(upper(t_SubLocation))) and OrgId = @rOrgId --and t_SubLocationId = 0    
            
 truncate table #tblTable            
 insert into #tblTable          
 select distinct t_SubLocation,t_SubLocationId,0 from @tblEmployee where Isnull(t_SubLocationId,0) = 0          
            
        
 exec sCommon.pTableRowIdGet @rOrgId, 'sIp.tStoreLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output           
 SET @lFromNextNumber = @lNextNumber - 1          
             
 MERGE sIp.tStoreLocationMaster AS Target USING           
 (          
 SELECT tid,Id,t_Id,t_Title          
 FROM #tblTable TT LEFT JOIN sIp.tStoreLocationMaster T ON TT.t_Id = T.Id          
 ) AS Source ON Target.Id = Source.t_Id           
 WHEN NOT MATCHED THEN          
 INSERT          
 (          
 Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime          
 )          
 VALUES          
 (          
 @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()          
 );          
            
 select @lCount = COUNT(1) FROM #tblTable          
 SET @lNextNumber  = @lCount + @lFromNextNumber           
 exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sIp.tStoreLocationMaster', @rCurrentNumber = @lNextNumber            
      
 update @tblEmployee set t_SubLocationId = Id, t_LocationId = ISNULL(LocationId,0) from sIp.tStoreLocationMaster     
 where Upper(Title) = Upper(t_SubLocation) and OrgId = @rOrgId    
    
    
  select @res = 1          
 END TRY          
 BEGIN CATCH          
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3          
  where Id = @rTemplateId          
            
  select @res = 0          
 END CATCH          
          
 BEGIN TRY         
     
  update @tblEmployee set t_Location = t_SubLocation from sCommon.tLocationMaster where t_LocationId = 0    
    
 truncate table #tblTable          
 insert into #tblTable          
 select distinct t_Location,t_LocationId,0 from @tblEmployee where t_LocationId = 0    
            
 exec sCommon.pTableRowIdGet @rOrgId, 'sCommon.tLocationMaster', 0, 1, 1,@outNextNumber = @lNextNumber output           
 SET @lFromNextNumber = @lNextNumber - 1          
             
 MERGE sCommon.tLocationMaster AS Target USING           
 (          
 SELECT tid,Id,t_Id,t_Title          
 FROM #tblTable TT LEFT JOIN sCommon.tLocationMaster T ON TT.t_Id = T.Id          
 ) AS Source ON Target.Id = Source.t_Id           
 WHEN NOT MATCHED THEN          
 INSERT          
 (          
 Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,CountryId,StateId          
 )          
 VALUES          
 (          
 @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate(),[sCommon].[fGetIntIdForOrg](100,@rorgId),[sCommon].[fGetIntIdForOrg](1,@rorgId)          
 );          
            
 select @lCount = COUNT(1) FROM #tblTable          
 SET @lNextNumber  = @lCount + @lFromNextNumber           
 exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sCommon.tLocationMaster', @rCurrentNumber = @lNextNumber          
            
 update @tblEmployee set t_LocationId = Id  from sCommon.tLocationMaster where Upper(Title) = Upper(t_Location) and OrgId = @rOrgId       
            
 update SLM Set SLM.LocationId = LM.id From sIp.tStoreLocationMaster SLM          
 inner join sCommon.tLocationMaster LM on Upper(LM.Title)=Upper(SLM.Title) and LM.OrgId = @rOrgId          
 Where Isnull(SLM.LocationId,0) = 0      
               
 --   IF OBJECT_ID(N'tempdb..#tblTable') IS NOT NULL    
 --BEGIN    
 -- drop table #tblTable    
 --END     
    
  select @res = 1          
 END TRY          
 BEGIN CATCH          
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3          
  where Id = @rTemplateId          
            
  select @res = 0          
 END CATCH          
         
 -- Location Auto Insert ends here                
                   
 -- Location Auto Insert ends here                  
    
--- employeegroup insert start    
    
BEGIN TRY      
               
  truncate table #tblTable             
  insert into #tblTable                  
  select distinct t_EmployeeGroup,ISNULL(t_EmployeeGroupId,0),0 from @tblEmployee                  
                
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeGroupMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title                 
   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeGroupMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                  
  --UPDATE set DepartmentGroupId=t_MainId                  
                       
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
   )                  
   VALUES                
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
   );                  
                  
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeGroupMaster', @rCurrentNumber = @lNextNumber                  
       
  update @tblEmployee set t_EmployeeGroupId = Id from sHrm.tEmployeeGroupMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_EmployeeGroup,'')))) and OrgId = @rOrgId                  
                    
                   
  select @res = 1                   
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH      
    


--- employeetypegroup insert start    
    
BEGIN TRY      
               
  truncate table #tblTable             
  insert into #tblTable                  
  select distinct t_EmployeeTypeGroup,ISNULL(t_EmployeeTypeGroupId,0),0 from @tblEmployee                  
               
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeTypeGroupMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeTypeGroupMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title                 
   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeTypeGroupMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                  
  --UPDATE set DepartmentGroupId=t_MainId                  
                       
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
   )                  
   VALUES                
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
   );                  
                  
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeTypeGroupMaster', @rCurrentNumber = @lNextNumber                  
       
  update @tblEmployee set t_EmployeeTypeGroupId = Id from sHrm.tEmployeeTypeGroupMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_EmployeeTypeGroup,'')))) and OrgId = @rOrgId                  
                    
                   
  select @res = 1                   
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH      
   -- select * from @tblEmployee
--- employeeTypegroup insert end    
    
    
--- employeeType insert start    
    
BEGIN TRY     
                
  truncate table #tblTable     
              
  insert into #tblTable                  
  select distinct t_EmployeeType,ISNULL(t_EmployeeTypeId,0),ISNULL(t_EmployeeTypeGroupId,0) from @tblEmployee                  
     
            
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeTypeMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId                
   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeTypeMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                  
  --UPDATE set DepartmentGroupId=t_MainId                  
                       
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,EmployeeTypeGroupId                  
   )                  
   VALUES                
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate() ,t_MainId                
   );                  
                  
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeTypeMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_EmployeeTypeId = Id from sHrm.tEmployeeTypeMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_EmployeeType,'')))) and EmployeeTypeGroupId = t_EmployeeTypeGroupId  and OrgId = @rOrgId                  
                  
                    
  select @res = 1                   
 END TRY                  
 BEGIN CATCH      
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH      
    --select * from @tblEmployee
--- employeetype insert end    
    
    
    
--- employeeSubType insert start    
    
BEGIN TRY    
                 
  truncate table #tblTable     
                   
  insert into #tblTable                  
  select distinct t_EmployeeSubType,ISNULL(t_EmployeeSubTypeId,0),ISNULL(t_EmployeeTypeId,0) from @tblEmployee                  
             
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeSubTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeSubTypeMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_Id,t_Title,t_MainId                
   FROM #tblTable TT LEFT JOIN sHrm.tEmployeeSubTypeMaster T ON TT.t_Id = T.Id                  
  ) AS Source ON Target.Id = Source.t_Id                  
  --WHEN MATCHED THEN                  
  --UPDATE set DepartmentGroupId=t_MainId                  
                       
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,EmployeeTypeId                  
   )                  
   VALUES                
   (                  
    @lFromNextNumber + tid,@rOrgId,t_Title,t_Title,0,@rCreatedUserId,getdate(),@rCreatedUserId,getdate() ,t_MainId                
   );                  
  print 3                   
  select @lCount = COUNT(1) FROM #tblTable                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeSubTypeMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_EmployeeSubTypeId = Id from sHrm.tEmployeeSubTypeMaster where Upper(Title) = Rtrim(Ltrim(Upper(Isnull(t_EmployeeSubType,'')))) and EmployeeTypeId = t_EmployeeTypeId  and OrgId = @rOrgId                  
         
              
                    
  select @res = 1                   
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH      
  IF OBJECT_ID(N'tempdb..#tblTable') IS NOT NULL    
 BEGIN    
  drop table #tblTable    
 END  
 --select * from @tblEmployee       
--- employeeSubType insert end    
    
    
    
                  
 BEGIN TRY                  
                   
  update @tblEmployee set t_StatusId = Id from sCommon.tStatusMaster where Title = t_Status and StatusTypeId = 4                  
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1                  
                    
  MERGE sHrm.tEmployeeMaster AS Target USING                   
  (                  
   SELECT tid,Id,t_EmployeeId,t_EmpCode,t_StatusId,t_FirstName,t_MiddleName,t_LastName,                  
   t_TargetGroupId,t_LocationId                  
   FROM @tblEmployee TT LEFT JOIN sHrm.tEmployeeMaster T ON ISNULL(TT.t_EmployeeId,0) = T.Id                  
  ) AS Source ON Target.Id = ISNULL(Source.t_EmployeeId,0)                  
  WHEN MATCHED THEN                  
   UPDATE SET FirstName = t_FirstName,MiddleName = t_MiddleName,LastName = t_LastName,                  
   StatusId = t_StatusId,WorkLocationId = t_LocationId,UpdatedDateTime=getDate(),ImportReferenceId=@rTemplateId,IsObsolete=0                  
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    Id,OrgId,Code,FirstName,MiddleName,LastName,StatusId,IsObsolete,CreatedUserId,CreatedDateTime,                  
    UpdatedUserId,UpdatedDateTime,IsTemporary,TargetGroupId,WorkLocationId,ImportReferenceId                  
   )                  
   VALUES                  
   (                  
    @lFromNextNumber + tid,@rOrgId,t_EmpCode,t_FirstName,t_MiddleName,t_LastName,t_StatusId,0,                  
    @rCreatedUserId,getdate(),@rCreatedUserId,getdate(),0,t_TargetGroupId,t_LocationId,@rTemplateId                  
   );                  
                   
  select @lCount = COUNT(1) FROM @tblEmployee                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeMaster', @rCurrentNumber = @lNextNumber                  
                    
  update @tblEmployee set t_EmployeeId = Id from sHrm.tEmployeeMaster where Code = t_EmpCode and OrgId = @rOrgId                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 update @tblEmployee set t_DateOfLeaving='1900-01-01' where ISNULL(t_DateOfLeaving,'')=''                   
 
 BEGIN TRY                  
  MERGE sHrm.tEmployeeJobDetail AS Target USING                   
  (                  
   SELECT tid,t_EmployeeId,t_DesignationId,t_LocationId,t_DepartmentId,t_DateOfJoining,t_CompanyId,                  
   ISNULL(t_DateOfLeaving,'1900-01-01')t_DateOfLeaving,t_GradeId,t_ReportingManagerId,t_EmployeeGroupId,t_EmployeeTypeId,t_EmployeeSubTypeId,t_ProcessTypeId,t_JobTitleId,t_legalEntityId               
   FROM @tblEmployee TT LEFT JOIN sHrm.tEmployeeJobDetail T ON TT.t_EmployeeId = T.EmployeeId                  
  ) AS Source ON Target.EmployeeId = Source.t_EmployeeId                  
  WHEN MATCHED THEN                  
   UPDATE SET EmployeeDesignationId = t_DesignationId,EmployeeLocationId = ISNULL(t_LocationId,0),                  
   OrganizationDepartmentId = t_DepartmentId,DateOfJoining = t_DateOfJoining,EmployeeCompanyId = t_CompanyId,                  
   DateOfLeaving = ISNULL(t_DateOfLeaving,'1900-01-01'),GradeId = t_GradeId,ReportingMangerEmployeeId = ISNULL(t_ReportingManagerId,0),                  
   IsSkilled = 1,UpdatedUserId = @rCreatedUserId,UpdatedDateTime = getdate(),LegalEntityId= ISNULL(t_legalEntityId ,0),    
   EmployeeGroupId=t_EmployeeGroupId,             
   EmployeeTypeId=t_EmployeeTypeId,EmployeeSubTypeId=t_EmployeeSubTypeId, ProcessTypeId = t_ProcessTypeId, EmployeeJobTitleId = ISNULL(t_JobTitleId  ,0)        
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    EmployeeId,OrgId,EmployeeDesignationId,EmployeeLocationId,OrganizationDepartmentId,DateOfJoining,                  
    EmployeeCompanyId,DateOfLeaving,GradeId,ReportingMangerEmployeeId,IsSkilled,UpdatedUserId,                  
    UpdatedDateTime,ProcessTypeId,EmployeeTypeId,EmployeeSubTypeId,EmployeeGroupCode,EmployeeGroupId,LegalEntityId,EmployeeJobTitleId 
   )              
   VALUES                  
   (              
    t_EmployeeId,@rOrgId,ISNULL(t_DesignationId,0),ISNULL(t_LocationId,0),ISNULL(t_DepartmentId,0),ISNULL(t_DateOfJoining,'1900-01-01'),ISNULL(t_CompanyId,0),--t_CompanyIdNew,                  
    ISNULL(t_DateOfLeaving,'1900-01-01'),ISNULL(t_GradeId,0),ISNULL(t_ReportingManagerId,0),1,              
    @rCreatedUserId,getdate(),ISNULL(t_ProcessTypeId,0),ISNULL(t_EmployeeTypeId,0),ISNULL(t_EmployeeSubTypeId,0),'-',ISNULL(t_EmployeeGroupId,0) ,ISNULL(t_legalEntityId  ,0),ISNULL(t_JobTitleId  ,0) 
   );                  
                     
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
  
  
 BEGIN TRY                  
  MERGE sHrm.tEmployeePersonalDetail AS Target USING                   
  (                  
   SELECT tid,t_EmployeeId,t_DateOfBirth,t_GenderId,t_BloodGroupId,t_MaritalStatusId,                
   t_AdharNo ,--t_DateofMarriage,
   t_PanNo,t_PFUANNo                
   FROM @tblEmployee TT LEFT JOIN sHrm.tEmployeePersonalDetail T ON TT.t_EmployeeId = T.EmployeeId                  
  ) AS Source ON Target.EmployeeId = Source.t_EmployeeId                  
  WHEN MATCHED THEN              
   UPDATE SET DateOfBirth = t_DateOfBirth,GenderId = t_GenderId,BloodGroupId = ISNULL(t_BloodGroupId,0),                  
   --IsDisability = 0,IsDisabilityCertified = 0,IsFireTraining = 0,IsFirstAidTraining = 0,                
   UidNumber = t_AdharNo,--DateofMarriage = t_DateofMarriage,                
   PanNo = t_PanNo,PFUANNo  = t_PFUANNo,                  
   UpdatedUserId = @rCreatedUserId,MaritalStatusId=t_MaritalStatusId                  
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    EmployeeId,OrgId,DateOfBirth,GenderId,BloodGroupId,IsDisability,IsDisabilityCertified,                  
    IsFireTraining,IsFirstAidTraining,UpdatedUserId,UpdatedDateTime,MaritalStatusId,                
 UidNumber,--DateofMarriage,
 PanNo,PFUANNo                
   )                  
   VALUES                  
   (                  
    t_EmployeeId,@rOrgId,t_DateOfBirth,t_GenderId,ISNULL(t_BloodGroupId,0),0,0,0,0,@rCreatedUserId,                  
    getdate(),t_MaritalStatusId, t_AdharNo, --t_DateofMarriage,                
 t_PanNo,t_PFUANNo                
   );                  
                     
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH                  
                   
 BEGIN TRY                  
  MERGE sHrm.tEmployeeCommunications AS Target USING                   
  (                  
   SELECT tid,t_EmployeeId,t_Address1,t_Address2,t_Address3,t_City,t_State,t_Country,replace(Rtrim(Ltrim(t_CorporateMob)),' ','')t_CorporateMob,t_CorporateEmail                  
   FROM @tblEmployee TT LEFT JOIN sHrm.tEmployeeCommunications T ON TT.t_EmployeeId = T.EmployeeId                  
  ) AS Source ON Target.EmployeeId = Source.t_EmployeeId                  
  WHEN MATCHED THEN                  
   UPDATE SET PresentStreetOne = t_Address1,PresentStreetTwo = t_Address2,PresentStreetThree = t_Address3,                  
   PresentCountry = t_Country,PresentState = t_State,PresentCity = t_City,                  
   PresentContactNo = case when len(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''))>10                   
         then left(replace(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''),'+91',''),50)                  
         else replace(Rtrim(Ltrim(t_CorporateMob)),' ','') end ,                  
   --PhoneNoCompany = t_CorporateMob,                  
   CompanyEmail = t_CorporateEmail,                  
   --PersonalEmail = t_CorporateEmail,                  
   MobileNumber = case when len(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''))>10                   
         then left(replace(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''),'+91',''),10)                  
         else replace(Rtrim(Ltrim(t_CorporateMob)),' ','') end ,                  
   CreatedUserId = @rCreatedUserId,                  
   CreatedDateTime = getdate(),UpdatedUserId = @rCreatedUserId,UpdatedDateTime = getdate()                  
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    EmployeeId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,PresentState,PresentCity,                  
    PresentContactNo,CompanyEmail,MobileNumber,CreatedUserId,CreatedDateTime,                  
    UpdatedUserId,UpdatedDateTime                  
   )                  
   VALUES                  
   (                  
    t_EmployeeId,t_Address1,t_Address2,t_Address3,t_Country,t_State,t_City,case when len(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''))>10                   
    then left(replace(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''),'+91',''),50) else replace(Rtrim(Ltrim(t_CorporateMob)),' ','') end,                  
    t_CorporateEmail,case when len(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''))>10 then left(replace(replace(Rtrim(Ltrim(t_CorporateMob)),' ',''),'+91',''),10)                  
    else replace(Rtrim(Ltrim(t_CorporateMob)),' ','') end,@rCreatedUserId,getdate(),@rCreatedUserId,getdate()                  
   );                  
                    
  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH       
 
 BEGIN TRY                  
  MERGE sHrm.tApprovalAuthority AS Target USING                   
  (                  
   SELECT tid,t_EmployeeId,t_CompanyHeadId, t_CompanyGroupHeadId, t_SubBussinesHeadId, t_BussinesHeadId,
   t_CoordinatorId, t_ExeCoordinatorId, t_DirectorId
   FROM @tblEmployee TT LEFT JOIN sHrm.tApprovalAuthority T ON TT.t_EmployeeId = T.EmployeeId                  
  ) AS Source ON Target.EmployeeId = Source.t_EmployeeId                  
  WHEN MATCHED THEN                  
   UPDATE SET CompanyHeadId = ISNULL(t_CompanyHeadId, 0), 
       CompanyGroupHeadId = ISNULL(t_CompanyGroupHeadId, 0), 
       SubBussinesHeadId = ISNULL(t_SubBussinesHeadId, 0),                  
       BussinesHeadId = ISNULL(t_BussinesHeadId, 0), 
       CoordinatorId = ISNULL(t_CoordinatorId, 0), 
       ExeCoordinatorId = ISNULL(t_ExeCoordinatorId, 0), 
       DirectorId = ISNULL(t_DirectorId, 0),                  
	   UpdatedUserId = @rCreatedUserId,
	   UpdatedDateTime = getdate()
  WHEN NOT MATCHED THEN                  
   INSERT                  
   (                  
    EmployeeId,CompanyHeadId,CompanyGroupHeadId,SubBussinesHeadId,BussinesHeadId,CoordinatorId,ExeCoordinatorId,DirectorId,       
    CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime                  
   )
   VALUES
   (                  
    t_EmployeeId, ISNULL(t_CompanyHeadId, 0), ISNULL(t_CompanyGroupHeadId, 0), ISNULL(t_SubBussinesHeadId, 0), ISNULL(t_BussinesHeadId, 0), 
    ISNULL(t_CoordinatorId, 0), ISNULL(t_ExeCoordinatorId, 0), ISNULL(t_DirectorId, 0),
	@rCreatedUserId,getdate(), @rCreatedUserId, getdate()
   );

  select @res = 1                  
 END TRY                  
 BEGIN CATCH                  
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH

 --User Add
 BEGIN TRY           
    -- Mantis: 0037352
	 ;WITH CTE AS
	 (
	 	SELECT tid, t_IsUserValid, t_UserName, ROW_NUMBER() OVER (PARTITION BY LTRIM(RTRIM(t_UserName)) ORDER BY tid) AS rn
	 	FROM @tblEmployee
	 )
	 update cte set t_IsUserValid = 1 from cte WHERE rn = 1;
                    
  exec sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 1, 1,@outNextNumber = @lNextNumber output                   
  SET @lFromNextNumber = @lNextNumber - 1
                    
  MERGE sSecurity.tUser AS Target USING         
  (                  
   SELECT tid,Id,t_FirstName,t_LastName,t_UserName,t_EmployeeId,t_EmpCode,t_StatusId,t_LocationId
   FROM @tblEmployee TT LEFT JOIN sSecurity.tUser T ON ISNULL(TT.t_EmployeeId,0) = T.Id
   Where TT.t_StatusId = 7 and ISNULL(TT.t_UserName, '') <> '' and t_IsUserValid = 1
  ) AS Source ON Target.SourceId = ISNULL(Source.t_EmployeeId,0) and SourceTypeId = 95
  WHEN NOT MATCHED THEN
   INSERT
   (                  
    Id,	DisplayTitle, LoginTitle, LoginPassword, LastLockOutDate, NumberOfLogonAttempt, IsObsolete,
    CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime, OrgId,
	SourceId, SourceTypeId
   )
   VALUES
   (                  
    @lFromNextNumber + tid,(t_FirstName + ' ' + t_LastName), t_UserName, LEFT(REPLACE(CONVERT(VARCHAR(40), NEWID()) + CONVERT(VARCHAR(40), NEWID()), '-', ''), 40), 
	sCommon.fGetDate(), 0, 0, @rCreatedUserId, sCommon.fGetDate(), @rCreatedUserId, sCommon.fGetDate(), 
	@rOrgId, t_EmployeeId, 95
   );

  select @lCount = COUNT(1) FROM @tblEmployee                  
  SET @lNextNumber  = @lCount + @lFromNextNumber                   
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sSecurity.tUser', @rCurrentNumber = @lNextNumber

  INSERT INTO sSecurity.tUserLocation (StoreLocationId, UserId, CreatedUserId, CreatedDateTime)
	SELECT t_SubLocationId, USR.Id, @rCreatedUserId, sCommon.fGetDate()
	FROM @tblEmployee e
	INNER JOIN sSecurity.tUser USR ON USR.SourceId = ISNULL(e.t_EmployeeId, 0) AND USR.SourceTypeId = 95
	WHERE e.t_StatusId = 7
	AND NOT EXISTS (
		SELECT 1
		FROM sSecurity.tUserLocation ul
		WHERE ul.UserId = USR.Id and ul.StoreLocationId = t_SubLocationId
	);

	INSERT INTO sSecurity.tUserRole (RoleId, UserId, IsObsolete, IsPrimary, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime)
	SELECT [sCommon].[fGetIntIdForOrg](10, @rOrgId), USR.Id, 0, 1, @rCreatedUserId, sCommon.fGetDate(), @rCreatedUserId, sCommon.fGetDate()
	FROM @tblEmployee e
	INNER JOIN sSecurity.tUser USR ON USR.SourceId = ISNULL(e.t_EmployeeId, 0) AND USR.SourceTypeId = 95
	WHERE e.t_StatusId = 7
	AND NOT EXISTS (
		SELECT 1
		FROM sSecurity.tUserRole ur
		WHERE ur.UserId = USR.Id
	);

  select @res = 1  
 END TRY
 BEGIN CATCH
  update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = ERROR_MESSAGE(),StatusCode = 3                  
  where Id = @rTemplateId                  
                    
  select @res = 0                  
 END CATCH
                  
 if(@res=1)       
 begin                  
 delete from sHrm.tVerticalMaster where id not in(select distinct VerticalId From sHrm.tCompanyGroupMaster)                  
 update [sHrm].[tWebApiImportEmployee] set [ValidationMessage] = 'Success',StatusCode=4 where Id = @rTemplateId                  
 end                  
 select @res as res                 
end
GO
PRINT N'Altering Procedure [dbo].[updateDocumentRound]...';


GO

ALTER PROCEDURE [dbo].[updateDocumentRound]
@Type int = 1,
@code varchar(300),
@rOrgId int,
@rFromRoundId int = 0,
@rToRoundId int = 0
as
begin
		
		Declare @EmployeeId bigint = (Select Id from sHrm.tEmployeeMaster where Code = @code and OrgID = @rOrgId)
		
		If (@Type = 1)
		BEGIN
			Update tbl_historydata set SetupId = @rToRoundId where employeeid = @EmployeeId and SetupId = @rFromRoundId
		END
		else If (@Type = 2)
		BEGIN
			Update tbl_historydataoutside set SetupId = @rToRoundId where employeeid = @EmployeeId and SetupId = @rFromRoundId
		END
		else
		BEGIN
			Update tbl_azurehistorydata set SetupId = @rToRoundId where employeeid = @EmployeeId and SetupId = @rFromRoundId
		END
		select 1
end
GO
PRINT N'Altering Procedure [sAlert].[pAppointmentEmployeeSchedulerGet]...';


GO
ALTER PROCEDURE [sAlert].[pAppointmentEmployeeSchedulerGet]  
      
    @rOrgId smallint,  
    @rTemplate nvarchar(max),  
    @rMailSubject nvarchar(100),  
    @rAppointmentDate date  
      
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON BEGIN  
 SELECT   
   EC.MobileNumber AS MobileNo,     EC.PersonalEmail AS EmailId,  
   REPLACE(@rTemplate,'[DoctorName]',ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'')) AS MsgText,  
   @rMailSubject AS Subject  
 FROM sAppointment.tAppointment AP  
   LEFT JOIN sHrm.tEmployeeMaster EM ON AP.PatientSourceId = EM.Id  
   LEFT JOIN sHrm.tEmployeeCommunications EC ON AP.DoctorEmployeeId = EC.EmployeeId  
 WHERE  
  (EM.OrgId=@rOrgId) AND AP.AppointmentDate = @rAppointmentDate  
END
GO
PRINT N'Altering Procedure [sAlert].[pSMSConfigurationAdd]...';


GO
ALTER PROCEDURE [sAlert].[pSMSConfigurationAdd]
	
	@rOrgId smallint,
	@rSMSURL nvarchar(1000),
	@rSMSCreditURL nvarchar(1000),
	@rLoginId nvarchar(50),
	@rLoginPassword nvarchar(200),
	@rLoginSenderId nvarchar(50),
	@rSMSXMLURL nvarchar(1000),
	@rVendorId smallint,
	@rSMSUnicodeURL nvarchar(1000)
	--,@rOrgGroupId smallint,
	--@rIsAllOrg bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 
--	 IF(@rIsAllOrg=1)
--	 BEGIN
--		DECLARE @lCount INT
--		CREATE TABLE #tTable  
--		(
--			Id bigint identity,
--			OrgId smallint
--		)
--		INSERT INTO #tTable
--		(
--			OrgId
--		)
--		SELECT Id FROM sSetup.tOrganizationMaster WHERE OrgGroupId=@rOrgGroupId
		
--		SELECT @lCount =  COUNT(Id) FROM #tTable
--		WHILE @lCount > 0 
--		BEGIN
--			SELECT @rOrgId=OrgId FROM #tTable WHERE Id = @lCount
--			IF NOT EXISTS(SELECT OrgId FROM sAlert.tSMSConfiguration WHERE OrgId=@rOrgId)
--BEGIN

--	INSERT INTO sAlert.tSMSConfiguration
--		(
--			OrgId,
--			SMSURL,
--			SMSCreditURL,
--			LoginId,
--			LoginPassword,
--			LoginSenderId,
--			SMSXMLURL,
--			VendorId
--		)
--	VALUES
--		(
--			@rOrgId,
--			@rSMSURL,
--			@rSMSCreditURL,
--			@rLoginId,
--			@rLoginPassword,
--			@rLoginSenderId,
--			@rSMSXMLURL,
--			@rVendorId
--		)
		             
--	END	 
--	 ELSE
	 --BEGIN
	 --   UPDATE  sAlert.tSMSConfiguration
	 --   SET
		--	SMSURL=@rSMSURL,
		--	SMSCreditURL=@rSMSCreditURL,
		--	LoginId=@rLoginId,
		--	LoginPassword=@rLoginPassword,
		--	LoginSenderId=@rLoginSenderId,
		--	SMSXMLURL=@rSMSXMLURL,
		--	VendorId=@rVendorId
	      
	      
	 --     WHERE OrgId = @rOrgId 	   
	 --END  
		--SELECT @rOrgId AS Result
		--	SET @lCount = @lCount - 1
		--END
	 --END
	 --ELSE
	 BEGIN
	 
 IF NOT EXISTS(SELECT OrgId FROM sAlert.tSMSConfiguration WHERE OrgId=@rOrgId)
BEGIN

	INSERT INTO sAlert.tSMSConfiguration
		(
			OrgId,
			SMSURL,
			SMSCreditURL,
			LoginId,
			LoginPassword,
			LoginSenderId,
			SMSXMLURL,
			VendorId,
			SMSUnicodeURL
		)
	VALUES
		(
			@rOrgId,
			@rSMSURL,
			@rSMSCreditURL,
			@rLoginId,
			@rLoginPassword,
			@rLoginSenderId,
			@rSMSXMLURL,
			@rVendorId,
			@rSMSUnicodeURL
		)
		             
	END	 
	 ELSE
	 BEGIN
	    UPDATE  sAlert.tSMSConfiguration
	    SET
			SMSURL=@rSMSURL,
			SMSCreditURL=@rSMSCreditURL,
			LoginId=@rLoginId,
			LoginPassword=@rLoginPassword,
			LoginSenderId=@rLoginSenderId,
			SMSXMLURL=@rSMSXMLURL,
			VendorId=@rVendorId,
			SMSUnicodeURL = @rSMSUnicodeURL
	      
	      
	      WHERE OrgId = @rOrgId 	   
	 END  
		SELECT @rOrgId AS Result
	END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
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 [sCommon].[pRptCompanyInformationInternalGet]...';


GO
ALTER PROCEDURE [sCommon].[pRptCompanyInformationInternalGet]	
	@rReportId [int] = 0,
	@rStoreLocationId [int] = 0,
	@rUserDisplayTitle varchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
		SELECT
			    CI.Id,
				case when CI.id=4001 or CI.id=6001 then CI.Title Else LM.Title END AS LocationName,
				LM.NameOfOrganization AS NameOfOrganization,
				LM.SmallAddress1,
				LM.SmallAddress2,
				CI.Code,
				CI.Title,
				CI.ParentCompanyName,
				CI.StreetOne + ', ' + CI.CityName AS FirstLine,
				--  StateName + ', ' + 
				--	CountryName + ', TIN No: ' + TinNumber AS SecondLine,
				--	'Tel: ' + PhoneNumberOffice AS ThirdLine,
				'Website: ' + CI.HomePage AS FourthLine,
				CI.StreetOne,
				CI.StreetTwo,
				CI.StreetThree,
				CI.StreetFour,
				CI.CityName,
				CI.StateName,
				CI.CountryName,
				CI.ZipCode,
				CI.PhoneNo,
				--CityName + ' ' + StateName AS CityState,
				--CountryName  + ' ' + ZipCode AS CountryZip,
				--ContactPerson,
				--PhoneNumberHome,
				--PhoneNumberOffice,
				--PhoneNumberMobile,
				--EmailPrimary,
				--EmailAlternative,
				--HomePage,
				SL.Title as SubLocation,
			    (SELECT CASE @rReportId when 20477 then 'Referral Certificate' 
				when 20476 then 'OPD Prescription List' 
				ELSE (ISNULL(RS.Title,R.Title)) END as ReportTitle
			     FROM sCommon.tReport R 
					 LEFT JOIN sCommon.tReportStateTitle RS On R.Id = RS.ReportId 				
					 LEFT JOIN (SELECT StateId FROM  sCommon.tLocationMaster LM 
					 INNER JOIN sIp.tStoreLocationMaster SL ON SL.LocationId = LM.id WHERE SL.Id = @rStoreLocationId
				) SLM  
				ON SLM.StateId = RS.StateId
				         
				WHERE ((R.Id = @rReportId) OR (@rReportId = 0))) AS ReportTitle,
				(SELECT R.ReportName FROM sCommon.tReport R 
					 LEFT JOIN sCommon.tReportStateTitle RS On R.Id = RS.ReportId 				
					 LEFT JOIN (SELECT StateId FROM  sCommon.tLocationMaster LM 
					 INNER JOIN sIp.tStoreLocationMaster SL ON SL.LocationId = LM.id WHERE SL.Id = @rStoreLocationId
				) SLM  
				ON SLM.StateId = RS.StateId
				         
			WHERE ((R.Id = @rReportId) OR (@rReportId = 0))) AS ReportName,
			CID.logo as Logo,
			 
			@rUserDisplayTitle as UserDisplayTitle	 
			FROM sIp.tStoreLocationMaster SL INNER JOIN sCommon.tLocationMaster LM					  			
			ON SL.LocationId = LM.Id INNER JOIN sCommon.tCompanyInformation CI 
			ON LM.OrgId = CI.Id	INNER JOIN sCommon.tCompanyInformationDetail CID
			on ci.ID = CID.orgid
			WHERE ((SL.Id = @rStoreLocationId) OR (ISNULL(@rStoreLocationId, 0) = 0))
			order by CI.Id Desc,LM.Title 
END
GO
PRINT N'Altering Procedure [sExamination].[pCreateSetupEmployee]...';


GO
ALTER PROCEDURE [sExamination].[pCreateSetupEmployee]  
(  
    @rOrgId INT,  
    @rEmployeeXML XML  ,
	@rUserId BIGINT 
)  
AS  
BEGIN  
    SET NOCOUNT ON;  
  
    BEGIN TRY  
        BEGIN TRAN;  
  
  DECLARE @tblEmployee TABLE  
        (  
            Id BIGINT,  
            SetupId INT,  
            EmployeeId BIGINT,  
            TargetGroupId INT,  
            CentralDoctorId BIGINT,  
            SiteDoctorId BIGINT,  
            CentralSpocId BIGINT,  
            SiteSpocId BIGINT,  
            OrgId INT  
        );  
  
        INSERT INTO @tblEmployee  
        SELECT    
            T.X.value('(ID)[1]', 'BIGINT'),  
            T.X.value('(SetupId)[1]', 'INT'),  
            T.X.value('(EmployeeId)[1]', 'BIGINT'),  
            T.X.value('(TargetGroupId)[1]', 'INT'),  
            T.X.value('(CentralDoctorId)[1]', 'BIGINT'),  
            T.X.value('(SiteDoctorId)[1]', 'BIGINT'),  
            T.X.value('(CentralSpocId)[1]', 'BIGINT'),  
            T.X.value('(SiteSpocId)[1]', 'BIGINT'),  
            T.X.value('(OrgId)[1]', 'INT')  
        FROM @rEmployeeXML.nodes('/NewDataSet/Employee') AS T(X);  
  
        -- Step 1: Move data from temp to final table  
        INSERT INTO [sExamination].[tSetupEmployee] (  
            Id, SetupId, EmployeeId, TargetGroupId, CentralDoctorId,  
            SiteDoctorId, CentralSpocId, SiteSpocId, OrgId  
        )  
        SELECT   
            Id, SetupId, EmployeeId, TargetGroupId, CentralDoctorId,  
            SiteDoctorId, CentralSpocId, SiteSpocId, OrgId  
        FROM @tblEmployee;  
  
        -- Step 2: Update CurrentNumber  
        UPDATE sCommon.tTableRowId  
        SET CurrentNumber = (SELECT MAX(Id) FROM sExamination.tSetupEmployee)  
        WHERE OrgId = @rOrgId  
          AND TableTitle = 'sExamination.tSetupEmployee';  
  
  --organization  
  INSERT INTO [sHrm].[tEntityHead] (EntitySourceTypeId, EntitySourceId, HeadEmployeeId, DesignationId)  
        SELECT DISTINCT 2010,@rOrgId,SiteDoctorId, 9  
        FROM @tblEmployee t  
        WHERE t.SiteDoctorId IS NOT NULL  
          AND NOT EXISTS (  
              SELECT 1   
              FROM [sHrm].[tEntityHead] e  
              WHERE e.HeadEmployeeId = t.SiteDoctorId  
     AND e.EntitySourceId = @rOrgId  
              AND e.EntitySourceTypeId = 2010  
     AND e.DesignationId = 9  
          );  
  
        INSERT INTO [sHrm].[tEntityHead] (EntitySourceTypeId, EntitySourceId, HeadEmployeeId, DesignationId)  
        SELECT DISTINCT 2010, @rOrgId, CentralDoctorId, 10  
        FROM @tblEmployee t  
        WHERE t.CentralDoctorId IS NOT NULL  
          AND NOT EXISTS (  
              SELECT 1   
              FROM [sHrm].[tEntityHead] e  
              WHERE e.HeadEmployeeId = t.CentralDoctorId  
     AND e.EntitySourceId = @rOrgId  
              AND e.EntitySourceTypeId = 2010  
     AND e.DesignationId = 10  
          );  
  
    --Business  
  INSERT INTO [sHrm].[tEntityHead] (EntitySourceTypeId, EntitySourceId, HeadEmployeeId, DesignationId)  
        SELECT DISTINCT 2012,SEC.Id,SiteDoctorId, 9  
        FROM @tblEmployee t  
  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = t.EmployeeId  
  INNER JOIN sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = EJD.EmployeeCompanyId  
  INNER join sHrm.tCompanyGroupMaster CGM on CGM.Id=ECM.CompanyGroupId  
  INNER join sHrm.tVerticalMaster VRM on VRM.Id=CGM.VerticalId  
  INNER join sHrm.tSectorMaster SEC on SEC.Id=VRM.SectorId  
        WHERE t.SiteDoctorId IS NOT NULL  
          AND NOT EXISTS (  
     SELECT 1   
              FROM [sHrm].[tEntityHead] e  
     WHERE e.HeadEmployeeId = t.SiteDoctorId  
     AND e.EntitySourceId = SEC.Id  
     AND e.EntitySourceTypeId = 2012  
     AND e.DesignationId = 9  
          );  
  
        INSERT INTO [sHrm].[tEntityHead] (EntitySourceTypeId, EntitySourceId, HeadEmployeeId, DesignationId)  
        SELECT DISTINCT 2012, SEC.Id, CentralDoctorId, 10  
        FROM @tblEmployee t  
  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = t.EmployeeId  
  INNER JOIN sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = EJD.EmployeeCompanyId  
  INNER join sHrm.tCompanyGroupMaster CGM on CGM.Id=ECM.CompanyGroupId  
  INNER join sHrm.tVerticalMaster VRM on VRM.Id=CGM.VerticalId  
  INNER join sHrm.tSectorMaster SEC on SEC.Id=VRM.SectorId  
        WHERE t.CentralDoctorId IS NOT NULL  
          AND NOT EXISTS (  
     SELECT 1   
              FROM [sHrm].[tEntityHead] e  
     WHERE e.HeadEmployeeId = t.CentralDoctorId  
     AND e.EntitySourceId = SEC.Id  
     AND e.EntitySourceTypeId = 2012  
     AND e.DesignationId = 10  
          );  
  
  --Sub Location  
  INSERT INTO [sHrm].[tEntityHead] (EntitySourceTypeId, EntitySourceId, HeadEmployeeId, DesignationId)  
        SELECT DISTINCT 1014,SM.StoreLocationId,SiteDoctorId, 9  
        FROM @tblEmployee t  
  INNER JOIN sExamination.tSetupMaster SM ON SM.Id = t.SetupId  
        WHERE t.SiteDoctorId IS NOT NULL  
          AND NOT EXISTS (  
              SELECT 1   
              FROM [sHrm].[tEntityHead] e  
              WHERE e.HeadEmployeeId = t.SiteDoctorId  
    AND e.EntitySourceId = SM.StoreLocationId  
                AND e.EntitySourceTypeId = 1014  
    AND e.DesignationId = 9  
          );  
  
        INSERT INTO [sHrm].[tEntityHead] (EntitySourceTypeId, EntitySourceId, HeadEmployeeId, DesignationId)  
        SELECT DISTINCT 1014, SM.StoreLocationId, CentralDoctorId, 10  
        FROM @tblEmployee t  
  INNER JOIN sExamination.tSetupMaster SM ON SM.Id = t.SetupId  
        WHERE t.CentralDoctorId IS NOT NULL  
          AND NOT EXISTS (  
              SELECT 1   
              FROM [sHrm].[tEntityHead] e  
              WHERE e.HeadEmployeeId = t.CentralDoctorId  
    AND e.EntitySourceId = SM.StoreLocationId  
                AND e.EntitySourceTypeId = 1014  
    AND e.DesignationId = 10  
          );  
  
        COMMIT TRAN;  
  
        SELECT 1 AS StatusCode; -- success  
      INSERT INTO sExamination.tSetupEmployeeLog
      (
          SetupEmployeeId,
          SetupId,
          SetupGroupId,
          EmployeeId,
          OrgId,
          TargetGroupId,
          CentralDoctorId,
          SiteDoctorId,
          CentralSpocId,
          SiteSpocId,
          ActionDate,
          ActionBy
      )
        SELECT 
            t.Id,
            t.SetupId,
            SM.SetupGroupId,
            t.EmployeeId,
            t.OrgId,
            t.TargetGroupId,
            t.CentralDoctorId,
            t.SiteDoctorId,
            t.CentralSpocId,
            t.SiteSpocId,
            sCommon.fGetDate(),
            @rUserId
        FROM @tblEmployee t
        INNER JOIN sExamination.tSetupMaster SM 
            ON SM.Id = t.SetupId
        WHERE 
            t.CentralDoctorId IS NOT NULL
            OR t.SiteDoctorId IS NOT NULL
            OR t.CentralSpocId IS NOT NULL
            OR t.SiteSpocId IS NOT NULL;
    END TRY  
    BEGIN CATCH  
        IF @@TRANCOUNT > 0 ROLLBACK TRAN;  
  
        SELECT   
            ERROR_NUMBER() AS ErrorNumber,  
            ERROR_MESSAGE() AS ErrorMessage,  
            0 AS StatusCode;  
    END CATCH;  
END;
GO
PRINT N'Altering Procedure [sExamination].[pExaminationMainTypeGetForEmployee]...';


GO

ALTER PROC [sExamination].[pExaminationMainTypeGetForEmployee]  
    @rOrgId INT,  
    @rUserId BIGINT  
AS  
BEGIN
    SET NOCOUNT ON;

    DECLARE @FolderName NVARCHAR(50) = CONVERT(VARCHAR(50), NEWID());

    -- ExaminationType
    DECLARE @ExaminationType NVARCHAR(MAX) = '<option value="0"> -- Select -- </option>';
    SELECT @ExaminationType += '<option value="' + CONVERT(VARCHAR, Id) + '">' + Title + '</option>'
    FROM sExamination.tMainTypeMaster
    WHERE Id IN (1,2,6)
    ORDER BY Title;

    -- HealthIndicator
    DECLARE @HealthIndicator NVARCHAR(MAX) = '<option value="0"> -- All -- </option>';
    SELECT @HealthIndicator += '<option value="' + CONVERT(VARCHAR, Id) + '">' + 
           ISNULL(NULLIF(HealthIndicatorLabel, ''), Title) + '</option>'
    FROM sExamination.tHealthIndicatorMaster
    WHERE IsObsolete = 0
    ORDER BY Title;

    -- LocationMainGroup
    DECLARE @LocationMainGroup NVARCHAR(MAX) = '<option value="0"> -- All -- </option>';
    SELECT @LocationMainGroup += '<option value="' + CONVERT(VARCHAR, Id) + '">' + Title + '</option>'
    FROM sCommon.tLocationMainGroupMaster
    WHERE IsObsolete = 0 AND OrgId = @rOrgId
    ORDER BY Title;

    -- FunctionMaster
    DECLARE @FunctionMaster NVARCHAR(MAX) = '<option value="0"> -- All -- </option>';
    SELECT @FunctionMaster += '<option value="' + CONVERT(VARCHAR, Id) + '">' + Title + '</option>'
    FROM sCommon.tFunctionMaster
    WHERE IsObsolete = 0 AND OrgId = @rOrgId
    ORDER BY Title;

    -- StoreLocation with User condition
    DECLARE @StoreLocation NVARCHAR(MAX) = '<option value="0"> -- All -- </option>';
    DECLARE @MyLocation NVARCHAR(MAX) = '<option value="0"> -- Select -- </option>';
    
    IF @rUserId = 0
    BEGIN
        SELECT 
            @StoreLocation += '<option value="' + CONVERT(VARCHAR, Id) + '">' + Title + '</option>',
            @MyLocation += '<option value="' + CONVERT(VARCHAR, Id) + '">' + Title + '</option>'
        FROM sIp.tStoreLocationMaster
        WHERE IsObsolete = 0 AND OrgId = @rOrgId
        ORDER BY Title;
    END
    ELSE
    BEGIN
        SELECT 
            @StoreLocation += '<option value="' + CONVERT(VARCHAR, SLM.Id) + '">' + SLM.Title + '</option>',
            @MyLocation += '<option value="' + CONVERT(VARCHAR, SLM.Id) + '">' + SLM.Title + '</option>'
        FROM sIp.tStoreLocationMaster SLM
        INNER JOIN sSecurity.tUserLocation UL ON SLM.Id = UL.StoreLocationId
        WHERE SLM.IsObsolete = 0 AND SLM.OrgId = @rOrgId AND UL.UserId = @rUserId
        ORDER BY SLM.Title;
    END

    -- Sector
    DECLARE @Sector NVARCHAR(MAX) = '<option value="0"> -- All -- </option>';
    SELECT @Sector += '<option value="' + CONVERT(VARCHAR, Id) + '">' + Title + '</option>'
    FROM sHrm.tSectorMaster
    WHERE IsObsolete = 0 AND OrgId = @rOrgId
    ORDER BY Title;

    -- HealthIndexParameter
    DECLARE @HealthIndexParameter NVARCHAR(MAX) = '<option value="0"> -- All -- </option>';
    SELECT @HealthIndexParameter += '<option value="' + CONVERT(VARCHAR, Id) + '">' + Title + '</option>'
    FROM sExamination.tHealthIndexParameterMaster
    WHERE IsObsolete = 0 AND OrgId = @rOrgId
    ORDER BY Id;

    -- HealthIndexParameterList
-- HealthIndexParameterList with exact spacing
DECLARE @HealthIndexParameterList NVARCHAR(MAX) = '<tr><td><input id="ChkDeptAll_0" type="checkbox" onclick="DepartmentAll(this);" />    <label for="DepartmentCheckBoxList">Check All</label></td></tr>';

SELECT @HealthIndexParameterList += '<tr><td><input id="ChkType_' + CONVERT(VARCHAR, Id) + '" type="checkbox" />     <label for=' + CONVERT(VARCHAR, Id) + '>' + Title + '</label></td></tr>'
FROM sExamination.tHealthIndexParameterMaster
WHERE IsObsolete = 0 AND OrgId = @rOrgId
ORDER BY StaticHealthIndexParameterId;
    -- TargetGroup
    DECLARE @TargetGroup NVARCHAR(MAX) = '<option value="0"> -- All -- </option>';
    SELECT @TargetGroup += '<option value="' + CONVERT(VARCHAR, Id) + '">' + Title + '</option>'
    FROM sHrm.tTargetGroupMaster
    WHERE IsObsolete = 0 AND OrgId = @rOrgId
    ORDER BY Title;

    -- Employee Type related dropdowns
    DECLARE @EmployeeTypeGroup NVARCHAR(MAX) = '<option value="0"> -- All -- </option>';
    DECLARE @EmployeeType NVARCHAR(MAX) = '<option value="0"> -- All -- </option>';
    DECLARE @EmployeeSubType NVARCHAR(MAX) = '<option value="0"> -- All -- </option>';
    
    SELECT @EmployeeTypeGroup += '<option value="' + CONVERT(VARCHAR, Id) + '">' + Title + '</option>'
    FROM sHrm.tEmployeeTypeGroupMaster
    WHERE IsObsolete = 0 AND OrgId = @rOrgId
    ORDER BY Title;
    
    SELECT @EmployeeType += '<option value="' + CONVERT(VARCHAR, Id) + '">' + Title + '</option>'
    FROM sHrm.tEmployeeTypeMaster
    WHERE IsObsolete = 0 AND OrgId = @rOrgId
    ORDER BY Title;
    
    SELECT @EmployeeSubType += '<option value="' + CONVERT(VARCHAR, Id) + '">' + Title + '</option>'
    FROM sHrm.tEmployeeSubTypeMaster
    WHERE IsObsolete = 0 AND OrgId = @rOrgId
    ORDER BY Title;

    -- NotificationGroup
    DECLARE @NotificationGroup NVARCHAR(MAX) = '<option value="0"> -- Select -- </option>';
    SELECT @NotificationGroup += '<option value="' + CONVERT(VARCHAR, Id) + '">' + Title + '</option>'
    FROM sAlert.tNotificationGroupMaster
    WHERE OrgId = @rOrgId;

    -- lColumnName with optimized CASE
-- lColumnName with exact spacing as original
DECLARE @lColumnName NVARCHAR(MAX) = '';

;WITH DiagnosisConditions AS (
    SELECT 
        Id,
        Title,
		OT.OrderIndex,
        Condition = CASE 
            WHEN Id = 1 THEN 'Tobacco=1'
            WHEN Id = 2 THEN 'Smoker=1'
            WHEN Id = 3 THEN 'Alcohol=1'
            WHEN Id = 4 THEN '"BMI=''Underweight''"'
            WHEN Id = 5 THEN '"BMI=''Overweight''"'
            WHEN Id = 6 THEN '"BMI=''Obese''"'
            WHEN Id = 7 THEN 'TB=1'
            WHEN Id = 8 THEN 'COPD=1'
            WHEN Id = 9 THEN '"BloodPressure=''PreHypertension''"'
            WHEN Id = 10 THEN '"BloodPressure=''Hypertension''"'
            WHEN Id = 11 THEN '"FBS=''Pre Diabetic''"'
            WHEN Id = 12 THEN '"FBS=''Diabetic''"'
            WHEN Id = 13 THEN 'IHD=1'
            WHEN Id = 14 THEN '"AudiometryACRight=''NIHLMild''"'
            WHEN Id = 15 THEN '"AudiometryACRight=''NIHLModerate''"'
            WHEN Id = 16 THEN '"AudiometryACRight=''NIHLSevere''"'
            WHEN Id = 26 THEN '1=2'
            WHEN Id = 27 THEN '"Hb=''Low Hb''"'
            WHEN Id = 28 THEN '"Cholesterol=''Hypercholesterolemia''"'
            WHEN Id = 29 THEN '"Cholesterol=''Borderline Cholesterol''"'
            WHEN Id = 30 THEN '"Triglyceride=''Hypertriglyceridemia''"'
            WHEN Id = 31 THEN '"Triglyceride=''Borderline Triglyceride''"'
            WHEN Id = 32 THEN '"LDL=''Elevated  LDL''"'
            WHEN Id = 33 THEN '"LDL=''Borderline LDL''"'
            WHEN Id = 34 THEN '"HDL=''Low HDL''"'
            WHEN Id = 35 THEN '"SGPT=''Elevated  SGPT''"'
            WHEN Id = 36 THEN '"SerumCreatinine=''High Serum Creatinine''"'
            WHEN Id = 37 THEN '"ECG=''Abnormal ECG''"'
            WHEN Id = 39 THEN '"TMT=''Abnormal TMT''"'
            WHEN Id = 40 THEN '"ECHO=''Abnormal ECHO''"'
            WHEN Id = 41 THEN '"Sonography=''Abnormal Sonography''"'
            WHEN Id = 42 THEN '"PFT=''ObstructivePFT''"'
            WHEN Id = 43 THEN '"PFT=''RestructivePFT''"'
            WHEN Id = 44 THEN '"PFT=''MixPFT''"'
            WHEN Id = 45 THEN '"Diabetic Existing=''Diabetic Existing''"'
            WHEN Id = 46 THEN '"Hypertension Existing=''Hypertension Existing''"'
            WHEN Id = 47 THEN '"Menzer index=''Menzer index''"'
            WHEN Id = 48 THEN '"Abnormal XRay=''Abnormal XRay''"'
            WHEN Id = 49 THEN 'ExAlcohol=1'
            WHEN Id = 50 THEN 'ExSmoker=1'
            WHEN Id = 51 THEN 'ExTobacco=1'
            WHEN Id = 52 THEN 'MetabolicSyndrome=1'
            WHEN Id = 53 THEN 'CVDMajorRisk=1'
            WHEN Id = 54 THEN 'CVDMinorRisk=1'
            WHEN Id = 55 THEN 'NCDsRisk=1'
            WHEN Id = 56 THEN '"T3=''Elevated T3''"'
            WHEN Id = 57 THEN '"T4=''Elevated T4''"'
            WHEN Id = 58 THEN '"TSH=''Elevated TSH''"'
            WHEN Id = 59 THEN '"PSA=''High PSA''"'
            WHEN Id = 60 THEN '"TotalBillirubin=''High Serum Billirubin''"'
            WHEN Id = 62 THEN '"UricAcid=''Hyperuricemia''"'
            WHEN Id = 63 THEN '"Iron=''Iron Deficiency Anaemia''"'
            WHEN Id = 65 THEN '"T3=''Low T3''"'
            WHEN Id = 66 THEN '"T4=''Low T4''"'
            WHEN Id = 67 THEN '"TSH=''Low TSH''"'
            WHEN Id = 68 THEN '"PLATELETS=''Thrombocytopenia''"'
            WHEN Id = 69 THEN '"VitaminB12=''Vitamin B12 deficiency''"'
            WHEN Id = 70 THEN '"VitaminD3=''Vitamin D3 deficiency''"'
			WHEN Id = 71 THEN 'IsNewHypertensionStatus=1'
			WHEN Id = 72 THEN 'IsNewHypertensionStatus=2'
			WHEN Id = 73 THEN 'IsNewDiabeticStatus=1'
			WHEN Id = 74 THEN 'IsNewDiabeticStatus=2'
			WHEN Id = 75 THEN '"BMI=''Morbidly Obese''"'
			WHEN Id = 76 THEN '"VitaminD3=''Vitamin D3 Toxicity Risk''"'
            ELSE ''
        END
    FROM sExamination.tDiagnosisTrackerMaster TM
    INNER JOIN sExamination.tDiagnosisTrackerOrg OT ON TM.Id = OT.DiagnosisTrackerId
    WHERE TM.IsObsolete = 0 AND OT.OrgId = @rOrgId
)
SELECT @lColumnName += '<tr><td><input id="' + CONVERT(VARCHAR, Id) + '" onclick="MessageBoxDivHide();" Condition=' + 
       Condition + ' type="checkbox" />     <label for="CheckBoxListColumnName">' + Title + '</label></td></tr>'
FROM DiagnosisConditions
WHERE Condition != ''
ORDER BY OrderIndex ASC;

---- Add additional conditions with exact spacing
--SET @lColumnName += '<tr><td><input id="0" onclick="MessageBoxDivHide();" Condition="IsNewDiabeticStatus=1" type="checkbox" /> <label for="CheckBoxListColumnName">IsNewPreDiabetic</label></td></tr> ';
--SET @lColumnName += '<tr><td><input id="0" onclick="MessageBoxDivHide();" Condition="IsNewDiabeticStatus=2" type="checkbox" /> <label for="CheckBoxListColumnName">IsNewDiabetic</label></td></tr> ';
--SET @lColumnName += '<tr><td><input id="0" onclick="MessageBoxDivHide();" Condition="IsNewHypertensionStatus=1" type="checkbox" /> <label for="CheckBoxListColumnName">IsNewPreHypertension</label></td></tr> ';
--SET @lColumnName += '<tr><td><input id="0" onclick="MessageBoxDivHide();" Condition="IsNewHypertensionStatus=2" type="checkbox" /> <label for="CheckBoxListColumnName">IsNewHypertension</label></td></tr> ';
    -- lLSDColumnName
DECLARE @lLSDColumnName NVARCHAR(MAX) = '';
    
;WITH LSDActiveConditions AS (
    SELECT 
        Id,
        Title,
		OT.OrderIndex,
        Condition = CASE 
            WHEN Id = 1 THEN 'Tobacco=1'  
            WHEN Id = 2 THEN 'Smoker=1'  
            WHEN Id = 3 THEN 'Alcohol=1'  
            WHEN Id = 4 THEN '"BMI=''Underweight''"'  
            WHEN Id = 5 THEN '"BMI=''Overweight''"'  
            WHEN Id = 6 THEN '"BMI=''Obese''"'  
            WHEN Id = 9 THEN '"BloodPressure=''PreHypertension''"'  
            WHEN Id = 10 THEN '"BloodPressure=''Hypertension''"'  
            WHEN Id = 11 THEN '"FBS=''Pre Diabetic''"'  
            WHEN Id = 12 THEN '"FBS=''Diabetic''"'  
            WHEN Id = 28 THEN '"Cholesterol=''Hypercholesterolemia''"'  
            WHEN Id = 29 THEN '"Cholesterol=''Borderline Cholesterol''"'  
            WHEN Id = 30 THEN '"Triglyceride=''Hypertriglyceridemia''"'  
            WHEN Id = 31 THEN '"Triglyceride=''Borderline Triglyceride''"'  
            WHEN Id = 32 THEN '"LDL=''Elevated  LDL''"'  
            WHEN Id = 33 THEN '"LDL=''Borderline LDL''"'  
            WHEN Id = 34 THEN '"HDL=''Low HDL''"'  
            WHEN Id = 49 THEN 'ExAlcohol=1'  
            WHEN Id = 50 THEN 'ExSmoker=1'  
            WHEN Id = 51 THEN 'ExTobacco=1'  
            WHEN Id = 53 THEN 'CVDMajorRisk=1'  
            WHEN Id = 54 THEN 'CVDMinorRisk=1'  
            WHEN Id = 55 THEN 'NCDsRisk=1'  
            WHEN Id = 56 THEN '"T3=''Elevated T3''"'  
            WHEN Id = 58 THEN '"TSH=''Elevated TSH''"'  
            WHEN Id = 60 THEN '"TotalBillirubin=''High Serum Billirubin''"'  
            WHEN Id = 62 THEN '"UricAcid=''Hyperuricemia''"'  
            WHEN Id = 65 THEN '"T3=''Low T3''"'  
            WHEN Id = 66 THEN '"T4=''Low T4''"'  
            WHEN Id = 67 THEN '"TSH=''Low TSH''"'  
            WHEN Id = 68 THEN '"PLATELETS=''Thrombocytopenia''"'  
            WHEN Id = 69 THEN '"VitaminB12=''Vitamin B12 deficiency''"'  
            WHEN Id = 70 THEN '"VitaminD3=''Vitamin D3 deficiency''"'
			WHEN Id = 71 THEN 'IsNewHypertensionStatus=1'
			WHEN Id = 72 THEN 'IsNewHypertensionStatus=2'
			WHEN Id = 73 THEN 'IsNewDiabeticStatus=1'
			WHEN Id = 74 THEN 'IsNewDiabeticStatus=2'
			WHEN Id = 75 THEN '"BMI=''Morbidly Obese''"'
			WHEN Id = 76 THEN '"VitaminD3=''Vitamin D3 Toxicity Risk''"'
            ELSE ''
        END
    FROM sExamination.tDiagnosisTrackerMaster TM
    INNER JOIN sExamination.tDiagnosisTrackerOrg OT ON TM.Id = OT.DiagnosisTrackerId
    WHERE TM.IsObsolete = 0 AND OT.OrgId = @rOrgId
        AND TM.Id IN (1,2,3,4,5,6,9,10,11,12,28,29,30,31,32,33,34,49,50,51,53,54,55,56,58,60,62,65,66,67,68,69,70,71,72,73,74,75,76)
)
SELECT @lLSDColumnName += '<tr><td><input id="' + CONVERT(VARCHAR, Id) + '" onclick="MessageBoxDivHide();" Condition=' + 
       Condition + ' type="checkbox" />         <label for="CheckBoxListColumnName">' + Title + '</label></td></tr>'
FROM LSDActiveConditions
ORDER BY OrderIndex ASC;

-- Add medication conditions with proper spacing
SET @lLSDColumnName += '<tr><td><input id="0" onclick="MessageBoxDivHide();" Condition="IsonSugarMedication=1" type="checkbox" /> <label for="CheckBoxListColumnName">IsonDiabetesMedication</label></td></tr> ';
SET @lLSDColumnName += '<tr><td><input id="0" onclick="MessageBoxDivHide();" Condition="IsonBPMedication=1" type="checkbox" /> <label for="CheckBoxListColumnName">IsonHypertensionMedication</label></td></tr> ';
    -- Return all results
    SELECT  
        @ExaminationType AS ExaminationType,
        '<option value="0"> -- Select -- </option>' AS RoundGroup,
        @HealthIndicator AS HealthIndicator,
        @LocationMainGroup AS LocationMainGroup,
        @FunctionMaster AS FunctionMaster,
        '<option value="0"> -- All -- </option>' AS StoreLocation,
        @StoreLocation AS SubLocation,
        @Sector AS Sector,
        @HealthIndexParameter AS HealthIndexParameter,
        @HealthIndexParameterList AS HealthIndexParameterList,
        '<option value="0"> -- All -- </option>' AS Round,
        @MyLocation AS MyLocation,
        @NotificationGroup AS NotificationGroup,
        @lColumnName AS ColumnName,
        '<option value="AND">AND</option><option value="OR">OR</option>' AS Condition,
        @TargetGroup AS TargetGroup,
        @FolderName AS FolderName,
        @lLSDColumnName AS lLSDColumnName,
        @EmployeeTypeGroup AS EmployeeTypeGroup,
        @EmployeeType AS EmployeeType,
        @EmployeeSubType AS EmployeeSubType;

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


GO

ALTER PROCEDURE [sExamination].[pGetAdditionalFieldConsultation]
@rSourceTypeId int = 3,
@rExaminationTypeId int = 17,
@rSourceId bigint = 0,
@rVisitPurposeId int = 0
as
BEGIN
	select 
		Item as Item,
		case when Upper(AdditionalFieldResponse)=Upper(Item) then ' selected' else '' end as AdditionalFieldResponse,
		InS.Id as InSId
		From sExamination.tAdditionalFieldSetup InS
		LEFT JOIN [sWellness].[tConsultationAdditionalFieldDetails] AFF ON InS.Id= AFF.AdditionalFieldSetupId and Isnull([AdditionalFieldId],0)=0
		Cross apply [sCommon].[fnSplit](FieldList,',')
		where FieldTypeId=2 and ISNULL(InS.SourceTypeId, 0) = @rSourceTypeId and ISNULL(InS.VisitPurposeId, 0) = @rVisitPurposeId
		and (ISNULL(InS.ExaminationTypeId, 0) = @rExaminationTypeId OR @rExaminationTypeId = 0)

	IF(@rSourceId > 0 AND EXISTS (Select Id FROM [sWellness].[tConsultationAdditionalFieldMaster] where ConsultationId = @rSourceId))
	BEGIN
		
		SELECT Id as AdditionalFieldId FROM [sWellness].[tConsultationAdditionalFieldMaster] where ConsultationId = @rSourceId
	END
	ELSE
	BEGIN
		SELECT 0 as AdditionalFieldId
	END

	IF EXISTS (Select Top 1 CAFM.Id from [sWellness].[tConsultationAdditionalFieldMaster] CAFM
				INNER JOIN [sWellness].[tWellnessConsultation] WC ON WC.Id = CAFM.ConsultationId
	           where ConsultationId = @rSourceId AND WC.CauseId = @rVisitPurposeId)
	BEGIN
		SELECT
			Isnull(convert(varchar,AFF.Id),'''''') as AFFId,
			convert(varchar,InS.Id)  as InSId,
			convert(varchar,Isnull(IsFieldMandatory,'0')) as IsFieldMandatory,
			convert(varchar,Isnull(InS.FieldTypeId,'0')) as InSFieldTypeId,
			Isnull(INS.FieldGroup,'') as FieldGroup,
			Isnull(INS.FieldRemark,'') as FieldRemark,
			convert(varchar,ISNULL([AdditionalFieldResponse],'')) as AdditionalFieldResponse,
			case when InS.FieldTypeId = 2 and @rSourceId <> 0 then [dbo].[fGetDropDownAdditionalFieldSetupNg](@rSourceId,Ins.Id)
				 else '' end as DropDownAdditionalSetup 
			FROM sExamination.tAdditionalFieldSetup InS
			LEFT JOIN [sWellness].[tConsultationAdditionalFieldDetails] AFF ON InS.Id= AFF.AdditionalFieldSetupId --and (@rSourceId <> 0 OR (@rSourceId = 0 and Isnull([AdditionalFieldId],0)=0))
			Where ISNULL(InS.SourceTypeId, 0) = @rSourceTypeId and ISNULL(InS.VisitPurposeId, 0) = @rVisitPurposeId
			and (ISNULL(InS.ExaminationTypeId, 0) = @rExaminationTypeId OR @rExaminationTypeId = 0)
			AND (Isnull([AdditionalFieldId],0) = (Select Top 1 Id from [sWellness].[tConsultationAdditionalFieldMaster] where ConsultationId = @rSourceId))
			ORDER BY FieldOrder
	END
	ELSE
	BEGIN
			SELECT
			Isnull(convert(varchar,AFF.Id),'''''') as AFFId,
			convert(varchar,InS.Id)  as InSId,
			convert(varchar,Isnull(IsFieldMandatory,'0')) as IsFieldMandatory,
			convert(varchar,Isnull(InS.FieldTypeId,'0')) as InSFieldTypeId,
			Isnull(INS.FieldGroup,'') as FieldGroup,
			Isnull(INS.FieldRemark,'') as FieldRemark,
			convert(varchar,ISNULL([AdditionalFieldResponse],'')) as AdditionalFieldResponse,
			case when InS.FieldTypeId = 2 and @rSourceId <> 0 then [dbo].[fGetDropDownAdditionalFieldSetupNg](@rSourceId,Ins.Id)
				 else '' end as DropDownAdditionalSetup 
			FROM sExamination.tAdditionalFieldSetup InS
			LEFT JOIN [sWellness].[tConsultationAdditionalFieldDetails] AFF ON InS.Id= AFF.AdditionalFieldSetupId and Isnull([AdditionalFieldId],0)=0
			Where ISNULL(InS.SourceTypeId, 0) = @rSourceTypeId and ISNULL(InS.VisitPurposeId, 0) = @rVisitPurposeId
			and (ISNULL(InS.ExaminationTypeId, 0) = @rExaminationTypeId OR @rExaminationTypeId = 0)
			ORDER BY FieldOrder
	END
END
GO
PRINT N'Altering Procedure [sExamination].[pGetAnnualHealthCheckupTicketAssignedAllDoctor]...';


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

    -- ================= DOCTOR SUMMARY =================
    SELECT          
        EM.Id,        
        ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS EmployeeName,        
        EC.CompanyEmail AS ToDoctor,        
        STUFF((
            SELECT DISTINCT ',' + EC2.CompanyEmail        
            FROM sSupport.tProviderAppointment A2        
            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        
            FOR XML PATH(''), TYPE        
        ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') AS CCDoctor        
    INTO #DoctorAssignmentSummary        
    FROM sSupport.tProviderAppointment A        
    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 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;        


    -- ================= COUNT DATA =================
    SELECT          
        D.Id,        
        D.ToDoctor,        
        D.CCDoctor,        
        D.EmployeeName,        
        SUM(CASE WHEN A.AssignDate >= DATEADD(HOUR, -48, GETDATE()) THEN 1 ELSE 0 END) AS NewAssigned,        
        SUM(CASE WHEN A.AssignDate < DATEADD(HOUR, -48, GETDATE()) THEN 1 ELSE 0 END) AS LongOpen,  
        SUM(CASE WHEN A.HealthIndicatorId = 608 THEN 1 ELSE 0 END) AS HighRisk,  
        SUM(CASE WHEN A.HealthIndicatorId = 607 THEN 1 ELSE 0 END) AS Pending,  
        SUM(CASE WHEN A.HealthIndicatorId = 611 THEN 1 ELSE 0 END) AS Mild,  
        SUM(CASE WHEN A.HealthIndicatorId = 612 THEN 1 ELSE 0 END) AS Moderate  
    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;        


    -- ================= FINAL OUTPUT =================
    SELECT          
        C.Id,        
        C.ToDoctor AS EmailId,        
        C.CCDoctor AS strCC,        
        C.NewAssigned,   
        C.LongOpen,       
        C.Pending,        
        C.HighRisk,     
        C.Mild,        
        C.Moderate,     
        @rMailSubject AS Subject,

        CA1.MsgText
    FROM #CountDoctorAssign C       

    -- ================= TEMPLATE BUILD =================
    CROSS APPLY (
        SELECT 
            REPLACE(
            REPLACE(
                @rTemplate,
                '[AssignedDoctor]', C.EmployeeName
            ),
            '[dynamicfield]',

            CONCAT(

                 CASE WHEN C.NewAssigned > 0 
                    THEN 'New Assigned: ' + CAST(C.NewAssigned AS NVARCHAR(20)) + ' <br/> '
                    ELSE '' END,

                CASE WHEN C.LongOpen > 0 
                    THEN 'Long Open: ' + CAST(C.LongOpen AS NVARCHAR(20)) + ' <br/> '
                    ELSE '' END,

                CASE WHEN C.Pending > 0 
                    THEN 'Pending: ' + CAST(C.Pending AS NVARCHAR(20)) + ' <br/> '
                    ELSE '' END,

                CASE WHEN C.HighRisk > 0 
                    THEN 'High Risk: ' + CAST(C.HighRisk AS NVARCHAR(20)) + ' <br/> '
                    ELSE '' END,

                CASE WHEN C.Mild > 0 
                    THEN 'Mild: ' + CAST(C.Mild AS NVARCHAR(20)) + ' <br/> '
                    ELSE '' END,

                CASE WHEN C.Moderate > 0 
                    THEN 'Moderate: ' + CAST(C.Moderate AS NVARCHAR(20)) 
                    ELSE '' END

            )
        )
    ) CA1(MsgText)


    -- ================= CLEANUP =================
    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'Altering Procedure [sExamination].[pGetOPDReferToDoctorBasedOnDesignation]...';


GO

ALTER Procedure [sExamination].[pGetOPDReferToDoctorBasedOnDesignation]  
@rOrgId INT,  
@rDesignationId INT,  
@rEmployeeLocationId INT = 0,
@rEmployeeId bigint
AS  
BEGIN  
declare @lAssignDoctorFreezeWiseOrEntityWiseConfigVal varchar(5); 
            
 select @lAssignDoctorFreezeWiseOrEntityWiseConfigVal = sConfig.fConfigurationValueGet('Provider.AssignDoctorFreezeWiseOrEntityWise',@rOrgId,0,0,0);

 IF (@lAssignDoctorFreezeWiseOrEntityWiseConfigVal = 'TRUE')
 BEGIN
	 IF(@rDesignationId = 9)  
	 BEGIN  
		SELECT DISTINCT HeadEmployeeId as Id, ISNULL(
				CASE 
					WHEN EM.EmployeePrefix IS NULL OR EM.EmployeePrefix = '' 
					THEN EM.FirstName + ' ' + EM.LastName
					ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName
				END, 
			'') AS Title from sHrm.tEntityHead EH  
		  INNER JOIN sExamination.tSetupEmployee SE ON SE.SiteDoctorId = EH.HeadEmployeeId
		  INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.HeadEmployeeId
		  WHERE DesignationId = @rDesignationId and EM.OrgId = @rOrgId and SE.EmployeeId = @rEmployeeId
	 END  
	 ELSE IF(@rDesignationId = 10) 
	 BEGIN  
		  SELECT DISTINCT HeadEmployeeId as Id, ISNULL(
				CASE 
					WHEN EM.EmployeePrefix IS NULL OR EM.EmployeePrefix = '' 
					THEN EM.FirstName + ' ' + EM.LastName
					ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName
				END, 
			'') AS Title from sHrm.tEntityHead EH  
		  INNER JOIN sExamination.tSetupEmployee SE ON SE.CentralDoctorId = EH.HeadEmployeeId
		  INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.HeadEmployeeId
		  WHERE DesignationId = @rDesignationId and EM.OrgId = @rOrgId and SE.EmployeeId = @rEmployeeId
	 END
	 ELSE
	 BEGIN
		SELECT DISTINCT HeadEmployeeId as Id, ISNULL(
				CASE 
					WHEN EM.EmployeePrefix IS NULL OR EM.EmployeePrefix = '' 
					THEN EM.FirstName + ' ' + EM.LastName
					ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName
				END, 
			'') AS Title from sHrm.tEntityHead EH
			INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.HeadEmployeeId
			WHERE DesignationId = @rDesignationId
	 END
 END
 ELSE
 BEGIN
	 IF(@rDesignationId = 9)  
	 BEGIN  
		  SELECT DISTINCT HeadEmployeeId as Id, ISNULL(
				CASE 
					WHEN EM.EmployeePrefix IS NULL OR EM.EmployeePrefix = '' 
					THEN EM.FirstName + ' ' + EM.LastName
					ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName
				END, 
			'') AS Title from sHrm.tEntityHead EH  
		  INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.HeadEmployeeId  
		  WHERE DesignationId = @rDesignationId and OrgId = @rOrgId
		  and EntitySourceTypeId = 1014 and EntitySourceId IN (Select Id from sIp.tStoreLocationMaster where LocationId = @rEmployeeLocationId)
	 END  
	 ELSE IF(@rDesignationId = 10)
	 BEGIN  
		  SELECT DISTINCT HeadEmployeeId as Id,  ISNULL(
				CASE 
					WHEN EM.EmployeePrefix IS NULL OR EM.EmployeePrefix = '' 
					THEN EM.FirstName + ' ' + EM.LastName
					ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName
				END, 
			'') AS Title from sHrm.tEntityHead EH  
		  INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.HeadEmployeeId  
		  WHERE DesignationId = @rDesignationId and OrgId = @rOrgId  
	 END
	 ELSE
	 BEGIN
		SELECT DISTINCT HeadEmployeeId as Id, ISNULL(
				CASE 
					WHEN EM.EmployeePrefix IS NULL OR EM.EmployeePrefix = '' 
					THEN EM.FirstName + ' ' + EM.LastName
					ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + EM.LastName
				END, 
			'') AS Title from sHrm.tEntityHead EH
			INNER JOIN [sHrm].[tEmployeeMaster] EM ON EM.Id = EH.HeadEmployeeId
			WHERE DesignationId = @rDesignationId
	 END
 END
END
GO
PRINT N'Altering Procedure [sExamination].[pHealthIndexGradeBind]...';


GO

ALTER PROC [sExamination].[pHealthIndexGradeBind] 
@rOrgID int,
@rHealthIndexGroupId int,
@rRoundGroupId int=0
AS
BEGIN

    DECLARE @HealthIndexGradeList nvarchar(max) = ''
    DECLARE @HealthIndexParameterList nvarchar(max) = ''


    SELECT @HealthIndexGradeList = @HealthIndexGradeList + '
	<tr>
		<td><input type="checkbox" ' + CASE
        WHEN hig.GradeId IS NOT NULL THEN 'checked'
        ELSE ''
    END + '   attrid=' + CONVERT(varchar, grd.Id) + '></td>
		<td>' + +CONVERT(varchar, ROW_NUMBER() OVER (ORDER BY Title)) + '</td>
		<td>' + ISNULL(grd.Code, '') + '</td>
		<td>' + ISNULL(grd.Title, '') + '</td>
	</tr>

	'
    FROM sHrm.tGradeMaster AS grd
    LEFT JOIN sExamination.tHealthIndexGroupGrade AS hig ON hig.GradeId = grd.Id AND hig.HealthIndexGroupId = @rHealthIndexGroupId and (ISNULL(hig.RoundGroupId,0) = @rRoundGroupId)
    WHERE IsObsolete = 0 AND OrgId = @rOrgID
    ORDER BY Title



    SELECT @HealthIndexParameterList = @HealthIndexParameterList + '
	<tr>
		<td><input type="checkbox"  ' + CASE
        WHEN hig.HealthIndexParameterId IS NOT NULL THEN 'checked'
        ELSE ''
    END + ' attrid=' + CONVERT(varchar, hpm.Id) + '></td>
		<td>' + CONVERT(varchar, ROW_NUMBER() OVER (ORDER BY Id)) + '</td>
		<td>' + ISNULL(hpm.Code, '') + '</td>
		<td>' + ISNULL(hpm.Title, '') + '</td>
	</tr>

	'
    FROM sExamination.tStaticHealthIndexParameterMaster AS hpm
    LEFT JOIN sExamination.tHealthIndexGroupParameter AS hig ON hig.HealthIndexParameterId = hpm.Id AND hig.HealthIndexGroupId = @rHealthIndexGroupId and (ISNULL(hig.RoundGroupId,0) = @rRoundGroupId)
    --WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 13, 16, 17)
	WHERE id NOT IN (12,14,18,19,21)
    ORDER BY Id




    IF (@rHealthIndexGroupId > 0)
    BEGIN
        SELECT HealthIndexGradeList = @HealthIndexGradeList, HealthIndexParameterList = @HealthIndexParameterList
    END
    ELSE
    BEGIN
        SELECT HealthIndexGradeList = '', HealthIndexParameterList = ''
    END


    SELECT grd.Id, grd.Code, grd.Title, hig.GradeId
    FROM sHrm.tGradeMaster AS grd
    LEFT JOIN sExamination.tHealthIndexGroupGrade AS hig ON hig.GradeId = grd.Id AND hig.HealthIndexGroupId = @rHealthIndexGroupId and (ISNULL(hig.RoundGroupId,0) = @rRoundGroupId)
    WHERE IsObsolete = 0 AND OrgId = @rOrgID
    ORDER BY Title

    SELECT hpm.Id, hpm.Code, hpm.Title, hig.HealthIndexParameterId
    FROM sExamination.tStaticHealthIndexParameterMaster AS hpm
    LEFT JOIN sExamination.tHealthIndexGroupParameter AS hig ON hig.HealthIndexParameterId = hpm.Id AND hig.HealthIndexGroupId = @rHealthIndexGroupId and (ISNULL(hig.RoundGroupId,0) = @rRoundGroupId)
    --WHERE id IN (1, 2, 3, 4, 5, 6, 7, 8, 10, 11,  13,  16, 17)
	WHERE Id NOT IN (12,14,18,19,21)
    ORDER BY Id


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


GO

ALTER PROCEDURE [sExamination].[pHealthIndexParameterDetailAdd]
@rId int,
@rCount int, 
@rHealthIndexParameterId int,
@rFieldName nvarchar(50),
@rFromValue nvarchar(50),
@rToValue nvarchar(50),
@rPoints int,
@rGenderId tinyint,
@rIsDelete bit,
@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
		--BEGIN TRY	
  -- BEGIN TRANSACTION
  
 Declare @lTypeId int
 SELECT @lTypeId= HealthIndexParameterTypeId from sExamination.tHealthIndexParameterMaster WHERE Id=@rHealthIndexParameterId AND OrgId = @rOrgId

IF(@rId = 0)
BEGIN

IF EXISTS (select 1 from sExamination.tHealthIndexParameterMaster HPM
INNER JOIN sExamination.tHealthIndexParameterDetail HPD ON HPD.HealthIndexParameterId=HPM.Id
WHERE HPM.HealthIndexParameterTypeId=@lTypeId AND HPM.OrgId = @rOrgId AND GenderId=@rGenderId AND HPD.FieldName like @rFieldName AND @lTypeId IN (4,5) AND @rCount=1) 
	BEGIN
			SELECT -200 AS Result
			RETURN
	END


 IF EXISTS (select 1 from sExamination.tHealthIndexParameterDetail where  FieldName = @rFieldName AND OrgId = @rOrgId AND GenderId=@rGenderId AND @rCount=1 AND @lTypeId IN (1,2,3,11,12))
	BEGIN
--Already Exists
		SELECT -200 AS Result
		RETURN
	END	  

	
	DECLARE @lNextNumber BIGINT     
	--EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sExamination.tHealthIndexParameterDetail', 0, 1, 1,@outNextNumber = @lNextNumber output
	SELECT @lNextNumber = ISNULL(MAX(Id), 0) + 1
	FROM sExamination.tHealthIndexParameterDetail where OrgId = @rOrgId

	INSERT INTO sExamination.tHealthIndexParameterDetail
		(
			Id,
			HealthIndexParameterId,
			FieldName,
			FromValue,
			ToValue,
			Points,
			GenderId,
			OrgId
		)
	VALUES
		(
			@lNextNumber,
			@rHealthIndexParameterId,
			@rFieldName,
			@rFromValue,
			@rToValue,
			@rPoints,
			@rGenderId,
			@rOrgId
		)

	 EXEC sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tHealthIndexParameterDetail', 
	 @rCurrentNumber = @lNextNumber

	END
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	 IF(@rIsDelete = 1)
		 BEGIN
	 DELETE FROM sExamination.tHealthIndexParameterDetail  WHERE Id = @rId 	
	 END
	
  END
  SELECT @lNextNumber AS Result
	 -- COMMIT TRANSACTION
  --       END TRY
         
  --      BEGIN CATCH
		--ROLLBACK TRANSACTION
		--SELECT -1 AS RESULT
	 --   END CATCH	
END
GO
PRINT N'Altering Procedure [sExamination].[pLoadEmployeeAgeWiseListGet]...';


GO

ALTER PROCEDURE [sExamination].[pLoadEmployeeAgeWiseListGet]
(  
@rOrgId int = 0,
@rLocationId int,
@rFromAge int = 0, 
@rToAge int = 0,
@rBirthMonth int = 0, 
@SortColumnName NVARCHAR(MAX)= '',
@IsAscendingOrder bit= 0,
@PageNumber int = 1,
@PageSize int = 20,
@GlobalSearch NVARCHAR(MAX)= ''
)
AS  
SET NOCOUNT ON  
BEGIN
  	;WITH PageNumbers AS(
	select 
	ROW_NUMBER() OVER(
			ORDER BY CASE WHEN @SortColumnName = 'EmployeeCode' AND @IsAscendingOrder = 0 THEN t.EmployeeCode END DESC,
					 CASE WHEN @SortColumnName = 'EmployeeCode' AND @IsAscendingOrder = 1 THEN t.EmployeeCode END,
					 CASE WHEN @SortColumnName = 'EmployeeName' AND @IsAscendingOrder = 0 THEN t.EmployeeName END DESC,
					 CASE WHEN @SortColumnName = 'EmployeeName' AND @IsAscendingOrder = 1 THEN t.EmployeeName END,
					 CASE WHEN @SortColumnName = 'CompanyEmail' AND @IsAscendingOrder = 0 THEN t.CompanyEmail END DESC,
					 CASE WHEN @SortColumnName = 'CompanyEmail' AND @IsAscendingOrder = 1 THEN t.CompanyEmail END,
					 CASE WHEN @SortColumnName = 'Age' AND @IsAscendingOrder = 0 THEN t.Age END DESC,
					 CASE WHEN @SortColumnName = 'Age' AND @IsAscendingOrder = 1 THEN t.Age END,
					 CASE WHEN @SortColumnName = 'Department' AND @IsAscendingOrder = 0 THEN t.Department END DESC,
					 CASE WHEN @SortColumnName = 'Department' AND @IsAscendingOrder = 1 THEN t.Department END,
					 CASE WHEN @SortColumnName = '' THEN t.EmployeeId END DESC
	) EID,
	COUNT(*) OVER() 'RecordCount',
	* from (
 SELECT EM.Id AS EmployeeId,  
 EM.Code AS EmployeeCode,  
 ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS EmployeeName,  
 95 AS ParticipantSourceTypeId,      
 JD.OrganizationDepartmentId AS OrganizationDepartmentId,  
 DM.Title AS Department, 
 A.Age AS Age, 
 ISNULL(EC.CompanyEmail,'') as CompanyEmail
 FROM   
 sHrm.tEmployeeMaster EM
 left join sHrm.tEmployeeJobDetail JD on JD.EmployeeId = EM.Id
 left join sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
 left join sCommon.tOrganizationDepartmentMaster DM on DM.Id = JD.OrganizationDepartmentId
 left join sHrm.tEmployeeCommunications EC on EC.EmployeeId = EM.Id
 CROSS APPLY (
    SELECT Age =
        DATEDIFF(YEAR, EPD.DateOfBirth, GETDATE()) 
        - CASE 
            WHEN DATEADD(YEAR, DATEDIFF(YEAR, EPD.DateOfBirth, GETDATE()), EPD.DateOfBirth) > GETDATE() 
            THEN 1 ELSE 0 
          END
) A
 WHERE EM.OrgId = @rOrgId AND EM.StatusId = 7
 AND JD.EmployeeLocationId = @rLocationId
 AND Isnull(EM.IsObsolete,0)=0
 AND (@rFromAge = 0 OR A.Age >= @rFromAge)
    AND (@rToAge = 0 OR A.Age <= @rToAge)
    AND (@rBirthMonth = 0 OR MONTH(EPD.DateOfBirth) = @rBirthMonth)
 ) t where  (ISNULL(@GlobalSearch,'') = '' OR ISNULL(t.EmployeeCode,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										   OR ISNULL(t.EmployeeName,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										   OR ISNULL(t.CompanyEmail,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										   OR ISNULL(t.Age,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%'
										   OR ISNULL(t.Department,'') LIKE '%'+ISNULL(@GlobalSearch,'')+'%')
	)
	SELECT  *
	FROM    PageNumbers
	WHERE  (@PageSize = -1 OR EID  BETWEEN ((@PageNumber - 1) * @PageSize + 1) AND (@PageNumber * @PageSize))
END
GO
PRINT N'Altering Procedure [sExamination].[pLSDDashboardGridGet]...';


GO
-- exec [sExamination].[pLSDDashboardGridGet] 2,999900137,101
-- drop proc [sExamination].[pLSDDashboardGridGet]
ALTER proc [sExamination].[pLSDDashboardGridGet]
@rOrgId int,
@rStoreLocationId int,
@rUserId bigint,
@rTypeId int,
@rtyp int,
@rsqlcondition varchar(50),
@rPageIndex int
as
begin
	declare @lResultHeader varchar(max) = '',@lResultGrid varchar(max) = '',@lResultPaging varchar(max)=''
	declare @lPageSize int = 100,@lCount int,@rFromDate varchar(100)='',@rToDate varchar(100)=''
	
	declare @SqlStatement nvarchar(max)='',@SqlSelect nvarchar(max)='',@SqlTables nvarchar(max)=''
	declare @SqlWheres nvarchar(max)='',@Sqlorders nvarchar(max)=''

	select @rToDate=convert(varchar,getdate(),102)
	if(@rTypeId=1)
	begin
		select @rFromDate = convert(varchar,dateadd(mm,-1,getdate()),102)
	end
	else if(@rTypeId=2)
	begin
		select @rFromDate = convert(varchar,dateadd(mm,-3,getdate()),102)
	end
	else if(@rTypeId=3)
	begin
		select @rFromDate = convert(varchar,dateadd(mm,-6,getdate()),102)
	end
	if(@rTypeId=4)
	begin
		select @rFromDate = convert(varchar,dateadd(mm,-12,getdate()),102)
	end
	
	if @rtyp = 0
	begin
		select @lResultHeader = @lResultHeader + '<tr><th align="left" scope="col">No</th>
		<th align="left" scope="col">Employee Code</th><th align="left" scope="col">Employee Name</th>
		<th align="left" scope="col">Department</th></tr>'
	end
	else if @rtyp = 1
	begin
		select @lResultHeader = @lResultHeader + '<tr><th align="left" scope="col">Department</th>
		<th align="left" scope="col">Employee Count</th></tr>'		
	end
	else
	begin
		select @lResultHeader = @lResultHeader + '<tr><th align="left" scope="col">Company</th><th align="left" scope="col">Employee Count</th></tr>'
	end
	IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL
		DROP TABLE #tbltmpEmployeeList

	CREATE TABLE #tbltmpEmployeeList
	(tid int identity(1,1),EmployeeCode varchar(300),EmployeeName varchar(300),DepartmentName varchar(300),
	CompanyName varchar(300),EmployeeId bigint)
	select @SqlSelect=@SqlSelect+'insert into #tbltmpEmployeeList
	select Distinct EMP.Code,isnull(EMP.FirstName,'''') + '' '' + isnull(EMP.LastName,''''),isnull(DPT.Title,''Not Assigned''),
	isnull(ECM.Title,''Not Assigned''),EMP.Id
	
	FROM sExamination.tExamination AS EXM
	INNER JOIN [sExamination].[tSetupMaster] STM ON STM.ID = EXM.SetupId
	INNER JOIN [sExamination].[tSubTypeMaster] SSM ON SSM.Id = STM.SubTypeId
	INNER JOIN [sHrm].[tEmployeeMaster] EMP ON EMP.ID = EXM.ParticipantSourceId and Isnull(EMP.Isobsolete,0)=0
	INNER JOIN sExamination.tDiagnosisTrackerEmployee AS dte ON dte.ExaminationId = EXM.Id
	INNER JOIN ssecurity.tUserLocation UL on EXM.StoreLocationId = UL.StoreLocationId
	LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] AS DPT ON DPT.Id = EXM.OrganizationDepartmentId
	LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM ON ECM.Id = EXM.EmployeeCompanyId
	WHERE EXM.ParticipantSourceTypeId = 95
	AND EXM.OrgId = ' + convert(varchar,@rOrgId) + '
	AND UL.UserId = ' + convert(varchar,@rUserId) + '
	AND (datediff(day,'''+@rFromDate+''',EXM.ExaminationDate)>=0)
	AND (datediff(day,EXM.ExaminationDate,'''+@rToDate+''')>=0 )
	AND '+ @rsqlcondition +''
	
	print @SqlSelect
	exec(@SqlSelect)

	declare @tbltmpEmployeeListDepartment table(tid int identity(1,1),EmployeeCnt varchar(300),DepartmentName varchar(300))
	insert into @tbltmpEmployeeListDepartment
	select count(EmployeeId),DepartmentName from #tbltmpEmployeeList group by DepartmentName
	
	declare @tbltmpEmployeeListCompany table(tid int identity(1,1),EmployeeCnt varchar(300),CompanyName varchar(300))
	insert into @tbltmpEmployeeListCompany
	select count(EmployeeId),CompanyName from #tbltmpEmployeeList group by CompanyName
	
	if @rtyp=0 -- Employee Wise List
	begin
		select @lCount = count(*) from #tbltmpEmployeeList
		select @lResultPaging = @lResultPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lCount,@lPageSize)
		
		select @lResultGrid = @lResultGrid + '<tr><td>' + convert(varchar,tid) + '</td>
		<td>' + isnull(EmployeeCode,'') + '</td><td>' + isnull(EmployeeName,'') + '</td>
		<td>' + isnull(DepartmentName,'') + '</td></tr>' from #tbltmpEmployeeList
		where tid between ((@lPageSize * (@rPageIndex-1)) + 1) and (@lPageSize * @rPageIndex)		
	end
	else if @rtyp =1 -- Department Wise List
	begin
		select @lCount = count(*) from @tbltmpEmployeeListDepartment
		select @lResultPaging = @lResultPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lCount,@lPageSize)
		
		select @lResultGrid = @lResultGrid + '<tr><td>' + isnull(DepartmentName,'') + '</td>
		<td>' + convert(varchar,EmployeeCnt) + '</td></tr>' from @tbltmpEmployeeListDepartment
		where tid between ((@lPageSize * (@rPageIndex-1)) + 1) and (@lPageSize * @rPageIndex)		
	end
	else -- Company Wise List
	begin
		select @lCount = count(*) from @tbltmpEmployeeListDepartment
		select @lResultPaging = @lResultPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lCount,@lPageSize)
		
		select @lResultGrid = @lResultGrid + '<tr><td>' + isnull(CompanyName,'') + '</td>
		<td>' + convert(varchar,EmployeeCnt) + '</td></tr>' from @tbltmpEmployeeListCompany
		where tid between ((@lPageSize * (@rPageIndex-1)) + 1) and (@lPageSize * @rPageIndex)		
	end
	
	select isnull(@lResultGrid,'') as result,isnull(@lResultHeader,'') as header,isnull(@lResultPaging,'') as Paging , isnull(@rtyp,0) AS ExportType
	select * from #tbltmpEmployeeList
end
GO
PRINT N'Altering Procedure [sExamination].[pPatientListGetNg]...';


GO
--exec sExamination.pPatientListGetNg 999900513,9999,1,'','',0,'1/2/2019','1/2/2021',999900155
ALTER PROC  [sExamination].[pPatientListGetNg]
@rMainTypeId int,
@rOrgId int,
@rPageindex int,
@rCode varchar(200),
@rName varchar(200),
@rDoctor bigint,
@rfdate varchar(20),
@rtdate varchar(20),
@rStoreLocationId int
AS 
BEGIN 

set @rCode = replace(@rCode,'\\','\')
	select @rfdate = case when @rfdate <> '' then CONVERT(VARCHAR(10), CONVERT(date, @rfdate, 105), 23) else '' end
	select @rtdate = case when @rtdate <> '' then CONVERT(VARCHAR(10), CONVERT(date, @rtdate, 105), 23) else '' end
	
	declare @rSetupId int,@result varchar(max)='',@lpaging varchar(max)='',@TotalRecords int,@PageSize int=10
	select @rSetupId = case when len(@rMainTypeId) > 4 then @rMainTypeId else sCommon.fGetIntIdForOrg(@rMainTypeId,@rOrgId) end
	
	declare @tblpatient table(tid int identity(1,1),pid bigint)
	insert into @tblpatient
	select R.Id
	from sExamination.tRegistration R
	left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = R.ParticipantSourceId AND R.ParticipantSourceTypeId = 1001
	left join sHrm.tEmployeeMaster EM2 on EM2.Id = EFD.EmployeeId
	left join sHrm.tEmployeeMaster EM on EM.Id = R.ParticipantSourceId AND R.ParticipantSourceTypeId = 95 
	left join sHrm.tCsrBenefiterMaster CSB on CSB.Id = R.ParticipantSourceId AND R.ParticipantSourceTypeId = 1009
	left join sHrm.tEmployeeMaster EM1 on EM1.Id = R.DoctorEmployeeId
	left join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId = EM.Id
	left join sCommon.tOrganizationDepartmentMaster ODM on ODM.Id = EJD.OrganizationDepartmentId
	inner join sExamination.vExtSetupMaster as VSM on VSM.Id = R.SetupId 
	where R.OrgId = @rOrgId and
	isnull(R.ExaminationId,0) = 0
	and (datediff(day,@rfdate,R.registrationDate)>=0 or @rfdate='') 
	and (datediff(day,R.registrationDate,@rtdate)>=0 or @rtdate='')
	and ((R.SetupId = @rSetupId) or (@rSetupId = 0))
	and ((R.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
	and ((R.DoctorEmployeeId = @rDoctor) or (@rDoctor = 0))
	and ((EM.Code like @rCode + '%') or (CSB.Code like @rCode + + '%') or (EM2.Code like @rCode + '%') or (isnull(@rCode,'') = ''))
	and (EM.FirstName like @rName + '%' or CSB.FirstName like @rName + '%' or EFD.Name like @rName + '%' or isnull(R.OtherName,'') like @rName + '%' or isnull(@rName,'')= '')
	order by R.Id desc
	
	select @TotalRecords = count(*)	from @tblpatient
	select @lpaging = @lpaging + dbo.fnc_SearchPagingFormat(@rPageindex,@TotalRecords,@PageSize)
	

	select isnull(R.Id,0) as Id,
	case when R.ParticipantSourceTypeId = 95 then	isnull(EM.Code,'')
	when R.ParticipantSourceTypeId = 1009 then isnull(CSB.Code,'') else isnull(EM2.Code,'') end as Code,
	isnull(R.OtherName,'') as OtherName,
	isnull(R.RegistrationNumber,'') as RegistrationNumber,
	case when R.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')
	when R.ParticipantSourceTypeId = 1009 then isnull(CSB.Code,'') else isnull(EM2.Code,'') end as PatientCode,
	case when R.ParticipantSourceTypeId = 95 then
	(isnull(EM.FirstName,'') + isnull(' ' + EM.MiddleName,'') + ' ' + isnull(EM.LastName,''))
	when R.ParticipantSourceTypeId = 1009 then case when isnull(R.OtherName,'') <> '' then isnull(R.OtherName,'') else
	(isnull(CSB.FirstName,'') + isnull(' ' + CSB.MiddleName, '') + ' ' + isnull(CSB.LastName,'')) end
	else isnull(EFD.Name,'') end as PatientName,
	isnull(EM1.FirstName,'') + isnull(' ' + EM1.MiddleName,'') + ' ' + isnull(EM1.LastName,'') as DoctorName,
	isnull(convert(varchar,R.RegistrationDate,103),'') as RegistrationDate,
    isnull(R.ParticipantSourceTypeId,0) as ParticipantSourceTypeId,
    case when R.ParticipantSourceTypeId = 95 then convert(varchar,isnull(EM.Id,0)) 
    when R.ParticipantSourceTypeId = 1009 THEN convert(varchar,isnull(CSB.Id,0)) ELSE convert(varchar,EFD.Id) end as EmployeeId,
    isnull(R.Id,0) as RegistrationId,
	isnull(R.ExaminationId,0) as ExaminationId,
    case when R.ParticipantSourceTypeId = 95 then isnull(EM.Code,'')
	when R.ParticipantSourceTypeId = 1009 then isnull(CSB.Code,'') else isnull(EM2.Code,'') end as EmployeeCode,
    case when R.ParticipantSourceTypeId = 95 then
	(isnull(EM.FirstName,'') + isnull(' ' + EM.MiddleName,'') + ' ' + isnull(EM.LastName,'') )
	when R.ParticipantSourceTypeId = 1009 then (isnull(CSB.FirstName,'') + isnull(' ' + CSB.MiddleName, '') + ' ' + isnull(CSB.LastName,'')) 
	else EFD.Name end as aName,
    --isnull(EP.GenderId,0)as GenderId,
	 case when R.ParticipantSourceTypeId = 95 then isnull(EP.GenderId,0)
	when R.ParticipantSourceTypeId = 1009 then isnull(CSB.GenderId,0) end as GenderId,
    case when R.ParticipantSourceTypeId = 95 then isnull((SELECT Title FROM sCommon.tGenderMaster WHERE Id=EP.GenderId),'')
	when R.ParticipantSourceTypeId = 1009 then isnull((SELECT Title FROM sCommon.tGenderMaster WHERE Id=CSB.GenderId),'') end as Gender,
    isnull(EP.DateOfBirth,'') as DOB,
    isnull(datediff(yy,EP.DateOfBirth,getdate()),0)as DateofDOB,
    isnull(EJD.OrganizationDepartmentId,0) as OrganizationDepartmentId,
    isnull(EJD.EmployeeDesignationId,0) as EmployeeDesignationId,
    isnull(R.DoctorEmployeeId,0) as DoctorEmployeeId,
    isnull((select Title from sHrm.tEmployeeDesignationMaster where Id = EJD.EmployeeDesignationId),'') as Title,
     isnull(EJD.ProcessTypeId,0)as ProcessTypeId,
     isnull(R.Age,0)as OtherAge,
     isnull(R.Months,0)as OtherMonths,
     isnull(R.GenderId,0)as OtherGenderId,
	 isnull(R.RegistrationDate,'')as RegistrationDate,
	 isnull(R.CompliantRemark,'')as CompliantRemark
    from sExamination.tRegistration R
    left join sHrm.tEmployeeFamilyDetails EFD on EFD.Id = R.ParticipantSourceId AND R.ParticipantSourceTypeId = 1001
	left join sHrm.tEmployeeMaster EM2 on EM2.Id = EFD.EmployeeId AND R.ParticipantSourceTypeId = 1001
	left join sHrm.tEmployeeMaster EM on EM.Id = R.ParticipantSourceId AND R.ParticipantSourceTypeId = 95 
	left join sHrm.tCsrBenefiterMaster CSB on CSB.Id = R.ParticipantSourceId AND R.ParticipantSourceTypeId = 1009
	left join sHrm.tEmployeeMaster EM1 on EM1.Id = R.DoctorEmployeeId
	left join sHrm.tEmployeeJobDetail EJD on EJD.EmployeeId = EM.Id
	left join sCommon.tOrganizationDepartmentMaster ODM on ODM.Id = EJD.OrganizationDepartmentId
	left join sHrm.tEmployeePersonalDetail EP on R.ParticipantSourceId = EP.EmployeeId	
	inner join sExamination.vExtSetupMaster as VSM on VSM.Id = R.SetupId,
	@tblpatient t
	where t.pid = R.Id AND t.tid between ((@PageSize * (@rPageindex-1)) + 1) and (@PageSize * @rPageindex)
	order by t.tid
	
	select @TotalRecords AS TotalRecords,@rfdate,@rtdate
	select * from @tblpatient

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


GO
ALTER proc [sExamination].[pSaveAssignDoctor]  
@rOrgId int,  
@rSetupEmployeeId bigint,  
@rCentralDoctorCode nvarchar(500),  
@rSiteDoctorCode nvarchar(500),  
@rCentralSpocCode nvarchar(500),  
@rSiteSpocCode nvarchar(500) ,
@rUserId nvarchar(500)
AS  
BEGIN  
  
declare @CentralDoctorId bigint = 0,@SiteDoctorId bigint = 0,@CentralSpocId bigint = 0,@SiteSpocId bigint = 0,  
@rEmployeeId bigint, @rEmployeeBusinessId int, @SetupId int, @EmployeeStoreLocationId int;  
select @CentralDoctorId = Id from sHrm.tEmployeeMaster where Code = @rCentralDoctorCode  
select @SiteDoctorId = Id from sHrm.tEmployeeMaster where Code = @rSiteDoctorCode  
select @CentralSpocId = Id from sHrm.tEmployeeMaster where Code = @rCentralSpocCode  
select @SiteSpocId = Id from sHrm.tEmployeeMaster where Code = @rSiteSpocCode  
select @rEmployeeId = EmployeeId from sExamination.tSetupEmployee where Id=@rSetupEmployeeId  
select @SetupId = SetupId from sExamination.tSetupEmployee where Id=@rSetupEmployeeId  
select @EmployeeStoreLocationId = StoreLocationId from sExamination.tSetupMaster where Id=@SetupId  
  
update sExamination.tSetupEmployee set CentralDoctorId=@CentralDoctorId,SiteDoctorId=@SiteDoctorId,CentralSpocId=@CentralSpocId,SiteSpocId=@SiteSpocId where Id=@rSetupEmployeeId  
INSERT INTO sExamination.tSetupEmployeeLog
(
    SetupEmployeeId,
    SetupId,
    SetupGroupId,   -- ✅ NEW
    EmployeeId,
    OrgId,
    CriteriaGroupId,
    NotDoneRemark,
    PlannedExaminationDate,
    TargetGroupId,
    CentralDoctorId,
    SiteDoctorId,
    CentralSpocId,
    SiteSpocId,
    ActionDate,
    ActionBy
)
SELECT 
    SE.Id,
    SE.SetupId,
    SEM.SetupGroupId,   -- ✅ FROM SetupMaster
    SE.EmployeeId,
    SE.OrgId,
    SE.CriteriaGroupId,
    SE.NotDoneRemark,
    SE.PlannedExaminationDate,
    SE.TargetGroupId,
    SE.CentralDoctorId,
    SE.SiteDoctorId,
    SE.CentralSpocId,
    SE.SiteSpocId,
    sCommon.fGetDate(),
    @rUserId
FROM sExamination.tSetupEmployee SE
INNER JOIN sExamination.tSetupMaster SEM 
    ON SEM.Id = SE.SetupId
WHERE SE.Id = @rSetupEmployeeId;
  
set @rEmployeeBusinessId = (select ISNULL(VRM.SectorId, 0) from sHrm.tEmployeeMaster EM  
INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id  
  INNER JOIN sHrm.tEmployeeCompanyMaster ECM ON ECM.Id = EJD.EmployeeCompanyId  
  INNER join sHrm.tCompanyGroupMaster CGM on CGM.Id=ECM.CompanyGroupId  
  INNER join sHrm.tVerticalMaster VRM on VRM.Id=CGM.VerticalId  
  Where EM.Id=@rEmployeeId)  
  
--SiteDoctor  
IF (@SiteDoctorId > 0)  
BEGIN  
 --Organization  
 IF NOT EXISTS (SELECT 1 FROM [sHrm].[tEntityHead] e WHERE e.HeadEmployeeId = @SiteDoctorId   
     AND e.EntitySourceId = @rOrgId AND e.EntitySourceTypeId = 2010 AND e.DesignationId = 9)  
 BEGIN  
   INSERT INTO [sHrm].[tEntityHead] (EntitySourceTypeId, EntitySourceId, HeadEmployeeId, DesignationId)  
   SELECT 2010,@rOrgId,@SiteDoctorId, 9  
 END  
  
 IF (@rEmployeeBusinessId > 0)  
 BEGIN  
  --Business  
  IF NOT EXISTS (SELECT 1 FROM [sHrm].[tEntityHead] e WHERE e.HeadEmployeeId = @SiteDoctorId   
        and e.EntitySourceId = @rEmployeeBusinessId AND e.EntitySourceTypeId = 2012 AND e.DesignationId = 9)  
  BEGIN  
    INSERT INTO [sHrm].[tEntityHead] (EntitySourceTypeId, EntitySourceId, HeadEmployeeId, DesignationId)  
    SELECT 2012,@rEmployeeBusinessId,@SiteDoctorId, 9  
  END  
 END  
 IF (@EmployeeStoreLocationId > 0)  
 BEGIN  
  --Sub Location  
  IF NOT EXISTS (SELECT 1 FROM [sHrm].[tEntityHead] e WHERE e.HeadEmployeeId = @SiteDoctorId   
        and e.EntitySourceId = @EmployeeStoreLocationId AND e.EntitySourceTypeId = 1014 AND e.DesignationId = 9)  
  BEGIN  
    INSERT INTO [sHrm].[tEntityHead] (EntitySourceTypeId, EntitySourceId, HeadEmployeeId, DesignationId)  
    SELECT 1014,@EmployeeStoreLocationId,@SiteDoctorId, 9  
  END  
 END  
  
END  
  
--CentralDoctor  
IF (@CentralDoctorId > 0)  
BEGIN  
 --Organization  
 IF NOT EXISTS (SELECT 1 FROM [sHrm].[tEntityHead] e WHERE e.HeadEmployeeId = @CentralDoctorId   
     AND e.EntitySourceId = @rOrgId AND e.EntitySourceTypeId = 2010 AND e.DesignationId = 10)  
 BEGIN  
   INSERT INTO [sHrm].[tEntityHead] (EntitySourceTypeId, EntitySourceId, HeadEmployeeId, DesignationId)  
   SELECT 2010,@rOrgId,@CentralDoctorId, 10  
 END  
  
 --Business  
 IF (@rEmployeeBusinessId > 0)  
 BEGIN  
  IF NOT EXISTS (SELECT 1 FROM [sHrm].[tEntityHead] e WHERE e.HeadEmployeeId = @CentralDoctorId   
      and e.EntitySourceId = @rEmployeeBusinessId AND e.EntitySourceTypeId = 2012 AND e.DesignationId = 10)  
  BEGIN  
   INSERT INTO [sHrm].[tEntityHead] (EntitySourceTypeId, EntitySourceId, HeadEmployeeId, DesignationId)  
   SELECT 2012,@rEmployeeBusinessId,@CentralDoctorId, 10  
  END  
 END  
 --Sub Location  
 IF (@EmployeeStoreLocationId > 0)  
 BEGIN  
  IF NOT EXISTS (SELECT 1 FROM [sHrm].[tEntityHead] e WHERE e.HeadEmployeeId = @CentralDoctorId   
      and e.EntitySourceId = @EmployeeStoreLocationId AND e.EntitySourceTypeId = 1014 AND e.DesignationId = 10)  
  BEGIN  
   INSERT INTO [sHrm].[tEntityHead] (EntitySourceTypeId, EntitySourceId, HeadEmployeeId, DesignationId)  
   SELECT 1014,@EmployeeStoreLocationId,@CentralDoctorId, 10  
  END  
 END  
END  
  
END
GO
PRINT N'Altering Procedure [sExamination].[pSMSHistoryGetfordashboard]...';


GO
ALTER PROCEDURE [sExamination].[pSMSHistoryGetfordashboard]                   
 @rEmployeeId Bigint,               
 @rOrgId smallint                  
              
                 
WITH EXECUTE AS CALLER                
AS                
SET NOCOUNT ON                
                
BEGIN             
Declare @rEmail nvarchar(100) set @rEmail = (select Top 1 CompanyEmail from sHrm.tEmployeeCommunications where EmployeeId=@rEmployeeId)    
    
    if (LEN(@rEmail) > 0)
	BEGIN
 SELECT  top 15                 
  AL.Id AS Id1,                
   AL.ContactId,                
  AL.AlertMessage  AS 'AlertMessage',            
   AL.AlertSubject,                
   AL.ResultMessage,                
   CASE WHEN AL.EventId>0 THEN EM.Title                
   ELSE AL.EventName                
   END AS EventName,                
   AL.SourceEvent,                
   U.DisplayTitle AS UserName,                
 --CONVERT(VARCHAR(10), AL.CreatedDateTime, 103) AS CreatedDateTime  --//as diss time not required 0051173
   AL.CreatedDateTime AS CreatedDateTime  
 FROM                
   sAlert.tAlertLog AL                
  LEFT JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId                
  INNER JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId                    
 WHERE AL.ContactId LIKE '%' + @rEmail + '%'               
 AND ((AL.OrgId=@rOrgId) OR (@rOrgId=0))          
 ANd AL.AlertModeId=1              
  ORDER BY AL.CreatedDateTime desc    
  END
END
GO
PRINT N'Altering Procedure [sExamination].[pVisitTypeMasterAdd]...';


GO

ALTER   PROCEDURE [sExamination].[pVisitTypeMasterAdd]	 
@rId int,
@rCode nvarchar(30),
@rTitle nvarchar(100),
@rIsObsolete bit,
@rOrgId smallint,
@rCreatedUserId bigint
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rId = 0)	
	BEGIN
		If Exists(select Id from sExamination.tVisitTypeMaster where Code=@rCode AND (OrgId=@rOrgId OR OrgId=1))
		BEGIN
			select -102 as Result
			RETURN
		END 

		If Exists(select Id from sExamination.tVisitTypeMaster where Title=@rTitle AND (OrgId=@rOrgId OR OrgId=1))
		BEGIN
			select -103 as Result
			RETURN
		END 
	END
	ELSE
	BEGIN
		If Exists(select Id from sExamination.tVisitTypeMaster where Code=@rCode AND (OrgId=@rOrgId OR OrgId=1) AND Id<>@rId)
		Begin
			select -102 as Result
			RETURN
		End
		
		If  Exists(select Id from sExamination.tVisitTypeMaster where Title=@rTitle AND (OrgId=@rOrgId OR OrgId=1) AND Id<>@rId)
		Begin
			select -103 as Result
			RETURN
		End
	END
	
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN		
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sExamination.tVisitTypeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		INSERT INTO sExamination.tVisitTypeMaster
		(
			Id,Code,Title,IsObsolete,OrgId,
			CreatedUserId,CreatedDateTime
		)
		VALUES
		(
			@lNextNumber,@rCode,@rTitle,@rIsObsolete,@rOrgId,
			@rCreatedUserId,sCommon.fGetDate()
		)

		SELECT 1 AS Result
	END
	ELSE
	BEGIN
		SET @lNextNumber = @rId
		UPDATE sExamination.tVisitTypeMaster 
		SET Code=@rCode,
		Title=@rTitle,
		UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=sCommon.fGetDate(),
		IsObsolete=@rIsObsolete
		WHERE Id = @rId
		SELECT 11 AS Result
	END
	COMMIT TRANSACTION
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeMasterAdd]...';


GO

ALTER PROCEDURE [sHrm].[pEmployeeMasterAdd]  
@rOrgId smallint,  
@rCode [nvarchar](100),  
@rFirstName [nvarchar](100),  
@rMiddleName [nvarchar](100),  
@rLastName [nvarchar](100),  
@rEmployeeTypeId int,  
@rDepartmentId int,  
@rLocationId int,  
@rDateOfBirth Date,  
@rDateOfJoining Date,  
@rGenderId int,  
@rStatusId [int],  
@rWorkLocationId [int],  
@rIsObsolete [bit],  
@rCreatedUserId [bigint],  
@rIsBirthDateUnknown bit,  
@OutEmployeeId bigint = null output,  
@rStoreLocationId int,  
@rContractorId int = null,   
@rEmployeeDesignationId INT,  
@rBloodGroupId INT = 0,  
@rEmployeeCompanyId INT = 0,  
@rProcessTypeId int,  
@rIsTemporary [bit] = 0,  
@rTemporaryCode [nvarchar](100)='',  
@rTargetGroupId int=0,  
@rDesignatedPositionId int=0,  
@rReferenceCode [nvarchar](100) = '',
@rEmployeePrefix [nvarchar](100) = '', 
@rNationalityId INT = 0  
  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
 DECLARE @lNextNumber BIGINT  
 DECLARE @loEmpNumber Nvarchar(100)  
 DECLARE @lEmpPrefixResult Int  
   
 IF(ISNULL(@rTemporaryCode,'') <> '') --15/03/2022 by Nidhi Pandey for Mantis : 0018096  
 BEGIN  
  IF EXISTS(SELECT Id FROM  sHrm.tEmployeeMaster where OrgID=@rOrgId AND TemporaryCode=@rTemporaryCode)  
  BEGIN     
   SELECT -2 AS RESULT  
   RETURN  
  END  
 END  
   
 if @rTemporaryCode = ''  
 begin  
  IF((@rCode = Null) OR (@rCode = ''))  
  BEGIN  
  IF EXISTS(SELECT Id FROM  sHrm.tEmployeeMaster where OrgID=@rOrgId AND Code=@rCode)  
   BEGIN     
    SELECT -2 AS RESULT  
    RETURN  
   END   
  END  
  IF((@rCode = Null) OR (@rCode = ''))  
  BEGIN  
   EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 94,@rStoreLocationId = 0, @rNextNumber = @loEmpNumber OUTPUT   
   SET @loEmpNumber = ISNULL(@loEmpNumber, '-300')  
   SET @lEmpPrefixResult = '-300'   
  END  
  ELSE  
  BEGIN  
   IF EXISTS(SELECT Id FROM sHrm.tEmployeeMaster where OrgID=@rOrgId AND Code=LTRIM(RTRIM(@rCode)))  
   BEGIN     
    SELECT -5 AS RESULT  
    RETURN  
   END
   ELSE  
   BEGIN  
   SET @loEmpNumber = @rCode  
   END  
  END  
 end  
  else  
 BEGIN  
  SET @loEmpNumber = 0  
 end  
   
 IF (@loEmpNumber <> '-300')  
 BEGIN  
  BEGIN TRY  
   BEGIN TRANSACTION  
   EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output  
  
   INSERT INTO sHrm.tEmployeeMaster  
   (  
    Id,Code,FirstName,MiddleName,LastName,StatusId,WorkLocationId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,  
    OrgId,IsTemporary,TemporaryCode,TargetGroupId,ReferenceCode ,EmployeePrefix 
   )  
   VALUES  
   (  
    @lNextNumber,case when isnull(@rTemporaryCode,'') <> '' then @rTemporaryCode else replace(@loEmpNumber,space(1),'') end,  
    @rFirstName,@rMiddleName,@rLastName,@rStatusId,isnull(@rWorkLocationId,0),@rIsObsolete,@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,  
    sCommon.fGetDate(),@rOrgId,@rIsTemporary,case when isnull(@rTemporaryCode,'') <> '' then @rTemporaryCode else replace(@loEmpNumber,space(1),'') end,@rTargetGroupId,@rReferenceCode ,@rEmployeePrefix 
   )  
  
   SELECT Id AS RESULT, case when @rIsTemporary = 1 then @rTemporaryCode else @loEmpNumber end AS EmpCode FROM sHrm.tEmployeeMaster WHERE  Id = @lNextNumber  
   SET @OutEmployeeId = @lNextNumber -- added for import employee  
  
   BEGIN              
    
    Execute sHrm.pEmployeeJobDetailAdd @rOrgId,@lNextNumber,0,@rEmployeeDesignationId,@rLocationId,@rDepartmentId,  
    @rDateOfJoining,'','',0,0,@rCreatedUserId,@rEmployeeCompanyId,@rEmployeeTypeId,@rContractorId,@rProcessTypeId,null,null,0,@rStoreLocationId,0,null,'',@rDesignatedPositionId  
  
    Execute sHrm.pEmployeePersonalDetailAdd @rOrgId,@lNextNumber,'',@rDateOfBirth,@rGenderId,0,0,'','',@rBloodGroupId,0,'','','','','',  
    0,'',0,'',0,0,@rCreatedUserId,@rIsBirthDateUnknown,'',null,'',@rNationalityId  
      
      
   END   
   COMMIT TRANSACTION  
  END TRY  
  BEGIN CATCH    
  
 ROLLBACK TRANSACTION   
   RAISERROR   
   (  
    'Error saving employee Master', -- Message text.  
    16, -- Severity.  
    1 -- State.  
   );  
  END CATCH  
 END    
 ELSE  
 BEGIN  
  SELECT @loEmpNumber AS RESULT  
 END     
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].[pStockItemForPrescriptionGet]...';


GO

ALTER   PROCEDURE [sIp].[pStockItemForPrescriptionGet]
@rOrgId int,
@rStockitemName Nvarchar(50) = '',
@rSubgroupCode Nvarchar(50) = '' ,	 
@rLocationId int,
@rSubGroupId int,
@rStockItemCategoryId int,
@rUserId bigint = null,
@rStoreLocationId int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN
		Select id,code,(StockItemName+' - (' + convert(varchar,Isnull(Quantity,'0'))+')')as StockItemName,
		StockItemName as StockItemTitle, DrugInstruction,DrugInstructionId,
		Dosage,IsNotInstore,IsAllowDirectIssue,Remark,ItemSubGroupId,StockItemCategoryId,IsGroupItem
		From(
		SELECT SIM.Id,SIM.Code,SIM.Title AS StockItemName,
		ISNULL(DI.Title,'') AS DrugInstruction,
		ISNULL(SIM.DrugInstructionId,0) AS DrugInstructionId,
		ISNULL(DI.Dosage,0) AS Dosage,SIM.IsNotInstore,
		SIM.IsAllowDirectIssue,SIM.Remark,
		SIM.ItemSubGroupId,SIM.StockItemCategoryId,
		(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
		WHERE SB.StockItemId = SIM.Id 
		AND ((SB.StorelocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
		and AvailableQuantity > 0 ) AS Quantity,Isnull(SIM.IsGroupItem,0) as IsGroupItem
		FROM sIp.tStockItemMaster SIM 
		INNER JOIN sIp.tItemSubGroupMaster SGM ON SGM.Id = SIM.ItemSubGroupId 
		LEFT JOIN sExamination.tDrugInstructionMaster DI ON DI.Id = SIM.DrugInstructionId
		--Inner join sProcurement.tStockBatch SB on SIM.Id=SB.StockItemId
		Where SIM.OrgId = @rOrgId AND SIM.IsObsolete = 0 
		AND SIM.IsDrug = 1 AND SIM.IsBlockedForIssue = 0
		--Developer: Deval, Date: 12/10/2023, Added Inhouse and RX
		AND ((@rStockitemName = 'InHouse' AND SIM.IsNotInstore = 0) OR (@rStockitemName = 'RX' AND SIM.IsNotInstore = 1) 
		OR (SIM.Title LIKE @rStockitemName + '%' ) OR (ISNULL(@rStockitemName, '') = ''))
		--AND ((SIM.Title LIKE @rStockitemName + '%' ) OR (ISNULL(@rStockitemName, '') = '')) 
		AND ((SGM.Code LIKE @rSubgroupCode) OR (ISNULL(@rSubgroupCode, '') = ''))
		AND (SIM.LocationId = @rLocationId) AND ((SIM.ItemSubGroupId = @rSubGroupId) or @rSubGroupId = -1)
		AND ((SIM.StockItemCategoryId = @rStockItemCategoryId) or @rStockItemCategoryId = -1)
		AND SIM.StockItemCategoryId not in (select ItemCategoryId from sSecurity.tUserRestrictItemCategory where UserId = @rUserId)
		)as Final
		order by Final.StockItemName
	END
END
GO
PRINT N'Altering Procedure [sProcurement].[pRptStockInward]...';


GO
ALTER PROCEDURE [sProcurement].[pRptStockInward]
 @rId bigint = 0
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

   SELECT  
				SIM.Code AS ItemNumber,
				SIM.Title AS ItemName,		
				SI.InwardByName,	
				SI.Number, 	
				SI.CreatedDateTime AS IssuedDate,
				--ID.InwardQuantity,
				ID.RequestedQuantity,
				LM.Title AS FromLocation,
				UOM.Title AS UOM ,
				B.Quantity AS InwardQuantity,
			    SB.Number AS 'BatchNo',
				B.VALUE	AS InwardValue	
				
		FROM  sProcurement.tStockInward SI		
		INNER JOIN sProcurement.tStockInwardDetail ID
		ON SI.Id = ID.StockInwardId
		INNER JOIN sIp.tStoreLocationMaster LM
		ON SI.ToStoreLocationId = LM.Id  
		INNER JOIN sIp.tStockItemMaster SIM
		ON ID.StockItemId  = SIM.Id 
		INNER JOIN sFinanceCommon.tStockUomMaster UOM  
		ON SIM.IssueStockUomId = UOM.Id  
		LEFT JOIN sProcurement.tStockInwardBatch B ON B.StockInwardDetailId = ID.Id
	    LEFT JOIN	sProcurement.tStockBatch SB ON SB.Id = B.StockBatchId 
	    
		WHERE SI.Id = @rId 
			
END
GO
PRINT N'Altering Procedure [sProcurement].[pStockInwardAdd_New]...';


GO

ALTER PROCEDURE [sProcurement].[pStockInwardAdd_New]
(
@rOrgId [int],
@rNumber Nvarchar(max) = '',
@rStockInwardRequestId bigInt=0, 
@rInwardByName Nvarchar(max) = '',
@rToStoreLocationId	Int,
@rRemark Nvarchar(max),
@rCreatedUserId	BigInt,
@rDetail Nvarchar(Max),
@rPOReference nvarchar(100),
@rInvoiceReference nvarchar(100),
@rLocationId int,
@rVendorId int,
@rIsCompleteRequest bit = false
)
AS
SET NOCOUNT ON
BEGIN


  BEGIN TRY	
	     

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

	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 1005,
	@rStoreLocationId = @rToStoreLocationId, @rNextNumber  = @rNumber OUTPUT
	
	SET @rNumber = ISNULL(@rNumber, '-300')
	IF @rNumber = '-300'
	BEGIN
		SELECT -300 AS Result, '' AS Number, 0 AS Id 
		RETURN
	END


	DECLARE @tStockInwardDetailBatch TABLE
	(
		Id Int IDENTITY(1, 1),
		StockInwardRequestDetailId bigint,		 
		StockItemId bigint,
		StockItemName nvarchar(max),
		ItemBatch Nvarchar(max) NULL,
		ItemExpiryDate Date NULL,	
		ItemManufacturingDate Date NULL,	
		InwardQuantity Decimal(12,2),
		RequestedQuantity Decimal(12,2),
		InwardValue Decimal(12,2),
		GST int
	)	
    INSERT INTO @tStockInwardDetailBatch
    SELECT
                                      
            T.c.value('@StockInwardRequestDetailId','bigint') AS StockInwardRequestDetailId,
            T.c.value('@StockItemId','bigint') AS StockItemId,
			REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(T.c.value('@StockItemName','nvarchar(max)'), '&#39;', ''''), '&lt;', '<'), '&quot;', '"'), '&gt;', '>'), '&amp;amp;', '&'), '#amp;amp;amp;', '') AS StockItemname,
            T.c.value('@ItemBatch','Nvarchar(max)') AS ItemBatch,
            T.c.value('@ItemExpiryDate','Date')   AS ItemExpiryDate,
            T.c.value('@ItemManufacturingDate','Date')   AS ItemManufacturingDate,
            T.c.value('@InwardQuantity','Decimal(12,2)') AS InwardQuantity,
            T.c.value('@RequestedQuantity','Decimal(12,2)') AS RequestedQuantity,
            T.c.value('@InwardValue','Decimal(12,2)') AS InwardValue,
            T.c.value('@GST','int') AS GST 
    FROM 
            @loXML.nodes('/Table/StockInward')T(c)

	
		DECLARE @lIsAppliedGSTVal varchar(5);     
      
		select @lIsAppliedGSTVal = sConfig.fConfigurationValueGet('Examination.IsAppliedGST',@rOrgId,@rToStoreLocationId,0,0);

		if(@lIsAppliedGSTVal = 'True')
		BEGIN
				update @tStockInwardDetailBatch set InwardValue = ((InwardValue * (CAST(GST AS FLOAT) / 100)) + InwardValue) where GST is NOT NULL and GST<>'';
		END
		--if exists(select 1 From sProcurement.tStockBatch SB 
		--		  inner join @tStockInwardDetailBatch S on Isnull(S.ItemBatch,'')=Isnull(SB.Number,'') and S.StockItemId=SB.StockItemId
		--		  where Isnull(SB.IsDiscard,0)=1)
		--begin
			
		--	SELECT -200 AS Result, '' AS Number, 0 AS Id 
		--	RETURN
		--end


  BEGIN TRANSACTION
   
  
	DECLARE @lNextNumberStockInward bigint,@lNextNumberStockInwardBatch bigint
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockInward', 0, 1, 1,@outNextNumber = @lNextNumberStockInward output

	INSERT INTO sProcurement.tStockInward
	(
		Id,Number,StockInwardRequestId,InwardByName,ToStoreLocationId,Remark,CreatedUserId,CreatedDateTime,OrgId,POReference,InvoiceReference,VendorId
	)
	VALUES
	(
		@lNextNumberStockInward,@rNumber,
		(CASE WHEN @rStockInwardRequestId = 0 THEN NULL ELSE @rStockInwardRequestId END),
		@rInwardByName,@rToStoreLocationId,@rRemark,@rCreatedUserId,sCommon.fGetDate(),
		@rOrgId,@rPOReference,@rInvoiceReference,@rVendorId
	)
    
	--changed by Keyur on 22/09/2021, changes for mantis 16442
	--if(@rStockInwardRequestId > 0 )
	--begin
	--	update sProcurement.tStockInwardRequest set statusID=533 where id=@rStockInwardRequestId
	--end
	if(@rIsCompleteRequest = 1)
	begin
		update sProcurement.tStockInwardRequest set statusID=533 where id=@rStockInwardRequestId
	end

	       
	declare @lCount int,@lIsBatchWise bit,@lbatchId int,@lNextNumberStockBatch int,@lExpiryDate date ,@lManufacturingDate date
	Declare @lItemId int,@lBatch nvarchar(300),@lInwardQty decimal(12,2),@lInwardValue decimal(12,2),@lIdCount int
	DECLARE @lNextNumberStockInwardDetail BigInt,@lStockItemname nvarchar(max)
		select @lCount=COUNT(*) from @tStockInwardDetailBatch 
		 
	IF EXISTS (SELECT 1 FROM @tStockInwardDetailBatch tid
				INNER JOIN sIp.tStockItemMaster sim ON tid.StockItemId = sim.Id
				INNER JOIN sProcurement.tStockBatch sb ON sb.Number = [ssetup].[fPortalXMLTagsReplaceReverse](tid.ItemBatch)
					AND sb.StoreLocationId = @rToStoreLocationId
					AND sb.StockItemId = tid.StockItemId
				WHERE sim.IsBatchWiseTracking = 1
				AND CONVERT(DATE, sb.ExpiryDate) <= sCommon.fGetDate()
			)
	BEGIN
		DECLARE @ExpiredBatches NVARCHAR(MAX)

		SELECT @ExpiredBatches = STUFF((
			SELECT ', ' + sim.Title + ' - ' + sb.Number
			FROM @tStockInwardDetailBatch tid
			INNER JOIN sIp.tStockItemMaster sim ON tid.StockItemId = sim.Id
			INNER JOIN sProcurement.tStockBatch sb ON sb.Number = [ssetup].[fPortalXMLTagsReplaceReverse](tid.ItemBatch)
				AND sb.StoreLocationId = @rToStoreLocationId
				AND sb.StockItemId = tid.StockItemId
			WHERE sim.IsBatchWiseTracking = 1
			AND CONVERT(DATE, sb.ExpiryDate) <= sCommon.fGetDate()
			FOR XML PATH(''), TYPE
		).value('.', 'NVARCHAR(MAX)'), 1, 2, '')

		SELECT -502 AS Result, 'Expired Batch of Item: ' + ISNULL(@ExpiredBatches, '') AS StatusMessage
		ROLLBACK TRANSACTION
		RETURN
	END

	while @lcount > 0
	BEGIN
					 
		Select @lItemId =StockItemId,@lBatch = [ssetup].[fPortalXMLTagsReplaceReverse](ItemBatch),@lInwardQty=InwardQuantity,@lInwardValue=InwardValue,@lIdCount=Id,@lExpiryDate =ItemExpiryDate ,@lManufacturingDate= ItemManufacturingDate
		,@lStockItemname=StockItemname
		from  @tStockInwardDetailBatch WHERE Id = @lcount
		Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster    Where Id = @lItemId   
		 
		SET @lbatchId = 0
		
			if (@lIsBatchWise=1)
			BEGIN						
				Select @lbatchId= Id from sProcurement.tStockBatch    
				Where  Number =@lBatch   AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId --AND @lIdCount=@lcount
				 
			END
			else 
			BEGIN
				Select @lbatchId= Id from sProcurement.tStockBatch    
				Where iSNULl( Number,'') =''  AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId--AND  @lIdCount=@lcount
	 
			END

			if(ISNULL(@lbatchId,0)=0)
			BEGIN
				 
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockBatch output
				 INSERT INTO sProcurement.tStockBatch (Id,StoreLocationId,StockItemId,Number,ExpiryDate,ManufactureDate,AvailableQuantity,CreatedUserId,CreatedDateTime,OrgId,Price)
				Select @lNextNumberStockBatch,@rToStoreLocationId,@lItemId,@lBatch,@lExpiryDate,@lManufacturingDate ,0,@rCreatedUserId,sCommon.fGetDate(),@rOrgId,0
				--from @tStockInwardDetailBatch where Id=@lcount
				
				 SET @lbatchId = @lNextNumberStockBatch
			END 
			 
			 if(@lbatchId>0)
			 BEGIN
				 
				if Exists(Select Id from sProcurement.tStockInwardDetail   
				 where  StockInwardId = @lNextNumberStockInward  and  StockItemId = @lItemId  )
				 BEGIN
						Select @lNextNumberStockInwardDetail= Id from  sProcurement.tStockInwardDetail
						 Where  StockInwardId = @lNextNumberStockInward AND StockIteMid =@lItemId
					 
				 END
				 else
				 BEGIN
					EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockInwardDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardDetail output
					 INSERT INTO sProcurement.tStockInwardDetail
					(
						Id,StockInwardId,StockItemId,InwardQuantity,RequestedQuantity, 
						StockInwardRequestDetailId,Remark,OrgId
					)
					SELECT @lNextNumberStockInwardDetail ,@lNextNumberStockInward,StockItemId,InwardQuantity,
					RequestedQuantity, StockInwardRequestDetailId,@rRemark,@rOrgId
					 from @tStockInwardDetailBatch where Id=@lcount
										 
				  
				END				
				 
				 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockInwardBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockInwardBatch output
				 
						INsert into sProcurement.tStockInwardBatch
						(Id,StockInwardDetailId,Quantity,StockBatchId,OrgId,Value,GST)
						Select @lNextNumberStockInwardBatch,@lNextNumberStockInwardDetail,InwardQuantity,@lbatchId,@rOrgID,InwardValue,GST
						from @tStockInwardDetailBatch where Id=@lcount
						
						--Update SB 
						--Set SB.AvailableQuantity = SB.AvailableQuantity + @lInwardQty,SB.Price = @lInwardValue from
						--sProcurement.tStockBatch SB  
						--WHERE Id = @lbatchId AND StockItemId = @lItemId AND SB.StoreLocationId =@rToStoreLocationId
     									
						Exec sIp.pWeightedAverageCostLogAdd_New @rOrgId =@rOrgId,@rSourceTypeId=1010,@rSourceId=@lNextNumberStockInwardBatch,
								@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lInwardQty ,@rValue=@lInwardValue,@rIsReceipt=1,
								@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId 
								,@rLocationId=@rLocationId,@rItemBatchId = @lbatchId,@rItemName = @lStockItemname

			 END
			set @lcount =@lcount-1
	END
	
	 
		SELECT 1 AS RESULT , @rNumber as Number,@lNextNumberStockInward as Id
		 COMMIT TRANSACTION
        END TRY
         
        BEGIN CATCH
        IF @@TRANCOUNT > 0  
		ROLLBACK TRANSACTION

		declare @error int, @message varchar(4000), @xstate int,@errorCount int, @errorLine int;
		declare @exceptiondetail nvarchar(max);

		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>               
		  </Table>'                
                
		  insert into sSystem.tExceptionLog(OrgId,ExceptionType,ExceptionMessage,ExceptionDetail,CreatedDateTime)             
		  Select @rOrgId,'StockInwardAdd_New_Error',5000,@exceptiondetail,getdate()

		SELECT -1 AS RESULT , @rNumber as Number,@lNextNumberStockInward as Id
	    END CATCH	
 
END
GO
PRINT N'Altering Procedure [sSecurity].[pGetScreenValidationList]...';


GO

ALTER   PROCEDURE [sSecurity].[pGetScreenValidationList]
    @ScreenId INT,
	@rOrgId INT
AS
BEGIN
BEGIN TRANSACTION;

	SELECT 
		SVFM.FieldId,
		SVFM.FieldName,
		S.Id as ScreenId,
		S.Title as ScreenName,
		Isnull(IsShow,0) as IsShow,
		Isnull(IsMandatory,0) as IsMandatory
	FROM sSecurity.tScreenValidationFieldMaster SVFM 
		LEFT JOIN sSecurity.tScreenValidation SV on SVFM.FieldId = SV.FieldId AND SV.OrgId = @rOrgId
		INNER JOIN sSecurity.tScreen S on  S.Id = SVFM.ScreenId
	WHERE (@ScreenId IS NULL OR @ScreenId = 0 OR SVFM.ScreenId = @ScreenId OR SVFM.ScreenId = 0);

COMMIT TRANSACTION;
END
GO
PRINT N'Altering Procedure [sSecurity].[pMenuGet_Wellness]...';


GO

ALTER PROCEDURE [sSecurity].[pMenuGet_Wellness]        
 @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        
            
  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=191810371 then 'fa fa-heart'
		 when Menu.Id=191810373 then 'fa fa-user-md'
		 when Menu.Id=191810378 then 'ft-user-plus'
		 when Menu.Id=35 then 'fa fa-support'
         when Menu.Id=191810381 then 'fa fa-edit'
         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)         
		  AND MM.Id IN (195,196,197,198,236)
          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 (191810371,191810373,191810378,191810337,35,191810381,191810382) 
          Or ParentMenuID in (191810371,191810373,191810378,191810337,35,191810381))
          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)    
		  AND MM.Id IN (195,196,197,236,198)
          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 (191810371,191810373,191810378,191810337,35,191810381))       
         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=191810371 then 'fa fa-heart'
		when Menu.Id=191810373 then 'fa fa-user-md'
		when Menu.Id=191810378 then 'ft-user-plus'
		when Menu.Id=35 then 'fa fa-support'
        when Menu.Id=191810381 then 'fa fa-edit'
        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 T.Id not in (20834,20853)   
		 AND MM.Id IN (195,196,197,236,198)
         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 (191810371,191810373,191810378,191810337,35,191810381,191810382) 
         Or ParentMenuID in (191810371,191810373,191810378,191810337,35,191810381))
         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) 
		 AND MM.Id IN (195,196,197,236,198)
		 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 (191810371,191810373,191810378,191810337,35,191810381))   
        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_Wellness]...';


GO

ALTER PROCEDURE [sSecurity].[pMenuGetRoleWise_Wellness]        
 @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        
               
  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=191810371 then 'fa fa-heart'
		 when Menu.Id=191810373 then 'fa fa-user-md'
		 when Menu.Id=191810378 then 'ft-user-plus'
		 when Menu.Id=35 then 'fa fa-support'
         when Menu.Id=191810381 then 'fa fa-edit'
         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) 
		  AND MM.Id IN (195,196,197,236,198)
          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 (191810371,191810373,191810378,35,191810337,191810381,191810382) Or ParentMenuID in (191810371,191810373,191810378,35,191810337,191810381))      
          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) 
		  AND MM.Id IN (195,196,197,236,198)
          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 (191810371,191810373,191810378,35,191810337,191810381))       
         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    
         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=191810371 then 'fa fa-heart'
		when Menu.Id=191810373 then 'fa fa-user-md'
		when Menu.Id=191810378 then 'ft-user-plus'
		when Menu.Id=35 then 'fa fa-support'
        when Menu.Id=191810381 then 'fa fa-edit'
        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 T.Id not in (20834,20853)  
		 AND MM.Id IN (195,196,197,236,198)
         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 (191810371,191810373,191810378,35,191810337,191810381,191810382) Or ParentMenuID in (191810371,191810373,191810378,35,191810337,191810381))      
         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) 
		 AND MM.Id IN (195,196,197,236,198)
		 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 (191810371,191810373,191810378,35,191810337,191810381))      
        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 [sWellness].[pGetProgramAdherenceData]...';


GO
ALTER PROCEDURE [sWellness].[pGetProgramAdherenceData] 
(
    @rEmployeeId BIGINT,
    @rWeekStart  DATE
)
AS
BEGIN

SET NOCOUNT ON;

--;WITH DateSeries AS
--(
--    SELECT DATEADD(DAY, v.n, @rWeekStart) AS TaskDate
--    FROM (VALUES (0),(1),(2),(3),(4),(5),(6)) v(n)
--),
--TaskList AS
--(
--    SELECT 
--        aa.AssignedActivityId,
--        t.Name AS TaskName
--    FROM sWellness.tAssignedActivity aa
--    INNER JOIN sWellness.tWellnessActivityTaskMaster t
--        ON aa.WellnessActivityTaskId = t.Id
--    WHERE aa.EmployeeId = @rEmployeeId
--      AND aa.WeekStart = @rWeekStart
--)

--SELECT
--    tl.TaskName,
--    ds.TaskDate,
--    CASE
--        WHEN at.Status IS NOT NULL THEN at.Status
--        WHEN ds.TaskDate < CAST(GETDATE() AS DATE) THEN 2
--        ELSE 0
--    END AS Status
--FROM TaskList tl

--CROSS JOIN DateSeries ds

--LEFT JOIN sWellness.tEmployeeTaskTrack at
--    ON at.AssignedActivityId = tl.AssignedActivityId
--    AND at.TaskDate = ds.TaskDate

--ORDER BY tl.TaskName, ds.TaskDate
DECLARE @cols NVARCHAR(MAX)
DECLARE @sql  NVARCHAR(MAX)


;WITH N AS
(
    SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 
    UNION ALL SELECT 3 UNION ALL SELECT 4 
    UNION ALL SELECT 5 UNION ALL SELECT 6
)
SELECT @cols = STUFF((
    SELECT ',' + QUOTENAME(
        CONVERT(VARCHAR(10), DATEADD(DAY,n,@rWeekStart), 23)
    )
    FROM N
    FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '')


SET @sql = '
;WITH DateSeries AS
(
    SELECT 
        DATEADD(DAY, v.n, ''' + CONVERT(VARCHAR(10),@rWeekStart,120) + ''') AS TaskDate,
        CONVERT(VARCHAR(10), DATEADD(DAY, v.n, ''' + CONVERT(VARCHAR(10),@rWeekStart,120) + '''), 23) AS ColumnName
    FROM (VALUES (0),(1),(2),(3),(4),(5),(6)) v(n)
),
BaseData AS
(
    SELECT 
        CASE WHEN aa.IsCustomActivityTask = 1 THEN aa.WellnessActivityCustom
		WHEN aa.IsCustomActivityTask = 0 THEN t.Name
		ELSE t.Name END as TaskName,
        ds.ColumnName,
        CASE 
            WHEN at.Status IS NOT NULL THEN at.Status
            WHEN ds.TaskDate < CAST(GETDATE() AS DATE) THEN 2
            ELSE 0
        END AS FinalStatus
    FROM sWellness.tAssignedActivity aa
    LEFT JOIN sWellness.tWellnessActivityTaskMaster t
        ON aa.WellnessActivityTaskId = t.Id
    CROSS JOIN DateSeries ds
    LEFT JOIN sWellness.tEmployeeTaskTrack at
        ON at.AssignedActivityId = aa.AssignedActivityId
        AND at.TaskDate = ds.TaskDate
    WHERE aa.EmployeeId = ' + CAST(@rEmployeeId AS VARCHAR) + '
      AND aa.WeekStart = ''' + CONVERT(VARCHAR(10),@rWeekStart,120) + '''
)
SELECT *
FROM BaseData
PIVOT
(
    MAX(FinalStatus)
    FOR ColumnName IN (' + @cols + ')
) p
ORDER BY TaskName;
'


EXEC(@sql)

END
GO
PRINT N'Creating Procedure [sCommon].[pManageDashletSettingAddUpdate]...';


GO

CREATE OR ALTER PROCEDURE [sCommon].[pManageDashletSettingAddUpdate]
@rOrgId smallint,
@rScreenId int,
@rUserId BIGINT,
@rDashboardJson nvarchar(max)
AS    
BEGIN
	IF NOT EXISTS(select Id from [sCommon].[tManageDashletSetting] where OrgId = OrgId and ScreenId = @rScreenId and UserId = @rUserId)
	BEGIN
		INSERT INTO [sCommon].[tManageDashletSetting] (OrgId, ScreenId, UserId, DashboardJson)
		Values (@rOrgId, @rScreenId, @rUserId, @rDashboardJson)
	END
	ELSE
	BEGIN
		UPDATE [sCommon].[tManageDashletSetting] set DashboardJson=@rDashboardJson 
		WHERE OrgId = OrgId and ScreenId = @rScreenId and UserId = @rUserId
	END
END
GO
PRINT N'Creating Procedure [sCommon].[pManageDashletSettingGet]...';


GO


CREATE OR ALTER PROCEDURE [sCommon].[pManageDashletSettingGet]
@rOrgId smallint,
@rScreenId int,
@rUserId BIGINT
AS
BEGIN
      IF NOT EXISTS(select Id from [sCommon].[tManageDashletSetting] where OrgId = OrgId and ScreenId = @rScreenId and UserId = @rUserId)
	  BEGIN
			select ''
	  END
	  ELSE
	  BEGIN
			select DashboardJson from [sCommon].[tManageDashletSetting] where OrgId = OrgId and ScreenId = @rScreenId and UserId = @rUserId
	  END
END
GO
PRINT N'Creating Procedure [sExamination].[pAddRoundEmployeeAgeWise]...';


GO

CREATE OR ALTER PROCEDURE [sExamination].[pAddRoundEmployeeAgeWise]
(
    @rEmployeeCodes NVARCHAR(MAX) = '',
    @rRoundId INT,
    @rOrgId INT,
    @rPlannedExaminationDate DATETIME = NULL,
    @rTargetGroupId INT = NULL
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @lNextDetailNumber BIGINT
    DECLARE @lInsertedCount INT = 0

    -- Get next number
    EXEC sCommon.pTableRowIdGet 
        @rOrgId, 
        'sExamination.tSetupEmployee', 
        0, 1, 1,
        @outNextNumber = @lNextDetailNumber OUTPUT

    -- INSERT
    INSERT INTO sExamination.tSetupEmployee
    (
        Id,
        SetupId,
        EmployeeId,
        OrgId,
        PlannedExaminationDate,
        TargetGroupId
    )
    SELECT 
        @lNextDetailNumber + ROW_NUMBER() OVER (ORDER BY EM.Id) AS Id,
        @rRoundId,
        EM.Id,
        @rOrgId,
        @rPlannedExaminationDate,
        @rTargetGroupId
    FROM sHrm.tEmployeeMaster EM
    WHERE 
    (
        EM.Code IN (SELECT item FROM sCommon.fnsplit(ISNULL(@rEmployeeCodes,''),',')) 
        OR ISNULL(@rEmployeeCodes,'') = ''
    )
    AND NOT EXISTS
    (
        SELECT 1 
        FROM sExamination.tSetupEmployee SE
        WHERE SE.SetupId = @rRoundId 
        AND SE.EmployeeId = EM.Id
    )

    -- Get inserted count
    SET @lInsertedCount = @@ROWCOUNT

    -- Update next number
    SET @lNextDetailNumber = ISNULL(@lInsertedCount, 0) + @lNextDetailNumber  

    EXEC sCommon.pTableRowIdModify 
        @rOrgId, 
        @rTableTitle = 'sExamination.tSetupEmployee', 
        @rCurrentNumber = @lNextDetailNumber

    SELECT 
        1 AS IsSuccess,
        'Employees added successfully' AS Message,
        @lInsertedCount AS InsertedCount

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


GO


CREATE OR ALTER PROCEDURE [sExamination].[pDiagnosisOrderWise]
AS
BEGIN
	SELECT DTM.Id, 
	CASE 
	WHEN DTM.Id = 5 THEN 'Overweight'
	WHEN DTM.Id = 9 THEN 'Prehypertension'
	WHEN DTM.Id = 75 THEN 'MorbidObesity'
	WHEN DTM.Id = 11 THEN 'Prediabetic'
	WHEN DTM.Id = 32 THEN 'Elevated_LDL'
	WHEN DTM.Id = 35 THEN 'HighSGPT'
	WHEN DTM.Id = 36 THEN 'HighSerumCreatinine'
	WHEN DTM.Id = 58 THEN 'HighTSH'
	WHEN DTM.Id = 59 THEN 'HighPSA'
	WHEN DTM.Id = 67 THEN 'LowTSH'
	WHEN DTM.Id = 69 THEN 'VitaminB12deficiency'
	WHEN DTM.Id = 70 THEN 'VitaminD3deficiency'
	WHEN DTM.Id = 76 THEN 'VitaminD3ToxicityRisk'
	ELSE DTM.Title END AS Title
	FROM sExamination.tDiagnosisTrackerMaster DTM
	INNER JOIN sExamination.tDiagnosisTrackerOrg DTO ON DTO.DiagnosisTrackerId = DTM.Id
	WHERE DTM.Id in (5,6,9,10,11,12,35,28,30,32,36,58,59,67,69,70,75,76)
	ORDER BY DTO.OrderIndex ASC
END
GO
PRINT N'Creating Procedure [sExamination].[pExaminationCustomSearchListGetWithPaginationNew]...';


GO
CREATE PROC [sExamination].[pExaminationCustomSearchListGetWithPaginationNew]
(
    @rPageIndex INT,
    @rOrgId INT,
    @rDepartmentId NVARCHAR(MAX)='',
    @rSetupId NVARCHAR(MAX)='',
    @rCode NVARCHAR(20),
    @rName NVARCHAR(50),
    @rDesignationId NVARCHAR(MAX)='',
    @rMainTypeId INT,
    @rStatusId NVARCHAR(MAX)='',
    @rStoreLocationId INT,
    @rFromDate DATE = NULL,
    @rToDate DATE = NULL,
    @rHealthIndicatorId INT,
    @rTag INT,
    @rEmployeeStoreLocationId INT=0,
    @rCompanyId NVARCHAR(MAX)='',
    @rDOJ DATE = NULL,
    @rEmployeeTypeGroupId NVARCHAR(MAX)='',
    @rFlag INT = 0,
    @SortColumnName NVARCHAR(MAX)= '',
    @IsAscendingOrder BIT= 0,
    @PageNumber INT = 1,
    @PageSize INT = 20,
    @GlobalSearch NVARCHAR(MAX)= '',
    @rDoctorId NVARCHAR(MAX)='',
    @rContractorId NVARCHAR(MAX)=''
)
AS
BEGIN

SET NOCOUNT ON;

-- 🔧 Normalize inputs
DECLARE @lCode NVARCHAR(20) = ISNULL(@rCode,'')
DECLARE @lName NVARCHAR(50) = ISNULL(@rName,'')
DECLARE @lGlobalSearch NVARCHAR(MAX) = ISNULL(@GlobalSearch,'')

SET @lCode = CASE WHEN @lCode='*' THEN '' ELSE @lCode END
SET @lName = CASE WHEN @lName='*' THEN '' ELSE @lName END

SET @lCode = sCommon.fSearchStringGet(@lCode)
SET @lName = sCommon.fSearchStringGet(@lName)

----------------------------------------------------------
-- 🔥 TEMP TABLE (REPLACES TABLE VARIABLE)
----------------------------------------------------------
CREATE TABLE #tbltmp
(
    eid BIGINT PRIMARY KEY
)

----------------------------------------------------------
-- 🔥 COMMON FILTERED ID SET (MERGED LOGIC)
----------------------------------------------------------
INSERT INTO #tbltmp(eid)
SELECT DISTINCT E.Id
FROM sExamination.tExamination E
INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
LEFT JOIN sExamination.tSubTypeMaster STM ON SM.SubTypeId = STM.Id
LEFT JOIN sExamination.tDiagnosis D ON D.SourceId = E.Id
LEFT JOIN sExamination.tExaminationRequest ER ON ER.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 CS ON E.ParticipantSourceId = CS.Id AND E.ParticipantSourceTypeId = 1009
LEFT JOIN sHrm.tEmployeeMaster EM2 ON EFD.EmployeeId = EM2.Id

LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = E.ParticipantSourceId
LEFT JOIN sHrm.tEmployeeTypeMaster TM ON EJD.EmployeeTypeId = TM.Id
LEFT JOIN sHrm.tEmployeeTypeGroupMaster ETM ON ETM.Id = TM.EmployeeTypeGroupId
LEFT JOIN sProcurement.tVendorMaster CONT ON CONT.Id = EJD.ContractorId

WHERE
    E.OrgId = @rOrgId

    -- 🔥 MainType logic merged
    AND (
        (@rMainTypeId = 9 AND ER.SubTypeId = @rMainTypeId)
        OR (@rMainTypeId <> 9 AND STM.MainTypeId = @rMainTypeId)
    )

    -- 🔥 Health indicator logic
    AND (
        (@rTag != 1 AND ISNULL(D.HealthindicatorId,0)=0)
        OR (@rTag = 1)
        OR (D.HealthindicatorId IS NULL)
    )

     --🔥 Filters
    AND (@lCode='' OR EM.Code LIKE @lCode OR EM2.Code LIKE @lCode OR CS.Code LIKE @lCode)
    AND (@lName='' OR EM.FirstName LIKE @lName+'%' OR EFD.Name LIKE @lName+'%' OR CS.FirstName LIKE @lName+'%')

    AND (@rStoreLocationId = 0 OR E.StoreLocationId = @rStoreLocationId)

    AND (@rFromDate IS NULL OR E.ExaminationDate >= @rFromDate)
    AND (@rToDate IS NULL OR E.ExaminationDate < DATEADD(DAY,1,@rToDate))

    AND (@rHealthIndicatorId = 0 OR D.HealthIndicatorId = @rHealthIndicatorId)

    --AND (@rDOJ IS NULL OR (EJD.DateOfJoining >= @rDOJ AND EJD.DateOfJoining < DATEADD(DAY,1,@rDOJ)))

    AND (ISNULL(EM.IsObsolete,0)=0 AND ISNULL(EM2.IsObsolete,0)=0)

    AND (@rFlag <> 1 OR EM.TargetGroupId = 10002)

    select * from #tbltmp;

----------------------------------------------------------
-- 🔥 FINAL DATASET (NO DUPLICATION)
----------------------------------------------------------
;WITH FinalData AS
(
    SELECT
        E.Id,
        E.ExaminationDate AS ExamDate,
        CONVERT(VARCHAR(10),E.ExaminationDate,103) AS ExaminationDate,
        SM.Title AS Setup,
        ODM.Title AS Department,
        EDM.Title AS Designation,
        ST.Title AS [Status],

        ParticipantCode =
            CASE
                WHEN E.ParticipantSourceTypeId = 95 THEN EM.Code
                WHEN E.ParticipantSourceTypeId = 1001 THEN EM2.Code
                ELSE CS.Code
            END,

        ParticipantName =
            CASE
                WHEN E.ParticipantSourceTypeId = 95 THEN EM.FirstName + ' ' + ISNULL(EM.LastName,'')
                WHEN E.ParticipantSourceTypeId = 1001 THEN EFD.Name
                ELSE CS.FirstName + ' ' + ISNULL(CS.LastName,'')
            END

    FROM #tbltmp t
    INNER JOIN sExamination.tExamination E ON E.Id = t.eid
    INNER JOIN sExamination.tSetupMaster SM ON E.SetupId = SM.Id
    LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM ON E.OrganizationDepartmentId = ODM.Id
    LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON E.EmployeeDesignationId = EDM.Id
    LEFT JOIN sExamination.tStatusMaster ST ON E.StatusId = ST.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 CS ON E.ParticipantSourceId = CS.Id AND E.ParticipantSourceTypeId = 1009
    LEFT JOIN sHrm.tEmployeeMaster EM2 ON EFD.EmployeeId = EM2.Id
)

----------------------------------------------------------
-- 🔥 PAGINATION + SORTING
----------------------------------------------------------
, PageNumbers AS
(
    SELECT
        ROW_NUMBER() OVER (
            ORDER BY
                CASE WHEN @SortColumnName='ExamDate' AND @IsAscendingOrder=0 THEN ExamDate END DESC,
                CASE WHEN @SortColumnName='ExamDate' AND @IsAscendingOrder=1 THEN ExamDate END,
                CASE WHEN @SortColumnName='' THEN Id END DESC
        ) AS RID,
        COUNT(*) OVER() AS RecordCount,
        *
    FROM FinalData
    WHERE
        (@lGlobalSearch='' OR
         ExaminationDate LIKE '%'+@lGlobalSearch+'%' OR
         Setup LIKE '%'+@lGlobalSearch+'%' OR
         ParticipantCode LIKE '%'+@lGlobalSearch+'%' OR
         ParticipantName LIKE '%'+@lGlobalSearch+'%' OR
         Department LIKE '%'+@lGlobalSearch+'%' OR
         [Status] LIKE '%'+@lGlobalSearch+'%')
)

SELECT *
FROM PageNumbers
WHERE (@PageSize=-1 OR RID BETWEEN ((@PageNumber-1)*@PageSize+1) AND (@PageNumber*@PageSize))

OPTION (OPTIMIZE FOR UNKNOWN)

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


GO
CREATE OR ALTER PROCEDURE [sExamination].[pGetAppointmentRequestedMailDetail]
(
	@rAppointmentId BIGINT,	
	@rOrgId SMALLINT,
	@rEventId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;

	DECLARE 
		@DoctorId BIGINT,
		@PatientSourceTypeId SMALLINT,
		@PatientSourceId BIGINT,
		@DoctorName NVARCHAR(200)='',
		@EmployeeName NVARCHAR(200)= '',
		@AppointmentDate NVARCHAR(500),
		@Template NVARCHAR(MAX),
		@MailSubject NVARCHAR(MAX),
		@EmployeeEmailId NVARCHAR(200),
		@CoachEmailId NVARCHAR(200),
		@FromTime NVARCHAR(10),
		@ToTime NVARCHAR(10);

		SELECT 
			@DoctorId = APP.DoctorEmployeeId,
			@PatientSourceTypeId = APP.PatientSourceTypeId,
			@PatientSourceId = APP.PatientSourceId,
			@AppointmentDate = ISNULL(CONVERT(VARCHAR(20),APP.AppointmentDate,103),'-'),
			@FromTime = CASE WHEN TimeS.FromTime IS NOT NULL AND LTRIM(RTRIM(TimeS.FromTime)) <> '' THEN CONVERT(VARCHAR(5), CAST(TimeS.FromTime AS TIME), 108) ELSE NULL END,
			@ToTime = CASE WHEN TimeS.ToTime IS NOT NULL AND LTRIM(RTRIM(TimeS.ToTime)) <> '' THEN CONVERT(VARCHAR(5), CAST(TimeS.ToTime AS TIME), 108) ELSE NULL END
		FROM
			[sWellness].[tAppointment] APP
		LEFT JOIN
			[sAppointment].[tTimeSlotMaster] TimeS
		ON
			TimeS.Id = APP.TimeSlotId
		WHERE
			APP.Id = @rAppointmentId;

		IF (@FromTime IS NOT NULL OR @ToTime IS NOT NULL)
		BEGIN
			SET @AppointmentDate = @AppointmentDate + ' From '
				+ ISNULL(@FromTime, '')
				+ CASE WHEN @FromTime IS NOT NULL AND @ToTime IS NOT NULL THEN ' To ' ELSE '' END
				+ ISNULL(@ToTime, '');
		END

		

		SELECT 
			@DoctorName = Users.DisplayTitle 
		FROM 
			[sHRM].[tEmployeeMaster] EM 
		INNER JOIN
			[sSecurity].[tUser] Users
		ON
			Users.SourceId = EM.Id
		WHERE 
			EM.Id = @DoctorId


		SELECT @CoachEmailId = (
								 SELECT 
								 	EMPCOM.CompanyEmail 
								 FROM 
								 	[sHrm].[tEmployeeMaster] EMPMAS 
								 INNER JOIN 
								 	[sHrm].[tEmployeeCommunications] EMPCOM
								 ON
								 	EMPCOM.EmployeeId = EMPMAS.Id
								  WHERE 
								 	EMPMAS.Id = @DoctorId
							   )

		SELECT @Template = ET.Template, @MailSubject = ET.MailSubject FROM [sAlert].[tEventTemplate] ET WHERE EventId = @rEventId AND AlertModeId = 1

		IF(@PatientSourceTypeId = 95)
		BEGIN
			SELECT @EmployeeName = EMP.FirstName + ' ' + EMP.LastName FROM [sHrm].[tEmployeeMaster] EMP WHERE EMP.Id = @PatientSourceId
			SELECT @EmployeeEmailId = (
										SELECT 
											EMPCOM.CompanyEmail 
										FROM 
											[sHrm].[tEmployeeMaster] EMPMAS 
										INNER JOIN 
											[sHrm].[tEmployeeCommunications] EMPCOM
										ON
											EMPCOM.EmployeeId = EMPMAS.Id
										 WHERE 
											EMPMAS.Id = @PatientSourceId
									   ) 
		END
		ELSE IF(@PatientSourceTypeId = 1009)
		BEGIN
			SELECT 
				@EmployeeName = CSR.FirstName + ' ' + CSR.LastName,
				@EmployeeEmailId = EmailId
			FROM 
				[sHrm].[tCsrBenefiterMaster] CSR
			WHERE 
				CSR.Id = @PatientSourceId
		END

		SET @Template = REPLACE(@Template, '[CoachName]', @DoctorName);
		SET @Template = REPLACE(@Template, '[EmployeeName]', @EmployeeName); 
		SET @Template = REPLACE(@Template, '[AppointmentDateTime]', @AppointmentDate);


		IF(@rEventId = 115)
		BEGIN
			SELECT @MailSubject AS Subject , @Template AS MsgText, @CoachEmailId AS EmailId, @EmployeeEmailId AS strCC
		END
		ELSE IF(@rEventId = 116)
		BEGIN
			SELECT @MailSubject AS Subject , @Template AS MsgText, @EmployeeEmailId AS EmailId, @CoachEmailId AS strCC
		END
END
GO
PRINT N'Creating Procedure [sExamination].[pGetEmployeeTestParameter]...';


GO
CREATE OR ALTER PROCEDURE [sExamination].[pGetEmployeeTestParameter] 
(
	@rOrgId SMALLINT,
	@rEmployeeCode NVARCHAR(100)
)
AS
SET NOCOUNT ON;
BEGIN

	DECLARE @EmployeeId BIGINT =
	(
		SELECT Id 
		FROM [sHrm].[tEmployeeMaster] 
		WHERE Code = @rEmployeeCode
	)
	

	IF(@EmployeeId IS NULL OR @EmployeeId = 0)
	BEGIN
		RETURN;
	END

	CREATE TABLE #EmployeeExamination
	(
		EId BIGINT PRIMARY KEY,
		ExaminationDate DATE,
		Round NVARCHAR(1000),
		RoundGroup NVARCHAR(1000)
	)

	INSERT INTO #EmployeeExamination
	SELECT 
		Exam.Id,
		Exam.ExaminationDate,
		SM.Title,
		SGM.Title
	FROM [sExamination].[tExamination] Exam
	INNER JOIN
		[sExamination].[tSetupMaster] SM 
	ON 
		SM.Id = Exam.SetupId
	INNER JOIN
		[sExamination].[tSetupGroupMaster] SGM 
	ON 
		SGM.Id = SM.SetupGroupId
	WHERE 
		Exam.ParticipantSourceId = @EmployeeId
	AND
		SM.[Id] <> [sCommon].[fGetIntIdForOrg](8,@rOrgId)


	---------------------------------------------------
	-- 2. Centralized Test Data
	---------------------------------------------------
	CREATE TABLE #TestData
	(
		EId BIGINT,
		ExaminationDate DATE,
		StaticTestParameterId INT,
		ServiceValue NVARCHAR(100)
	)

	INSERT INTO #TestData
	SELECT 
		E.Id,
		E.ExaminationDate,
		TP.StaticTestParameterId,
		TRD.ServiceValue
	FROM sExamination.tTestRequestDetail TRD
	INNER JOIN sExamination.tTestRequest TR ON TRD.TestRequestId = TR.Id				
	INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id
	INNER JOIN sOrderEntry.tTestParameterMaster TP ON TD.TestParameterId = TP.Id
	INNER JOIN sExamination.tExamination E ON TR.SourceId = E.Id
	INNER JOIN sExamination.tSetupMaster SM ON SM.Id = E.SetupId
	INNER JOIN sExamination.tSubTypeMaster STM ON STM.Id = SM.SubTypeId
	WHERE 
		E.ParticipantSourceId = @EmployeeId
		AND E.ParticipantSourceTypeId = 95
		AND ISNULL(TRD.ServiceValue,'') <> ''		
		AND TP.StaticTestParameterId IN (2,19,20,21,25,27,31,32,33,34,38,49,54,126,127)

	CREATE NONCLUSTERED INDEX IX_TestData 
	ON #TestData (StaticTestParameterId, ExaminationDate DESC)

	SELECT 
		EE.ExaminationDate,
		EE.Round,
		EE.RoundGroup,
		ISNULL(CONVERT(DECIMAL(10,2), ROUND(D.HealthIndex,2)),0) AS HealthIndex,
		ISNULL(Vtl.BMI,0) AS BMI,
		ISNULL(Vtl.BloodPressureSystolic,0) AS BPSystolic,
		ISNULL(Vtl.BloodPressureDiastolic,0) AS BPDiastolic,
		ISNULL(HBData.HB,0) AS HB,
		ISNULL(HBA1CData.HBA1C,0) AS HBA1C,
		ISNULL(Vtl.BodyWeight,0) AS Weight,
		ISNULL(CholData.Cholesterol,0) AS Cholesterol,
		ISNULL(FBSData.FBS,0) AS FBS,
		ISNULL(HDLData.HDL,0) AS HDL,
		ISNULL(LDLData.LDL,0) AS LDL,
		ISNULL(PPBSData.PPBS,0) AS PPBS,
		ISNULL(RBSData.RBS,0) AS RBS,
		ISNULL(CreatinineData.SerumCreatinine,0) AS SerumCreatinine,
		ISNULL(UricAcidData.UricAcid,0) AS SerumUricAcid,
		ISNULL(SGPTData.SGPT,0) AS SGPT,
		ISNULL(TriglycerideData.Triglyceride,0) AS Triglyceride,
		ISNULL(TSHData.TSH,0) AS TSH,
		ISNULL(B12Data.VitaminB12,0) AS VitaminB12,
		ISNULL(D3Data.VitaminD3,0) AS VitaminD3
	FROM 
		#EmployeeExamination EE
	LEFT JOIN 
		[sExamination].[tVital] Vtl ON Vtl.SourceId = EE.EId
	LEFT JOIN 
		[sExamination].[tExamination] E ON E.Id = EE.EId AND E.ParticipantSourceTypeId = 95
	LEFT JOIN 
		[sExamination].[tDiagnosis] D ON D.SourceId = E.Id AND ISNULL(D.HealthIndex,0) > 0
	LEFT JOIN 
		[sExamination].[tSetupMaster] SM  ON SM.Id = E.SetupId
	LEFT JOIN 
		[sExamination].[tSubTypeMaster] STM ON STM.Id = SM.SubTypeId AND STM.MainTypeId = 1
	OUTER APPLY	-- FBS (19)
	(
		SELECT TOP 1 TD.ServiceValue AS FBS
		FROM #TestData TD WHERE TD.StaticTestParameterId = 19 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) FBSData

	OUTER APPLY -- HBA1C (25)
	(
		SELECT TOP 1 TD.ServiceValue AS HBA1C
		FROM #TestData TD WHERE TD.StaticTestParameterId = 25 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) HBA1CData

	OUTER APPLY -- LDL (34)
	(
		SELECT TOP 1 TD.ServiceValue AS LDL
		FROM #TestData TD WHERE TD.StaticTestParameterId = 34 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) LDLData

	OUTER APPLY -- Cholesterol (31)
	(
		SELECT TOP 1 TD.ServiceValue AS Cholesterol
		FROM #TestData TD WHERE TD.StaticTestParameterId = 31 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) CholData

	OUTER APPLY -- RBS (21)
	(
		SELECT TOP 1 TD.ServiceValue AS RBS
		FROM #TestData TD WHERE TD.StaticTestParameterId = 21 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) RBSData

	OUTER APPLY -- HB (2)
	(
		SELECT TOP 1 TD.ServiceValue AS HB
		FROM #TestData TD WHERE TD.StaticTestParameterId = 2 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) HBData

	OUTER APPLY -- HDL (2)
	(
		SELECT TOP 1 TD.ServiceValue AS HDL
		FROM #TestData TD WHERE TD.StaticTestParameterId = 33 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) HDLData

	OUTER APPLY -- PPBS (20)
	(
		SELECT TOP 1 TD.ServiceValue AS PPBS
		FROM #TestData TD WHERE TD.StaticTestParameterId = 20 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) PPBSData

	OUTER APPLY -- SERUM CREATININE (27)
	(
		SELECT TOP 1 TD.ServiceValue AS SerumCreatinine
		FROM #TestData TD WHERE TD.StaticTestParameterId = 27 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) CreatinineData

	OUTER APPLY -- SERUM URIC ACID (49)
	(
		SELECT TOP 1 TD.ServiceValue AS UricAcid
		FROM #TestData TD WHERE TD.StaticTestParameterId = 49 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) UricAcidData

	OUTER APPLY -- SGPT (38)
	(
		SELECT TOP 1 TD.ServiceValue AS SGPT
		FROM #TestData TD WHERE TD.StaticTestParameterId = 38 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) SGPTData

	OUTER APPLY -- Triglyceride (32)
	(
		SELECT TOP 1 TD.ServiceValue AS Triglyceride
		FROM #TestData TD WHERE TD.StaticTestParameterId = 32 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) TriglycerideData

	OUTER APPLY -- TSH (54)
	(
		SELECT TOP 1 TD.ServiceValue AS TSH
		FROM #TestData TD WHERE TD.StaticTestParameterId = 54 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) TSHData
	
	OUTER APPLY -- Vitamin B12 (126)
	(
		SELECT TOP 1 TD.ServiceValue AS VitaminB12
		FROM #TestData TD WHERE TD.StaticTestParameterId = 126 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) B12Data
	
	OUTER APPLY -- Vitamin D3 (127)
	(
		SELECT TOP 1 TD.ServiceValue AS VitaminD3
		FROM #TestData TD WHERE TD.StaticTestParameterId = 127 AND TD.ExaminationDate <= EE.ExaminationDate ORDER BY TD.ExaminationDate DESC
	) D3Data

	ORDER BY EE.ExaminationDate DESC
	
	DROP TABLE #EmployeeExamination
	DROP TABLE #TestData

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


GO

CREATE OR ALTER PROCEDURE [sExamination].[pImproveDeteriorateTestParameterGet]
@rEmployeeId bigint, 
@rSetup1Id int,  
@rSetup2Id int
AS
BEGIN

DECLARE @rExamination1Id bigint, @rExamination2Id bigint;

-- Get Examination Ids
SELECT @rExamination1Id = Id
FROM sExamination.tExamination
WHERE ParticipantSourceTypeId = 95
AND ParticipantSourceId = @rEmployeeId
AND SetupId = @rSetup1Id;

SELECT @rExamination2Id = Id
FROM sExamination.tExamination
WHERE ParticipantSourceTypeId = 95
AND ParticipantSourceId = @rEmployeeId
AND SetupId = @rSetup2Id;

SELECT
    TestParameter,
    ISNULL(Round1, '') AS Round1,
    ISNULL(Round2, '') AS Round2,
    CASE 
        WHEN ISNUMERIC(Round1) = 1 
         AND ISNUMERIC(Round2) = 1
         AND Round1 NOT LIKE '%[^0-9.]%'
         AND Round2 NOT LIKE '%[^0-9.]%'
        THEN
            CASE 
                WHEN CAST(Round2 AS FLOAT) > CAST(Round1 AS FLOAT) THEN '1'
                WHEN CAST(Round2 AS FLOAT) < CAST(Round1 AS FLOAT) THEN '2'
                ELSE '3'
            END
        ELSE '3'
    END AS Status
FROM
(
    ------------------------------------------------------------------
    -- Vital Comparison
    ------------------------------------------------------------------
    SELECT
        T1.VitalName AS TestParameter,
        CAST(T1.Round1 AS VARCHAR(100)) AS Round1,
        CAST(T2.Round2 AS VARCHAR(100)) AS Round2
    FROM
    (
        SELECT 
            'BMI' AS VitalName,
            BMI AS Round1
        FROM sExamination.tVital
        WHERE SourceId = @rExamination1Id
        AND ISNULL(BMI,0) > 0

        UNION ALL

        SELECT 
            'BloodPressureSystolic',
            BloodPressureSystolic
        FROM sExamination.tVital
        WHERE SourceId = @rExamination1Id
        AND ISNULL(BloodPressureSystolic,0) > 0

        UNION ALL

        SELECT 
            'BloodPressureDiastolic',
            BloodPressureDiastolic
        FROM sExamination.tVital
        WHERE SourceId = @rExamination1Id
        AND ISNULL(BloodPressureDiastolic,0) > 0
    ) T1
    INNER JOIN
    (
        SELECT 
            'BMI' AS VitalName,
            BMI AS Round2
        FROM sExamination.tVital
        WHERE SourceId = @rExamination2Id
        AND ISNULL(BMI,0) > 0

        UNION ALL

        SELECT 
            'BloodPressureSystolic',
            BloodPressureSystolic
        FROM sExamination.tVital
        WHERE SourceId = @rExamination2Id
        AND ISNULL(BloodPressureSystolic,0) > 0

        UNION ALL

        SELECT 
            'BloodPressureDiastolic',
            BloodPressureDiastolic
        FROM sExamination.tVital
        WHERE SourceId = @rExamination2Id
        AND ISNULL(BloodPressureDiastolic,0) > 0
    ) T2
    ON T1.VitalName = T2.VitalName

    UNION ALL

    ------------------------------------------------------------------
    -- Test Parameter Comparison
    ------------------------------------------------------------------
    SELECT
        T1.Title AS TestParameter,
        T1.ServiceValue AS Round1,
        T2.ServiceValue AS Round2
    FROM
    (
        SELECT 
            TPM.Id AS TestParameterId,
            TPM.Title,
            TRD.ServiceValue
        FROM sExamination.tTestRequestDetail TRD
        INNER JOIN sOrderEntry.tTestDetail TD 
            ON TD.Id = TRD.TestDetailId
        INNER JOIN sOrderEntry.tTestParameterMaster TPM 
            ON TPM.Id = TD.TestParameterId
        WHERE TRD.TestRequestId IN
        (
            SELECT Id 
            FROM sExamination.tTestRequest 
            WHERE SourceId = @rExamination1Id
        ) and TPM.StaticTestParameterId IN (2,19,21,23,25,27,31,32,33,34,38,58,105,107,108,109,166)
    ) T1
    INNER JOIN
    (
        SELECT 
            TPM.Id AS TestParameterId,
            TPM.Title,
            TRD.ServiceValue
        FROM sExamination.tTestRequestDetail TRD
        INNER JOIN sOrderEntry.tTestDetail TD 
            ON TD.Id = TRD.TestDetailId
        INNER JOIN sOrderEntry.tTestParameterMaster TPM 
            ON TPM.Id = TD.TestParameterId
        WHERE TRD.TestRequestId IN
        (
            SELECT Id 
            FROM sExamination.tTestRequest 
            WHERE SourceId = @rExamination2Id
        ) and TPM.StaticTestParameterId IN (2,19,21,23,25,27,31,32,33,34,38,58,105,107,108,109,166)
    ) T2
    ON T1.TestParameterId = T2.TestParameterId

) X
ORDER BY TestParameter;

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


GO
CREATE OR ALTER PROCEDURE [sExamination].[pPeriodicExaminationFreezeAllDataListGetLog]         
(          
    @rOrgId INT = 0,          
    @rSetupId INT = 0,          
    @rEmployeeId BIGINT = 0,          
    @rUserId BIGINT     
     
)          
AS          
BEGIN          
    SET NOCOUNT ON;          
        
    SELECT        
        COUNT(*) OVER() AS RecordCount,        
        
        L.SetupEmployeeId,          
        L.SetupId,          
        L.EmployeeId AS ParticipantSourceId,          
        
        EM.Code AS ParticipantCode,          
        ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.LastName, '') AS ParticipantName,          
        
        ISNULL(EM1.FirstName, '') + ' ' + ISNULL(EM1.LastName, '') AS CentralDoctor,          
        ISNULL(EM1.Code, '') AS CentralDoctorCode,          
        
        ISNULL(EM2.FirstName, '') + ' ' + ISNULL(EM2.LastName, '') AS SiteDoctor,          
        ISNULL(EM2.Code, '') AS SiteDoctorCode,          
        
        ISNULL(EM3.FirstName, '') + ' ' + ISNULL(EM3.LastName, '') AS CentralSpoc,          
        ISNULL(EM3.Code, '') AS CentralSpocCode,          
        
        ISNULL(EM4.FirstName, '') + ' ' + ISNULL(EM4.LastName, '') AS SiteSpoc,          
        ISNULL(EM4.Code, '') AS SiteSpocCode,        
        
        L.ActionDate as CreatedDateTime,        
       --L.ActionBy        
  ISNULL(EM5.FirstName, '') + ' ' + ISNULL(EM5.LastName, '') AS CreatedUserName        
        
    FROM sExamination.tSetupEmployeeLog L         
    INNER JOIN sExamination.tSetupEmployee SE ON SE.Id = L.SetupEmployeeId   -- and l.EmployeeId=Se.EmployeeId    
    INNER JOIN sExamination.tSetupMaster SEM ON SEM.Id = L.SetupId          
    INNER JOIN sSecurity.tUserLocation UL ON UL.StoreLocationId = SEM.StoreLocationId          
    INNER JOIN sHrm.tEmployeeMaster EM ON L.EmployeeId = EM.Id          
    LEFT JOIN  sSecurity.tUser EMU  ON L.ActionBy = EMU.id        
    LEFT JOIN sHrm.tEmployeeMaster EM1 ON L.CentralDoctorId = EM1.Id          
    LEFT JOIN sHrm.tEmployeeMaster EM2 ON L.SiteDoctorId = EM2.Id          
    LEFT JOIN sHrm.tEmployeeMaster EM3 ON L.CentralSpocId = EM3.Id          
    LEFT JOIN sHrm.tEmployeeMaster EM4 ON L.SiteSpocId = EM4.Id          
     LEFT JOIN sHrm.tEmployeeMaster EM5 ON EMU.SourceId = EM5.Id          
        
        
        
WHERE          
  (@rSetupId = 0 OR L.SetupId = @rSetupId)          
    AND (@rOrgId = 0 OR L.OrgId = @rOrgId)          
    AND (@rUserId = 0 OR UL.UserId = @rUserId)     
 AND (@rEmployeeId = 0 OR L.EmployeeId = @rEmployeeId)      
 order by l.logid desc
      
end
GO
PRINT N'Creating Procedure [sExamination].[pRegistrationGetDashboard]...';


GO
CREATE OR ALTER PROCEDURE [sExamination].[pRegistrationGetDashboard]  
@rId  bigint= 0,     
@rOrgId smallint,   
@rFromDate datetime='',  
@rToDate datetime='',  
@rStoreLocationId int=0,  
@rSetupId int=0,  
@rDoctorEmployeeId bigint,  
@rEmployeeCode nvarchar(20)='',  
@rEmployeeName nvarchar(100)='',  
@rCauseId int=0  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
 SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)  
   
 SELECT R.Id,R.OrgId,R.ParticipantSourceTypeId,R.ParticipantSourceId,  
 R.SetupId,ISNULL(R.StatusId,0) AS StatusId,R.RegistrationDate,R.DoctorEmployeeId,  
 R.StoreLocationId,ISNull(R.CauseId,0) AS  CauseId,Isnull(R.Pulse,0) AS Pulse,  
 ISNULL(R.Temperature,0) AS Temperature,  
 ISNULL(R.BloodPressureSystolic,0) AS BloodPressureSystolic,  
 ISNULL(R.BloodPressureDiastolic,0) AS BloodPressureDiastolic,  
 ISNULL(R.Respiration,0) AS Respiration,ISNULL(R.Height,0) AS Height,  
 ISNULL(R.BodyWeight,0) AS BodyWeight,ISNULL(R.BMI,0) AS BMI,  
 ISNULL(R.ChestExpansion,0) AS ChestExpansion,  
 ISNULL(R.AbdominalGirth,0) AS AbdominalGirth ,  
 ISNULL(R.ElbowWidth,0 ) AS ElbowWidth,ISNULL(R.Waist,0) AS Waist,  
 ISNULL(R.Hip,0) AS Hip,R.Remark,VSM.MainTypeId,VSM.MainType,  
 VSM.Title AS Setup,Isnull(ODM.Id,0) AS DepartmentId,  
 EM1.FirstName + ISNULL(' ' + EM1.MiddleName, '') + ' ' + ISNULL(EM1.LastName,'') AS DoctorName,  
 CASE WHEN R.ParticipantSourceTypeId = 95 THEN ISNULL(EM.Id,0) WHEN R.ParticipantSourceTypeId = 1009 THEN ISNULL(CSB.Id,0) ELSE EFD.Id END AS DependentId,  
 CASE WHEN R.ParticipantSourceTypeId = 95 THEN EM.Code WHEN R.ParticipantSourceTypeId = 1009 THEN CSB.Code ELSE EM2.Code END AS PatientCode,  
 CASE WHEN R.ParticipantSourceTypeId = 95 THEN (EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + Isnull(EM.LastName,''))   
 when R.OtherName != '' and R.ParticipantSourceTypeId = 1009 then isnull(R.OtherName,'')  
 WHEN R.ParticipantSourceTypeId = 1009 THEN (CSB.FirstName + ISNULL(' ' + CSB.MiddleName, '') + ' ' + CSB.LastName) ELSE EFD.Name END AS PatientName,  
 isnull(R.OtherName,'') as OtherName,isnull(R.RegistrationNumber,'') as RegistrationNumber,  
 isnull(R.Age,0) as Age,isnull(R.Months,0) as Months,isnull(R.GenderId,0) as GenderId,isnull(R.ChestExpansionInhalation,0) as ChestExpansionInhalation,  
 isnull(R.ChestExpansionExhalation,0) as ChestExpansionExhalation,  
 CASE WHEN R.ParticipantSourceTypeId = 1009 THEN ISNULL(CSB.MobileNo,0) ELSE '' END AS MobileNo,  
 CASE WHEN R.ParticipantSourceTypeId = 1009 THEN ISNULL(CSB.UIDNumber,0) ELSE '' END AS UIDNumber,  
 Isnull(R.TimeSlotId,0) as TimeSlotId,  
 (Left(convert(varchar,TSM.FromTime,108),5) + '-' + Left(convert(varchar,TSM.ToTime,108),5)) as TimeSlot,  
 isnull(R.FromTime,'') as FromTime,  
 isnull(R.ToTime,'') as ToTime,
  isnull(R.SPo2,0) as SPO2,
  ISNULL(R.AppointmentId,0) as AppointmentId,
  R.CompliantRemark, ISNULL(R.VisitTypeId, 0) AS VisitTypeId
 FROM sExamination.tRegistration R LEFT JOIN sHrm.tEmployeeFamilyDetails EFD  
 ON EFD.Id = R.ParticipantSourceId AND R.ParticipantSourceTypeId = 1001  
 LEFT JOIN sHrm.tEmployeeMaster  EM2 ON EM2.Id = EFD.EmployeeId AND R.ParticipantSourceTypeId = 1001  
 LEFT JOIN sHrm.tEmployeeMaster  EM ON EM.Id = R.ParticipantSourceId  AND R.ParticipantSourceTypeId = 95   
 LEFT JOIN sHrm.tCsrBenefiterMaster  CSB ON CSB.Id = R.ParticipantSourceId AND R.ParticipantSourceTypeId = 1009  
 LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id = R.DoctorEmployeeId  
 LEFT JOIN sHrm.tEmployeeJobDetail  EJD ON EJD.EmployeeId = EM.Id  
 LEFT JOIN sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId  
 INNER JOIN sExamination.vExtSetupMaster AS VSM ON VSM.Id = R.SetupId  
 LEFT JOIN sAppointment.tTimeSlotMaster TSM On TSM.Id=R.TimeslotId  
 where ((R.Id=@rId) OR (@rId=0)) AND R.OrgId=@rOrgId  
 AND isnull(R.ExaminationId,0) = 0
 AND ((R.registrationDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))  
 AND ((registrationDate<=@rTodate) OR(ISNULL(@rTodate,'')=''))  
 AND ((R.SetupId = @rSetupId) OR (@rSetupId = 0))  
 AND ((R.StoreLocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))  
 AND ((R.DoctorEmployeeId = @rDoctorEmployeeId) OR (@rDoctorEmployeeId = 0))  
 AND ((EM.Code = @rEmployeeCode) OR (CSB.Code=@rEmployeeCode) OR (EM2.Code=@rEmployeeCode) OR (ISNULL(@rEmployeeCode,'') = ''))  
 AND ((EM.FirstName like @rEmployeeName + '%') OR (CSB.FirstName like @rEmployeeName + '%')  
 OR (EFD.Name like @rEmployeeName + '%') or R.OtherName like @rEmployeeName + '%' OR (Isnull(@rEmployeeName,'')= ''))  
 and(R.CauseId=@rCauseId or @rCauseId=0)  
 order by R.Id desc  
END
GO
PRINT N'Creating Procedure [sExamination].[pValidateAgeWiseEmployeeRound]...';


GO
CREATE OR ALTER PROCEDURE [sExamination].[pValidateAgeWiseEmployeeRound]
(
    @rEmployeeCodes NVARCHAR(MAX) = '',
    @rRoundId INT
)
AS
BEGIN

    DECLARE @rRoundGroupId INT;

    SET @rRoundGroupId = (
        SELECT SetupGroupId 
        FROM sExamination.tSetupMaster 
        WHERE Id = @rRoundId
    );

    select EM.Code, EM.FirstName from sExamination.tSetupEmployee SE
	INNER JOIN sExamination.tSetupMaster SM ON SM.Id = SE.SetupId
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = SE.EmployeeId
	WHERE SM.SetupGroupId = @rRoundGroupId
	and (EM.Code in (SELECT item FROM  sCommon.fnsplit(ISNULL(@rEmployeeCodes,''),',')) OR ISNULL(@rEmployeeCodes,'')='');

END
GO
PRINT N'Creating Procedure [sFeedback].[pAddOrUpdateFeedbackQuestions]...';


GO
CREATE OR ALTER PROCEDURE [sFeedback].[pAddOrUpdateFeedbackQuestions]
(
	@rFeedbackTemplateId INT,
	@rUserId BIGINT,
    @rQuestionList [sFeedback].[udt_FeedbackTemplateQuestions] READONLY,
    @Result INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

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

    DELETE FTD
    FROM [sFeedback].[tFeedbackTemplateDetail] FTD
    WHERE FTD.FeedbackTemplateId = @rFeedbackTemplateId
    AND FTD.Id NOT IN (SELECT Id FROM @rQuestionList);

    UPDATE T
    SET 
		T.QuestionText = S.QuestionText,
		T.AnswerType = S.AnswerType,
		T.IsRequired = S.IsRequired,
		T.OrderIndex = S.OrderIndex,
		T.IsObsolete = S.IsObsolete,
		T.UpdatedUserId = @rUserId,
		T.UpdatedDatetime = sCommon.fGetDate()
    FROM 
		[sFeedback].[tFeedbackTemplateDetail] T
    INNER JOIN 
		@rQuestionList S
	ON
		T.FeedbackTemplateId = @rFeedbackTemplateId
	AND
		T.Id = S.Id
        

    SET @ModifiedRows = @ModifiedRows + @@ROWCOUNT;

    INSERT INTO [sFeedback].[tFeedbackTemplateDetail]
    (
        FeedbackTemplateId,
		QuestionText,
		AnswerType,
		IsRequired,
		OrderIndex,
		IsObsolete,
		CreatedUserId,
		CreatedDatetime
    )
    SELECT 
		@rFeedbackTemplateId,
        Q.QuestionText,
		Q.AnswerType,
		Q.IsRequired,
		Q.OrderIndex,
		Q.IsObsolete,
		@rUserId,
		sCommon.fGetDate()
    FROM @rQuestionList  Q
    WHERE Q.Id NOT IN (SELECT Id FROM [sFeedback].[tFeedbackTemplateDetail] WHERE FeedbackTemplateId = @rFeedbackTemplateId)

    SET @ModifiedRows = @ModifiedRows + @@ROWCOUNT;

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


GO


CREATE OR ALTER PROCEDURE [sFeedback].[pAddOrUpdateFeedbackTemplate]
(
    @rId INT,
    @rOrgId SMALLINT,
    @rName NVARCHAR(250),
    @rFeedbackCategoryId INT,
	@rFeedbackTypeId INT,
    @rFeedbackDescription NVARCHAR(250),
    @rIsAnonymus BIT,
    @rExpireDuration DATETIME,
	@rTrigerDuration DATETIME,
	@rPriority TINYINT,
	@rCanAssign BIT,
	@rIsObsolete BIT,
    @rUserId BIGINT
)
AS
SET NOCOUNT ON
BEGIN
    DECLARE @lNextNumber BIGINT = 0;

    IF EXISTS(SELECT 1 FROM [sFeedback].[tFeedbackTemplate] WHERE Id <> @rId  AND Name = @rName  AND  OrgId = @rOrgId)
    BEGIN
        SELECT CAST(-102 AS NVARCHAR(10)) AS Result  -- Duplocate
        RETURN
    END
	IF(@rIsObsolete = 1)
	BEGIN
		IF EXISTS(SELECT Id FROM [sFeedback].[tFeedback] WHERE FeedbackTemplateId = @rId)
		BEGIN
			SELECT -104 AS Result -- Cannot inactive feedback template if it's used even once
			RETURN
		END
	END

    BEGIN TRY
        BEGIN TRANSACTION

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

            INSERT INTO [sFeedback].[tFeedbackTemplate]
            (
                Id, OrgId, Name, 
				FeedbackCategoryId, FeedbackTypeId, FeedbackDescription,
				IsAnonymus, ExpireDuration, TrigerDuration, Priority, CanAssign,
				IsObsolete, CreatedUserId, CreatedDatetime
				
            )
            VALUES
            (   
                @lNextNumber, @rOrgId, @rName,
				@rFeedbackCategoryId, @rFeedbackTypeId, @rFeedbackDescription,     
				@rIsAnonymus, @rExpireDuration, @rTrigerDuration, @rPriority, @rCanAssign,
				@rIsObsolete, @rUserId, sCommon.fGetDate()
            )
        END
        ELSE
        BEGIN
            UPDATE [sFeedback].[tFeedbackTemplate]
            SET
                Name = @rName,
                FeedbackCategoryId = @rFeedbackCategoryId,
                FeedbackTypeId = @rFeedbackTypeId,
                FeedbackDescription = @rFeedbackDescription,
                IsAnonymus = @rIsAnonymus,
                ExpireDuration = @rExpireDuration,
                TrigerDuration = @rTrigerDuration,
				Priority = @rPriority,
				CanAssign = @rCanAssign,
				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 [sFeedback].[pDeleteFeedbackTemplate]...';


GO
CREATE OR ALTER PROCEDURE [sFeedback].[pDeleteFeedbackTemplate]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	
	DECLARE @Record INT = 0;

	SET @Record = (SELECT COUNT(Id) FROM [sFeedback].[tFeedback] WHERE FeedbackTemplateId = @rId)

	IF(@Record > 0)
	BEGIN
		SELECT -103 AS Result;
	END
	ELSE
	BEGIN
		DELETE FROM [sFeedback].[tFeedbackTemplate] WHERE Id = @rId
		DELETE FROM [sFeedback].[tFeedbackTemplateDetail] WHERE FeedbackTemplateId = @rId
		
		SELECT 1 AS Result;
	END

END
GO
PRINT N'Creating Procedure [sFeedback].[pDeleteFeedbackTemplateQuestion]...';


GO
CREATE OR ALTER PROCEDURE [sFeedback].[pDeleteFeedbackTemplateQuestion]
(
	@rId INT,
	@rQuestionId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	
	DECLARE @Record INT = 0;

	SET @Record = (SELECT COUNT(Id) FROM [sFeedback].[tFeedbackDetail] WHERE FeedbackId = @rId AND FeedbackTemplateDetailId = @rQuestionId)

	IF(@Record > 0)
	BEGIN
		SELECT -103 AS Result;
	END
	ELSE
	BEGIN
		DELETE FROM [sFeedback].[tFeedbackTemplateDetail] WHERE FeedbackTemplateId = @rId AND Id = @rQuestionId
		SELECT 1 AS Result;
	END

END
GO
PRINT N'Creating Procedure [sFeedback].[pGetFeedbackTemplate]...';


GO


CREATE OR ALTER PROCEDURE [sFeedback].[pGetFeedbackTemplate]
(
	@rId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
		SELECT
			Id,
			Name,
			FeedbackCategoryId,
			FeedbackTypeId,
			FeedbackDescription,
			IsAnonymus,
			ExpireDuration,
			TrigerDuration,
			Priority,
			CanAssign,
			IsObsolete,
			OrgId
		FROM
			[sFeedback].[tFeedbackTemplate] FT
		WHERE
			FT.Id = @rId 
		AND
			FT.OrgId = @rOrgId
END
GO
PRINT N'Creating Procedure [sFeedback].[pListFeedbackCatogory]...';


GO
CREATE OR ALTER PROCEDURE [sFeedback].[pListFeedbackCatogory]
(
	@rIsObsolete SMALLINT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SELECT 
		FCM.Id,
		ISNULL(FCM.Code,'-') AS Code,
		ISNULL(FCM.Name,'-') AS Name,
		FCM.IsObsolete,
		CASE WHEN FCM.IsObsolete = 0 THEN 'Active' ELSE 'InActive' END AS IsActive
	FROM 
		[sFeedback].[tFeedbackCategoryMaster] FCM
	WHERE 
		@rIsObsolete = 2
    OR 
		FCM.IsObsolete = @rIsObsolete;
END
GO
PRINT N'Creating Procedure [sFeedback].[pListFeedbackTemplate]...';


GO
CREATE OR ALTER PROCEDURE [sFeedback].[pListFeedbackTemplate]
(	
	@rName NVARCHAR(200),
	@rCategoryId INT,
	@rTypeId INT,
	@rPriorityId SMALLINT,
	@rUserId BIGINT,
	@rOrgId SMALLINT
)
AS
SET NOCOUNT ON;
BEGIN
	
		SELECT
			FT.Id,
			ISNULL(FT.Name ,'-') AS Name,
			ISNULL(FCM.Name, '-') AS CategoryName,
			ISNULL(FTM.Name, '-') AS TypeName,
			ISNULL(FT.FeedbackDescription,'-') AS FeedbackDescription,
			FT.IsAnonymus,
			CASE WHEN FT.IsAnonymus = 1 THEN 'YES' ELSE 'NO' END AS IsAnonymusString,	
			FT.ExpireDuration,
			ISNULL(CONVERT(VARCHAR(10), FT.ExpireDuration, 103), '-') AS ExpireDurationString,
			FT.TrigerDuration,
			ISNULL(CONVERT(VARCHAR(10), FT.TrigerDuration, 103), '-') AS TrigerDurationString,
			FT.Priority,
			CASE WHEN FT.Priority = 1 THEN 'LOW' WHEN FT.Priority = 2 THEN 'Medium' WHEN FT.Priority = 3 THEN 'High' ELSE 'Unknown' END AS PriorityString,
			FT.CanAssign,
			CASE WHEN FT.CanAssign = 1 THEN 'Yes' ELSE 'No' END AS CanAssignString,
			FT.IsObsolete,
			CASE WHEN FT.IsObsolete = 1 THEN 'InActive' ELSE 'Active' END AS IsObsoleteString
		FROM 
			[sFeedback].[tFeedbackTemplate] FT
		LEFT JOIN
			[sFeedback].[tFeedbackCategoryMaster] FCM
		ON
			FCM.Id = FT.FeedbackCategoryId
		LEFT JOIN
			[sFeedback].[tFeedbackTypeMaster] FTM
		ON
			FTM.Id = FT.FeedbackTypeId
		WHERE
		  ((@rName IS NULL) OR (FT.Name LIKE '%' + @rName + '%'))
		AND
		  ((@rCategoryId = 0) OR (@rCategoryId = FT.FeedbackCategoryId))
		AND
		  ((@rTypeId = 0) OR (@rTypeId = FT.FeedbackTypeId))
		AND
			((@rPriorityId = 0) OR (@rPriorityId = FT.Priority))
		AND
			FT.OrgId = @rOrgId
		ORDER BY
			FT.Id
		DESC
END
GO
PRINT N'Creating Procedure [sFeedback].[pListFeedbackTemplateQuestions]...';


GO
CREATE OR ALTER PROCEDURE [sFeedback].[pListFeedbackTemplateQuestions]
(
	@rFeedbackTemplateId INT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SET NOCOUNT ON;
	
	SELECT
		FTD.Id,
		FTD.FeedbackTemplateId,
		FTD.QuestionText,
		FTD.AnswerType,
		FTD.IsRequired,
		FTD.OrderIndex,
		FTD.IsObsolete
	FROM
		[sFeedback].[tFeedbackTemplateDetail] FTD
	INNER JOIN
		[sFeedback].[tFeedbackTemplate] FT
	ON
		FT.Id = FTD.FeedbackTemplateId
	AND
		FT.OrgId = @rOrgId
	WHERE
		FTD.FeedbackTemplateId = @rFeedbackTemplateId

END
GO
PRINT N'Creating Procedure [sFeedback].[pListFeedbackType]...';


GO
CREATE OR ALTER PROCEDURE [sFeedback].[pListFeedbackType]
(
	@rIsObsolete SMALLINT,
	@rOrgId SMALLINT
)
AS
BEGIN
	SELECT 
		FTM.Id,
		ISNULL(FTM.Code,'-') AS Code,
		ISNULL(FTM.Name,'-') AS Name,
		ISNULL(FTM.FeedbackScale,0) AS FeedbackScale,
		FTM.IsObsolete,
		CASE WHEN FTM.IsObsolete = 0 THEN 'Active' ELSE 'InActive' END AS IsActive
	FROM 
		[sFeedback].[tFeedbackTypeMaster] FTM
	WHERE 
		@rIsObsolete = 2
    OR 
		FTM.IsObsolete = @rIsObsolete;
END
GO
PRINT N'Creating Procedure [sPharmacy].[pPharmacyQueueListingGetDashboard]...';


GO
CREATE OR ALTER PROCEDURE [sPharmacy].[pPharmacyQueueListingGetDashboard]
   	@rOrgID [int] = 0,  
	@rLocationId int 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	DECLARE @FromDate DATETIME = CAST(GETDATE() AS DATE);
DECLARE @ToDate   DATETIME = DATEADD(DAY, 1, @FromDate);
	SELECT 
	P.ID,
	Code = 
	CASE AED.ParticipantSourceTypeId WHEN 95 THEN EM.Code WHEN 1001 THEN EM2.Code 
	WHEN 1009 THEN BM.Code END,
	PatientName = CASE AED.ParticipantSourceTypeId WHEN 95 THEN isnull(EM.FirstName,'') + ' ' + isnull(EM.LastName,'')
	WHEN 1001 THEN EFD.Name WHEN 1009 THEN 
	(case when isnull(ETO.OtherName,'') <> '' then ETO.OtherName else (isnull(BM.FirstName,'') + ' ' + isnull(BM.LastName,'')) end) END ,
	case when isnull(U.DisplayTitle,'') <> '' then U.DisplayTitle
	else ISNULL(EM1.FirstName,'') + ' ' + ISNULL( EM1.LastName,'') end AS EmployeeName,
	CASE AED.ParticipantSourceTypeId WHEN 95 THEN 'SELF' WHEN 1001 THEN RM.Title WHEN 1009 THEN 'Other'	END As Relation,
	AED.ExaminationDate,
	AED.ExaminationNumber
	FROM sExamination.tPrescription P with(NOLOCK)
	INNER JOIN sSecurity.tUser U ON U.Id = P.CreatedUserId
	INNER JOIN sExamination.tExamination AED ON AED.Id = P.SourceId
	INNER JOIN sExamination.tSetupMaster SM on AED.SetupId = SM.Id
	INNER JOIN sExamination.tSubTypeMaster ST on SM.SubTypeId = ST.Id
	LEFT JOIN sExamination.tOPD ETO on ETO.ExaminationId= AED.Id
	LEFT JOIN sHrm.tEmployeeMaster EM1 ON EM1.Id=AED.DoctorEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EM on AED.ParticipantSourceId = EM.Id and AED.ParticipantSourceTypeId = 95
	LEFT JOIN sHrm.tEmployeeFamilyDetails EFD on AED.ParticipantSourceId = EFD.Id and AED.ParticipantSourceTypeId = 1001
	LEFT JOIN sHrm.tCsrBenefiterMaster BM on AED.ParticipantSourceId = BM.Id and AED.ParticipantSourceTypeId = 1009
	LEFT JOIN sHrm.tEmployeeMaster EM2 on EFD.EmployeeId = EM2.Id
	LEFT JOIN sCommon.tRelationshipMaster RM ON RM.Id=EFD.RelationshipId
	WHERE isnull(AED.IsCancel,0) = 0 
	AND AED.ExaminationDate >= @FromDate
    AND AED.ExaminationDate <  @ToDate
	AND P.IsDispensed = 0
	AND ST.MainTypeId = 8 AND AED.OrgId = P.OrgId
	AND AED.StoreLocationId = @rLocationId AND P.IsObsolete  = 0 AND IsDirect = 0
	AND P.OrgId = @rOrgID 
	AND isnull(IsOtherIssue,0) = 0 order by P.Id desc
END

GO
PRINT N'Creating Procedure [sWellness].[pAddOrUpdateMHIUpdationCategoryBulk]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateMHIUpdationCategoryBulk]
( 
    @rUserId BIGINT,
	@rLocationId INT,
	@rInsertType SMALLINT,
	@rLastUpdateType SMALLINT,
    @rMHICategoryList [sWellness].[udt_MHIBulkCategoryImport] READONLY,
    @Result INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ModifiedRows INT = 0;

    MERGE [sWellness].[tMHIScoreUpdation] AS T
    USING
    (
        SELECT 
            E.Id AS ParticipantSourceId,
            M.HBA1CCategory,
            M.LDLCategory,
            M.BMICategory,
            M.BPCategory,
            M.StressCategory,
            M.LifestyleCategory
        FROM @rMHICategoryList M
        INNER JOIN [sHrm].[tEmployeeMaster] E
            ON E.Code = M.EmployeeCode
    ) AS S
    ON T.ParticipantSourceId = S.ParticipantSourceId

    WHEN MATCHED THEN
        UPDATE SET
            T.HBA1CCategory = S.HBA1CCategory,
            T.BMICategory = S.BMICategory,
            T.LDLCategory = S.LDLCategory,
            T.BPCategory = S.BPCategory,
            T.StressCategory = S.StressCategory,
            T.LifestyleCategory = S.LifestyleCategory,
			T.LocationId = @rLocationId,
            T.InsertType = @rInsertType,
			T.LastUpdateType = @rLastUpdateType,
            T.UpdatedUserId = @rUserId,
            T.UpdatedDateTime = sCommon.fGetDate()

    WHEN NOT MATCHED THEN
        INSERT
        (
            ParticipantSourceTypeId,
            ParticipantSourceId,
			HBA1CCategory,
            BMICategory,
            LDLCategory,
			BPCategory,
            StressCategory,
            LifestyleCategory,
			LocationId,
			InsertType,
			LastUpdateType,
            CreatedUserId,
            CreatedDateTime
        )
        VALUES
        (
            95,
            S.ParticipantSourceId,
            S.HBA1CCategory,
            S.BMICategory,
            S.LDLCategory,
            S.BPCategory,
            S.StressCategory,
            S.LifestyleCategory,
			@rLocationId,
			@rInsertType,
			@rLastUpdateType,
            @rUserId,
            sCommon.fGetDate()
        );

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


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateMHIUpdationSurveyBulk]
( 
    @rUserId BIGINT,
	@rLocationId INT,
	@rInsertType SMALLINT,
	@rLastUpdateType SMALLINT,
    @rEmployeeMHISurveyBulkList [sWellness].[udt_MHIScoreUpdateThroughtSurveyBulk] READONLY,
    @Result INT OUTPUT
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ModifiedRows INT = 0;

    MERGE [sWellness].[tMHIScoreUpdation] AS T
    USING
    (
        SELECT 
            E.Id AS ParticipantSourceId,
            M.Stress,
            M.LifeStyle
        FROM @rEmployeeMHISurveyBulkList M
        INNER JOIN [sHrm].[tEmployeeMaster] E
            ON E.Code = M.EmployeeCode
    ) AS S
    ON T.ParticipantSourceId = S.ParticipantSourceId

    WHEN MATCHED THEN
        UPDATE SET
            T.Stress = S.Stress,
            T.LifeStyle = S.LifeStyle,
			T.LocationId = @rLocationId,
			T.InsertType = @rInsertType,
			T.LastUpdateType = @rLastUpdateType,
            T.UpdatedUserId = @rUserId,
            T.UpdatedDateTime = sCommon.fGetDate()

    WHEN NOT MATCHED THEN
        INSERT
        (
            ParticipantSourceTypeId,
            ParticipantSourceId,
            Stress,
            LifeStyle,
			LocationId,
			InsertType,
			LastUpdateType,
            CreatedUserId,
            CreatedDateTime
        )
        VALUES
        (
            95,
            S.ParticipantSourceId,
            S.Stress,
            S.LifeStyle,
			@rLocationId,
			@rInsertType,
			@rLastUpdateType,
            @rUserId,
            sCommon.fGetDate()
        );

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


GO

CREATE OR ALTER PROCEDURE [sWellness].[pAddOrUpdateProgramMHICategory]
(
	@rOrgId SMALLINT,	
    @rEmployeeId BIGINT,
	@rEmployeeSourceTypeId INT,
    @rInsertType SMALLINT,

    -- Raw values (kept for storage only)
    @rBMI NUMERIC(10,2) = NULL,
    @rSystolicBP NUMERIC(10,0)=NULL,
    @rDiastolicBP NUMERIC(10,0)=NULL,
    @rHBA1C NUMERIC(10,2)=NULL,
    @rLDL NUMERIC(10,2)=NULL,

    -- NEW: Direct Scores
    @rBMIScore SMALLINT,
    @rHBA1CScore SMALLINT,
    @rLDLScore SMALLINT,
    @rBPScore SMALLINT,
    @rStressScore SMALLINT,
    @rLifestyleScore SMALLINT,
	@rLocationId INT,
    @rUserId BIGINT
)
AS
SET NOCOUNT ON;
BEGIN
	DECLARE @lNextNumber BIGINT = 0;

	BEGIN TRY
	BEGIN TRANSACTION

	-- =========================================
	-- Normalize Scores (0 → NULL)
	-- =========================================
	DECLARE 
		@BMIScore SMALLINT = CASE WHEN @rBMIScore IN (1,2,3) THEN @rBMIScore ELSE NULL END,
		@HBA1CScore SMALLINT = CASE WHEN @rHBA1CScore IN (1,2,3) THEN @rHBA1CScore ELSE NULL END,
		@LDLScore SMALLINT = CASE WHEN @rLDLScore IN (1,2,3) THEN @rLDLScore ELSE NULL END,
		@BPScore SMALLINT = CASE WHEN @rBPScore IN (1,2,3) THEN @rBPScore ELSE NULL END,
		@StressIndex SMALLINT = CASE WHEN @rStressScore IN (1,2,3) THEN @rStressScore ELSE NULL END,
		@LifestyleIndex SMALLINT = CASE WHEN @rLifestyleScore IN (1,2,3) THEN @rLifestyleScore ELSE NULL END,
		@AssignedMHIIndicatorId INT = 0;

	-- =========================================
	-- Category Mapping
	-- =========================================
	DECLARE 
		@BMICategory NVARCHAR(30),
		@HBA1CCategory NVARCHAR(30),
		@LDLCategory NVARCHAR(30),
		@BPCategory NVARCHAR(30),
		@StressCategory NVARCHAR(30),
		@LifeStyleCategory NVARCHAR(30);

	SET @BMICategory = CASE @BMIScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END;
	SET @HBA1CCategory = CASE @HBA1CScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END;
	SET @LDLCategory = CASE @LDLScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END;
	SET @BPCategory = CASE @BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END;
	SET @StressCategory = CASE @StressIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END;
	SET @LifeStyleCategory = CASE @LifestyleIndex WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' END;

	-- =========================================
	-- INSERT / UPDATE BASE DATA
	-- =========================================
	IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScore] WHERE EmployeeId = @rEmployeeId)
	BEGIN
		EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore', 0,1,1, @outNextNumber = @lNextNumber OUTPUT

		INSERT INTO [sWellness].[tMHIScore]
		(
			Id,OrgId,ProgramId,EmployeeId,EmployeeSourceTypeId,LastUpdateType,
			HBA1C,HBA1CScore,HBA1CCategory,
			LDL,LDLScore,LDLCategory,
			BMI,BMIScore,BMICategory,
			BP,BPScore,BPCategory,
			Stress,StressScore,StressCategory,
			Lifestyle,LifestyleScore,LifestyleCategory, LocationId,
			CreatedUserId,CreatedDatetime
		)
		VALUES
		(
			@lNextNumber,@rOrgId,0,@rEmployeeId,@rEmployeeSourceTypeId,@rInsertType,
			@rHBA1C,@HBA1CScore,@HBA1CCategory,
			@rLDL,@LDLScore,@LDLCategory,
			@rBMI,@BMIScore,@BMICategory,
			CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)),@BPScore,@BPCategory,
			@rStressScore,@StressIndex,@StressCategory,
			@rLifestyleScore,@LifestyleIndex,@LifeStyleCategory,@rLocationId,
			@rUserId,sCommon.fGetDate()
		)
	END
	ELSE
	BEGIN
		UPDATE [sWellness].[tMHIScore]
		SET
			HBA1C=@rHBA1C,
			HBA1CScore=@HBA1CScore,
			HBA1CCategory=@HBA1CCategory,

			LDL=@rLDL,
			LDLScore=@LDLScore,
			LDLCategory=@LDLCategory,

			BMI=@rBMI,
			BMIScore=@BMIScore,
			BMICategory=@BMICategory,

			BP=CAST(@rSystolicBP AS VARCHAR(10)) + '/' + CAST(@rDiastolicBP AS VARCHAR(10)),
			BPScore=@BPScore,
			BPCategory=@BPCategory,

			Stress=@rStressScore,
			StressScore=@StressIndex,
			StressCategory=@StressCategory,

			Lifestyle=@rLifestyleScore,
			LifestyleScore=@LifestyleIndex,
			LifestyleCategory=@LifeStyleCategory,

			UpdatedUserId=@rUserId,
			UpdatedDatetime=sCommon.fGetDate(),

			LastUpdateType = @rInsertType,
			LocationId = @rLocationId


		WHERE EmployeeId=@rEmployeeId;

		SET @lNextNumber = @@ROWCOUNT;
	END

	-- =========================================
	-- BIOMETRICS CALCULATION (STRICT)
	-- =========================================
	DECLARE @BiometricScore DECIMAL(10,2)=NULL,
			@BiometricsCategory VARCHAR(30)=NULL,
			@TotalBiometrics INT=NULL;

	IF(@BMIScore IS NOT NULL AND @HBA1CScore IS NOT NULL AND @LDLScore IS NOT NULL AND @BPScore IS NOT NULL)
	BEGIN
		SET @TotalBiometrics = @BMIScore + @HBA1CScore + @LDLScore + @BPScore;
		SET @BiometricScore = (100.0 * @TotalBiometrics) / 4;

		SET @BiometricsCategory =
			CASE 
				WHEN @BiometricScore <= 100 THEN 'Optimal'
				WHEN @BiometricScore < 150 THEN 'SubOptimal'
				ELSE 'Alert'
			END
	END

	-- =========================================
	-- SURVEY CALCULATION (STRICT)
	-- =========================================
	DECLARE @SurveyCategory VARCHAR(30)=NULL;

	IF(@StressIndex IS NOT NULL AND @LifestyleIndex IS NOT NULL)
	BEGIN
		SET @SurveyCategory =
			CASE 
				WHEN @StressIndex = 3 OR @LifestyleIndex = 3 THEN 'Alert'
				WHEN @StressIndex = 2 OR @LifestyleIndex = 2 THEN 'SubOptimal'
				ELSE 'Optimal'
			END
	END

	-- =========================================
	-- MHI CALCULATION (STRICT)
	-- =========================================
	DECLARE @MHICategory VARCHAR(30)=NULL,
			@MHICategoryId SMALLINT=0,
			@AssignedProgramId INT=0;

	IF(@BiometricsCategory IS NOT NULL AND @SurveyCategory IS NOT NULL)
	BEGIN
		SET @MHICategory =
			CASE 
				WHEN @BiometricsCategory='Alert' OR @SurveyCategory='Alert' THEN 'Alert'
				WHEN @BiometricsCategory='SubOptimal' OR @SurveyCategory='SubOptimal' THEN 'SubOptimal'
				ELSE 'Optimal'
			END;

		SET @MHICategoryId =
			CASE 
				WHEN @MHICategory='Optimal' THEN 1
				WHEN @MHICategory='SubOptimal' THEN 2
				WHEN @MHICategory='Alert' THEN 3
				ELSE 0
			END;
	END

	IF(@MHICategoryId > 0)
	BEGIN
		SET @AssignedMHIIndicatorId = (SELECT TOP 1 Id FROM [sWellness].[tStaticMHICategoryIndicator] WHERE Id = @MHICategoryId)
		IF(@AssignedMHIIndicatorId > 0)
		BEGIN
			SET @AssignedProgramId = (SELECT TOP 1 Id FROM [sWellness].[tProgramMaster] WHERE MHIIndicatorId = @AssignedMHIIndicatorId AND CategoryId = 1 AND IsObsolete = 0)
		END
	END

	-- =========================================
	-- FINAL UPDATE
	-- =========================================
	UPDATE [sWellness].[tMHIScore]
	SET
		Biometrics=@BiometricScore,
		BiometricsCategory=@BiometricsCategory,
		SurveyCategory=@SurveyCategory,
		MHICategory=@MHICategory,
		MHICategoryId=@MHICategoryId,
		ProgramId = @AssignedProgramId,
		UpdatedUserId=@rUserId,
		UpdatedDatetime=sCommon.fGetDate()
	WHERE EmployeeId=@rEmployeeId;

	SET @lNextNumber = @@ROWCOUNT;

	IF (@lNextNumber > 0)
	BEGIN
			EXEC sWellness.pInsertMHIScoreHistoryIfChanged
				@rEmployeeId = @rEmployeeId,
				@rUserId     = @rUserId;
	END

	COMMIT TRANSACTION
	SELECT '1' AS Result

	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0 ROLLBACK
		SELECT '-1' AS Result, ERROR_MESSAGE()
	END CATCH
END
GO
PRINT N'Creating Procedure [sWellness].[pAssignMHIProgramCategoryBulk]...';


GO

CREATE OR ALTER PROCEDURE [sWellness].[pAssignMHIProgramCategoryBulk]
(
      @rOrgId SMALLINT,
      @rUserId BIGINT,
	  @rLocationId INT,
	  @rInsertType SMALLINT,
      @rMHIScoreList [sWellness].[udt_MHIBulkCategoryImport] READONLY,
      @InsertedCount INT OUTPUT,
      @UpdatedCount INT OUTPUT,
      @SkippedEmployeeCodeCount INT OUTPUT,
      @TotalProcessed INT OUTPUT
)
AS
BEGIN
SET NOCOUNT ON;

BEGIN TRY
BEGIN TRANSACTION;

DECLARE @MergeResult TABLE
(
    ActionType NVARCHAR(10),
    EmployeeId BIGINT
);

------------------------------------------------
-- NORMALIZATION (ALLOW 0)
------------------------------------------------
SELECT *
INTO #Calculated
FROM
(
    SELECT
          EM.EmployeeId,
          EM.GenderId,

          CA.HBA1C,
          CA.LDL,
          CA.BMI,
          CA.BP,
          CA.Stress,
          CA.Lifestyle,

          CA.BMI AS BMIScore,
          CA.HBA1C AS HBA1CScore,
          CA.LDL AS LDLScore,
          CA.BP AS BPScore,
          CA.Stress AS StressScore,
          CA.Lifestyle AS LifestyleScore

    FROM @rMHIScoreList S
    JOIN sHrm.vExtEmployeeMaster EM 
        ON EM.Code = S.EmployeeCode

    CROSS APPLY
    (
        SELECT
            CASE 
                WHEN LOWER(S.HBA1CCategory)='optimal' THEN 1
                WHEN LOWER(S.HBA1CCategory)='suboptimal' THEN 2
                WHEN LOWER(S.HBA1CCategory)='alert' THEN 3
                WHEN TRY_CAST(S.HBA1CCategory AS INT) IN (0,1,2,3) THEN TRY_CAST(S.HBA1CCategory AS INT)
            END,

            CASE 
                WHEN LOWER(S.LDLCategory)='optimal' THEN 1
                WHEN LOWER(S.LDLCategory)='suboptimal' THEN 2
                WHEN LOWER(S.LDLCategory)='alert' THEN 3
                WHEN TRY_CAST(S.LDLCategory AS INT) IN (0,1,2,3) THEN TRY_CAST(S.LDLCategory AS INT)
            END,

            CASE 
                WHEN LOWER(S.BMICategory)='optimal' THEN 1
                WHEN LOWER(S.BMICategory)='suboptimal' THEN 2
                WHEN LOWER(S.BMICategory)='alert' THEN 3
                WHEN TRY_CAST(S.BMICategory AS INT) IN (0,1,2,3) THEN TRY_CAST(S.BMICategory AS INT)
            END,

            CASE 
                WHEN LOWER(S.BPCategory)='optimal' THEN 1
                WHEN LOWER(S.BPCategory)='suboptimal' THEN 2
                WHEN LOWER(S.BPCategory)='alert' THEN 3
                WHEN TRY_CAST(S.BPCategory AS INT) IN (0,1,2,3) THEN TRY_CAST(S.BPCategory AS INT)
            END,

            CASE 
                WHEN LOWER(S.StressCategory)='optimal' THEN 1
                WHEN LOWER(S.StressCategory)='suboptimal' THEN 2
                WHEN LOWER(S.StressCategory)='alert' THEN 3
                WHEN TRY_CAST(S.StressCategory AS INT) IN (0,1,2,3) THEN TRY_CAST(S.StressCategory AS INT)
            END,

            CASE 
                WHEN LOWER(S.LifestyleCategory)='optimal' THEN 1
                WHEN LOWER(S.LifestyleCategory)='suboptimal' THEN 2
                WHEN LOWER(S.LifestyleCategory)='alert' THEN 3
                WHEN TRY_CAST(S.LifestyleCategory AS INT) IN (0,1,2,3) THEN TRY_CAST(S.LifestyleCategory AS INT)
            END
    ) CA (HBA1C, LDL, BMI, BP, Stress, Lifestyle)

    WHERE 
        CA.HBA1C IN (0,1,2,3) AND
        CA.LDL IN (0,1,2,3) AND
        CA.BMI IN (0,1,2,3) AND
        CA.BP IN (0,1,2,3) AND
        CA.Stress IN (0,1,2,3) AND
        CA.Lifestyle IN (0,1,2,3)

) X;

------------------------------------------------
-- CONVERT 0 → NULL (CRITICAL FIX)
------------------------------------------------
UPDATE #Calculated
SET 
    BMIScore = NULLIF(BMIScore,0),
    HBA1CScore = NULLIF(HBA1CScore,0),
    LDLScore = NULLIF(LDLScore,0),
    BPScore = NULLIF(BPScore,0),
    StressScore = NULLIF(StressScore,0),
    LifestyleScore = NULLIF(LifestyleScore,0);

------------------------------------------------
-- SKIPPED COUNT
------------------------------------------------
SELECT @SkippedEmployeeCodeCount =
(
    SELECT COUNT(*)
    FROM @rMHIScoreList S
    LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.Code = S.EmployeeCode
    WHERE EM.EmployeeId IS NULL
);

------------------------------------------------
-- DERIVED LOGIC
------------------------------------------------
ALTER TABLE #Calculated ADD 
Biometrics DECIMAL(10,2),
BiometricsCategory VARCHAR(30),
SurveyCategory VARCHAR(30),
MHICategory VARCHAR(30),
MHICategoryId SMALLINT,
ProgramId INT;

UPDATE #Calculated
SET Biometrics =
CASE 
    WHEN BMIScore IS NULL OR HBA1CScore IS NULL OR LDLScore IS NULL OR BPScore IS NULL THEN NULL
    ELSE (100.0 * (BMIScore + HBA1CScore + LDLScore + BPScore)) / 4
END;

UPDATE #Calculated
SET BiometricsCategory =
CASE 
    WHEN Biometrics IS NULL THEN NULL 
    WHEN Biometrics <= 100 THEN 'Optimal'
    WHEN Biometrics < 150 THEN 'SubOptimal'
    ELSE 'Alert'
END;

UPDATE #Calculated
SET SurveyCategory =
CASE
    WHEN StressScore IS NULL OR LifestyleScore IS NULL THEN NULL
    WHEN StressScore = 3 OR LifestyleScore = 3 THEN 'Alert'
    WHEN StressScore = 2 OR LifestyleScore = 2 THEN 'SubOptimal'
    WHEN StressScore = 1 AND LifestyleScore = 1 THEN 'Optimal'
END;

UPDATE #Calculated
SET MHICategory =
CASE
    WHEN BiometricsCategory IS NULL OR SurveyCategory IS NULL THEN 'NotApplicable'
    WHEN BiometricsCategory='Alert' OR SurveyCategory='Alert' THEN 'Alert'
    WHEN BiometricsCategory='SubOptimal' OR SurveyCategory='SubOptimal' THEN 'SubOptimal'
    WHEN BiometricsCategory='Optimal' AND SurveyCategory='Optimal' THEN 'Optimal'
    ELSE 'NotApplicable'
END;

UPDATE #Calculated
SET MHICategoryId =
CASE
    WHEN MHICategory='Optimal' THEN 1
    WHEN MHICategory='SubOptimal' THEN 2
    WHEN MHICategory='Alert' THEN 3
    ELSE 0
END;

UPDATE C 
SET ProgramId = ISNULL(PM.Id, 0)
FROM #Calculated C
LEFT JOIN sWellness.tStaticMHICategoryIndicator I ON I.Id = C.MHICategoryId
LEFT JOIN sWellness.tProgramMaster PM 
    ON PM.MHIIndicatorId = I.Id 
   AND PM.CategoryId = 1 
   AND PM.IsObsolete = 0;

------------------------------------------------
-- UPDATE
------------------------------------------------
UPDATE T
SET
BMIScore=C.BMIScore,
BMICategory=CASE WHEN C.BMIScore IS NULL THEN NULL WHEN C.BMIScore=1 THEN 'Optimal' WHEN C.BMIScore=2 THEN 'SubOptimal' ELSE 'Alert' END,

HBA1CScore=C.HBA1CScore,
HBA1CCategory=CASE WHEN C.HBA1CScore IS NULL THEN NULL WHEN C.HBA1CScore=1 THEN 'Optimal' WHEN C.HBA1CScore=2 THEN 'SubOptimal' ELSE 'Alert' END,

LDLScore=C.LDLScore,
LDLCategory=CASE WHEN C.LDLScore IS NULL THEN NULL WHEN C.LDLScore=1 THEN 'Optimal' WHEN C.LDLScore=2 THEN 'SubOptimal' ELSE 'Alert' END,

BPScore=C.BPScore,
BPCategory=CASE WHEN C.BPScore IS NULL THEN NULL WHEN C.BPScore=1 THEN 'Optimal' WHEN C.BPScore=2 THEN 'SubOptimal' ELSE 'Alert' END,

StressScore=C.StressScore,
StressCategory=CASE WHEN C.StressScore IS NULL THEN NULL WHEN C.StressScore=1 THEN 'Optimal' WHEN C.StressScore=2 THEN 'SubOptimal' ELSE 'Alert' END,

LifestyleScore=C.LifestyleScore,
LifestyleCategory=CASE WHEN C.LifestyleScore IS NULL THEN NULL WHEN C.LifestyleScore=1 THEN 'Optimal' WHEN C.LifestyleScore=2 THEN 'SubOptimal' ELSE 'Alert' END,

Biometrics=C.Biometrics,
BiometricsCategory=C.BiometricsCategory,
SurveyCategory=C.SurveyCategory,
MHICategory=C.MHICategory,
MHICategoryId=C.MHICategoryId,
ProgramId=C.ProgramId,

LocationId = @rLocationId,
LastUpdateType = @rInsertType,

UpdatedUserId=@rUserId,
UpdatedDatetime=sCommon.fGetDate()

OUTPUT 'UPDATE',inserted.EmployeeId INTO @MergeResult
FROM sWellness.tMHIScore T
JOIN #Calculated C ON C.EmployeeId=T.EmployeeId;

------------------------------------------------
-- INSERT
------------------------------------------------
DECLARE @EmployeeId BIGINT,@NextId BIGINT;

DECLARE curInsert CURSOR FAST_FORWARD FOR
SELECT EmployeeId
FROM #Calculated C
WHERE NOT EXISTS
(
    SELECT 1 FROM sWellness.tMHIScore T WHERE T.EmployeeId=C.EmployeeId
);

OPEN curInsert;
FETCH NEXT FROM curInsert INTO @EmployeeId;

WHILE @@FETCH_STATUS=0
BEGIN

EXEC sCommon.pTableRowIdGet
@rOrgId,'sWellness.tMHIScore',0,1,1,@outNextNumber=@NextId OUTPUT;

INSERT INTO sWellness.tMHIScore
(
Id,OrgId,ProgramId,EmployeeId,EmployeeSourceTypeId,LastUpdateType,
BMIScore,BMICategory,
HBA1CScore,HBA1CCategory,
LDLScore,LDLCategory,
BPScore,BPCategory,
StressScore,StressCategory,
LifestyleScore,LifestyleCategory,
Biometrics,BiometricsCategory,
SurveyCategory,MHICategory,MHICategoryId, LocationId,
CreatedUserId,CreatedDatetime
)
SELECT
@NextId,@rOrgId,C.ProgramId,C.EmployeeId,95,@rInsertType,
C.BMIScore,CASE WHEN C.BMIScore IS NULL THEN NULL WHEN C.BMIScore=1 THEN 'Optimal' WHEN C.BMIScore=2 THEN 'SubOptimal' ELSE 'Alert' END,
C.HBA1CScore,CASE WHEN C.HBA1CScore IS NULL THEN NULL WHEN C.HBA1CScore=1 THEN 'Optimal' WHEN C.HBA1CScore=2 THEN 'SubOptimal' ELSE 'Alert' END,
C.LDLScore,CASE WHEN C.LDLScore IS NULL THEN NULL WHEN C.LDLScore=1 THEN 'Optimal' WHEN C.LDLScore=2 THEN 'SubOptimal' ELSE 'Alert' END,
C.BPScore,CASE WHEN C.BPScore IS NULL THEN NULL WHEN C.BPScore=1 THEN 'Optimal' WHEN C.BPScore=2 THEN 'SubOptimal' ELSE 'Alert' END,
C.StressScore,CASE WHEN C.StressScore IS NULL THEN NULL WHEN C.StressScore=1 THEN 'Optimal' WHEN C.StressScore=2 THEN 'SubOptimal' ELSE 'Alert' END,
C.LifestyleScore,CASE WHEN C.LifestyleScore IS NULL THEN NULL WHEN C.LifestyleScore=1 THEN 'Optimal' WHEN C.LifestyleScore=2 THEN 'SubOptimal' ELSE 'Alert' END,
C.Biometrics,C.BiometricsCategory,
C.SurveyCategory,C.MHICategory,C.MHICategoryId, @rLocationId,
@rUserId,sCommon.fGetDate()
FROM #Calculated C
WHERE C.EmployeeId=@EmployeeId;

INSERT INTO @MergeResult VALUES('INSERT',@EmployeeId);

FETCH NEXT FROM curInsert INTO @EmployeeId;
END

CLOSE curInsert;
DEALLOCATE curInsert;

------------------------------------------------
-- HISTORY
------------------------------------------------
DECLARE @EmpId BIGINT;

DECLARE curHistory CURSOR FAST_FORWARD FOR
SELECT DISTINCT EmployeeId FROM @MergeResult;

OPEN curHistory;
FETCH NEXT FROM curHistory INTO @EmpId;

WHILE @@FETCH_STATUS=0
BEGIN
EXEC sWellness.pInsertMHIScoreHistoryIfChanged
@rEmployeeId=@EmpId,
@rUserId=@rUserId;

FETCH NEXT FROM curHistory INTO @EmpId;
END

CLOSE curHistory;
DEALLOCATE curHistory;

------------------------------------------------
-- COUNTS
------------------------------------------------
SELECT
@InsertedCount=ISNULL(SUM(CASE WHEN ActionType='INSERT' THEN 1 END),0),
@UpdatedCount=ISNULL(SUM(CASE WHEN ActionType='UPDATE' THEN 1 END),0)
FROM @MergeResult;

SET @TotalProcessed =
ISNULL(@InsertedCount,0)
+ISNULL(@UpdatedCount,0)
+ISNULL(@SkippedEmployeeCodeCount,0);

COMMIT TRANSACTION;

END TRY
BEGIN CATCH
IF @@TRANCOUNT>0 ROLLBACK;

SET @InsertedCount=-1;
SET @UpdatedCount=-1;
SET @SkippedEmployeeCodeCount=-1;
SET @TotalProcessed=-1;

SELECT ERROR_MESSAGE() ErrorMessage,ERROR_LINE() ErrorLine;
END CATCH

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


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAssignMHIProgramCategoryThroughSurveyBulk]
(
      @rOrgId SMALLINT
    , @rUserId BIGINT
	, @rLocationId INT
	, @rInsertType SMALLINT
    , @rEmployeeMHISurveyBulkList [sWellness].[udt_MHIScoreUpdateThroughtSurveyBulk] READONLY
    , @InsertedCount INT OUTPUT
    , @UpdatedCount INT OUTPUT
    , @SkippedEmployeeCodeCount INT OUTPUT
    , @TotalProcessed INT OUTPUT
)
AS
BEGIN

	SET NOCOUNT ON;

		BEGIN TRY
		BEGIN TRANSACTION;

			DECLARE @MergeResult TABLE( ActionType NVARCHAR(10), EmployeeId BIGINT );

			SELECT
				  EM.EmployeeId, S.Stress, S.LifeStyle
			INTO 
				#InputData
			FROM 
				@rEmployeeMHISurveyBulkList S
			JOIN 
				[sHrm].[vExtEmployeeMaster] EM
			ON 
				EM.Code = S.EmployeeCode;

			SELECT @SkippedEmployeeCodeCount =
			(
				SELECT 
					COUNT(*)
				FROM
					@rEmployeeMHISurveyBulkList S
				LEFT JOIN 
					sHrm.vExtEmployeeMaster EM ON EM.Code = S.EmployeeCode
				WHERE 
					EM.EmployeeId IS NULL
			);


			SELECT
				  I.EmployeeId
				, I.Stress
				, I.LifeStyle
				, CASE WHEN I.Stress IS NULL THEN NULL WHEN I.Stress <= 13 THEN 1 WHEN I.Stress <= 26 THEN 2 ELSE 3 END AS StressScore
				, CASE WHEN I.LifeStyle IS NULL THEN NULL WHEN I.LifeStyle <= 49 THEN 3 WHEN I.LifeStyle <= 70 THEN 2 ELSE 1 END AS LifestyleScore
			INTO 
				#Calculated
			FROM
				#InputData I;


			ALTER TABLE 
				#Calculated
			ADD 
				SurveyCategory VARCHAR(30), BiometricsCategory VARCHAR(30), MHICategory VARCHAR(30), MHICategoryId SMALLINT, ProgramId INT;


			UPDATE 
				#Calculated
			SET 
				SurveyCategory =
			CASE
				WHEN StressScore IS NULL OR LifestyleScore IS NULL THEN NULL
				WHEN StressScore = 3 OR LifestyleScore = 3 THEN 'Alert'
				WHEN StressScore = 2 OR LifestyleScore = 2 THEN 'SubOptimal'
				WHEN StressScore = 1 AND LifestyleScore = 1 THEN 'Optimal'
			END;


			UPDATE C
			SET 
				BiometricsCategory = T.BiometricsCategory
			FROM
				#Calculated C
			LEFT JOIN
				sWellness.tMHIScore T ON T.EmployeeId = C.EmployeeId;


			UPDATE 
				#Calculated
			SET 
				MHICategory =
			CASE
				WHEN BiometricsCategory IS NULL OR SurveyCategory IS NULL THEN 'NotApplicable'
				WHEN BiometricsCategory = 'Alert' OR SurveyCategory = 'Alert' THEN 'Alert'
				WHEN BiometricsCategory = 'SubOptimal' OR SurveyCategory = 'SubOptimal' THEN 'SubOptimal'
				WHEN BiometricsCategory = 'Optimal' AND SurveyCategory = 'Optimal' THEN 'Optimal'
				ELSE 'NotApplicable'
			END;


			UPDATE 
				#Calculated
			SET 
				MHICategoryId = CASE WHEN MHICategory = 'Optimal' THEN 1 WHEN MHICategory = 'SubOptimal' THEN 2 WHEN MHICategory = 'Alert' THEN 3 ELSE 0
			END;

			UPDATE C
			SET 
				ProgramId = ISNULL(PM.Id, 0)
			FROM 
				#Calculated C
			LEFT JOIN 
				[sWellness].[tStaticMHICategoryIndicator] I ON I.Id = C.MHICategoryId
			LEFT JOIN 
				[sWellness].[tProgramMaster] PM ON PM.MHIIndicatorId = I.Id
			AND 
				PM.CategoryId = 1
			AND 
				PM.IsObsolete = 0;


			UPDATE T
			SET
				Stress = C.Stress,
				StressScore = C.StressScore,
				StressCategory = CASE WHEN C.StressScore = 1 THEN 'Optimal' WHEN C.StressScore = 2 THEN 'SubOptimal' WHEN C.StressScore = 3 THEN 'Alert' END,
				Lifestyle = C.LifeStyle,
				LifestyleScore = C.LifestyleScore,
				LifestyleCategory = CASE WHEN C.LifestyleScore = 1 THEN 'Optimal' WHEN C.LifestyleScore = 2 THEN 'SubOptimal' WHEN C.LifestyleScore = 3 THEN 'Alert' END,
				SurveyCategory = C.SurveyCategory,
				MHICategory = C.MHICategory,
				MHICategoryId = C.MHICategoryId,
				ProgramId = C.ProgramId,
				LocationId = @rLocationId,
				LastUpdateType = @rInsertType,
				UpdatedUserId = @rUserId,
				UpdatedDatetime = sCommon.fGetDate()

			OUTPUT 
				'UPDATE', inserted.EmployeeId INTO @MergeResult
			FROM 
				sWellness.tMHIScore T
			JOIN 
				#Calculated C
			ON 
				C.EmployeeId = T.EmployeeId;


			DECLARE @EmployeeId BIGINT, @NextId BIGINT;

			DECLARE curInsert CURSOR FAST_FORWARD FOR
			SELECT EmployeeId
			FROM #Calculated C
			WHERE NOT EXISTS
			(
				SELECT 1 FROM [sWellness].[tMHIScore] T WHERE T.EmployeeId = C.EmployeeId
			);

			OPEN curInsert;
				FETCH NEXT FROM curInsert INTO @EmployeeId;

				WHILE @@FETCH_STATUS = 0
				BEGIN

					EXEC sCommon.pTableRowIdGet @rOrgId,'sWellness.tMHIScore',0,1,1, @outNextNumber = @NextId OUTPUT;

					INSERT INTO sWellness.tMHIScore
					(
						Id, OrgId, EmployeeId,
						Stress, StressScore, StressCategory,
						Lifestyle, LifestyleScore, LifestyleCategory,
						SurveyCategory, MHICategory, MHICategoryId,
						ProgramId, LocationId, LastUpdateType,
						CreatedUserId, CreatedDatetime
					)
					SELECT
						@NextId, @rOrgId, C.EmployeeId,
						C.Stress, C.StressScore, CASE WHEN C.StressScore = 1 THEN 'Optimal' WHEN C.StressScore = 2 THEN 'SubOptimal' WHEN C.StressScore = 3 THEN 'Alert' END,
						C.LifeStyle, C.LifestyleScore, CASE WHEN C.LifestyleScore = 1 THEN 'Optimal' WHEN C.LifestyleScore = 2 THEN 'SubOptimal' WHEN C.LifestyleScore = 3 THEN 'Alert' END,
						C.SurveyCategory, C.MHICategory, C.MHICategoryId,
						C.ProgramId, @rLocationId, @rInsertType,
						@rUserId, sCommon.fGetDate()
					FROM 
						#Calculated C
					WHERE
						C.EmployeeId = @EmployeeId;

					INSERT INTO @MergeResult VALUES ('INSERT', @EmployeeId);

					FETCH NEXT FROM curInsert INTO @EmployeeId;
				END

			CLOSE curInsert;
			DEALLOCATE curInsert;

			DECLARE @EmpId BIGINT;

			DECLARE curHistory CURSOR FAST_FORWARD FOR
			SELECT DISTINCT EmployeeId FROM @MergeResult;

			OPEN curHistory;
			FETCH NEXT FROM curHistory INTO @EmpId;

			WHILE @@FETCH_STATUS = 0
			BEGIN
				EXEC sWellness.pInsertMHIScoreHistoryIfChanged
					@rEmployeeId = @EmpId,
					@rUserId = @rUserId;

				FETCH NEXT FROM curHistory INTO @EmpId;
			END

			CLOSE curHistory;
			DEALLOCATE curHistory;


			SELECT
				@InsertedCount = ISNULL(SUM(CASE WHEN ActionType='INSERT' THEN 1 END),0),
				@UpdatedCount = ISNULL(SUM(CASE WHEN ActionType='UPDATE' THEN 1 END),0)
			FROM @MergeResult;

			SET @TotalProcessed = ISNULL(@InsertedCount,0) + ISNULL(@UpdatedCount,0) + ISNULL(@SkippedEmployeeCodeCount,0);

		COMMIT TRANSACTION;
		END TRY
		BEGIN CATCH

		IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;

		SET @InsertedCount = -1;
		SET @UpdatedCount = -1;
		SET @SkippedEmployeeCodeCount = -1;
		SET @TotalProcessed = -1;

		SELECT ERROR_MESSAGE() AS ErrorMessage, ERROR_LINE() AS ErrorLine;

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


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAssignMHIProgramThroughCategoryBulk]
(
      @rOrgId SMALLINT
    , @rUserId BIGINT
    , @rMHICategoryList [sWellness].[udt_MHIBulkCategoryImport] READONLY
    , @InsertedCount INT OUTPUT
    , @UpdatedCount INT OUTPUT
    , @SkippedEmployeeCodeCount INT OUTPUT
    , @TotalProcessed INT OUTPUT
)
AS
BEGIN

SET NOCOUNT ON;

BEGIN TRY
BEGIN TRANSACTION;

DECLARE @MergeResult TABLE
(
    ActionType NVARCHAR(10),
    EmployeeId BIGINT
);

------------------------------------------------
-- Parameter ranges
------------------------------------------------
SELECT
      HIPM.StaticHealthIndexParameterId
    , HIPD.FromValue
    , HIPD.ToValue
    , CASE
        WHEN HIPD.Points = 10 THEN 1
        WHEN HIPD.Points = 6 THEN 2
        WHEN HIPD.Points = 3 THEN 3
        ELSE HIPD.Points
      END Score
    , HIPD.DiagnosisRemark Category
    , HIPD.GenderId
INTO #TempParameterRange
FROM sExamination.tHealthIndexParameterMaster HIPM
JOIN sExamination.tHealthIndexParameterDetail HIPD
ON HIPD.HealthIndexParameterId = HIPM.Id
WHERE HIPM.StaticHealthIndexParameterId IN (1,2,5,17,23);

------------------------------------------------
-- Map EmployeeCode → EmployeeId
------------------------------------------------
SELECT
      EM.EmployeeId,
	  EM.GenderId,
	  S.HBA1CCategory,
	  S.LDLCategory,
	  S.BMICategory,
	  S.BPCategory,
	  S.StressCategory,
	  S.LifestyleCategory
INTO #InputData
FROM @rMHICategoryList S
JOIN sHrm.vExtEmployeeMaster EM
ON EM.Code = S.EmployeeCode;

------------------------------------------------
-- Count skipped employees
------------------------------------------------
SELECT
@SkippedEmployeeCodeCount =
(
SELECT COUNT(*)
FROM @rMHICategoryList S
LEFT JOIN sHrm.vExtEmployeeMaster EM
ON EM.Code = S.EmployeeCode
WHERE EM.EmployeeId IS NULL
);


------------------------------------------------
-- Score calculation
------------------------------------------------
SELECT
      I.*
    , BMI.Score BMIScore
    , BMI.Category BMICategory
    , HBA1C.Score HBA1CScore
    , HBA1C.Category HBA1CCategory
    , LDL.Score LDLScore
    , LDL.Category LDLCategory
   -- , CASE WHEN SYS.Score > DIA.Score THEN SYS.Score ELSE DIA.Score END BPScore
	, CASE WHEN SYS.Score IS NULL OR DIA.Score IS NULL THEN NULL WHEN SYS.Score > DIA.Score THEN SYS.Score ELSE DIA.Score END AS BPScore
    , CASE WHEN I.Stress IS NULL THEN NULL WHEN I.Stress <= 13 THEN 1 WHEN I.Stress <= 26 THEN 2 ELSE 3 END StressScore
    , CASE  WHEN I.LifeStyle IS NULL THEN NULL WHEN I.LifeStyle <=49 THEN 3 WHEN I.LifeStyle <=70 THEN 2 ELSE 1 END LifestyleScore
INTO #Calculated
FROM #InputData I

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=1
AND I.BMI BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) BMI

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=2
AND I.HBA1C BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) HBA1C

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=5
AND I.LDL BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) LDL

OUTER APPLY
(
    SELECT TOP 1 Score
    FROM #TempParameterRange
    WHERE StaticHealthIndexParameterId=23
    AND I.SystolicBP BETWEEN FromValue AND ToValue
    AND GenderId=I.GenderId
    ORDER BY FromValue DESC
) SYS

OUTER APPLY
(
    SELECT TOP 1 Score
    FROM #TempParameterRange
    WHERE StaticHealthIndexParameterId=17
    AND I.DiastolicBP BETWEEN FromValue AND ToValue
    AND GenderId=I.GenderId
    ORDER BY FromValue DESC
) DIA;

------------------------------------------------
-- Derived calculations
------------------------------------------------
ALTER TABLE #Calculated
ADD Biometrics DECIMAL(10,2),
BiometricsCategory VARCHAR(30),
SurveyCategory VARCHAR(30),
MHICategory VARCHAR(30),
MHICategoryId SMALLINT,
ProgramId INT;

--UPDATE #Calculated
--SET Biometrics =
--(100.0*(ISNULL(BMIScore,0)+ISNULL(HBA1CScore,0)+ISNULL(LDLScore,0)+ISNULL(BPScore,0)))/4;

UPDATE #Calculated
SET Biometrics =
CASE 
    WHEN BMIScore IS NULL OR HBA1CScore IS NULL OR LDLScore IS NULL OR BPScore IS NULL THEN NULL
    ELSE (100.0 * (BMIScore + HBA1CScore + LDLScore + BPScore)) / 4
END;

--UPDATE #Calculated
--SET BiometricsCategory =
--CASE WHEN Biometrics <=100 THEN 'Optimal'
--WHEN Biometrics <150 THEN 'SubOptimal'
--ELSE 'Alert' END;

UPDATE #Calculated
SET BiometricsCategory =
CASE 
    WHEN Biometrics IS NULL THEN NULL 
	WHEN Biometrics <= 100 THEN 'Optimal'
	WHEN Biometrics < 150 THEN 'SubOptimal'
	ELSE 'Alert'
END;


UPDATE #Calculated
SET SurveyCategory =
CASE
	WHEN StressScore IS NULL OR LifestyleScore IS NULL THEN NULL
	WHEN StressScore=3 OR LifestyleScore=3 THEN 'Alert'
	WHEN StressScore=2 OR LifestyleScore=2 THEN 'SubOptimal'
	WHEN StressScore=1 AND LifestyleScore=1 THEN 'Optimal'
	ELSE NULL
END;

UPDATE #Calculated
SET MHICategory =
CASE
WHEN BiometricsCategory IS NULL OR SurveyCategory IS NULL THEN 'NotApplicable'
WHEN BiometricsCategory='Alert' OR SurveyCategory='Alert' THEN 'Alert'
WHEN BiometricsCategory='SubOptimal' OR SurveyCategory='SubOptimal' THEN 'SubOptimal'
WHEN BiometricsCategory='Optimal' AND SurveyCategory='Optimal' THEN 'Optimal'
ELSE 'NotApplicable'
END;

UPDATE #Calculated
SET MHICategoryId =
CASE
WHEN MHICategory IS NULL THEN 0
WHEN MHICategory='Optimal' THEN 1
WHEN MHICategory='SubOptimal' THEN 2
WHEN MHICategory='Alert' THEN 3
ELSE 0
END;

------------------------------------------------
-- Program assignment
------------------------------------------------
--UPDATE C
--SET ProgramId = ISNULL(PM.Id,0)
--FROM #Calculated C
--JOIN sWellness.tStaticMHICategoryIndicator I
--ON I.Id=C.MHICategoryId
--JOIN sWellness.tProgramMaster PM
--ON PM.MHIIndicatorId=I.Id
--AND PM.CategoryId=1
--AND PM.IsObsolete=0;

UPDATE C
SET ProgramId = ISNULL(PM.Id, 0)
FROM #Calculated C
LEFT JOIN sWellness.tStaticMHICategoryIndicator I
    ON I.Id = C.MHICategoryId
LEFT JOIN sWellness.tProgramMaster PM
    ON PM.MHIIndicatorId = I.Id
   AND PM.CategoryId = 1
   AND PM.IsObsolete = 0;

------------------------------------------------
-- UPDATE existing rows
------------------------------------------------
UPDATE T
SET
BMI=C.BMI,
BMIScore=C.BMIScore,
BMICategory=C.BMICategory,

HBA1C=C.HBA1C,
HBA1CScore=C.HBA1CScore,
HBA1CCategory=C.HBA1CCategory,

LDL=C.LDL,
LDLScore=C.LDLScore,
LDLCategory=C.LDLCategory,

BP=CAST(C.SystolicBP AS VARCHAR(10))+'/'+CAST(C.DiastolicBP AS VARCHAR(10)),
BPScore=C.BPScore,
BPCategory=CASE C.BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal'  WHEN 3 THEN 'Alert' ELSE NULL END,

Stress = C.Stress,
StressScore = C.StressScore,
StressCategory = CASE WHEN C.StressScore IS NULL THEN NULL WHEN C.StressScore = 1 THEN 'Optimal' WHEN C.StressScore = 2 THEN 'SubOptimal' ELSE 'Alert' END,

Lifestyle = C.LifeStyle,
LifestyleScore = C.LifestyleScore,
LifestyleCategory =  CASE WHEN C.LifestyleScore IS NULL THEN NULL WHEN C.LifestyleScore = 1 THEN 'Optimal'  WHEN C.LifestyleScore = 2 THEN 'SubOptimal' ELSE 'Alert' END,

Biometrics=C.Biometrics,
BiometricsCategory=C.BiometricsCategory,

SurveyCategory=C.SurveyCategory,
MHICategory=C.MHICategory,
MHICategoryId=C.MHICategoryId,

ProgramId=C.ProgramId,

UpdatedUserId=@rUserId,
UpdatedDatetime=sCommon.fGetDate()

OUTPUT 'UPDATE',inserted.EmployeeId INTO @MergeResult
FROM sWellness.tMHIScore T
JOIN #Calculated C ON C.EmployeeId=T.EmployeeId;

------------------------------------------------
-- INSERT new rows
------------------------------------------------
DECLARE @EmployeeId BIGINT,@NextId BIGINT;

DECLARE curInsert CURSOR FAST_FORWARD FOR
SELECT EmployeeId
FROM #Calculated C
WHERE NOT EXISTS
(
SELECT 1 FROM sWellness.tMHIScore T WHERE T.EmployeeId=C.EmployeeId
);

OPEN curInsert;
FETCH NEXT FROM curInsert INTO @EmployeeId;

WHILE @@FETCH_STATUS=0
BEGIN

EXEC sCommon.pTableRowIdGet
@rOrgId,'sWellness.tMHIScore',0,1,1,@outNextNumber=@NextId OUTPUT;

INSERT INTO sWellness.tMHIScore
(
	Id,OrgId,ProgramId,EmployeeId,EmployeeSourceTypeId,LastUpdateType,
	HBA1C,HBA1CScore,HBA1CCategory,
	LDL,LDLScore,LDLCategory,
	BMI,BMIScore,BMICategory,
	BP,BPScore,BPCategory,
	Stress,StressScore,StressCategory,
	Lifestyle,LifestyleScore,LifestyleCategory,
	Biometrics,BiometricsCategory,
	SurveyCategory,MHICategory,MHICategoryId,
	CreatedUserId,CreatedDatetime
)
SELECT
	@NextId,@rOrgId,C.ProgramId,C.EmployeeId,95,4,
	C.HBA1C,C.HBA1CScore,C.HBA1CCategory,
	C.LDL,C.LDLScore,C.LDLCategory,
	C.BMI,C.BMIScore,C.BMICategory,
	CAST(C.SystolicBP AS VARCHAR(10))+'/'+CAST(C.DiastolicBP AS VARCHAR(10)), C.BPScore, CASE C.BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal'  WHEN 3 THEN 'Alert' ELSE NULL END,
	C.Stress, C.StressScore, CASE C.StressScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END,
	C.LifeStyle, C.LifestyleScore, CASE C.LifestyleScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END,
	C.Biometrics,C.BiometricsCategory,
	C.SurveyCategory,C.MHICategory,C.MHICategoryId,
	@rUserId,sCommon.fGetDate()
FROM #Calculated C
WHERE C.EmployeeId=@EmployeeId;


INSERT INTO @MergeResult VALUES('INSERT',@EmployeeId);

FETCH NEXT FROM curInsert INTO @EmployeeId;
END

CLOSE curInsert;
DEALLOCATE curInsert;

------------------------------------------------
-- History
------------------------------------------------
DECLARE @EmpId BIGINT;

DECLARE curHistory CURSOR FAST_FORWARD FOR
SELECT DISTINCT EmployeeId FROM @MergeResult;

OPEN curHistory;
FETCH NEXT FROM curHistory INTO @EmpId;

WHILE @@FETCH_STATUS=0
BEGIN
EXEC sWellness.pInsertMHIScoreHistoryIfChanged
@rEmployeeId=@EmpId,
@rUserId=@rUserId;

FETCH NEXT FROM curHistory INTO @EmpId;
END

CLOSE curHistory;
DEALLOCATE curHistory;

------------------------------------------------
-- Output counts
------------------------------------------------
SELECT
@InsertedCount=ISNULL(SUM(CASE WHEN ActionType='INSERT' THEN 1 END),0),
@UpdatedCount=ISNULL(SUM(CASE WHEN ActionType='UPDATE' THEN 1 END),0)
FROM @MergeResult;

SET @TotalProcessed =
ISNULL(@InsertedCount,0)
+ISNULL(@UpdatedCount,0)
+ISNULL(@SkippedEmployeeCodeCount,0);

COMMIT TRANSACTION;

END TRY
BEGIN CATCH

IF @@TRANCOUNT>0 ROLLBACK TRANSACTION;

SET @InsertedCount=-1;
SET @UpdatedCount=-1;
SET @SkippedEmployeeCodeCount=-1;
SET @TotalProcessed=-1;

SELECT ERROR_MESSAGE() ErrorMessage,ERROR_LINE() ErrorLine;

END CATCH

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


GO
CREATE OR ALTER PROCEDURE [sWellness].[pAssignProgramThroughCategoryBulk]
(
      @rOrgId SMALLINT
    , @rUserId BIGINT
    , @rMHICategoryList [sWellness].[udt_MHIBulkCategoryImport] READONLY
    , @InsertedCount INT OUTPUT
    , @UpdatedCount INT OUTPUT
    , @SkippedEmployeeCodeCount INT OUTPUT
    , @TotalProcessed INT OUTPUT
)
AS
BEGIN

SET NOCOUNT ON;

BEGIN TRY
BEGIN TRANSACTION;

DECLARE @MergeResult TABLE
(
    ActionType NVARCHAR(10),
    EmployeeId BIGINT
);

SELECT
      HIPM.StaticHealthIndexParameterId
    , HIPD.FromValue
    , HIPD.ToValue
    , CASE
        WHEN HIPD.Points = 10 THEN 1
        WHEN HIPD.Points = 6 THEN 2
        WHEN HIPD.Points = 3 THEN 3
        ELSE HIPD.Points
      END Score
    , HIPD.DiagnosisRemark Category
    , HIPD.GenderId
INTO #TempParameterRange
FROM sExamination.tHealthIndexParameterMaster HIPM
JOIN sExamination.tHealthIndexParameterDetail HIPD
ON HIPD.HealthIndexParameterId = HIPM.Id
WHERE HIPM.StaticHealthIndexParameterId IN (1,2,5,17,23);


SELECT
      EM.EmployeeId
    , EM.GenderId
    , S.[HBA1CCategory]
    , S.[LDLCategory]
    , S.[BMICategory]
    , S.[BPCategory]
    , S.[StressCategory]
    , S.[LifestyleCategory]
INTO #InputData
FROM @rMHICategoryList S
JOIN sHrm.vExtEmployeeMaster EM
ON EM.Code = S.EmployeeCode;


SELECT
@SkippedEmployeeCodeCount =
(
SELECT COUNT(*)
FROM @rMHICategoryList S
LEFT JOIN sHrm.vExtEmployeeMaster EM
ON EM.Code = S.EmployeeCode
WHERE EM.EmployeeId IS NULL
);


SELECT
      I.*
    , BMI.Score BMIScore
    , BMI.Category BMICategory
    , HBA1C.Score HBA1CScore
    , HBA1C.Category HBA1CCategory
    , LDL.Score LDLScore
    , LDL.Category LDLCategory
	, CASE WHEN SYS.Score IS NULL OR DIA.Score IS NULL THEN NULL WHEN SYS.Score > DIA.Score THEN SYS.Score ELSE DIA.Score END AS BPScore
    , CASE WHEN I.Stress IS NULL THEN NULL WHEN I.Stress <= 13 THEN 1 WHEN I.Stress <= 26 THEN 2 ELSE 3 END StressScore
    , CASE  WHEN I.LifeStyle IS NULL THEN NULL WHEN I.LifeStyle <=49 THEN 3 WHEN I.LifeStyle <=70 THEN 2 ELSE 1 END LifestyleScore
INTO #Calculated
FROM #InputData I

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=1
AND I.BMI BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) BMI

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=2
AND I.HBA1C BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) HBA1C

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=5
AND I.LDL BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) LDL

OUTER APPLY
(
    SELECT TOP 1 Score
    FROM #TempParameterRange
    WHERE StaticHealthIndexParameterId=23
    AND I.SystolicBP BETWEEN FromValue AND ToValue
    AND GenderId=I.GenderId
    ORDER BY FromValue DESC
) SYS

OUTER APPLY
(
    SELECT TOP 1 Score
    FROM #TempParameterRange
    WHERE StaticHealthIndexParameterId=17
    AND I.DiastolicBP BETWEEN FromValue AND ToValue
    AND GenderId=I.GenderId
    ORDER BY FromValue DESC
) DIA;

------------------------------------------------
-- Derived calculations
------------------------------------------------
ALTER TABLE #Calculated
ADD Biometrics DECIMAL(10,2),
BiometricsCategory VARCHAR(30),
SurveyCategory VARCHAR(30),
MHICategory VARCHAR(30),
MHICategoryId SMALLINT,
ProgramId INT;


UPDATE #Calculated
SET Biometrics =
CASE 
    WHEN BMIScore IS NULL OR HBA1CScore IS NULL OR LDLScore IS NULL OR BPScore IS NULL THEN NULL
    ELSE (100.0 * (BMIScore + HBA1CScore + LDLScore + BPScore)) / 4
END;


UPDATE #Calculated
SET BiometricsCategory =
CASE 
    WHEN Biometrics IS NULL THEN NULL 
	WHEN Biometrics <= 100 THEN 'Optimal'
	WHEN Biometrics < 150 THEN 'SubOptimal'
	ELSE 'Alert'
END;


UPDATE #Calculated
SET SurveyCategory =
CASE
	WHEN StressScore IS NULL OR LifestyleScore IS NULL THEN NULL
	WHEN StressScore=3 OR LifestyleScore=3 THEN 'Alert'
	WHEN StressScore=2 OR LifestyleScore=2 THEN 'SubOptimal'
	WHEN StressScore=1 AND LifestyleScore=1 THEN 'Optimal'
	ELSE NULL
END;

UPDATE #Calculated
SET MHICategory =
CASE
WHEN BiometricsCategory IS NULL OR SurveyCategory IS NULL THEN 'NotApplicable'
WHEN BiometricsCategory='Alert' OR SurveyCategory='Alert' THEN 'Alert'
WHEN BiometricsCategory='SubOptimal' OR SurveyCategory='SubOptimal' THEN 'SubOptimal'
WHEN BiometricsCategory='Optimal' AND SurveyCategory='Optimal' THEN 'Optimal'
ELSE 'NotApplicable'
END;

UPDATE #Calculated
SET MHICategoryId =
CASE
WHEN MHICategory IS NULL THEN 0
WHEN MHICategory='Optimal' THEN 1
WHEN MHICategory='SubOptimal' THEN 2
WHEN MHICategory='Alert' THEN 3
ELSE 0
END;


UPDATE C
SET ProgramId = ISNULL(PM.Id, 0)
FROM #Calculated C
LEFT JOIN sWellness.tStaticMHICategoryIndicator I
    ON I.Id = C.MHICategoryId
LEFT JOIN sWellness.tProgramMaster PM
    ON PM.MHIIndicatorId = I.Id
   AND PM.CategoryId = 1
   AND PM.IsObsolete = 0;

------------------------------------------------
-- UPDATE existing rows
------------------------------------------------
UPDATE T
SET
BMI=C.BMI,
BMIScore=C.BMIScore,
BMICategory=C.BMICategory,

HBA1C=C.HBA1C,
HBA1CScore=C.HBA1CScore,
HBA1CCategory=C.HBA1CCategory,

LDL=C.LDL,
LDLScore=C.LDLScore,
LDLCategory=C.LDLCategory,

BP=CAST(C.SystolicBP AS VARCHAR(10))+'/'+CAST(C.DiastolicBP AS VARCHAR(10)),
BPScore=C.BPScore,
BPCategory=CASE C.BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal'  WHEN 3 THEN 'Alert' ELSE NULL END,

Stress = C.Stress,
StressScore = C.StressScore,
StressCategory = CASE WHEN C.StressScore IS NULL THEN NULL WHEN C.StressScore = 1 THEN 'Optimal' WHEN C.StressScore = 2 THEN 'SubOptimal' ELSE 'Alert' END,

Lifestyle = C.LifeStyle,
LifestyleScore = C.LifestyleScore,
LifestyleCategory =  CASE WHEN C.LifestyleScore IS NULL THEN NULL WHEN C.LifestyleScore = 1 THEN 'Optimal'  WHEN C.LifestyleScore = 2 THEN 'SubOptimal' ELSE 'Alert' END,

Biometrics=C.Biometrics,
BiometricsCategory=C.BiometricsCategory,

SurveyCategory=C.SurveyCategory,
MHICategory=C.MHICategory,
MHICategoryId=C.MHICategoryId,

ProgramId=C.ProgramId,

UpdatedUserId=@rUserId,
UpdatedDatetime=sCommon.fGetDate()

OUTPUT 'UPDATE',inserted.EmployeeId INTO @MergeResult
FROM sWellness.tMHIScore T
JOIN #Calculated C ON C.EmployeeId=T.EmployeeId;

------------------------------------------------
-- INSERT new rows
------------------------------------------------
DECLARE @EmployeeId BIGINT,@NextId BIGINT;

DECLARE curInsert CURSOR FAST_FORWARD FOR
SELECT EmployeeId
FROM #Calculated C
WHERE NOT EXISTS
(
SELECT 1 FROM sWellness.tMHIScore T WHERE T.EmployeeId=C.EmployeeId
);

OPEN curInsert;
FETCH NEXT FROM curInsert INTO @EmployeeId;

WHILE @@FETCH_STATUS=0
BEGIN

EXEC sCommon.pTableRowIdGet
@rOrgId,'sWellness.tMHIScore',0,1,1,@outNextNumber=@NextId OUTPUT;

INSERT INTO sWellness.tMHIScore
(
	Id,OrgId,ProgramId,EmployeeId,EmployeeSourceTypeId,LastUpdateType,
	HBA1C,HBA1CScore,HBA1CCategory,
	LDL,LDLScore,LDLCategory,
	BMI,BMIScore,BMICategory,
	BP,BPScore,BPCategory,
	Stress,StressScore,StressCategory,
	Lifestyle,LifestyleScore,LifestyleCategory,
	Biometrics,BiometricsCategory,
	SurveyCategory,MHICategory,MHICategoryId,
	CreatedUserId,CreatedDatetime
)
SELECT
	@NextId,@rOrgId,C.ProgramId,C.EmployeeId,95,4,
	C.HBA1C,C.HBA1CScore,C.HBA1CCategory,
	C.LDL,C.LDLScore,C.LDLCategory,
	C.BMI,C.BMIScore,C.BMICategory,
	CAST(C.SystolicBP AS VARCHAR(10))+'/'+CAST(C.DiastolicBP AS VARCHAR(10)), C.BPScore, CASE C.BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal'  WHEN 3 THEN 'Alert' ELSE NULL END,
	C.Stress, C.StressScore, CASE C.StressScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END,
	C.LifeStyle, C.LifestyleScore, CASE C.LifestyleScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END,
	C.Biometrics,C.BiometricsCategory,
	C.SurveyCategory,C.MHICategory,C.MHICategoryId,
	@rUserId,sCommon.fGetDate()
FROM #Calculated C
WHERE C.EmployeeId=@EmployeeId;


INSERT INTO @MergeResult VALUES('INSERT',@EmployeeId);

FETCH NEXT FROM curInsert INTO @EmployeeId;
END

CLOSE curInsert;
DEALLOCATE curInsert;

------------------------------------------------
-- History
------------------------------------------------
DECLARE @EmpId BIGINT;

DECLARE curHistory CURSOR FAST_FORWARD FOR
SELECT DISTINCT EmployeeId FROM @MergeResult;

OPEN curHistory;
FETCH NEXT FROM curHistory INTO @EmpId;

WHILE @@FETCH_STATUS=0
BEGIN
EXEC sWellness.pInsertMHIScoreHistoryIfChanged
@rEmployeeId=@EmpId,
@rUserId=@rUserId;

FETCH NEXT FROM curHistory INTO @EmpId;
END

CLOSE curHistory;
DEALLOCATE curHistory;

------------------------------------------------
-- Output counts
------------------------------------------------
SELECT
@InsertedCount=ISNULL(SUM(CASE WHEN ActionType='INSERT' THEN 1 END),0),
@UpdatedCount=ISNULL(SUM(CASE WHEN ActionType='UPDATE' THEN 1 END),0)
FROM @MergeResult;

SET @TotalProcessed =
ISNULL(@InsertedCount,0)
+ISNULL(@UpdatedCount,0)
+ISNULL(@SkippedEmployeeCodeCount,0);

COMMIT TRANSACTION;

END TRY
BEGIN CATCH

IF @@TRANCOUNT>0 ROLLBACK TRANSACTION;

SET @InsertedCount=-1;
SET @UpdatedCount=-1;
SET @SkippedEmployeeCodeCount=-1;
SET @TotalProcessed=-1;

SELECT ERROR_MESSAGE() ErrorMessage,ERROR_LINE() ErrorLine;

END CATCH

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


GO

CREATE OR ALTER PROCEDURE [sWellness].[pMHICategoryUpdationAddUpdate]
(
	@rId INT=0,
	@rParticipantSourceTypeId SMALLINT,
	@rParticipantSourceId BIGINT,
	@rHBA1CCategory SMALLINT,
	@rLDLCategory SMALLINT,
	@rBMICategory SMALLINT,
	@rBPCategory SMALLINT,
	@rStressCategory SMALLINT,
	@rLifestyleCategory SMALLINT,
	@rLocationId INT,
	@rInsertType SMALLINT,
	@rLastUpdateType SMALLINT,
	@rUserId BIGINT
)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY
		BEGIN TRAN
			DECLARE @lNextNumber BIGINT 
			IF NOT EXISTS (SELECT 1 FROM [sWellness].[tMHIScoreUpdation] WHERE ParticipantSourceId = @rParticipantSourceId and ParticipantSourceTypeId = @rParticipantSourceTypeId)
			BEGIN
			INSERT INTO [sWellness].[tMHIScoreUpdation]
					(
						ParticipantSourceTypeId,
						ParticipantSourceId,
						InsertType,
						HBA1CCategory,
						LDLCategory,
						BMICategory,
						BPCategory,
						StressCategory,
						LifestyleCategory,
						LastUpdateType,
						LocationId,
						CreatedUserId,
						CreatedDateTime
					)
					values
					(
						@rParticipantSourceTypeId,
						@rParticipantSourceId,
						@rInsertType,
						@rHBA1CCategory,
						@rLDLCategory,
						@rBMICategory,
						@rBPCategory,
						@rStressCategory,
						@rLifestyleCategory,
						@rLastUpdateType,
						@rLocationId,
						@rUserId,
						sCommon.fGetDate()
					)
	        SET @lNextNumber = SCOPE_IDENTITY();
			END
			ELSE
			BEGIN
				Update [sWellness].[tMHIScoreUpdation]
				SET 
					InsertType = @rInsertType,
					HBA1CCategory = @rHBA1CCategory,
					LDLCategory = @rLDLCategory,
					BMICategory = @rBMICategory,
					BPCategory = @rBPCategory,
					StressCategory = @rStressCategory,
					LifestyleCategory = @rLifestyleCategory,
					LastUpdateType = @rLastUpdateType,
					LocationId = @rLocationId,
					UpdatedUserId = @rUserId,
					UpdatedDateTime = sCommon.fGetDate()
				WHERE 
					ParticipantSourceId=@rParticipantSourceId 
				AND 
					ParticipantSourceTypeId = @rParticipantSourceTypeId

				SET @lNextNumber=1
			END
		COMMIT TRAN
		Select @lNextNumber as Result
	END TRY

	BEGIN CATCH
		ROLLBACK TRAN
		Select -105 as Result
		select ERROR_MESSAGE()
	END CATCH		
END
GO
PRINT N'Altering Procedure [sWellness].[pAddOrUpdateProgramMHIScoreBulk]...';


GO


ALTER   PROCEDURE [sWellness].[pAddOrUpdateProgramMHIScoreBulk]
(
      @rOrgId SMALLINT
    , @rUserId BIGINT
	, @rLocationId INT
	, @rInsertType SMALLINT
    , @rMHIScoreList [sWellness].[udt_MHIScoreUpdateBulk] READONLY
    , @InsertedCount INT OUTPUT
    , @UpdatedCount INT OUTPUT
    , @SkippedEmployeeCodeCount INT OUTPUT
    , @TotalProcessed INT OUTPUT
)
AS
BEGIN

SET NOCOUNT ON;

BEGIN TRY
BEGIN TRANSACTION;

DECLARE @MergeResult TABLE
(
    ActionType NVARCHAR(10),
    EmployeeId BIGINT
);

------------------------------------------------
-- Parameter ranges
------------------------------------------------
SELECT
      HIPM.StaticHealthIndexParameterId
    , HIPD.FromValue
    , HIPD.ToValue
    , CASE
        WHEN HIPD.Points = 10 THEN 1
        WHEN HIPD.Points = 6 THEN 2
        WHEN HIPD.Points = 3 THEN 3
        ELSE HIPD.Points
      END Score
    , HIPD.DiagnosisRemark Category
    , HIPD.GenderId
INTO #TempParameterRange
FROM sExamination.tHealthIndexParameterMaster HIPM
JOIN sExamination.tHealthIndexParameterDetail HIPD
ON HIPD.HealthIndexParameterId = HIPM.Id
WHERE HIPM.StaticHealthIndexParameterId IN (1,2,5,17,23);

------------------------------------------------
-- Map EmployeeCode → EmployeeId
------------------------------------------------
SELECT
      EM.EmployeeId
    , EM.GenderId
    , S.BMI
    , S.SystolicBP
    , S.DiastolicBP
    , S.HBA1C
    , S.LDL
    , S.Stress
    , S.LifeStyle
INTO #InputData
FROM @rMHIScoreList S
JOIN sHrm.vExtEmployeeMaster EM
ON EM.Code = S.EmployeeCode;

------------------------------------------------
-- Count skipped employees
------------------------------------------------
SELECT
@SkippedEmployeeCodeCount =
(
SELECT COUNT(*)
FROM @rMHIScoreList S
LEFT JOIN sHrm.vExtEmployeeMaster EM
ON EM.Code = S.EmployeeCode
WHERE EM.EmployeeId IS NULL
);


------------------------------------------------
-- Score calculation
------------------------------------------------
SELECT
      I.*
    , BMI.Score BMIScore
    , BMI.Category BMICategory
    , HBA1C.Score HBA1CScore
    , HBA1C.Category HBA1CCategory
    , LDL.Score LDLScore
    , LDL.Category LDLCategory
   -- , CASE WHEN SYS.Score > DIA.Score THEN SYS.Score ELSE DIA.Score END BPScore
	, CASE WHEN SYS.Score IS NULL OR DIA.Score IS NULL THEN NULL WHEN SYS.Score > DIA.Score THEN SYS.Score ELSE DIA.Score END AS BPScore
    , CASE WHEN I.Stress IS NULL THEN NULL WHEN I.Stress <= 13 THEN 1 WHEN I.Stress <= 26 THEN 2 ELSE 3 END StressScore
    , CASE  WHEN I.LifeStyle IS NULL THEN NULL WHEN I.LifeStyle <=49 THEN 3 WHEN I.LifeStyle <=70 THEN 2 ELSE 1 END LifestyleScore
INTO #Calculated
FROM #InputData I

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=1
AND I.BMI BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) BMI

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=2
AND I.HBA1C BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) HBA1C

OUTER APPLY
(
SELECT TOP 1 Score,Category
FROM #TempParameterRange
WHERE StaticHealthIndexParameterId=5
AND I.LDL BETWEEN FromValue AND ToValue
AND GenderId=I.GenderId
) LDL

OUTER APPLY
(
    SELECT TOP 1 Score
    FROM #TempParameterRange
    WHERE StaticHealthIndexParameterId=23
    AND I.SystolicBP BETWEEN FromValue AND ToValue
    AND GenderId=I.GenderId
    ORDER BY FromValue DESC
) SYS

OUTER APPLY
(
    SELECT TOP 1 Score
    FROM #TempParameterRange
    WHERE StaticHealthIndexParameterId=17
    AND I.DiastolicBP BETWEEN FromValue AND ToValue
    AND GenderId=I.GenderId
    ORDER BY FromValue DESC
) DIA;

------------------------------------------------
-- Derived calculations
------------------------------------------------
ALTER TABLE #Calculated
ADD Biometrics DECIMAL(10,2),
BiometricsCategory VARCHAR(30),
SurveyCategory VARCHAR(30),
MHICategory VARCHAR(30),
MHICategoryId SMALLINT,
ProgramId INT;

--UPDATE #Calculated
--SET Biometrics =
--(100.0*(ISNULL(BMIScore,0)+ISNULL(HBA1CScore,0)+ISNULL(LDLScore,0)+ISNULL(BPScore,0)))/4;

UPDATE #Calculated
SET Biometrics =
CASE 
    WHEN BMIScore IS NULL OR HBA1CScore IS NULL OR LDLScore IS NULL OR BPScore IS NULL THEN NULL
    ELSE (100.0 * (BMIScore + HBA1CScore + LDLScore + BPScore)) / 4
END;

--UPDATE #Calculated
--SET BiometricsCategory =
--CASE WHEN Biometrics <=100 THEN 'Optimal'
--WHEN Biometrics <150 THEN 'SubOptimal'
--ELSE 'Alert' END;

UPDATE #Calculated
SET BiometricsCategory =
CASE 
    WHEN Biometrics IS NULL THEN NULL 
	WHEN Biometrics <= 100 THEN 'Optimal'
	WHEN Biometrics < 150 THEN 'SubOptimal'
	ELSE 'Alert'
END;


UPDATE #Calculated
SET SurveyCategory =
CASE
	WHEN StressScore IS NULL OR LifestyleScore IS NULL THEN NULL
	WHEN StressScore=3 OR LifestyleScore=3 THEN 'Alert'
	WHEN StressScore=2 OR LifestyleScore=2 THEN 'SubOptimal'
	WHEN StressScore=1 AND LifestyleScore=1 THEN 'Optimal'
	ELSE NULL
END;

UPDATE #Calculated
SET MHICategory =
CASE
WHEN BiometricsCategory IS NULL OR SurveyCategory IS NULL THEN 'NotApplicable'
WHEN BiometricsCategory='Alert' OR SurveyCategory='Alert' THEN 'Alert'
WHEN BiometricsCategory='SubOptimal' OR SurveyCategory='SubOptimal' THEN 'SubOptimal'
WHEN BiometricsCategory='Optimal' AND SurveyCategory='Optimal' THEN 'Optimal'
ELSE 'NotApplicable'
END;

UPDATE #Calculated
SET MHICategoryId =
CASE
WHEN MHICategory IS NULL THEN 0
WHEN MHICategory='Optimal' THEN 1
WHEN MHICategory='SubOptimal' THEN 2
WHEN MHICategory='Alert' THEN 3
ELSE 0
END;

------------------------------------------------
-- Program assignment
------------------------------------------------
--UPDATE C
--SET ProgramId = ISNULL(PM.Id,0)
--FROM #Calculated C
--JOIN sWellness.tStaticMHICategoryIndicator I
--ON I.Id=C.MHICategoryId
--JOIN sWellness.tProgramMaster PM
--ON PM.MHIIndicatorId=I.Id
--AND PM.CategoryId=1
--AND PM.IsObsolete=0;

UPDATE C
SET ProgramId = ISNULL(PM.Id, 0)
FROM #Calculated C
LEFT JOIN sWellness.tStaticMHICategoryIndicator I
    ON I.Id = C.MHICategoryId
LEFT JOIN sWellness.tProgramMaster PM
    ON PM.MHIIndicatorId = I.Id
   AND PM.CategoryId = 1
   AND PM.IsObsolete = 0;

------------------------------------------------
-- UPDATE existing rows
------------------------------------------------
UPDATE T
SET
BMI=C.BMI,
BMIScore=C.BMIScore,
BMICategory=C.BMICategory,

HBA1C=C.HBA1C,
HBA1CScore=C.HBA1CScore,
HBA1CCategory=C.HBA1CCategory,

LDL=C.LDL,
LDLScore=C.LDLScore,
LDLCategory=C.LDLCategory,

BP=CAST(C.SystolicBP AS VARCHAR(10))+'/'+CAST(C.DiastolicBP AS VARCHAR(10)),
BPScore=C.BPScore,
BPCategory=CASE C.BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal'  WHEN 3 THEN 'Alert' ELSE NULL END,

Stress = C.Stress,
StressScore = C.StressScore,
StressCategory = CASE WHEN C.StressScore IS NULL THEN NULL WHEN C.StressScore = 1 THEN 'Optimal' WHEN C.StressScore = 2 THEN 'SubOptimal' ELSE 'Alert' END,

Lifestyle = C.LifeStyle,
LifestyleScore = C.LifestyleScore,
LifestyleCategory =  CASE WHEN C.LifestyleScore IS NULL THEN NULL WHEN C.LifestyleScore = 1 THEN 'Optimal'  WHEN C.LifestyleScore = 2 THEN 'SubOptimal' ELSE 'Alert' END,

Biometrics=C.Biometrics,
BiometricsCategory=C.BiometricsCategory,

SurveyCategory=C.SurveyCategory,
MHICategory=C.MHICategory,
MHICategoryId=C.MHICategoryId,

ProgramId=C.ProgramId,
LastUpdateType = @rInsertType,
LocationId = @rLocationId,


UpdatedUserId=@rUserId,
UpdatedDatetime=sCommon.fGetDate()

OUTPUT 'UPDATE',inserted.EmployeeId INTO @MergeResult
FROM sWellness.tMHIScore T
JOIN #Calculated C ON C.EmployeeId=T.EmployeeId;

------------------------------------------------
-- INSERT new rows
------------------------------------------------
DECLARE @EmployeeId BIGINT,@NextId BIGINT;

DECLARE curInsert CURSOR FAST_FORWARD FOR
SELECT EmployeeId
FROM #Calculated C
WHERE NOT EXISTS
(
SELECT 1 FROM sWellness.tMHIScore T WHERE T.EmployeeId=C.EmployeeId
);

OPEN curInsert;
FETCH NEXT FROM curInsert INTO @EmployeeId;

WHILE @@FETCH_STATUS=0
BEGIN

EXEC sCommon.pTableRowIdGet
@rOrgId,'sWellness.tMHIScore',0,1,1,@outNextNumber=@NextId OUTPUT;

INSERT INTO sWellness.tMHIScore
(
	Id, OrgId, ProgramId, EmployeeId, EmployeeSourceTypeId, LastUpdateType,
	HBA1C,HBA1CScore,HBA1CCategory,
	LDL,LDLScore,LDLCategory,
	BMI,BMIScore,BMICategory,
	BP,BPScore,BPCategory,
	Stress,StressScore,StressCategory,
	Lifestyle,LifestyleScore,LifestyleCategory,
	Biometrics,BiometricsCategory,
	SurveyCategory,MHICategory,MHICategoryId, LocationId,
	CreatedUserId,CreatedDatetime
)
SELECT
	@NextId, @rOrgId, C.ProgramId, C.EmployeeId, 95, @rInsertType,
	C.HBA1C,C.HBA1CScore,C.HBA1CCategory,
	C.LDL,C.LDLScore,C.LDLCategory,
	C.BMI,C.BMIScore,C.BMICategory,
	CAST(C.SystolicBP AS VARCHAR(10))+'/'+CAST(C.DiastolicBP AS VARCHAR(10)), C.BPScore, CASE C.BPScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal'  WHEN 3 THEN 'Alert' ELSE NULL END,
	C.Stress, C.StressScore, CASE C.StressScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END,
	C.LifeStyle, C.LifestyleScore, CASE C.LifestyleScore WHEN 1 THEN 'Optimal' WHEN 2 THEN 'SubOptimal' WHEN 3 THEN 'Alert' ELSE NULL END,
	C.Biometrics,C.BiometricsCategory,
	C.SurveyCategory,C.MHICategory,C.MHICategoryId, @rLocationId,
	@rUserId,sCommon.fGetDate()
FROM #Calculated C
WHERE C.EmployeeId=@EmployeeId;


INSERT INTO @MergeResult VALUES('INSERT',@EmployeeId);

FETCH NEXT FROM curInsert INTO @EmployeeId;
END

CLOSE curInsert;
DEALLOCATE curInsert;

------------------------------------------------
-- History
------------------------------------------------
DECLARE @EmpId BIGINT;

DECLARE curHistory CURSOR FAST_FORWARD FOR
SELECT DISTINCT EmployeeId FROM @MergeResult;

OPEN curHistory;
FETCH NEXT FROM curHistory INTO @EmpId;

WHILE @@FETCH_STATUS=0
BEGIN
EXEC sWellness.pInsertMHIScoreHistoryIfChanged
@rEmployeeId=@EmpId,
@rUserId=@rUserId;

FETCH NEXT FROM curHistory INTO @EmpId;
END

CLOSE curHistory;
DEALLOCATE curHistory;

------------------------------------------------
-- Output counts
------------------------------------------------
SELECT
@InsertedCount=ISNULL(SUM(CASE WHEN ActionType='INSERT' THEN 1 END),0),
@UpdatedCount=ISNULL(SUM(CASE WHEN ActionType='UPDATE' THEN 1 END),0)
FROM @MergeResult;

SET @TotalProcessed =
ISNULL(@InsertedCount,0)
+ISNULL(@UpdatedCount,0)
+ISNULL(@SkippedEmployeeCodeCount,0);

COMMIT TRANSACTION;

END TRY
BEGIN CATCH

IF @@TRANCOUNT>0 ROLLBACK TRANSACTION;

SET @InsertedCount=-1;
SET @UpdatedCount=-1;
SET @SkippedEmployeeCodeCount=-1;
SET @TotalProcessed=-1;

SELECT ERROR_MESSAGE() ErrorMessage,ERROR_LINE() ErrorLine;

END CATCH

END
GO
PRINT N'Creating Extended Property [sExamination].[vExtPrescriptionDetail].[MS_DiagramPane1]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPane1', @value = N'[0E232FF0-B466-11cf-A24F-00AA00A3EFFF, 1.00]
Begin DesignProperties = 
   Begin PaneConfigurations = 
      Begin PaneConfiguration = 0
         NumPanes = 4
         Configuration = "(H (1[40] 4[20] 2[20] 3) )"
      End
      Begin PaneConfiguration = 1
         NumPanes = 3
         Configuration = "(H (1 [50] 4 [25] 3))"
      End
      Begin PaneConfiguration = 2
         NumPanes = 3
         Configuration = "(H (1 [50] 2 [25] 3))"
      End
      Begin PaneConfiguration = 3
         NumPanes = 3
         Configuration = "(H (4 [30] 2 [40] 3))"
      End
      Begin PaneConfiguration = 4
         NumPanes = 2
         Configuration = "(H (1 [56] 3))"
      End
      Begin PaneConfiguration = 5
         NumPanes = 2
         Configuration = "(H (2 [66] 3))"
      End
      Begin PaneConfiguration = 6
         NumPanes = 2
         Configuration = "(H (4 [50] 3))"
      End
      Begin PaneConfiguration = 7
         NumPanes = 1
         Configuration = "(V (3))"
      End
      Begin PaneConfiguration = 8
         NumPanes = 3
         Configuration = "(H (1[56] 4[18] 2) )"
      End
      Begin PaneConfiguration = 9
         NumPanes = 2
         Configuration = "(H (1 [75] 4))"
      End
      Begin PaneConfiguration = 10
         NumPanes = 2
         Configuration = "(H (1[66] 2) )"
      End
      Begin PaneConfiguration = 11
         NumPanes = 2
         Configuration = "(H (4 [60] 2))"
      End
      Begin PaneConfiguration = 12
         NumPanes = 1
         Configuration = "(H (1) )"
      End
      Begin PaneConfiguration = 13
         NumPanes = 1
         Configuration = "(V (4))"
      End
      Begin PaneConfiguration = 14
         NumPanes = 1
         Configuration = "(V (2))"
      End
      ActivePaneConfig = 0
   End
   Begin DiagramPane = 
      Begin Origin = 
         Top = 0
         Left = 0
      End
      Begin Tables = 
         Begin Table = "PD"
            Begin Extent = 
               Top = 6
               Left = 38
               Bottom = 136
               Right = 257
            End
            DisplayFlags = 280
            TopColumn = 0
         End
         Begin Table = "SIM"
            Begin Extent = 
               Top = 138
               Left = 38
               Bottom = 268
               Right = 245
            End
            DisplayFlags = 280
            TopColumn = 0
         End
      End
   End
   Begin SQLPane = 
   End
   Begin DataPane = 
      Begin ParameterDefaults = ""
      End
   End
   Begin CriteriaPane = 
      Begin ColumnWidths = 11
         Column = 1440
         Alias = 900
         Table = 1170
         Output = 720
         Append = 1400
         NewValue = 1170
         SortType = 1350
         SortOrder = 1410
         GroupBy = 1350
         Filter = 1350
         Or = 1350
         Or = 1350
         Or = 1350
      End
   End
End
', @level0type = N'SCHEMA', @level0name = N'sExamination', @level1type = N'VIEW', @level1name = N'vExtPrescriptionDetail';


GO
PRINT N'Creating Extended Property [sExamination].[vExtPrescriptionDetail].[MS_DiagramPaneCount]...';


GO
EXECUTE sp_addextendedproperty @name = N'MS_DiagramPaneCount', @value = 1, @level0type = N'SCHEMA', @level0name = N'sExamination', @level1type = N'VIEW', @level1name = N'vExtPrescriptionDetail';


GO
PRINT N'Refreshing Function [sExamination].[fGetPulmonaryResult]...';


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


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


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


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


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


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


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


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


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


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


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


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].[pRptMedicineConsuptionWithArchive]...';


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


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


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


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 [sMro].[pMROFullViewArchiveGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sMro].[pMROFullViewArchiveGet]';


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


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


GO
PRINT N'Refreshing Procedure [dbo].[Consolidatedcost]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[Consolidatedcost]';


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [sMro].[pEmployeeExaminationListGetDS]...';


GO
EXECUTE sp_refreshsqlmodule N'[sMro].[pEmployeeExaminationListGetDS]';


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


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


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


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


GO
PRINT N'Refreshing Procedure [sMro].[pExaminationArchiveCustomSearch]...';


GO
EXECUTE sp_refreshsqlmodule N'[sMro].[pExaminationArchiveCustomSearch]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [sWellness].[PempDashboardDetailGet_MHI]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[PempDashboardDetailGet_MHI]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [sMro].[pEmployeeExaminationListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sMro].[pEmployeeExaminationListGet]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_getDocuments_Contractor]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getDocuments_Contractor]';


GO
PRINT N'Refreshing Procedure [sWellness].[PGetEmployeeMHIDetailDashboard]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[PGetEmployeeMHIDetailDashboard]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_SettingsToUpdateTestsForMobile]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_SettingsToUpdateTestsForMobile]';


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


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


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


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


GO
PRINT N'Refreshing Procedure [sPharmacy].[pValidatePrescription]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pValidatePrescription]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_updateAllLDLHDLRatio]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_updateAllLDLHDLRatio]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateUrineParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateUrineParameters]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [sPermit].[sp_GetPermitVertigoWorkers]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPermit].[sp_GetPermitVertigoWorkers]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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].[pDiagnosisTrackerEmployeeUpdateALLBySourceIds]...';


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_GeneralTemplateSettings]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_GeneralTemplateSettings]';


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateLDLHDLANDRatio]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateLDLHDLANDRatio]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_getOutSideDocuments_newsearch]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getOutSideDocuments_newsearch]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_getDocumentsOPDIdWise]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getDocumentsOPDIdWise]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_getAzureDocuments_newsearch_Ng]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getAzureDocuments_newsearch_Ng]';


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_getAzureDocuments_newsearch]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getAzureDocuments_newsearch]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_getDocuments_newsearch_Ng]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getDocuments_newsearch_Ng]';


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_getOutSideDocuments_newsearch_Ng]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getOutSideDocuments_newsearch_Ng]';


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


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


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


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


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].[pCreateGeneralTemplateExaminationN]...';


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_SettingsGeneralTemplateAndParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_SettingsGeneralTemplateAndParameters]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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].[pDiagnosisTrackerMetabolicSyndromeUpdate]...';


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [sSupport].[pGetAllProvidedAppointmentFromTemplate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pGetAllProvidedAppointmentFromTemplate]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_getAzureDocuments_Visit]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getAzureDocuments_Visit]';


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_getDocuments_Visit]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getDocuments_Visit]';


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_getOutSideDocuments_Visit]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getOutSideDocuments_Visit]';


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_AutoImportEmployees]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_AutoImportEmployees]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [sSupport].[pProviderHealthIndicator]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pProviderHealthIndicator]';


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


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


GO
PRINT N'Refreshing Procedure [sMro].[pCustomOPDHistoryListGetWithPagination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sMro].[pCustomOPDHistoryListGetWithPagination]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_getDocuments_newsearchNew]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getDocuments_newsearchNew]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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].[pUnfitListingListGet]...';


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


GO
PRINT N'Refreshing Procedure [sSupport].[pAssignAppointmentToDoctor]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pAssignAppointmentToDoctor]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_getInjurie_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getInjurie_new]';


GO
PRINT N'Refreshing Procedure [sSupport].[pAssignAppointmentToDoctorXml]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pAssignAppointmentToDoctorXml]';


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


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


GO
PRINT N'Refreshing Procedure [sSupport].[pCalculateHealthIndicator]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pCalculateHealthIndicator]';


GO
PRINT N'Refreshing Procedure [sSupport].[pDataUploadedUpdateXml]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pDataUploadedUpdateXml]';


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].[pCommonExaminationHistoryPMEContractWorkerListGet]...';


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [sMro].[pVisitsListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sMro].[pVisitsListGet]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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].[pHabitHygineGetOPDNg_new]...';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[prc_getDocuments_newsearch]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getDocuments_newsearch]';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
PRINT N'Refreshing Procedure [dbo].[DiseaseDetailDataformisGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[DiseaseDetailDataformisGet]';


GO
PRINT N'Refreshing Procedure [dbo].[DiseaseDetailDataGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[DiseaseDetailDataGet]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_DeleteAudiometryDatasByRoundGroup]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_DeleteAudiometryDatasByRoundGroup]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_DeleteExaminationDataBySetup]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_DeleteExaminationDataBySetup]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_getDocuments_newsearchNewDocumentSearch]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getDocuments_newsearchNewDocumentSearch]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_GetDuplicateDataLocAndSetupOCADANI]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_GetDuplicateDataLocAndSetupOCADANI]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_getHospitalReferral_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getHospitalReferral_new]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_getInjurie]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getInjurie]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_getInjuriesRegistered_DrReaddy]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_getInjuriesRegistered_DrReaddy]';


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_LoadSettingsForLDLHDL]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_LoadSettingsForLDLHDL]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_MeargEmployeeWithExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_MeargEmployeeWithExamination]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_test]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_test]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateDIABETICParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateDIABETICParameters]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateLDLHDLRatio]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateLDLHDLRatio]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdateLDLHDLRatioALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdateLDLHDLRatioALL]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_UpdatePublish]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_UpdatePublish]';


GO
PRINT N'Refreshing Procedure [dbo].[tmpGetSetupDate]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[tmpGetSetupDate]';


GO
PRINT N'Refreshing Procedure [dbo].[VisitplanWiseTypeDataGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[VisitplanWiseTypeDataGet]';


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


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


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


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


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


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


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


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


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 [sAlert].[pReportingManagerMailIds]...';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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].[pBindPrescriptionGridNursing]...';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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].[pEmployeeHealthIndexGet]...';


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


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


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


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


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


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


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


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


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


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


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


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].[pExaminationCSRHistoryListGet_Old]...';


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetEmployeeDataOnStatusSelect]';


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].[pGetEmployeeDetailsByIDS]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetEmployeeDetailsByIDS]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetEmployeeDocumentsFromAPI]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetEmployeeDocumentsFromAPI]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetEmployeeExaminationViewDatasNg_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetEmployeeExaminationViewDatasNg_new]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetEmployeeHealthIndex]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetEmployeeHealthIndex]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetEmployeementExaminationListUsingCode]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetEmployeementExaminationListUsingCode]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExaminationCountForEmployee]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExaminationCountForEmployee]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExaminationDetailsByExaminationId]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExaminationDetailsByExaminationId]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExaminationDetailsById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExaminationDetailsById]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExaminationListUsingCode]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExaminationListUsingCode]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExaminationListUsingCode_old]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExaminationListUsingCode_old]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExaminationTests]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExaminationTests]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExaminationVitalsAll]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExaminationVitalsAll]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExpenseDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExpenseDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetFlagEmployeesBySetupGroup]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetFlagEmployeesBySetupGroup]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetFlagEmployeesBySetupGroupN]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetFlagEmployeesBySetupGroupN]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetHeight]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetHeight]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetInjuryFormDetailsForEmail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetInjuryFormDetailsForEmail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetInjuryFormFields]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetInjuryFormFields]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetInjuryListingFields]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetInjuryListingFields]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetOPDCountDetailForAlert]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetOPDCountDetailForAlert]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetOpdCreatedDateTime]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetOpdCreatedDateTime]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetOPDDetailsForEmail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetOPDDetailsForEmail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetOPDNextPrevious]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetOPDNextPrevious]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetOpdNumberCreatedDateTime]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetOpdNumberCreatedDateTime]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetOPDRecords]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetOPDRecords]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetPendingFreezeList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetPendingFreezeList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetPreEmployeementEmployeeFlagBySetup]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetPreEmployeementEmployeeFlagBySetup]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetSearchAllExaminationDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetSearchAllExaminationDatas]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetSearchAllExaminationDatasAll]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetSearchAllExaminationDatasAll]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetSearchAllExaminationDatasAllWithPagination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetSearchAllExaminationDatasAllWithPagination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetSearchAllExaminationDatasList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetSearchAllExaminationDatasList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetSetupListGroupwise]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetSetupListGroupwise]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetSourceIdAndDate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetSourceIdAndDate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetTargetGroupWiseTestCount]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetTargetGroupWiseTestCount]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetVertigoOPDDetailsByUniqueIdandUniqueIdType]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetVertigoOPDDetailsByUniqueIdandUniqueIdType]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHabitHygineGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHabitHygineGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHabitListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHabitListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisComparisonGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisComparisonGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisEmployeeGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisEmployeeGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisEmployeeParameterGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisEmployeeParameterGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisEmployeeParameterGetWithMail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisEmployeeParameterGetWithMail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyCompanyGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyCompanyGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyCompanyGroupGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyCompanyGroupGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyDepartmentGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyDepartmentGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyDepartmentGroupGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyDepartmentGroupGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyEmployeeGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyEmployeeGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyEmployeeGetByDepartment]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyEmployeeGetByDepartment]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyEmployeeGetByStoreLocation]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyEmployeeGetByStoreLocation]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyEmployeeHealthIndexGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyEmployeeHealthIndexGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyFunctionGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyFunctionGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyLocationGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyLocationGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyLocationMainGroupGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyLocationMainGroupGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyLocationMainSubGroupGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyLocationMainSubGroupGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyOrgGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyOrgGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyOrgGetOne]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyOrgGetOne]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyOrgGetTwo]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyOrgGetTwo]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchySectorGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchySectorGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyStoreLocationGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyStoreLocationGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisHierarchyVerticalGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisHierarchyVerticalGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHealthAnalysisOrgReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHealthAnalysisOrgReport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHeightAgeGetForPulmonaryImport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHeightAgeGetForPulmonaryImport]';


GO
PRINT N'Refreshing Procedure [sExamination].[PHelathIndexMissingParameter]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[PHelathIndexMissingParameter]';


GO
PRINT N'Refreshing Procedure [sExamination].[PHelathIndexMissingParameterNew]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[PHelathIndexMissingParameterNew]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHematologyHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHematologyHistoryListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHepaticProfileHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHepaticProfileHistoryListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHistoryGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHistoryGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHRExaminationRequestGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHRExaminationRequestGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportExaminationALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportExaminationALL]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportExaminationAudiometryALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportExaminationAudiometryALL]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportExaminationInvestigationALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportExaminationInvestigationALL]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportExaminationInvestigationALL_NEW]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportExaminationInvestigationALL_NEW]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportGeneralExaminationALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportGeneralExaminationALL]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportPulmonaryExaminationALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportPulmonaryExaminationALL]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportPulmonaryExaminationALL_NEW]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportPulmonaryExaminationALL_NEW]';


GO
PRINT N'Refreshing Procedure [sExamination].[pInjuryFormGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pInjuryFormGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pLastMedicinGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pLastMedicinGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pLipidProfileHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pLipidProfileHistoryListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pLocationWiseHealthAnalysisGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pLocationWiseHealthAnalysisGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pLSDDashboardListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pLSDDashboardListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMeargeExaminations]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMeargeExaminations]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMISDashBoardOpdMovement]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMISDashBoardOpdMovement]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMISDashBoardPeriodicCount]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMISDashBoardPeriodicCount]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMISDashBoardPreEmploymentCount]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMISDashBoardPreEmploymentCount]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMISExaminationDashboardLocationWiseHealthAnalysis]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMISExaminationDashboardLocationWiseHealthAnalysis]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMISHealthAnalysisEmployeeGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMISHealthAnalysisEmployeeGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobDiagnosisSectorGet_Temp]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobDiagnosisSectorGet_Temp]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobEmployeeExaminationRoundListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobEmployeeExaminationRoundListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobExaminationBiometricEmployeeDetailsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobExaminationBiometricEmployeeDetailsGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobExaminationSummaryEmployeeList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobExaminationSummaryEmployeeList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobGetDiseaseAnalysisList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobGetDiseaseAnalysisList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobGetDiseaseAnalysisListHtml]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobGetDiseaseAnalysisListHtml]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobGetDiseaseSystemList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobGetDiseaseSystemList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobGetDiseaseSystemListHtml]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobGetDiseaseSystemListHtml]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobGetEmployeeExaminationViewDatas]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobGetEmployeeExaminationViewDatas]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobGetEmployeeTypeCountList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobGetEmployeeTypeCountList]';


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].[pMobHealthIndexGraphGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobHealthIndexGraphGet]';


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].[pMobMISExaminationDashboardDiagnosisTracker]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobMISExaminationDashboardDiagnosisTracker]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobMISHealthAnalysis]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobMISHealthAnalysis]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobOpdDashBoardExpense]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobOpdDashBoardExpense]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobPeriodicExaminationAllDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobPeriodicExaminationAllDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobPeriodicExaminationDataGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobPeriodicExaminationDataGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobPMEpendingEmployeeList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobPMEpendingEmployeeList]';


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].[pMobTargetGroupCountDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobTargetGroupCountDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pNewlyDiagnosedGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pNewlyDiagnosedGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pNewlyDiagnosedUpdateAll]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pNewlyDiagnosedUpdateAll]';


GO
PRINT N'Refreshing Procedure [sExamination].[pNextPreviousOPDEXaminationGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pNextPreviousOPDEXaminationGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pNextPreviousOPDGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pNextPreviousOPDGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDConslingCost]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDConslingCost]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDConslingcount]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDConslingcount]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDDashboardcostdetailList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDDashboardcostdetailList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOpdDashBoardExpense]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOpdDashBoardExpense]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOPDFitnessHistory]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOPDFitnessHistory]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOpdQuickRemove]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOpdQuickRemove]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOpdQuickRemoveByNumber]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOpdQuickRemoveByNumber]';


GO
PRINT N'Refreshing Procedure [sExamination].[pOtherStockOPDDetailsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pOtherStockOPDDetailsGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPastHistoryGetExaminationAll]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPastHistoryGetExaminationAll]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPastHistoryGetExaminationAllNg]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPastHistoryGetExaminationAllNg]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPeriodicDashboardAnalyticsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPeriodicDashboardAnalyticsGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPeriodicDashboardGridGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPeriodicDashboardGridGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPeriodicDashboardGridGet_N]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPeriodicDashboardGridGet_N]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPeriodicExaminationAllDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPeriodicExaminationAllDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPeriodicExaminationHistoryListGet_Old]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPeriodicExaminationHistoryListGet_Old]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPeriodicFreezeAllAnalyticsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPeriodicFreezeAllAnalyticsGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPeriodicFreezeAnalyticsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPeriodicFreezeAnalyticsGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPeriodicFreezeAnalyticsGetForMIS]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPeriodicFreezeAnalyticsGetForMIS]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPersonalGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPersonalGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPersonalHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPersonalHistoryListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPrescriptionDataAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPrescriptionDataAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPrescriptionDirectDataAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPrescriptionDirectDataAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPrescriptionIssueReturnDataGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPrescriptionIssueReturnDataGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pProviderAppointmentEmployeeList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pProviderAppointmentEmployeeList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPulmonaryPreditingGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPulmonaryPreditingGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pReferralTestRequestGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pReferralTestRequestGet]';


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].[pRenalProfileHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRenalProfileHistoryListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pResporatoryHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pResporatoryHistoryListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRestrictLipidAutocalculationByRound]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRestrictLipidAutocalculationByRound]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRestrictLipidAutocalculationByRoundGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRestrictLipidAutocalculationByRoundGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRiskCategoryDashboardDataGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRiskCategoryDashboardDataGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCardDisease]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCardDisease]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCardHabit]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCardHabit]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptDignosisRemark]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptDignosisRemark]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptDiseaseSummary]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptDiseaseSummary]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptExaminationGeneralTestReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptExaminationGeneralTestReport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptExaminationPastHistoryDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptExaminationPastHistoryDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptExaminationTestReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptExaminationTestReport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptFitnessCerti]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptFitnessCerti]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptFitnessCerti_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptFitnessCerti_New]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptForm22MedicalHistory]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptForm22MedicalHistory]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptGetBMIEvaluationReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptGetBMIEvaluationReport]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptGetHealthCardEmploymentDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptGetHealthCardEmploymentDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptGetHealthCardSubGeneralParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptGetHealthCardSubGeneralParameters]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptGetPrescriptionEmailParameters]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptGetPrescriptionEmailParameters]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptOPDActivityCertificate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptOPDActivityCertificate]';


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].[pRptReferral]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptReferral]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptReferralCertificate]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptReferralCertificate]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptServiceCost]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptServiceCost]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptServiceItemWiseConsumption]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptServiceItemWiseConsumption]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptTestReportAcuity]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptTestReportAcuity]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptTestReportAcuity_OLD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptTestReportAcuity_OLD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSavePastHistoryDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSavePastHistoryDetails]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSaveTestResultsFirst]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSaveTestResultsFirst]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSearchIncidentsListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSearchIncidentsListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSearchIncidentsListGetNg_new]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSearchIncidentsListGetNg_new]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSetImportTitleByIds]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSetImportTitleByIds]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSetupDepartmentAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSetupDepartmentAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSetupEmployeeAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSetupEmployeeAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSetupEmployeeTempRemove]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSetupEmployeeTempRemove]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSetupGroupStatusGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSetupGroupStatusGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSpecificProfileHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSpecificProfileHistoryListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pStoolHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pStoolHistoryListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pSubmitCounselingRemarkSend]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pSubmitCounselingRemarkSend]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTargetGroupCountDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTargetGroupCountDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTargetGroupCountDetail_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTargetGroupCountDetail_New]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTempDiagnosisRemarkAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTempDiagnosisRemarkAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTempDiagnosisRemarkAdd_Dynamic]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTempDiagnosisRemarkAdd_Dynamic]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTempWellEmployeeDiseaseHabitAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTempWellEmployeeDiseaseHabitAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestAnalysisExportDetailGet_OLD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestAnalysisExportDetailGet_OLD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTestAnalysisGet_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTestAnalysisGet_New]';


GO
PRINT N'Refreshing Procedure [sExamination].[pThyroidProfileHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pThyroidProfileHistoryListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTotalHealthIndexGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTotalHealthIndexGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTranferedProviderAppointmentListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTranferedProviderAppointmentListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTransferEmployeeRound]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTransferEmployeeRound]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTransferEmployeeRoundGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTransferEmployeeRoundGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pupdate_visitpurpose]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pupdate_visitpurpose]';


GO
PRINT N'Refreshing Procedure [sExamination].[pUpdateEmployeeToExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pUpdateEmployeeToExamination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pUpdateHealthParametersByRound]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pUpdateHealthParametersByRound]';


GO
PRINT N'Refreshing Procedure [sExamination].[pUpdatetDiagnosisBySetupGroupId]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pUpdatetDiagnosisBySetupGroupId]';


GO
PRINT N'Refreshing Procedure [sExamination].[pUrineHistoryListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pUrineHistoryListGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pValidateDeleteEmployeeExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pValidateDeleteEmployeeExamination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pValidateMeargeExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pValidateMeargeExamination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pVisitPurposeEmployeeTypeWise]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pVisitPurposeEmployeeTypeWise]';


GO
PRINT N'Refreshing Procedure [sExamination].[pVitalGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pVitalGet]';


GO
PRINT N'Refreshing Procedure [sHrm].[pCsrBenifitOtherSubGroupMasterAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pCsrBenifitOtherSubGroupMasterAdd]';


GO
PRINT N'Refreshing Procedure [sHrm].[pEmployeeCsrBenifitGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pEmployeeCsrBenifitGet]';


GO
PRINT N'Refreshing Procedure [sHrm].[pEmployeeFamilyDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pEmployeeFamilyDelete]';


GO
PRINT N'Refreshing Procedure [sHrm].[pMobEmployeeMasterListingGet_old]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pMobEmployeeMasterListingGet_old]';


GO
PRINT N'Refreshing Procedure [sHrm].[pMobEmployeeMedicalDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pMobEmployeeMedicalDetails]';


GO
PRINT N'Refreshing Procedure [sIncident].[pIncidentListingAccidentAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sIncident].[pIncidentListingAccidentAdd]';


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 [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 [sIncident].[pRptIncidentReport]...';


GO
EXECUTE sp_refreshsqlmodule N'[sIncident].[pRptIncidentReport]';


GO
PRINT N'Refreshing Procedure [sIncident].[pRptIncidentSummary]...';


GO
EXECUTE sp_refreshsqlmodule N'[sIncident].[pRptIncidentSummary]';


GO
PRINT N'Refreshing Procedure [sIp].[pGroupItemWiseReportGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sIp].[pGroupItemWiseReportGet]';


GO
PRINT N'Refreshing Procedure [sMro].[pEmployeeLastExaminationGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sMro].[pEmployeeLastExaminationGet]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pDispenseAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pDispenseAdd]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pDispenseDrugDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pDispenseDrugDetails]';


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].[pRptStockTransactionList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sProcurement].[pRptStockTransactionList]';


GO
PRINT N'Refreshing Procedure [sSecurity].[GetEventReminderFollowUp]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSecurity].[GetEventReminderFollowUp]';


GO
PRINT N'Refreshing Procedure [sSecurity].[pSecurityDashboardDetailsGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSecurity].[pSecurityDashboardDetailsGet]';


GO
PRINT N'Refreshing Procedure [sSupport].[pAssignSurveyMasterOPDFeedbackGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pAssignSurveyMasterOPDFeedbackGet]';


GO
PRINT N'Refreshing Procedure [sSupport].[pEmployeeCountSectorGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pEmployeeCountSectorGet]';


GO
PRINT N'Refreshing Procedure [sSupport].[pGetProviderDocumentUploadAndExaminationPending]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pGetProviderDocumentUploadAndExaminationPending]';


GO
PRINT N'Refreshing Procedure [sSupport].[pMyVaccineListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pMyVaccineListGet]';


GO
PRINT N'Refreshing Procedure [sSupport].[pProviderCheckupCountGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pProviderCheckupCountGet]';


GO
PRINT N'Refreshing Procedure [sSupport].[pProviderDashboardEmployeeWiseGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pProviderDashboardEmployeeWiseGet]';


GO
PRINT N'Refreshing Procedure [sSupport].[pProviderDashboardLocationGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pProviderDashboardLocationGet]';


GO
PRINT N'Refreshing Procedure [sSupport].[pProviderDashboardVerticalGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pProviderDashboardVerticalGet]';


GO
PRINT N'Refreshing Procedure [sSupport].[pProviderWiseAppointmentDocListAPiGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pProviderWiseAppointmentDocListAPiGet]';


GO
PRINT N'Refreshing Procedure [sSupport].[pVaccineLogDashboardGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pVaccineLogDashboardGet]';


GO
PRINT N'Refreshing Procedure [sSupport].[pVaccineStatusGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSupport].[pVaccineStatusGet]';


GO
PRINT N'Refreshing Procedure [sTool].[pEmployeeExaminationDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pEmployeeExaminationDelete]';


GO
PRINT N'Refreshing Procedure [sTool].[pSubLocationAllTranjectionReset]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pSubLocationAllTranjectionReset]';


GO
PRINT N'Refreshing Procedure [sTool].[pSubLocationExaminationDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pSubLocationExaminationDelete]';


GO
PRINT N'Refreshing Procedure [sTool].[pSubLocationStockDelete]...';


GO
EXECUTE sp_refreshsqlmodule N'[sTool].[pSubLocationStockDelete]';


GO
PRINT N'Refreshing Procedure [sWellness].[GetEmployeeMHIScoreDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[GetEmployeeMHIScoreDetail]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetCompletedHealthIndexEmployeeList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetCompletedHealthIndexEmployeeList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pUpdateMHIScoreRoundLocationWise]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pUpdateMHIScoreRoundLocationWise]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPulmonaryAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPulmonaryAdd]';


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 [sExamination].[pExistingDiseaseGetExaminationAll]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExistingDiseaseGetExaminationAll]';


GO
PRINT N'Refreshing Procedure [sExamination].[pServiceListingGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pServiceListingGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptWellEmployee_Check]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptWellEmployee_Check]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHabitHygineGetExaminationAll]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHabitHygineGetExaminationAll]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptPeriodicForm_Old]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptPeriodicForm_Old]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCardMain]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCardMain]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptCardTest]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptCardTest]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptTestReport_OLD]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptTestReport_OLD]';


GO
PRINT N'Refreshing Procedure [sExamination].[pAudiometryUpdateGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pAudiometryUpdateGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pAudiometryUpdateGet_New_N]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pAudiometryUpdateGet_New_N]';


GO
PRINT N'Refreshing Procedure [sExamination].[pCompareParameterResultDepartmentwise]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pCompareParameterResultDepartmentwise]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDignosisRemarkWellEmployee]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDignosisRemarkWellEmployee]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDignosisRemarkWellEmployee_Dynamic]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDignosisRemarkWellEmployee_Dynamic]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExistingDiseaseGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExistingDiseaseGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pExposureGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pExposureGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pGetExaminationVitals]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pGetExaminationVitals]';


GO
PRINT N'Refreshing Procedure [sExamination].[pHabitHygineGetExaminationAllNg]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pHabitHygineGetExaminationAllNg]';


GO
PRINT N'Refreshing Procedure [sExamination].[pLastAutoSave]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pLastAutoSave]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPulmonaryUpdateGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPulmonaryUpdateGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptDignosisRemark_Dynamic]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptDignosisRemark_Dynamic]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptXrayILO]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptXrayILO]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptPulmonary]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptPulmonary]';


GO
PRINT N'Refreshing Procedure [sAlert].[pEmployeeExaminationGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAlert].[pEmployeeExaminationGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pAudiometryDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pAudiometryDetailGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pProviderCountGet_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pProviderCountGet_New]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptExaminationDetail]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptExaminationDetail]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisUpdateResultALLTrackerBySourceIds]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisUpdateResultALLTrackerBySourceIds]';


GO
PRINT N'Refreshing Procedure [sAudit].[pActivityLogGetTest]...';


GO
EXECUTE sp_refreshsqlmodule N'[sAudit].[pActivityLogGetTest]';


GO
PRINT N'Refreshing Procedure [sConfig].[pDeleteImportData]...';


GO
EXECUTE sp_refreshsqlmodule N'[sConfig].[pDeleteImportData]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportPeriodicList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportPeriodicList]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDepartmentFreezeEmployeeAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDepartmentFreezeEmployeeAdd]';


GO
PRINT N'Refreshing Procedure [sExamination].[pTempWellEmployeeAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pTempWellEmployeeAdd]';


GO
PRINT N'Refreshing Procedure [dbo].[prc_AutoImportEmployees_Cummins]...';


GO
EXECUTE sp_refreshsqlmodule N'[dbo].[prc_AutoImportEmployees_Cummins]';


GO
PRINT N'Refreshing Procedure [sCommon].[pSapMissingEmployeeDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pSapMissingEmployeeDetailGet]';


GO
PRINT N'Refreshing Procedure [sCommon].[pSapMissingEmployeeGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sCommon].[pSapMissingEmployeeGet]';


GO
PRINT N'Refreshing Procedure [sSecurity].[pSapErrorReportDetails]...';


GO
EXECUTE sp_refreshsqlmodule N'[sSecurity].[pSapErrorReportDetails]';


GO
PRINT N'Refreshing Procedure [sWellness].[pMobWellnessAppointmentNotificationDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pMobWellnessAppointmentNotificationDetailGet]';


GO
PRINT N'Refreshing Procedure [sWellness].[pWellnessAppointmenScheduleListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pWellnessAppointmenScheduleListGet]';


GO
PRINT N'Refreshing Procedure [sWellness].[pWellnessConsultationRemove]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pWellnessConsultationRemove]';


GO
PRINT N'Refreshing Procedure [sWellness].[pMobWellnessAppointmentListByDoctorId]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pMobWellnessAppointmentListByDoctorId]';


GO
PRINT N'Refreshing Procedure [sWellness].[pMobWellnessAppointmentListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pMobWellnessAppointmentListGet]';


GO
PRINT N'Refreshing Procedure [sWellness].[pAddOrUpdateProgramMHIScore]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pAddOrUpdateProgramMHIScore]';


GO
PRINT N'Refreshing Procedure [sWellness].[pAddOrUpdatePrograms]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pAddOrUpdatePrograms]';


GO
PRINT N'Refreshing Procedure [sWellness].[pEmployeeMHIScoreList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pEmployeeMHIScoreList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetEmployeeHealthIndex]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetEmployeeHealthIndex]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetEmployeeListCoach]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetEmployeeListCoach]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetNonAdherenceEmpList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetNonAdherenceEmpList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetNonAdherenceTaskList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetNonAdherenceTaskList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetWellnessEmployeeProgramDetailsById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetWellnessEmployeeProgramDetailsById]';


GO
PRINT N'Refreshing Procedure [sWellness].[pIsProgramMasterUsed]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pIsProgramMasterUsed]';


GO
PRINT N'Refreshing Procedure [sWellness].[pWellnessConsultationList]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pWellnessConsultationList]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetMHIParameterGraph]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetMHIParameterGraph]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetMHIProgramHistoryGraph]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetMHIProgramHistoryGraph]';


GO
PRINT N'Refreshing Procedure [sWellness].[pListPastProgramForEmployee]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pListPastProgramForEmployee]';


GO
PRINT N'Refreshing Procedure [sWellness].[GetConsultationDocumentsById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[GetConsultationDocumentsById]';


GO
PRINT N'Refreshing Procedure [sWellness].[pGetConsultationDetailsById]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pGetConsultationDetailsById]';


GO
PRINT N'Refreshing Procedure [sWellness].[pListAssignedEmployeeTask]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pListAssignedEmployeeTask]';


GO
PRINT N'Refreshing Procedure [sWellness].[pListEmployeeEncounterNotes]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pListEmployeeEncounterNotes]';


GO
PRINT N'Refreshing Procedure [sWellness].[pMobEmployeeConsultationListGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pMobEmployeeConsultationListGet]';


GO
PRINT N'Refreshing Procedure [sWellness].[pNextPreviousConsultationGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pNextPreviousConsultationGet]';


GO
PRINT N'Refreshing Procedure [sHrm].[pImportEmployee]...';

GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pImportEmployee]';

GO
PRINT N'Refreshing Procedure [sPharmacy].[pDrugDetailGetNEW]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pDrugDetailGetNEW]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pDrugDispenseDetailGetNEW_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pDrugDispenseDetailGetNEW_New]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pDrugDetailHistoryGetNEW]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pDrugDetailHistoryGetNEW]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pDrugDispenseDetailHistoryGetNEW_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pDrugDispenseDetailHistoryGetNEW_New]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pGetDrugDispenseGridOption]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pGetDrugDispenseGridOption]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pGetDrugDispenseDetailGridOption_New]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pGetDrugDispenseDetailGridOption_New]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pDrugDispenseDetailGetNEW]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pDrugDispenseDetailGetNEW]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pDrugDispenseDetailHistoryGetNEW]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pDrugDispenseDetailHistoryGetNEW]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pGetDrugDispenseDetailGridOption]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pGetDrugDispenseDetailGridOption]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pDrugDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pDrugDetailGet]';


GO
PRINT N'Refreshing Procedure [sPharmacy].[pDrugDetailHistoryGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sPharmacy].[pDrugDetailHistoryGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pRptExaminationAnalysis_Check]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pRptExaminationAnalysis_Check]';


GO
PRINT N'Refreshing Procedure [sExamination].[pMobExaminationGraphGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pMobExaminationGraphGet]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDeleteImportExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDeleteImportExamination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pServiceListingResultAllGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pServiceListingResultAllGet]';


GO
PRINT N'Refreshing Procedure [sHrm].[pImportExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pImportExamination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pDiagnosisUpdateResultALL]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pDiagnosisUpdateResultALL]';


GO
PRINT N'Refreshing Procedure [sExamination].[pImportPulmonaryExamination]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pImportPulmonaryExamination]';


GO
PRINT N'Refreshing Procedure [sExamination].[pPeriodicFreezeHazardEmployeeAdd]...';


GO
EXECUTE sp_refreshsqlmodule N'[sExamination].[pPeriodicFreezeHazardEmployeeAdd]';


GO
PRINT N'Refreshing Procedure [sWellness].[PEmpDashboardDetailGet]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[PEmpDashboardDetailGet]';


GO
PRINT N'Refreshing Procedure [sHrm].[pImportEmployees_Amex]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pImportEmployees_Amex]';


GO
PRINT N'Refreshing Procedure [sHrm].[pImportEmployees_NEW]...';


GO
EXECUTE sp_refreshsqlmodule N'[sHrm].[pImportEmployees_NEW]';


GO
PRINT N'Refreshing Procedure [sWellness].[pConsultationAddOrUpdateProgramMHIScore]...';


GO
EXECUTE sp_refreshsqlmodule N'[sWellness].[pConsultationAddOrUpdateProgramMHIScore]';