
ALTER PROCEDURE [sWellness].[pConsultationLoadAllDropDownLists]
    @rStoreLocationId INT,
    @rOrgId INT,
    @rLocationId INT
AS
BEGIN
    SET NOCOUNT ON;

    -- Query 1: Employee/Doctor data
    SELECT 
        d.EmployeeId as Id,
        ISNULL(e.EmployeePrefix + ' ', '') + e.FirstName + ' ' + e.LastName AS Title 
    FROM sCwb.tDoctorMaster d 
    INNER JOIN sHrm.tEmployeeMaster e ON d.EmployeeId = e.Id 
    INNER JOIN sCwb.tDoctorStoreLocation S ON d.EmployeeId = S.EmployeeId 
    WHERE S.SubLocationId = @rStoreLocationId AND d.OrgId = @rOrgId
        AND e.StatusId = 7 AND ISNULL(d.IsWellness,0) = 1;

    -- Query 2: Clinic Master
    SELECT Id, Title, isnull(DoctorName,'') as DoctorName
    FROM sCommon.tClinicMaster 
    WHERE IsObsolete = 0 
        AND OrgId = @rOrgId 
        AND LocationId = @rLocationId;

    -- Query 3: Wellness Visit Purpose
    SELECT WVP.Id, WVP.Title
    FROM sWellness.tWellnessVisitPurposeMaster WVP
    WHERE WVP.IsObsolete = 0 AND WVP.OrgId = @rOrgId;

    -- Query 4: Referred to OHC Doctor
    SELECT EM.Id as Id,
	ISNULL(EM.EmployeePrefix + ' ','') + ISNULL(EM.FirstName + ' ','') + ISNULL(EM.LastName + ' ','') as Title
	from sCwb.tDoctorMaster DM
	INNER JOIN sCwb.tDoctorStoreLocation DSL ON DSL.EmployeeId = DM.EmployeeId
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.EmployeeId
	WHERE DSL.SubLocationId=@rStoreLocationId AND EM.StatusId = 7 
	AND DM.OrgId = @rOrgId AND ISNULL(DM.IsWellness,0) = 0
    ORDER BY Id, Title DESC;

    -- Query 5: Gender Master
    SELECT 
        Id,
        Title 
    FROM sCommon.tGenderMaster 
    WHERE IsObsolete = 0;

	-- Query 6: Wellness Activity Category
    SELECT Id, Title 
    FROM [sWellness].[tWellnessActivityCategoryMaster]
    WHERE IsObsolete = 0;

	-- Query 7: Wellness Activity
    SELECT ActivityId as Id, ActivityName as Title, WellnessActivityCategoryId, DefaultUnitId
    FROM [sWellness].[tWellnessActivityMaster]
    WHERE IsObsolete = 0;

	-- Query 8: Wellness Activity Task
    SELECT Id,[Name] as Title,ActivityId, TargetValue, 
		   FrequencyTypeId, FrequencyCount, DurationDays
    FROM [sWellness].[tWellnessActivityTaskMaster]
END;

Go

ALTER TABLE sExamination.tGeneralTemplateParameterRange
ADD StaticGeneralTemplateParameterRangeId int

Go


ALTER PROCEDURE [sExamination].[pSaveClinicalTestParametersById]
@rId int,
@rpid varchar(max),
@rOrgId int
as
begin
    DECLARE @lNextNumber bigint,@lFromNextNumber bigint,@lCount int;
	declare @lGeneralTemplateId int,@lStaticGeneralTemplateId int
	select @lGeneralTemplateId = sCommon.fGetIntIdForOrg(@rId,@rOrgId),@lStaticGeneralTemplateId = @rId
	
	if not exists(select 1 from sExamination.tGeneralTemplateMaster where Id = @lGeneralTemplateId and OrgId = @rOrgId)
	begin
		insert into sExamination.tGeneralTemplateMaster
		(
			Id,Code,Title,GeneralTemplateGroupId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,
			OrgId,StaticGeneralTemplateId,OrderIndex
		)
		
		select @lGeneralTemplateId,Code,Title,GeneralTemplateGroupId,
		IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,@rOrgId,Id,OrderIndex
		from sExamination.tStaticGeneralTemplateMaster where Id = @lStaticGeneralTemplateId
	end
	
	if not exists(select 1 from sOrderEntry.tServiceMaster where Id = @lGeneralTemplateId and OrgId = @rOrgId)
	begin
		insert into sOrderEntry.tServiceMaster
		(
			Id,Code,Title,ServiceSubGroupId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,OrgId
		)
		
		select @lGeneralTemplateId,Code,Title,sCommon.fGetIntIdForOrg(GeneralTemplateGroupId,@rOrgId),
		IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,@rOrgId
		from sExamination.tStaticGeneralTemplateMaster where Id = @lStaticGeneralTemplateId
	end
	
	if not exists ( select 1 from sExamination.tAreaMaster where Id = @lGeneralTemplateId and OrgId = @rOrgId and AreaTypeId = 3)
	begin
		insert into sExamination.tAreaMaster
		(
			Id,Title,Remark,AreaTypeId,AreaGroupId,IsObsolete,PagePath,OrderIndex,ImagePath,OrgId,StaticAreaId
		)
		
		select @lGeneralTemplateId,Title,'p',3,2,IsObsolete,
		'~/Pages/Examination/GeneralTemplateExamination.aspx?GeneralTemplateId=' + convert(varchar,@lGeneralTemplateId),1,
		'~/Images/Icon 16x16/icon_general.gif',@rOrgId,Id
		from sExamination.tStaticGeneralTemplateMaster where Id = @lStaticGeneralTemplateId
	end
	
	if not exists ( select 1 from sExamination.tAreaOrganizationMaster oa inner join sExamination.tAreaMaster a
	on oa.AreaId = a.Id	where oa.AreaId = @lGeneralTemplateId and oa.OrgId = @rOrgId
	and a.AreaTypeId = 3 and a.OrgId =@rOrgId and a.Id = @lGeneralTemplateId)
	begin
		insert into sExamination.tAreaOrganizationMaster
		(
			Id,OrgId,AreaId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
		)
		
		select @lGeneralTemplateId,@rOrgId,@lGeneralTemplateId,IsObsolete,CreatedUserId,CreatedDateTime,
		UpdatedUserId,UpdatedDateTime from sExamination.tStaticGeneralTemplateMaster where Id = @lStaticGeneralTemplateId
	end
	
	declare @tbltmpParameters table(tid int identity(1,1),p_StaticParamId int,p_ParamId int,p_TestId int)
	insert into @tbltmpParameters
	select Item,sCommon.fGetIntIdForOrg(Item,@rOrgId),@lGeneralTemplateId from dbo.fSplitStr(@rpid,',') where Item <> ''
	
	delete from sExamination.tGeneralTemplateParameter where GeneralTemplateId = @lGeneralTemplateId and Isnull(StaticGeneralTemplateParameterId,0)>0
	
	MERGE sExamination.tGeneralTemplateParameter AS Target USING 
	(
		SELECT p_ParamId,p_StaticParamId,p_TestId,SP.Title,SP.ParameterValueTypeId,SP.NumericFormat,
		SP.UOM,SP.IsObsolete,SP.OrderIndex,SP.CreatedUserId,SP.CreatedDateTime,SP.UpdatedUserId,SP.UpdatedDateTime,
		ROW_NUMBER() OVER(ORDER BY T.Id) as rno,
		(
			SELECT MAX(T.Id) FROM sExamination.tGeneralTemplateParameter t
		) as maxid
		
		FROM @tbltmpParameters TT INNER JOIN sExamination.tStaticGeneralTemplateParameter SP
		ON TT.p_StaticParamId = SP.Id LEFT JOIN sExamination.tGeneralTemplateParameter T
		ON TT.p_ParamId = T.Id	AND TT.p_TestId = T.GeneralTemplateId
	) AS Source ON Target.Id = Source.p_ParamId AND Target.GeneralTemplateId = Source.p_TestId	
	WHEN NOT MATCHED THEN
		INSERT
		(
			[Id],Title,GeneralTemplateId,ParameterValueTypeId,UOM,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,
			UpdatedDateTime,OrgId,StaticGeneralTemplateParameterId,OrderIndex
		)
		VALUES
		(
			p_ParamId,Title,@lGeneralTemplateId,ParameterValueTypeId,UOM,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,
			UpdatedDateTime,@rOrgId,p_StaticParamId,OrderIndex
		);
	
	delete PL from sExamination.tGeneralTemplateParameterList PL inner join @tbltmpParameters P on P.p_ParamId = PL.GeneralTemplateParameterId

	
	declare @tbltmpParameterList table(tid int identity(1,1),l_StaticParamId int,l_ParamId int,l_StaticId int,l_Id int)
	insert into @tbltmpParameterList
	select p_StaticParamId,p_ParamId,Id,sCommon.fGetIntIdForOrg(Id,@rOrgId)
	from sExamination.tStaticGeneralTemplateParameterList L 
	inner join @tbltmpParameters P	on L.StaticGeneralTemplateParameterId = P.p_StaticParamId
	
	
	declare @lFromNumber int
	select @lFromNumber = max(Id) from sExamination.tGeneralTemplateParameterList
	select @lFromNumber = isnull(@lFromNumber,0)
	
	--declare @lCount int,@i int
	--select @lCount = count(1),@i = 1 from @tbltmpParameterList
	--print @lCount
	--	while @i <= @lCount
	--		begin

	--			INSERT Into	sExamination.tGeneralTemplateParameterList
	--			(Id,GeneralTemplateParameterId,Title,IsObsolete,IsNormal,Diagnosis,Recommendation,OrgId,StaticGeneralTemplateParameterListId)
	--			select  @lFromNumber+tid,l_ParamId,sp.Title,sp.IsObsolete,sp.IsNormal,sp.Diagnosis,sp.Recommendation,@rOrgId as orgid,l_StaticId
	--			FROM @tbltmpParameterList TT 
	--			INNER JOIN sExamination.tStaticGeneralTemplateParameterList SP	ON SP.Id = TT.l_StaticId
	--			where TT.tid=@i
	--			set @i=@i+1
	--		end		
	


	MERGE sExamination.tGeneralTemplateParameterList AS Target USING 
	(
		SELECT l_StaticParamId,l_ParamId,l_StaticId,l_Id,SP.Title,SP.IsObsolete,SP.IsNormal,SP.Diagnosis,SP.Recommendation,
		ROW_NUMBER() OVER(ORDER BY T.Id) as rno,
		(
			SELECT MAX(t1.Id) FROM sExamination.tGeneralTemplateParameterList t1
		) as maxid
		
		FROM @tbltmpParameterList TT 
		INNER JOIN sExamination.tStaticGeneralTemplateParameterList SP	ON SP.Id = TT.l_StaticId 
		left JOIN sExamination.tGeneralTemplateParameterList T	ON TT.l_ParamId = T.GeneralTemplateParameterId
	) AS Source ON Target.id = Source.l_StaticId 
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,GeneralTemplateParameterId,Title,IsObsolete,IsNormal,Diagnosis,Recommendation,OrgId,StaticGeneralTemplateParameterListId
		)
		VALUES
		(
			@lFromNumber + rno,l_ParamId,Title,IsObsolete,IsNormal,Diagnosis,Recommendation,@rOrgId,l_StaticId
		);
		
	delete PR from sExamination.tGeneralTemplateParameterRange PR
	WHERE PR.GeneralTemplateParameterId not in (select p_ParamId from @tbltmpParameters)
	
	declare @tbltmpParameterRange table(tid int identity(1,1),r_StaticParamId int,r_ParamId int,r_StaticId int,r_Id int)
	insert into @tbltmpParameterRange
	select  p_StaticParamId,p_ParamId,Id,sCommon.fGetIntIdForOrg(Id,@rOrgId)
	from sExamination.tStaticGeneralTemplateParameterRange R inner join @tbltmpParameters P
	on R.StaticGeneralTemplateParameterId = P.p_StaticParamId
	
	select @lFromNumber = max(Id) from sExamination.tGeneralTemplateParameterRange
	select @lFromNumber = isnull(@lFromNumber,0)
	
	EXECUTE sCommon.pTableRowIdGet @rOrgId,'sExamination.tGeneralTemplateParameterRange', 0, 1, 1,@outNextNumber = @lFromNextNumber output
	MERGE sExamination.tGeneralTemplateParameterRange AS Target USING 
	(
		SELECT r_StaticParamId,r_ParamId,r_StaticId,r_Id,SP.GenderId,SP.AgeFrom,SP.AgeTo,SP.Minimum,SP.Maximum,
		SP.Remark,SP.IsObsolete,SP.IsNormal,SP.Diagnosis,SP.Recommendation,
		ROW_NUMBER() OVER(ORDER BY T.Id) as rno		
		FROM @tbltmpParameterRange TT 
		INNER JOIN sExamination.tStaticGeneralTemplateParameterRange SP ON TT.r_StaticId = SP.Id 
		LEFT JOIN sExamination.tGeneralTemplateParameterRange T ON TT.r_StaticId = T.StaticGeneralTemplateParameterRangeId
	) AS Source ON Target.GeneralTemplateParameterId = Source.r_ParamId and Target.StaticGeneralTemplateParameterRangeId = Source.r_StaticId
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,GeneralTemplateParameterId,GenderId,AgeFrom,AgeTo,Minimum,Maximum,Remark,IsObsolete,IsNormal,Diagnosis,Recommendation,OrgId,StaticGeneralTemplateParameterRangeId
		)
		VALUES
		(
			@lFromNextNumber + rno,r_ParamId,GenderId,AgeFrom,AgeTo,Minimum,Maximum,Remark,IsObsolete,IsNormal,Diagnosis,Recommendation,@rOrgId,r_StaticId
		);

	select @lCount = COUNT(1) FROM @tbltmpParameterRange                 
  SET @lNextNumber  = @lCount + @lFromNextNumber                 
  exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tGeneralTemplateParameterRange', @rCurrentNumber = @lNextNumber 
end

GO


ALTER PROCEDURE [sExamination].[pImportALLOPDExamination]
@rstrExamination nvarchar(max),
@rstrPrescription nvarchar(max),
@rCreatedUserId bigint,
@rOrgId int,
@rStoreLocationId int,
@rUserSourceId bigint = 0 ---[Developer:Nidhi, Mantis:26061, Date:13/07/2023]

as
begin
	declare @lNextNumber bigint,@lFromNextNumber bigint,@cntExam int,@incExam int,@lCount int,@i int	
	declare @lxmlExamination xml,@lxmlPrescription xml
	
	set @lxmlExamination = CAST(@rstrExamination AS xml)
	set @lxmlPrescription = CAST(@rstrPrescription AS xml)
	
	declare @tblExamination table
	(
		tid int identity(1,1),e_ParticipantSourceId bigint,e_ParticipantSourceTypeId int,
		e_ExaminationDate nvarchar(200),e_CauseId int,e_SetupId int,e_DeptId int,e_MainTypeId int,
		e_DiseaseAll nvarchar(max),e_Name nvarchar(300)
		,e_InTime nvarchar(20), e_OutTime nvarchar(20),e_ComplaintRemark nvarchar(1000),e_VitalRemark nvarchar(300),
		e_FurtherActionId int,e_SubLocationId int,e_ExaminationId bigint,e_ProcessTypeId int,e_CriteriaGroupId int,
		e_CompanyId int,e_TargetGroupId int,e_DesignationId int,e_GradeId int,e_ExamNumber nvarchar(500),e_Height int,e_BodyWeight decimal(10,2),
        e_Temperature decimal(5,2),e_SPO2 decimal(5,2),e_Pulse smallint,e_BloodPressureSystolic int,e_BloodPressureDiastolic smallint ,e_Pediatric bit,e_HighRisk bit
	)
	insert into @tblExamination
	select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,
	T.c.value('@ParticipantSourceTypeId','int') as ParticipantSourceTypeId,
	T.c.value('@ExaminationDate','nvarchar(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','nvarchar(max)') as Disease,
	T.c.value('@Name','nvarchar(300)') as Name,
	T.c.value('@InTime','nvarchar(20)') as InTime,
	T.c.value('@OutTime','nvarchar(20)') as OutTime,
	T.c.value('@ComplaintRemark','nvarchar(1000)') as ComplaintRemark,
	T.c.value('@VitalRemark','nvarchar(300)') as VitalRemark,
	T.c.value('@FurtherActionId','int') as FurtherActionId,
    T.c.value('@SubLocationId','int') as SubLocationId,--[Mantis:0039663 by Shivam on 23/01/2025]
	0,null,null,null,null,null,null,null,  
	T.c.value('@Height','int') as Height,--[0042109] all below Added by Shiv Thapa on 24/07/2025
    T.c.value('@Weight','decimal(10,2)') as BodyWeight,
    T.c.value('@Temperature','decimal(5,2)') as Temperature,
    T.c.value('@SPO2','decimal(5,2)') as SPO2,
    T.c.value('@Pulse','smallint') as Pulse,
	T.c.value('@BPSys','int') as BloodPressureSystolic,
	T.c.value('@BPDia','smallint') as BloodPressureDiastolic,
    T.c.value('@Pediatric','bit') as Pediatric,
	T.c.value('@HighRisk','bit') as HighRisk
	from @lxmlExamination.nodes('/Examinations/Examination')T(c)
	
	update @tblExamination set e_ProcessTypeId = JD.ProcessTypeId,e_TargetGroupId = EM.TargetGroupId,
	e_CompanyId = JD.EmployeeCompanyId,e_DesignationId = JD.EmployeeDesignationId,e_GradeId = JD.GradeId	
	from @tblExamination inner join sHrm.tEmployeeMaster EM on e_ParticipantSourceId = EM.Id
	inner join sHrm.tEmployeeJobDetail JD on e_ParticipantSourceId = JD.EmployeeId
	
	select @incExam = count(*) from sExamination.tExamination where isnull(Examinationnumber,'') <> ''
	and DATEDIFF(day,CreatedDateTime,getdate())>=0 and SetupId = sCommon.fGetIntIdForOrg(8,@rOrgId)
	and StoreLocationId = @rStoreLocationId 
	
	update @tblExamination set e_examinationid = Id from sExamination.tExamination where ParticipantSourceId = e_ParticipantSourceId
	and ParticipantSourceTypeId = e_ParticipantSourceTypeId and  SetupId = e_SetupId and Convert(nvarchar(200),ExaminationDate,103) = Convert(nvarchar(200),e_ExaminationDate,103)
	and   ISNULL(e_Name,'') = ISNULL(OPDOtherName,'') and isnull(IsCancel,0) = 0 -- othername issue in importopd medicine by Nidhi Pandey

	--select * from @tblExamination
	--exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tExamination', 0, 1, 1,@outNextNumber = @lNextNumber output	
	--SET @lFromNextNumber = @lNextNumber - 1

 ---- othername issue in importopd medicine by Nidhi Pandey
	--declare @countExam int = (select Count(*) from @tblExamination)
	--Declare @tempExmId bigint = 0, @tempothername nvarchar(300) = ''
	--while(@countExam != 0)
	--BEGIN
	--set @tempExmId = 0 set @tempothername= ''
	--	if Exists(Select 1 from @tblExamination where e_examinationid != 0 and e_ParticipantSourceTypeId = 1009 and tid = @countExam)
	--	BEGIN
	--		select @tempExmId =e_examinationid ,@tempothername = e_Name  from @tblExamination where e_examinationid != 0 and e_ParticipantSourceTypeId = 1009 and tid = @countExam
	--		if not Exists(Select 1 from sExamination.tOPD where ExaminationId = @tempExmId and OtherName = @tempothername)
	--		BEGIN
	--			update @tblExamination set e_examinationid = 0 where tid = @countExam
	--		END
	--	END
	--	set @countExam = @countExam - 1
	--END
	
	---- othername issue in importopd medicine by Nidhi Pandey
	
	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,e_Name,e_SubLocationId
		FROM @tblExamination 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 IsCancel = 0   --- Nidhi Pandey; Import again after IsCancel issue ; 24/04/2024
	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,  --Nidhi Pandey; as suggested by Manthan Sir, dt - 3/07/2023
			ExaminationNumber,OPDOtherName
		)
		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(nvarchar(11), e_ExaminationDate) end,
			@rCreatedUserId,sCommon.fGetDate(),@rCreatedUserId,sCommon.fGetDate(),0,e_SubLocationId,e_CauseId,
			e_ProcessTypeId,e_CompanyId,e_TargetGroupId,e_DesignationId,e_CriteriaGroupId,e_GradeId,@rUserSourceId,
			'OPD-' + sCommon.fGetFormattedDate()  + RIGHT(100000 + (@incExam + tid) ,5),e_Name
		);
	

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

	update @tblExamination set e_examinationid = Id from sExamination.tExamination where ParticipantSourceId = e_ParticipantSourceId
	and ParticipantSourceTypeId = e_ParticipantSourceTypeId and  SetupId = e_SetupId and Convert(nvarchar(200),ExaminationDate,103) = Convert(nvarchar(200),e_ExaminationDate,103)	
	and OPDOtherName = e_Name and isnull(IsCancel,0) = 0 -- othername issue in importopd medicine by Nidhi Pandey
	
	
	
	--select * from @tblExamination



	-- update @tblExamination set e_examinationid = final.Id 
	-- from (
	-- select top 1 *
	-- From(
	-- select  Id,ParticipantSourceId,ParticipantSourceTypeId,SetupId 
	--  From sExamination.tExamination as b
	--  inner join @tblExamination as t 
	--  on b.ParticipantSourceId=t.e_ParticipantSourceId and b.ParticipantSourceTypeId = t.e_ParticipantSourceTypeId and  b.SetupId = t.e_SetupId 
	--  order by b.id desc
	--  ) as temp
	--) as final
	--where final.ParticipantSourceId = e_ParticipantSourceId
	--and final.ParticipantSourceTypeId = e_ParticipantSourceTypeId and  final.SetupId = e_SetupId

	--select @lCount = COUNT(1) FROM @tblExamination 
	--SET @lNextNumber  = @lCount + @lFromNextNumber	
	--exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tExamination', @rCurrentNumber = @lNextNumber
	
	--exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tExaminDisease', 0, 1, 1,@outNextNumber = @lNextNumber output	
	--SET @lFromNextNumber = @lNextNumber - 1
	--select * from @tblExamination
	--return
	MERGE sExamination.tExaminDisease AS Target USING 
	(
		SELECT Id,e_examinationid,tid
		FROM @tblExamination 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 nvarchar(200)
	)
	insert into @tblDisease
	select null,e_ParticipantSourceId,e_ParticipantSourceTypeId,e_examinationid,null,Item
	from @tblExamination cross apply dbo.fSplitStr(replace(e_DiseaseAll,'+',','),',') where Item <> ''
	
	update @tblDisease set d_DisaeseId = Id from sExamination.tDiseaseMaster where OrgId = @rOrgId and d_Name = Title
	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 nvarchar(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
		);
	
	--select @lCount = COUNT(1) FROM @tblDiseaseN 
	--SET @lNextNumber  = @lCount + @lFromNextNumber	
	--exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tExaminDiseaseDetail', @rCurrentNumber = @lNextNumber
	
	declare @tblPrescription table
	(
		tid int identity(1,1),p_ParticipantSourceId bigint,p_ParticipantSourceTypeId int,p_StockId int,
		p_Quantity nvarchar(100),p_IsNotStore bit,p_IsBatchWise bit,p_IsDispense bit,p_FrequencyId int,
		p_Dose nvarchar(100),p_DrugQty nvarchar(100),p_DrugFrequecyText nvarchar(300),p_DrugInstruction nvarchar(300),
		p_DrugScheduleId int,p_SourceTypeId int,p_QueueTypeId int,p_StoreLocationId int,p_IsAutoDispense bit,
		p_LocationId int,p_IsDirect bit,p_Duration nvarchar(50),p_IsAllowDirectIssue bit,
		p_OtherName nvarchar(300),p_ExaminationDate nvarchar(200) -- Nidhi Pandey; Mantis - 27787; DT - 04/10/2023
		,p_ExaminationId bigint,p_PrescriptionId bigint,p_StockBatchId int,p_PrescriptionDetailId bigint,p_DispenseId bigint,
		pp_RemainQty decimal(12,2),pp_AverageCost decimal(12,2),pp_InwardValue decimal(12,2),pp_DispenseBatchId bigint
	)
	insert into @tblPrescription
	select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,
	T.c.value('@ParticipantSourceTypeId','int') as ParticipantSourceTypeId,
	T.c.value('@StockId','int') as StockId,
	T.c.value('@StockQty','nvarchar(100)') as StockQty,
	T.c.value('@IsNotInStore','bit') as IsNotInStore,
	T.c.value('@IsBatchWise','bit') as IsBatchWise,
	T.c.value('@IsDispense','bit') as IsDispense,
	T.c.value('@DrugFrequencyId','int') as DrugFrequencyId,
	T.c.value('@Dosage','nvarchar(100)') as Dosage,
	T.c.value('@DrugQuantity','nvarchar(100)') as DrugQuantity,
	T.c.value('@DrugFrequencyText','nvarchar(300)') as DrugFrequencyText,
	T.c.value('@DrugInstruction','nvarchar(300)') as DrugInstruction,
	T.c.value('@DrugScheduleId','int') as DrugScheduleId,
	T.c.value('@SourceTypeId','int') as SourceTypeId,
	T.c.value('@QueueTypeId','int') as QueueTypeId,
	T.c.value('@StoreLocationId','int') as StoreLocationId,
	T.c.value('@IsAutoDispense','bit') as IsAutoDispense,
	T.c.value('@LocationId','int') as LocationId,
	T.c.value('@IsDirect','bit') as IsDirect,
	T.c.value('@Duration','nvarchar(50)') as Duration,
	T.c.value('@IsAllowDirectIssue','bit') as IsAllowDirectIssue,
	T.c.value('@OtherName','nvarchar(300)') as OtherName,
	T.c.value('@ExaminationDate','nvarchar(200)') as ExaminationDate, -- Nidhi Pandey; Mantis - 27787; DT - 04/10/2023
	null,null,null,null,null,null,null,null,null
	from @lxmlPrescription.nodes('/Examinations/Prescription')T(c)
	
	update w set p_ExaminationId = e_examinationid from @tblPrescription w
	inner join @tblExamination on e_ParticipantSourceId = p_ParticipantSourceId and e_ParticipantSourceTypeId = p_ParticipantSourceTypeId and e_Name = p_OtherName
	and e_ExaminationDate = p_ExaminationDate  -- Nidhi Pandey; Mantis - 27787; DT - 04/10/2023
	
	update w set w.p_StockBatchId = p.Id from @tblPrescription w inner join sProcurement.tStockBatch p
	on w.p_StockId = p.StockItemId and p.StoreLocationId = w.p_StoreLocationId and p.OrgId = @rOrgId
	and isnull(p.Number,'') = ''
	
	--select * from @tblPrescription

	declare @tblPrescriptionN table
	(
		tid int identity(1,1),p_ParticipantSourceId bigint,p_ParticipantSourceTypeId int,p_ExaminationId bigint
	)
	insert into @tblPrescriptionN
	select e_ParticipantSourceId,e_ParticipantSourceTypeId,e_examinationid from @tblExamination
	where e_ParticipantSourceId in (select p_ParticipantSourceId from @tblPrescription)
	and e_ParticipantSourceTypeId in (select p_ParticipantSourceTypeId from @tblPrescription)
	
	declare @lAutoDispense bit,@lDirect bit
	
	select top 1 @lAutoDispense = p_IsAutoDispense,@lDirect = p_IsDirect from @tblPrescription
	
	exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tPrescription', 0, 1, 1,@outNextNumber = @lNextNumber output	
	SET @lFromNextNumber = @lNextNumber - 1
	
	MERGE sExamination.tPrescription AS Target USING 
	(
		SELECT Id,p_ExaminationId,tid
		FROM @tblPrescriptionN TT LEFT JOIN sExamination.tPrescription T ON TT.p_ExaminationId = T.SourceId
	) AS Source ON Target.SourceId = Source.p_ExaminationId	
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,SourceTypeId,SourceId,Number,IsObsolete,CreatedUserId,CreatedDateTime,DoctorEmployeeId, --Nidhi Pandey; as suggested by Manthan Sir, dt - 3/07/2023
			IsDispensed,UpdatedDateTime,UpdatedUserId,Remark,OrgId,IsDirect
		)
		VALUES
		(
			@lFromNextNumber + tid,1002,p_ExaminationId,@lFromNextNumber + tid,
			0,@rCreatedUserId,sCommon.fGetDate(),@rUserSourceId,0,sCommon.fGetDate(),@rCreatedUserId,'',@rOrgId,@lDirect
		);
	
	update @tblPrescription set p_PrescriptionId = Id from sExamination.tPrescription where p_ExaminationId = SourceId
	
	select @lCount = COUNT(1) FROM @tblPrescriptionN
	SET @lNextNumber  = @lCount + @lFromNextNumber	
	exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tPrescription', @rCurrentNumber = @lNextNumber
	
	exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tPrescriptionDetail', 0, 1, 1,@outNextNumber = @lNextNumber output	
	SET @lFromNextNumber = @lNextNumber - 1
	
	MERGE sExamination.tPrescriptionDetail AS Target USING 
	(
		SELECT Id,p_PrescriptionId,p_StockId,p_FrequencyId,p_DrugQty,p_Dose,p_DrugFrequecyText,
		p_DrugInstruction,p_DrugScheduleId,p_ExaminationId,p_Duration,p_Quantity,p_IsAllowDirectIssue,
		p_IsNotStore,p_StoreLocationId,p_SourceTypeId,p_QueueTypeId,tid
		FROM @tblPrescription TT LEFT JOIN sExamination.tPrescriptionDetail T ON TT.p_PrescriptionId = T.PrescriptionId
		and TT.p_StockId = T.StockItemId
	) AS Source ON Target.PrescriptionId = Source.p_PrescriptionId and Target.StockItemId = Source.p_StockId	
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,PrescriptionId,StockItemId,DrugInstruction,Duration,Remark,
			PrescribedQuantity,IsDirectIssue,IsObsolete,CreateduserId,UpdatedUserId,
			IsDispensed,UpdatedDateTime,OrgId,DispensedQuantity,IsNotInStore,Dosage,
			DurgDosageQty,DrugDosageFrequencyId,DrugDosageScheduleId
		)
		VALUES
		(
			@lFromNextNumber + tid,p_PrescriptionId,p_StockId,p_DrugInstruction,1,'',
			p_Quantity,p_IsAllowDirectIssue,0,@rCreatedUserId,@rCreatedUserId,
			0,sCommon.fGetDate(),@rOrgId,0,p_IsNotStore,p_Dose,
			p_Dose,p_FrequencyId,p_DrugScheduleId
		);
	
	select @lCount = COUNT(1) FROM @tblPrescription 
	SET @lNextNumber  = @lCount + @lFromNextNumber	
	exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sExamination.tPrescriptionDetail', @rCurrentNumber = @lNextNumber
	
	update w set w.p_PrescriptionDetailId = p.Id from @tblPrescription w inner join sExamination.tPrescriptionDetail p
	on w.p_PrescriptionId = p.PrescriptionId and w.p_StockId = p.StockItemId
	
	if @lAutoDispense <> '0'
	begin
		--UPDATE PD SET PD.DispensedQuantity = p_Quantity
		--FROM sExamination.tPrescriptionDetail PD inner join @tblPrescription w ON PD.Id = w.p_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 @tblPrescription w ON PD.Id = w.p_PrescriptionDetailId
		where p_QueueTypeId = 2
		
		UPDATE e SET e.StatusId = 4 from sExamination.tExamination e inner join
		@tblPrescriptionN w on w.p_ExaminationId = e.Id
		
		update w set w.p_DispenseId = p.Id from @tblPrescription w inner join sPharmacy.tDispense p
		on w.p_PrescriptionDetailId = p.PrescriptionDetailId
		
		exec sCommon.pTableRowIdGet @rOrgId, 'sPharmacy.tDispense', 0, 1, 1,@outNextNumber = @lNextNumber output	
		SET @lFromNextNumber = @lNextNumber - 1
		
		MERGE sPharmacy.tDispense AS Target USING 
		(
			SELECT Id,p_PrescriptionDetailId,tid
			FROM @tblPrescription TT LEFT JOIN sPharmacy.tDispense T ON TT.p_PrescriptionDetailId = T.Id
		) AS Source ON Target.Id = Source.p_PrescriptionDetailId
		WHEN MATCHED THEN
			UPDATE SET PrescriptionDetailId = p_PrescriptionDetailId
		WHEN NOT MATCHED THEN
			INSERT
			(
				Id,PrescriptionDetailId,CreatedUserId,CreatedDateTime,OrgId
			)
			VALUES
			(
				@lFromNextNumber + tid,p_PrescriptionDetailId,@rCreatedUserId,sCommon.fGetDate(),@rOrgId
			);
			
		select @lCount = COUNT(1) FROM @tblPrescription
		SET @lNextNumber  = @lCount + @lFromNextNumber	
		exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sPharmacy.tDispense', @rCurrentNumber = @lNextNumber
		
		update w set w.p_DispenseId = p.Id from @tblPrescription w inner join sPharmacy.tDispense p
		on w.p_PrescriptionDetailId = p.PrescriptionDetailId
		
		update w set w.pp_RemainQty = (p.PrescribedQuantity - p.DispensedQuantity)
		from @tblPrescription w inner join sExamination.tPrescriptionDetail p on w.p_PrescriptionDetailId = p.Id
		
		update w set w.pp_AverageCost = WeightedAverageCost from @tblPrescription w
		inner join sIp.tStockItemPlanning p on w.p_StockId = p.StockItemId and w.p_StoreLocationId = p.StoreLocationId
		
		update @tblPrescription set pp_InwardValue = (pp_AverageCost * pp_RemainQty)
		
		update w set w.pp_DispenseBatchId = p.Id from @tblPrescription w inner join sPharmacy.tDispenseBatch p
		on w.p_DispenseId = p.DispenseId
		
		exec sCommon.pTableRowIdGet @rOrgId, 'sPharmacy.tDispenseBatch', 0, 1, 1,@outNextNumber = @lNextNumber output	
		SET @lFromNextNumber = @lNextNumber - 1
		
		MERGE sPharmacy.tDispenseBatch AS Target USING 
		(
			SELECT Id,p_StockBatchId,p_DispenseId,pp_RemainQty,pp_AverageCost,p_IsNotStore,tid
			FROM @tblPrescription TT LEFT JOIN sPharmacy.tDispenseBatch T ON TT.p_DispenseId = T.Id			
		) AS Source ON Target.Id = Source.p_DispenseId		
		WHEN NOT MATCHED THEN
			INSERT
			(
				Id,DispenseId,StockBatchId,Quantity,UnitCost,OrgId,ReturnQuantity
			)
			VALUES
			(
				@lFromNextNumber + tid,p_DispenseId,p_StockBatchId,
				pp_RemainQty,pp_AverageCost,@rOrgId,0
			);
			
		select @lCount = COUNT(1),@i = 1 FROM @tblPrescription
		SET @lNextNumber  = @lCount + @lFromNextNumber	
		exec sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sPharmacy.tDispenseBatch', @rCurrentNumber = @lNextNumber
		
		update w set w.pp_DispenseBatchId = p.Id from @tblPrescription w inner join sPharmacy.tDispenseBatch p
		on w.p_DispenseId = p.DispenseId
		
		while @i <= @lCount
		begin
			declare @rSourceTypeId int,@rSourceId bigint,@rItemSourceTypeId int,@rItemSourceId int,
			@rQuantity decimal(12,2),@rValue decimal(12,2),@rLocationId int,@rItemBatchId int,
			@rIsNotInStore bit			
			
			select @rSourceTypeId = 48,@rSourceId = pp_DispenseBatchId,@rItemSourceId = p_StockId,
			@rItemSourceTypeId = 34,@rQuantity = pp_RemainQty,@rValue = pp_InwardValue,@rStoreLocationId = p_StoreLocationId,
			@rLocationId = p_LocationId,@rItemBatchId = p_StockBatchId,@rIsNotInStore = p_IsNotStore
			from @tblPrescription where tid = @i
						
			if @rIsNotInStore = 0
			begin			
				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 inner join @tblPrescription w on P.Id = w.p_PrescriptionId
			end
			select @i = @i + 1
		end
	end
	
	declare @tblExaminationOPD table
	(
		tid int identity(1,1),e_ParticipantSourceId bigint,e_ParticipantSourceTypeId int,
		e_Name nvarchar(300),e_ExaminationId bigint,e_InTime nvarchar(20),e_OutTime nvarchar(20),e_FurtherActionId int,e_Pediatric bit
	)
	insert into @tblExaminationOPD
	select e_ParticipantSourceId,e_ParticipantSourceTypeId,e_Name,e_ExaminationId,e_InTime,e_OutTime,e_FurtherActionId,e_Pediatric from @tblExamination where e_ParticipantSourceTypeId = 1009
	--select * from @tblExaminationOPD
	MERGE sExamination.tOPD AS Target USING 
	(
		SELECT e_Name,e_ExaminationId,tid,e_InTime,e_OutTime,e_FurtherActionId,e_Pediatric
		FROM @tblExaminationOPD TT LEFT JOIN sExamination.tOPD T ON TT.e_examinationid = T.ExaminationId
	) AS Source ON Target.ExaminationId = Source.e_examinationid
	when Matched Then
	Update set 	OPDTime = e_InTime,OPDOutTime = e_OutTime,FurtherActionId = e_FurtherActionId , IsPediatric=e_Pediatric  
	WHEN NOT MATCHED THEN
		INSERT
		(
			ExaminationId,OtherName,OPDTime,OPDOutTime,FurtherActionId,IsPediatric,VisitTypeId
		)
		VALUES
		(
			e_ExaminationId,e_Name,e_InTime,e_OutTime,e_FurtherActionId,e_Pediatric,1
		);
	
	insert into @tblExaminationOPD
	select e_ParticipantSourceId,e_ParticipantSourceTypeId,e_Name,e_ExaminationId,e_InTime,e_OutTime,e_FurtherActionId,e_Pediatric from @tblExamination where e_ParticipantSourceTypeId != 1009
--	select * from @tblExaminationOPD
	MERGE sExamination.tOPD AS Target USING 
	(
		SELECT e_Name,e_ExaminationId,tid,e_InTime,e_OutTime,e_FurtherActionId,e_Pediatric
		FROM @tblExaminationOPD TT LEFT JOIN sExamination.tOPD T ON TT.e_examinationid = T.ExaminationId where TT.e_ParticipantSourceTypeId != 1009
	) AS Source ON Target.ExaminationId = Source.e_examinationid
	when Matched Then
	Update set 	OPDTime = e_InTime,OPDOutTime = e_OutTime,FurtherActionId = e_FurtherActionId, IsPediatric=e_Pediatric,FitnessStatus='-1'--0042109
	WHEN NOT MATCHED THEN
		INSERT
		(
			ExaminationId,OtherName,OPDTime,OPDOutTime,FurtherActionId,IsPediatric,FitnessStatus,VisitTypeId
		)
		VALUES
		(
			e_ExaminationId,'',e_InTime,e_OutTime,e_FurtherActionId,e_Pediatric,'-1',1
		);
	---MGMotor req
	

	

	MERGE sExamination.tVital AS Target USING 
	(
		SELECT Id,e_examinationid,tid,e_VitalRemark,e_Height,e_BodyWeight,e_Pulse,e_Temperature,e_SPO2,e_BloodPressureSystolic,e_BloodPressureDiastolic
		FROM @tblExamination TT LEFT JOIN sExamination.tVital T ON TT.e_examinationid = T.SourceId
	) AS Source ON Target.SourceId = Source.e_examinationid
	When MATCHED THEN
		UPDATE SET Remark = e_VitalRemark,
				Height = e_Height,
                BodyWeight = e_BodyWeight,
                Pulse = e_Pulse,
                Temperature = e_Temperature,
                SPo2 = e_SPO2,
				BloodPressureSystolic =e_BloodPressureSystolic,  
				BloodPressureDiastolic =e_BloodPressureDiastolic,
                BMI = CASE 
                 WHEN Source.e_Height IS NOT NULL AND Source.e_Height > 0
                      AND Source.e_BodyWeight IS NOT NULL AND Source.e_BodyWeight > 0
                 THEN CAST(
                         CASE 
                             WHEN (CAST(Source.e_BodyWeight AS DECIMAL(18,6)) /
                                   POWER(CAST(Source.e_Height AS DECIMAL(18,6)) / 100.0, 2)
                                  ) > 999.99
                             THEN 999.99
                             ELSE ROUND(
                                    CAST(Source.e_BodyWeight AS DECIMAL(18,6)) /
                                    POWER(CAST(Source.e_Height AS DECIMAL(18,6)) / 100.0, 2),
                                    2
                                  )
                         END AS DECIMAL(5,2)
                      )
                 ELSE BMI
              END

	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,SourceTypeId,SourceId,Remark,Height,BodyWeight,Pulse,Temperature,SPo2,BloodPressureSystolic,BloodPressureDiastolic,OrgId,IsObsolete,CreatedUserId,CreatedDateTime,BMI
		)
		VALUES
		(
			e_examinationid,1002,e_examinationid,e_VitalRemark,e_Height,e_BodyWeight,e_Pulse,e_Temperature,e_SPO2,e_BloodPressureSystolic,e_BloodPressureDiastolic,@rOrgId,0,@rCreatedUserId,sCommon.fGetDate()
			,  CASE 
            WHEN e_Height IS NOT NULL AND e_Height > 0
                 AND e_BodyWeight IS NOT NULL AND e_BodyWeight > 0
            THEN CAST(
                    CASE 
                        WHEN (CAST(e_BodyWeight AS DECIMAL(18,6)) /
                              POWER(CAST(e_Height AS DECIMAL(18,6)) / 100.0, 2)
                             ) > 999.99
                        THEN 999.99
                        ELSE ROUND(
                               CAST(e_BodyWeight AS DECIMAL(18,6)) /
                               POWER(CAST(e_Height AS DECIMAL(18,6)) / 100.0, 2),
                               2
                             )
                    END AS DECIMAL(5,2)
                 )
            ELSE 0
        END	);

	--exec sCommon.pTableRowIdGet @rOrgId, 'sExamination.tComplaint', 0, 1, 1,@outNextNumber = @lComplaintNextNumber output	
	
	MERGE sExamination.tComplaint AS Target USING 
	(
		SELECT Id,e_examinationid,tid,e_ComplaintRemark
		FROM @tblExamination TT LEFT JOIN sExamination.tComplaint T ON TT.e_examinationid = T.SourceId
	) AS Source ON Target.SourceId = Source.e_examinationid
	When MATCHED THEN
		UPDATE SET Remark = e_ComplaintRemark	
	WHEN NOT MATCHED THEN
		INSERT
		(
			Id,SourceTypeId,SourceId,Remark,OrgId,IsObsolete
		)
		VALUES
		(
			e_examinationid,1002,e_examinationid,e_ComplaintRemark,@rOrgId,0
		);
	
		 

	--MGmotor req end


	select '' as res
	select * from @tblExamination
	select * from @tblExaminationOPD	
end

GO

update [sExamination].[tOPD] set VisitTypeId = 1 where VisitTypeId is NULL

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 (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


ALTER PROC [sExamination].[pImportALLExaminationDatas]  
@rstrExaminationXML nvarchar(max),      
@rstrVitalXML nvarchar(max),      
@rstrDiseaseXML nvarchar(max),      
@rstrHabitXML nvarchar(max),      
@rstrHistoryXML nvarchar(max),      
@rstrDiagnosisXML nvarchar(max),      
@rstrTestXML nvarchar(max),      
@rMainTypeId int,      
@rstr nvarchar(50),      
@rstrGeneralXML nvarchar(max),      
@rstrPulmonary nvarchar(max) = null,      
@rstrAudiometry nvarchar(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 nvarchar(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 nvarchar(50),e_DoctorName nvarchar(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','nvarchar(200)') as Examination_Date,      
  T.c.value('@Doctor','nvarchar(200)') as Doctor,      
  T.c.value('@DoctorId','nvarchar(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 nvarchar(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(nvarchar(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(nvarchar(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 nvarchar(200),v_Weight nvarchar(200),      
   v_Pulse nvarchar(200),v_BPSys nvarchar(200),v_BPDia nvarchar(200),v_Respiration nvarchar(200),v_AbdominalGirth nvarchar(200),      
   v_ChestExpansion nvarchar(200),v_Waist nvarchar(200),v_Hip nvarchar(200),v_ElbowWidth nvarchar(200),v_Temperature nvarchar(200),      
   v_id bigint,v_NatureId int,v_examinationid bigint,v_SetupId int,v_OrgId int,v_Inhalation nvarchar(200),v_Exhalation nvarchar(200), v_Remark nvarchar(300)  
  )      
  insert into #tbltmpVitals      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@Height','nvarchar(200)') as Height,      
  T.c.value('@Weight','nvarchar(200)') as Weight,      
  T.c.value('@Pulse','nvarchar(200)') as Pulse,      
  T.c.value('@BPSys','nvarchar(200)') as BPSys,      
  T.c.value('@BPDia','nvarchar(200)') as BPDia,      
  T.c.value('@Respiration','nvarchar(200)') as Respiration,      
  T.c.value('@AbdominalGirth','nvarchar(200)') as AbdominalGirth,      
  T.c.value('@ChestExpansion','nvarchar(200)') as ChestExpansion,      
  T.c.value('@Waist','nvarchar(200)') as Waist,      
  T.c.value('@Hip','nvarchar(200)') as Hip,      
  T.c.value('@ElbowWidth','nvarchar(200)') as ElbowWidth,      
  T.c.value('@Temperature','nvarchar(200)') as Temperature,null,0,0,0,0,      
  T.c.value('@Inhalation','nvarchar(200)') as Inhalation,      
  T.c.value('@Exhalation','nvarchar(200)') as Exhalation,     
  T.c.value('@Vital_Remark','nvarchar(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 nvarchar(1000),      
   d_Recommendation nvarchar(1000),d_examinationid bigint,d_id bigint,d_date nvarchar(50)      
  )      
  insert into #tbltmpDiagnosis      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  T.c.value('@Diagnosis','nvarchar(200)') as Diagnosis,      
T.c.value('@Recommendation','nvarchar(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(nvarchar(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 nvarchar(200),h_Chewer nvarchar(200),h_Smoker nvarchar(200),      
   h_AlcoholSocial nvarchar(200),h_Drug nvarchar(200),h_AlcoholId int,h_ChewerId int,h_SmokerId int,h_AlcoholSocialId int,      
   h_DrugId int,h_ParticipantAraId bigint,h_AlcoholName nvarchar(200),h_ChewerName nvarchar(200),h_SmokerName nvarchar(200),      
   h_AlcoholSocialName nvarchar(200),h_DrugName nvarchar(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','nvarchar(200)') as Alcohol,      
  T.c.value('@Chewer','nvarchar(200)') as Chewer,      
  T.c.value('@Smoker','nvarchar(200)') as Smoker,      
  T.c.value('@AlcoholSocial','nvarchar(200)') as AlcoholSocial,      
  T.c.value('@Drug','nvarchar(200)') as Drug,0,0,0,0,0,null,      
  case T.c.value('@Alcohol','nvarchar(200)') when 'y' then 'Alcohol' when 'yes' then 'Alcohol' when '1' then 'Alcohol' else '' end,      
  case T.c.value('@Chewer','nvarchar(200)') when 'y' then 'Chewer' when 'yes' then 'Chewer' when '1' then 'Chewer' else '' end,      
  case T.c.value('@Smoker','nvarchar(200)') when 'y' then 'Smoker' when 'yes' then 'Smoker' when '1' then 'Smoker' else '' end,      
  case T.c.value('@AlcoholSocial','nvarchar(200)') when 'y' then 'Alcohol-Social' when 'yes' then 'Alcohol-Social' when '1' then 'Alcohol-Social' else '' end,      
  case T.c.value('@Drug','nvarchar(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 nvarchar(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 nvarchar(500),      
   d_ExaminationId bigint,d_OrgId int,d_AreaId int,d_ParticipantAreaId bigint,d_ExistingDiseaseId bigint,d_OtherDisease nvarchar(2000)      
  )      
  insert into #tbltmpDisease      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  replace(T.c.value('@ExistingDiseaseSelf','nvarchar(500)'),'+',',') as DiseaseSelf,0,0,0,0,null,    --mantis:0033673 by shivam(15/05/2024)  
replace(T.c.value('@ExistingOtherDiseaseSelf','nvarchar(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 nvarchar(200),      
  d_Name nvarchar(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 nvarchar(2000),h_Mother nvarchar(200),      
   h_Father nvarchar(200),h_Brother nvarchar(200),h_Sister nvarchar(200),h_Surgery nvarchar(2000),h_ExaminationId bigint,h_OrgId int,      
   h_ParticipantAreaId bigint,h_AreaId int,AreaName nvarchar(200),h_HistoryId bigint, h_TreatmentHistoryRemark nvarchar(2000),h_PastHistoryRemark nvarchar(2000),  
   h_PastMedicalHistorySelf nvarchar(2000),h_HistoryMother nvarchar(2000),h_HistoryFather nvarchar(2000)  
  )      
  insert into @tbltmpHistory      
  select T.c.value('@ParticipantSourceId','bigint') as ParticipantSourceId,      
  replace(T.c.value('@PastHistorySelf','nvarchar(2000)'),'+',',') as PastHistorySelf,      
  replace(T.c.value('@PastHistoryMother','nvarchar(200)'),'+',',') as PastHistoryMother,      
  replace(T.c.value('@PastHistoryFather','nvarchar(200)'),'+',',') as PastHistoryFather,      
  replace(T.c.value('@PastHistoryBrother','nvarchar(200)'),'+',',') as PastHistoryBrother,      
  replace(T.c.value('@PastHistorySister','nvarchar(200)'),'+',',') as PastHistorySister,      
  T.c.value('@PastSurgicalHistorySelf','nvarchar(2000)') as Surgery,0,0,null,null,'Past History',null,T.c.value('@TreatmentHistoryRemark','nvarchar(2000)') as TreatmentHistoryRemark      
  ,T.c.value('@PastHistoryRemark','nvarchar(2000)') as PastHistoryRemark,  
  T.c.value('@PastMedicalHistorySelf','nvarchar(2000)') as PastMedicalHistorySelf,  --mantis:0033673 by shivam(15/05/2024)  
  T.c.value('@HistoryMother','nvarchar(2000)') as HistoryMother, --Mantis: 0032861, Date: 13/04/2024 by Deval  
  T.c.value('@HistoryFather','nvarchar(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 nvarchar(200),ParticipantAreaId bigint,Name nvarchar(200),      
   h_Surgery nvarchar(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 nvarchar(200),ParticipantAreaId bigint,Name nvarchar(200),      
   h_Surgery nvarchar(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 nvarchar(200),ParticipantAreaId bigint,Name nvarchar(200),      
   h_Surgery nvarchar(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 nvarchar(200),ParticipantAreaId bigint,Name nvarchar(200),      
   h_Surgery nvarchar(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 nvarchar(200),ParticipantAreaId bigint,Name nvarchar(200),      
   h_Surgery nvarchar(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 nvarchar(300),t_Remark nvarchar(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','nvarchar(300)') as Result,      
  left(T.c.value('@Remark','nvarchar(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 (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 nvarchar(300),t_Remark nvarchar(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 nvarchar(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 nvarchar(300),@lHDLVal nvarchar(300),@lCHOLEVal nvarchar(300),@lTryVal nvarchar(300)     
   declare @lVLDL nvarchar(300)='',@lLDL nvarchar(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(nvarchar,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(nvarchar,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(nvarchar,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(nvarchar,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 nvarchar(1000),g_Rem nvarchar(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','nvarchar(1000)') as Result,      
  T.c.value('@Remark','nvarchar(1500)') as Remark,null,null,null,null,null      
  from @loXMLGeneral.nodes('/General/Clinic')T(c) where T.c.value('@Result','nvarchar(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 nvarchar(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 nvarchar(100),pl_Fev1 nvarchar(100),      
   pl_PEFR nvarchar(100),pl_FVCP nvarchar(100),pl_FEV1P nvarchar(100),pl_FEV3P nvarchar(100),pl_PEFP nvarchar(100),      
   pl_FEF2575P nvarchar(100),pl_FEF212P nvarchar(100),pl_FEF25P nvarchar(100),pl_FEF50P nvarchar(100),pl_FEF75P nvarchar(100),   
   pl_Fev6 nvarchar(100), pl_FEV6P nvarchar(100),  
   pl_SVCP nvarchar(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 nvarchar(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','nvarchar(100)') as FVC,      
  T.c.value('@FEV1','nvarchar(100)') as FEV1,      
  T.c.value('@PEFR','nvarchar(100)') as PEFR,      
  T.c.value('@FVCP','nvarchar(100)') as FVCP,      
  T.c.value('@FEV1P','nvarchar(100)') as FEV1P,      
  T.c.value('@FEV3P','nvarchar(100)') as FEV3P,      
  T.c.value('@PEFP','nvarchar(100)') as PEFP,      
  T.c.value('@FEF2575P','nvarchar(100)') as FEF2575P,      
  T.c.value('@FEF212P','nvarchar(100)') as FEF212P,      
  T.c.value('@FEF25P','nvarchar(100)') as FEF25P,      
  T.c.value('@FEF50P','nvarchar(100)') as FEF50P,      
  T.c.value('@FEF75P','nvarchar(100)') as FEF75P,      
  T.c.value('@FEV6','nvarchar(100)') as FEV6,  
  T.c.value('@FEV6P','nvarchar(100)') as FEV6P,  
  T.c.value('@SVCP','nvarchar(100)') as SVCP,      
  null,null,null,null,null,null,null,null,null,null,null,null,  
  T.c.value('@MVVP','nvarchar(100)') as MVVP,null,null,null,null,null,
  T.c.value('@PulmonaryRemark','nvarchar(100)') as PulmonaryRemark,
  T.c.value('@IntensityId','nvarchar(100)') as IntensityId,
  T.c.value('@IntensityResultId','nvarchar(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 nvarchar(max),a_AudioRightACIds nvarchar(max),      
   a_AudioLeftBCIds nvarchar(max),a_AudioRightBCIds nvarchar(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','nvarchar(10)') = 'y' or T.c.value('@By_Rule','nvarchar(10)') = 'yes' or T.c.value('@By_Rule','nvarchar(10)') = '1' then 1 else 0 end as By_Rule,      
  T.c.value('@AudioLeftACIds','nvarchar(max)') as e_AudioLeftACIds,      
  T.c.value('@AudioRightACIds','nvarchar(max)') as AudioRightACIds,      
  T.c.value('@AudioLeftBCIds','nvarchar(max)') as AudioLeftBCIds,      
  T.c.value('@AudioRightBCIds','nvarchar(max)') as AudioRightBCIds,      
  null,null,null,null,null,
  T.c.value('@LeftManualRemark','nvarchar(2000)') as LeftManualRemark,
  T.c.value('@RightManualRemark','nvarchar(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 nvarchar(max),e_AudioRightACIds nvarchar(max),      
   e_AudioLeftBCIds nvarchar(max),e_AudioRightBCIds nvarchar(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 nvarchar(100),      
  RightAcValue nvarchar(100),LeftBcValue nvarchar(100),RightBcValue nvarchar(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 nvarchar(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


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 (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


 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 (TestRequestId,TestDetailId)
  
GO


ALTER PROCEDURE [sProcurement].[pStockTransferAdd_New]
(
@rOrgId [int],
@rNumber Nvarchar(20) = '',
@rStockTransferRequestId Int=0, 
@rTransferredByName Nvarchar(100) = '',
@rFromStoreLocationId		Int,
@rToStoreLocationId			Int,
@rRemark Nvarchar(300),
@rCreatedUserId	BigInt,
@rDetail Nvarchar(Max)	,
@rLocationId int
 
)
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY

    BEGIN TRANSACTION

	DECLARE @loXML XML
	SET @loXML = CAST(@rDetail AS XML)
	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 25,@rStoreLocationId = @rFromStoreLocationId, @rNextNumber  = @rNumber OUTPUT

	
		SET @rNumber = ISNULL(@rNumber, '-300')

		IF @rNumber = '-300'
		BEGIN
		    IF @@TRANCOUNT > 0
					ROLLBACK TRANSACTION;

			SELECT -300 AS Result, '' AS Number, 0 AS Id ,0 as MainId
			RETURN
		END


		DECLARE @tStockTransferDetail TABLE
		(
			Id Int IDENTITY(1, 1),
			StockItemId Int,
			StockItemName nvarchar(100),
			TransferredQuantity Decimal(12,2),
			ItemBatch Nvarchar(300) NULL,
			RequestedQuantity Decimal(12,2)  ,
			StockBatchId int,
			ExpiryDate Datetime
		)	
		INSERT INTO @tStockTransferDetail
		SELECT
				T.c.value('@StockItemId','Int') AS StockItemId,
				T.c.value('@StockItemName','nvarchar(50)') As StockItemName,
				T.c.value('@TransferredQuantity','Nvarchar(300)') AS TransferredQuantity,
            
				  T.c.value('@ItemBatch','Nvarchar(300)') AS ItemBatch,
				T.c.value('@RequestedQuantity','Decimal(12,2)') AS RequestedQuantity , 
				 T.c.value('@StockBatchId','int') AS StockBatchId,
				 T.c.value('@ExpiryDate','Datetime') AS ExpiryDate 
		FROM 
				@loXML.nodes('/Root/StockTransferDetail')T(c)

  
		DECLARE @lNextNumberStockTransfer INT,@lNextNumberStockTransferBatch int
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockTransfer', 0, 1, 1,@outNextNumber = @lNextNumberStockTransfer output

		INSERT INTO sProcurement.tStockTransfer
		(
			Id,Number,StockTransferRequestId,FromStoreLocationId,ToStoreLocationId,TransferredByName,Remark,CreatedUserId,CreatedDateTime,OrgId 
		)
		VALUES
		(
			@lNextNumberStockTransfer,@rNumber,
			@rStockTransferRequestId,
			@rFromStoreLocationId,@rToStoreLocationId,@rTransferredByName,@rRemark,@rCreatedUserId,sCommon.fGetDate(),
			@rOrgId 
		)
            
		declare @lCount int,@lIsBatchWise bit,@lFrombatchId int,@lTobatchId int, @lNextNumberStockBatch int,@lExpiryDate date
		Declare @lItemId int,@lBatch nvarchar(300),@lTransferedQty decimal(12,2),@lTransferValue decimal(12,2),@lIdCount int
		DECLARE @lNextNumberStockTransferDetail BigInt,@lAvailbleQuantity decimal(12,2),@lWeightedAverageCost decimal(12,2),@lStockItemName nvarchar(50)
	
		select @lCount=COUNT(*) from @tStockTransferDetail 
		
		while @lcount > 0
		BEGIN
					 
			Select @lItemId =StockItemId,@lBatch = ItemBatch,@lTransferedQty=TransferredQuantity, @lIdCount=Id ,
			@lFrombatchId = StockBatchId,@lStockItemName=sSetup.fPortalXMLTagsReplaceReverse(StockItemName),@lExpiryDate=ExpiryDate,
			@lStockItemName = StockItemName
			from  @tStockTransferDetail WHERE Id = @lcount
		
			Select  @lWeightedAverageCost=ISNULL(WeightedAverageCost,0) from sIp.tStockItemPlanning    Where StockItemId = @lItemId AND StoreLocationId =  @rFromStoreLocationId  	
		
			Select @lIsBatchWise=IsBatchWiseTracking from sIp.tStockItemMaster    Where Id = @lItemId   
		 
			Select @lAvailbleQuantity=AvailableQuantity from sProcurement.tStockBatch WHERE Id = @lFrombatchId AND StockItemId = @lItemId AND  StoreLocationId =@rFromStoreLocationId
						
			if(@lAvailbleQuantity < @lTransferedQty)
			BEGIN
				 IF @@TRANCOUNT > 0
					ROLLBACK TRANSACTION;

				 SELECT -101 As Result, @lStockItemName as Number
				 RETURN
			END
			
			if(@lFrombatchId  <=0)
			BEGIN
			    IF @@TRANCOUNT > 0
					ROLLBACK TRANSACTION;

				SELECT -102 as Result, @lStockItemName as Number
				RETURN
			END
			 
			if(@lFrombatchId>0)
			BEGIN
				if Exists(Select Id from sProcurement.tStockTransferDetail   
				where  StockTransferId = @lNextNumberStockTransfer  and  StockItemId = @lItemId  )
			BEGIN
				Select @lNextNumberStockTransferDetail= Id from  sProcurement.tStockTransferDetail
				Where  StockTransferId = @lNextNumberStockTransfer AND StockIteMid =@lItemId
					 
			 END
			else
			BEGIN
		
	
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockTransferDetail', 0, 1, 1,@outNextNumber = @lNextNumberStockTransferDetail output
				 INSERT INTO sProcurement.tStockTransferDetail
				 (
				 Id,StockTransferId,StockItemId,TransferredQuantity,Remark,RequestedQuantity,  OrgId
				 )
				 SELECT @lNextNumberStockTransferDetail ,@lNextNumberStockTransfer,StockItemId,TransferredQuantity,@rRemark,
				 RequestedQuantity,   @rOrgId
				 from @tStockTransferDetail where Id=@lcount
			 
			
			END		
			SET @lTObatchId = 0
			if (@lIsBatchWise=1)
			BEGIN						
				Select @lTObatchId= Id from sProcurement.tStockBatch    
				Where  Number =@lBatch   AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId --AND @lIdCount=@lcount
				 
			END
			else 
			BEGIN
				Select @lTObatchId= Id from sProcurement.tStockBatch    
				Where ISNULL(Number,0) =0  AND  StoreLocationId = @rToStoreLocationId AND StockItemId = @lItemId--AND  @lIdCount=@lcount
			END
			if(ISNULL(@lTobatchId,0)=0)
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockBatch output
				INSERT INTO sProcurement.tStockBatch (Id,StoreLocationId,StockItemId,Number,ExpiryDate,AvailableQuantity,CreatedUserId,CreatedDateTime,OrgId,Price,IsDiscard)
				Select @lNextNumberStockBatch,@rToStoreLocationId,@lItemId,@lBatch,@lExpiryDate ,0,@rCreatedUserId,sCommon.fGetDate(),@rOrgId,0,0
				SET @lTobatchId = @lNextNumberStockBatch
			END 
			   EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sProcurement.tStockTransferBatch', 0, 1, 1,@outNextNumber = @lNextNumberStockTransferBatch output
				 
			   INsert into sProcurement.tStockTransferBatch (Id,StockTransferDetailId,FromStockBatchId,ToStockBatchId,Quantity,OrgId)
			   Select @lNextNumberStockTransferBatch,@lNextNumberStockTransferDetail, @lFrombatchId,@lTobatchId,@lTransferedQty,@rOrgID 
			   from @tStockTransferDetail where Id=@lcount
						
			   SET @lTransferValue = ISNULL(@lWeightedAverageCost,0) * ISNULL(@lTransferedQty,0)
						
			   Exec sIp.pWeightedAverageCostLogAdd_New @rOrgId =@rOrgId,@rSourceTypeId=52,@rSourceId=@lNextNumberStockTransferBatch,
					@rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lTransferedQty ,@rValue=@lTransferValue,@rIsReceipt=0,
					@rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rFromStoreLocationId ,@rLocationId=@rLocationId
					,@rStoreLocationClosingQuantity = 0,@rIsTransferReceipt=0,
					@rItemBatchId = @lFrombatchId,@rItemName = @lStockItemName  
						
						
				Exec sIp.pWeightedAverageCostLogAdd_New @rOrgId =@rOrgId,@rSourceTypeId=52,@rSourceId=@lNextNumberStockTransferBatch,
					 @rItemSourceTypeId = 34,@rItemSourceId=@lItemId,@rQuantity=@lTransferedQty ,@rValue=@lTransferValue,@rIsReceipt=1,
					 @rCreatedUserId = @rCreatedUserId,@rStoreLocationId = @rToStoreLocationId ,@rLocationId=@rLocationId
					 ,@rStoreLocationClosingQuantity = 0,@rIsTransferReceipt=1 ,
					 @rItemBatchId = @lTobatchId,@rItemName = @lStockItemName
			
		 END
				 set @lcount =@lcount-1
		  END

		COMMIT TRANSACTION
	
		SELECT 1 AS RESULT, @lStockItemName as StockItemName, @rNumber as Number, @lNextNumberStockTransfer as MainId
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION

    SELECT ERROR_NUMBER() AS Result,
           ERROR_MESSAGE() AS Number

END CATCH
END

GO


ALTER PROCEDURE [sExamination].[pImproveDeteriorateTestParameterGet]
@rEmployeeId bigint, 
@rSetup1Id int,  
@rSetup2Id int
AS
BEGIN
	DECLARE @rExamination1Id bigint, @rExamination2Id bigint, @rOrgId smallint;

	set @rOrgId = (select Top 1 Id from sCommon.tCompanyInformation where Id > 100)

	 DECLARE @BPConfig varchar(50)
	 SELECT @BPConfig = ISNULL(cm.ItemValue,pm.ItemValue)
	 FROM sConfig.tConfigurationMaster PM
	 LEFT JOIN sConfig.tConfigurationSetup CM ON CM.ConfigurationId = PM.Id
		AND SourceId = @rOrgId AND SourceTypeId = 1016
	 WHERE PM.Id = 170

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

	CREATE TABLE #SeverityResult
	(
		TestParameter VARCHAR(200),
		Round1 VARCHAR(100),
		Round2 VARCHAR(100),
		Severity1 INT NULL,
		Severity2 INT NULL
	);

	INSERT INTO #SeverityResult
	(
		TestParameter,
		Round1,
		Round2,
		Severity1,
		Severity2
	)
	SELECT
		'BMI',
		CAST(V1.BMI AS VARCHAR(100)),
		CAST(V2.BMI AS VARCHAR(100)),

		CASE
			WHEN BR1.Title = 'Normal' THEN 1
			WHEN BR1.Title IN ('Underweight','Overweight') THEN 2
			WHEN BR1.Title = 'Obese' THEN 3
			WHEN BR1.Title = 'Morbidly Obese' THEN 4
		END,

		CASE
			WHEN BR2.Title = 'Normal' THEN 1
			WHEN BR2.Title IN ('Underweight','Overweight') THEN 2
			WHEN BR2.Title = 'Obese' THEN 3
			WHEN BR2.Title = 'Morbidly Obese' THEN 4
		END
	FROM sExamination.tVital V1
	INNER JOIN sExamination.tVital V2
		ON 1 = 1
	LEFT JOIN sExamination.tBMIRangeMaster BR1
		ON V1.BMI BETWEEN BR1.FromRange AND BR1.ToRange
	   AND BR1.IsObsolete = 0
	LEFT JOIN sExamination.tBMIRangeMaster BR2
		ON V2.BMI BETWEEN BR2.FromRange AND BR2.ToRange
	   AND BR2.IsObsolete = 0
	WHERE V1.SourceId = @rExamination1Id
	AND V2.SourceId = @rExamination2Id;

	INSERT INTO #SeverityResult
	(
		TestParameter,
		Round1,
		Round2,
		Severity1,
		Severity2
	)
	SELECT
		'BloodPressure',
		CAST(BP1.BloodPressureSystolic AS NVARCHAR(50)) + '/' + CAST(BP1.BloodPressureDiastolic AS NVARCHAR(50)) AS BP1Value,
		CAST(BP2.BloodPressureSystolic AS NVARCHAR(50)) + '/' + CAST(BP2.BloodPressureDiastolic AS NVARCHAR(50)) AS BP2Value,
		CASE
			WHEN BP1.BPStatus IN ('Optimal','Normal') THEN 1
			WHEN BP1.BPStatus IN ('High Normal','PreHypertension','Hypotension') THEN 2
			WHEN BP1.BPStatus IN ('Stage I HTN','Hypertension') THEN 3
			WHEN BP1.BPStatus = 'Stage II HTN' THEN 4
			WHEN BP1.BPStatus IN ('Stage III HTN','Hypertension Crisis') THEN 5
		END,

		CASE
			WHEN BP2.BPStatus IN ('Optimal','Normal') THEN 1
			WHEN BP2.BPStatus IN ('High Normal','PreHypertension','Hypotension') THEN 2
			WHEN BP2.BPStatus IN ('Stage I HTN','Hypertension') THEN 3
			WHEN BP2.BPStatus = 'Stage II HTN' THEN 4
			WHEN BP2.BPStatus IN ('Stage III HTN','Hypertension Crisis') THEN 5
		END
	FROM
	(
		SELECT CASE WHEN @BPConfig = 'Diastolic'
				THEN
				(
					SELECT TOP 1 BRM.Title
					FROM sExamination.tBloodPressureRangeMaster BRM
					WHERE VTL.BloodPressureDiastolic BETWEEN BRM.FromRange AND BRM.ToRange
					AND BRM.IsObsolete = 0
				)
				WHEN @BPConfig = 'AHA'
				THEN
					CASE
						WHEN VTL.BloodPressureSystolic >= 180 
							 OR VTL.BloodPressureDiastolic >= 110
							THEN 'Hypertension Crisis'
						WHEN VTL.BloodPressureSystolic >= 140 
							 OR VTL.BloodPressureDiastolic >= 90
							THEN 'Hypertension'
						WHEN (VTL.BloodPressureSystolic BETWEEN 121 AND 139)
							 OR (VTL.BloodPressureDiastolic BETWEEN 81 AND 89)
							THEN 'PreHypertension'
						WHEN VTL.BloodPressureSystolic <= 90
							 OR VTL.BloodPressureDiastolic <= 60
							THEN 'Hypotension'
						WHEN (VTL.BloodPressureSystolic BETWEEN 91 AND 120)
							 AND (VTL.BloodPressureDiastolic BETWEEN 61 AND 80)
							THEN 'Normal'
					END
				ELSE
					CASE
						WHEN VTL.BloodPressureDiastolic >= 110
							 OR VTL.BloodPressureSystolic >= 180
							THEN 'Stage III HTN'
						WHEN (VTL.BloodPressureDiastolic BETWEEN 100 AND 109)
							 OR (VTL.BloodPressureSystolic BETWEEN 160 AND 179)
							THEN 'Stage II HTN'
						WHEN (VTL.BloodPressureDiastolic BETWEEN 90 AND 99)
							 OR (VTL.BloodPressureSystolic BETWEEN 140 AND 159)
							THEN 'Stage I HTN'
						WHEN (VTL.BloodPressureDiastolic BETWEEN 85 AND 89)
							 OR (VTL.BloodPressureSystolic BETWEEN 130 AND 139)
							THEN 'High Normal'
						WHEN (VTL.BloodPressureDiastolic BETWEEN 80 AND 84)
							 OR (VTL.BloodPressureSystolic BETWEEN 120 AND 129)
							THEN 'Normal'
						WHEN VTL.BloodPressureDiastolic < 80
							 AND VTL.BloodPressureSystolic < 120
							THEN 'Optimal'
					END
			END AS BPStatus, VTL.BloodPressureSystolic, VTL.BloodPressureDiastolic
		FROM sExamination.tVital VTL
		WHERE VTL.SourceId = @rExamination1Id
		AND ISNULL(VTL.BloodPressureSystolic,0) > 0 AND ISNULL(VTL.BloodPressureDiastolic,0) > 0
	) BP1
	CROSS JOIN
	(
	   SELECT CASE WHEN @BPConfig = 'Diastolic'
				THEN
				(
					SELECT TOP 1 BRM.Title
					FROM sExamination.tBloodPressureRangeMaster BRM
					WHERE VTL.BloodPressureDiastolic BETWEEN BRM.FromRange AND BRM.ToRange
					AND BRM.IsObsolete = 0
				)
				WHEN @BPConfig = 'AHA'
				THEN
					CASE
						WHEN VTL.BloodPressureSystolic >= 180 
							 OR VTL.BloodPressureDiastolic >= 110
							THEN 'Hypertension Crisis'
						WHEN VTL.BloodPressureSystolic >= 140 
							 OR VTL.BloodPressureDiastolic >= 90
							THEN 'Hypertension'
						WHEN (VTL.BloodPressureSystolic BETWEEN 121 AND 139)
							 OR (VTL.BloodPressureDiastolic BETWEEN 81 AND 89)
							THEN 'PreHypertension'
						WHEN VTL.BloodPressureSystolic <= 90
							 OR VTL.BloodPressureDiastolic <= 60
							THEN 'Hypotension'
						WHEN (VTL.BloodPressureSystolic BETWEEN 91 AND 120)
							 AND (VTL.BloodPressureDiastolic BETWEEN 61 AND 80)
							THEN 'Normal'
					END
				ELSE
					CASE
						WHEN VTL.BloodPressureDiastolic >= 110
							 OR VTL.BloodPressureSystolic >= 180
							THEN 'Stage III HTN'
						WHEN (VTL.BloodPressureDiastolic BETWEEN 100 AND 109)
							 OR (VTL.BloodPressureSystolic BETWEEN 160 AND 179)
							THEN 'Stage II HTN'
						WHEN (VTL.BloodPressureDiastolic BETWEEN 90 AND 99)
							 OR (VTL.BloodPressureSystolic BETWEEN 140 AND 159)
							THEN 'Stage I HTN'
						WHEN (VTL.BloodPressureDiastolic BETWEEN 85 AND 89)
							 OR (VTL.BloodPressureSystolic BETWEEN 130 AND 139)
							THEN 'High Normal'
						WHEN (VTL.BloodPressureDiastolic BETWEEN 80 AND 84)
							 OR (VTL.BloodPressureSystolic BETWEEN 120 AND 129)
							THEN 'Normal'
						WHEN VTL.BloodPressureDiastolic < 80
							 AND VTL.BloodPressureSystolic < 120
							THEN 'Optimal'
					END
			END AS BPStatus, VTL.BloodPressureSystolic, VTL.BloodPressureDiastolic
		FROM sExamination.tVital VTL
		WHERE VTL.SourceId = @rExamination2Id
		AND ISNULL(VTL.BloodPressureSystolic,0) > 0 AND ISNULL(VTL.BloodPressureDiastolic,0) > 0
	) BP2;

	CREATE TABLE #tbltmpTestDetail        
	 (        
	  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        
	 )
	 CREATE CLUSTERED INDEX IX_tbltmpTestDetail ON #tbltmpTestDetail(t_TestParameterId, t_ExaminationId, t_TestType, t_ParameterValueTypeId)

	 INSERT INTO #tbltmpTestDetail        
	 SELECT TPM.Id,TRD.ServiceValue,EP.DateOfBirth,EP.GenderId,TPM.ParameterValueTypeId,        
	 TPM.ListValueTypeId,1,DATEDIFF(yy,EP.DateOfBirth,GETDATE()),TRD.Id,ED.Id,
	 TPM.StaticTestParameterId        
	 FROM sExamination.tExamination ED        
	 INNER JOIN sHrm.tEmployeePersonalDetail EP ON ED.ParticipantSourceId = EP.EmployeeId        
	 INNER JOIN sExamination.tTestRequest TR ON ED.Id = TR.SourceId        
	 INNER JOIN sExamination.tTestRequestDetail TRD ON TR.Id = TRD.TestRequestId        
	 INNER JOIN sOrderEntry.tTestDetail TD ON TRD.TestDetailId = TD.Id        
	 INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TD.TestParameterId = TPM.Id        
	 WHERE ED.Id IN (@rExamination1Id, @rExamination2Id)        
	 AND TPM.ParameterValueTypeId IN (1, 2) AND TPM.IsObsolete = 0        
	 AND ISNULL(TRD.ServiceValue, '') <> ''

	Insert Into #SeverityResult
	SELECT T1.Title AS TestParameter,
			T1.ServiceValue AS Round1,
			T2.ServiceValue AS Round2,
		CASE WHEN EXISTS 
		(
			SELECT 1
			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) = 1 AND TD.t_ParameterValueTypeId = 1 AND t_TestType = 1        
			AND CONVERT(decimal(18, 9), t_ServiceValue) BETWEEN CAST(TPD.Minimum AS decimal(12, 4)) AND CAST(TPD.Maximum AS decimal(12, 4))
			AND LTRIM(RTRIM(t_ServiceValue)) <> '+' AND t_ServiceValue NOT LIKE '%e%' AND t_ServiceValue NOT LIKE '%E%'
			AND ISNUMERIC(t_ServiceValue) = 1 AND TD.t_ExaminationId = @rExamination1Id
			AND TPD.TestParameterId = T1.TestParameterId
		)
		THEN 1 WHEN T1.ServiceValue IN ('Normal','Negative') THEN 1 
		WHEN ISNULL(T1.ServiceValue,'') = '' THEN NULL ELSE 2 END,
		CASE WHEN EXISTS 
		(
			SELECT 1
			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) = 1 AND TD.t_ParameterValueTypeId = 1 AND t_TestType = 1        
			AND CONVERT(decimal(18, 9), t_ServiceValue) BETWEEN CAST(TPD.Minimum AS decimal(12, 4)) AND CAST(TPD.Maximum AS decimal(12, 4))
			AND LTRIM(RTRIM(t_ServiceValue)) <> '+' AND t_ServiceValue NOT LIKE '%e%' AND t_ServiceValue NOT LIKE '%E%'
			AND ISNUMERIC(t_ServiceValue) = 1 AND TD.t_ExaminationId = @rExamination2Id
			AND TPD.TestParameterId = T2.TestParameterId
		)
		THEN 1 WHEN T2.ServiceValue IN ('Normal','Negative') THEN 1 
		WHEN ISNULL(T2.ServiceValue,'') = '' THEN NULL ELSE 2 END
		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

	select *, CASE
		WHEN Severity1 = Severity2 THEN CASE WHEN Severity1 = 1 THEN '1' ELSE '2' END
		WHEN Severity2 < Severity1 THEN '1'
		WHEN Severity2 > Severity1 THEN '2'
		ELSE '3' END Status 
	from #SeverityResult

	DROP TABLE #tbltmpTestDetail
	DROP TABLE #SeverityResult
END

GO


BEGIN TRANSACTION

update [sExamination].[tStaticGeneralTemplateParameter] set NormalRange='0-100' 
where UCode = 'EYE_IntraOcularPressure'

IF @@ROWCOUNT = 1
    COMMIT TRANSACTION;
ELSE
    ROLLBACK TRANSACTION;

GO


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

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

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

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

GO