
CREATE OR ALTER VIEW [sAppointment].[vExtPatientAppointmentDetail]
AS  
SELECT     A.Id, A.AppointmentNumber, A.PatientSourceTypeId, A.PatientSourceId,   
                      CASE WHEN A.PatientSourceTypeId = 95 THEN EM.Id WHEN A.PatientSourceTypeId = 1009 THEN CSB.Id ELSE EFD.Id END AS DependentId,   
                      --CASE WHEN A.PatientSourceTypeId = 95 THEN (EM.FirstName + ISNULL(' ' + EM.MiddleName, '') + ' ' + EM.LastName)   
                      --WHEN A.PatientSourceTypeId = 1009 THEN CASE WHEN isnull(A.OtherName,'') <> '' then A.OtherName else (CSB.FirstName + ISNULL(' ' + CSB.MiddleName, '') + ' ' + CSB.LastName) end ELSE EFD.Name END AS PatientName,
					 
    CASE 
        WHEN A.PatientSourceTypeId = 95 THEN
            LTRIM(RTRIM(
                ISNULL(EM.FirstName,'') +
                CASE WHEN ISNULL(EM.MiddleName,'') <> '' THEN ' ' + EM.MiddleName ELSE '' END +
                CASE WHEN ISNULL(EM.LastName,'') <> '' THEN ' ' + EM.LastName ELSE '' END
            ))
        WHEN A.PatientSourceTypeId = 1009 THEN
            CASE 
                WHEN ISNULL(A.OtherName,'') <> '' THEN A.OtherName
                ELSE LTRIM(RTRIM(
                    ISNULL(CSB.FirstName,'') +
                    CASE WHEN ISNULL(CSB.MiddleName,'') <> '' THEN ' ' + CSB.MiddleName ELSE '' END +
                    CASE WHEN ISNULL(CSB.LastName,'') <> '' THEN ' ' + CSB.LastName ELSE '' END
                ))
            END
        ELSE EFD.Name
    END AS PatientName,
                      A.AppointmentDate, A.FromTime, A.ToTime, A.DoctorEmployeeId, A.StoreLocationId, A.SetupId,   
                      CASE WHEN A.PatientSourceTypeId = 95 THEN EM.Code WHEN A.PatientSourceTypeId = 1009 THEN CSB.Code ELSE EM2.Code END AS EmployeeCode,   
                      CASE WHEN A.PatientSourceTypeId = 95 THEN EM.Id WHEN A.PatientSourceTypeId = 1009 THEN CSB.Id ELSE EFD.Id END AS EmployeeId,   
                      CASE WHEN A.PatientSourceTypeId = 95 THEN 'Self' WHEN A.PatientSourceTypeId = 1009 THEN 'Other' ELSE RM.Title END AS Relation,   
                      CASE WHEN A.PatientSourceTypeId = 95 THEN ISNULL(GM.Title, '') WHEN A.PatientSourceTypeId = 1009 THEN ISNULL(GM2.Title, '')   
                      ELSE CASE WHEN ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId), '') = '' THEN  
                      (select Title from sCommon.tGenderMaster where Id = EFD.GenderId) ELSE  
                      ISNULL([sCommon].[fGenderFromRelationIdGet](EFD.RelationshipId), '') END END AS Gender,   
                      CASE WHEN A.PatientSourceTypeId = 95 THEN EJD.EmployeeLocationId WHEN A.PatientSourceTypeId = 1009 THEN CSB.LocationId ELSE EJD1.EmployeeLocationId END  
                       AS LocationId, EM1.FirstName + ' ' + EM1.LastName AS DoctorName, A.OrgId, A.IsRegister, A.IsObsolete,   
                      ODM.Title AS DepartmentName, ODM.Id AS DepartmentId, SM.Title AS StatusName, SLM.Title AS StoreLocation, VSM.MainTypeId AS ExaminationTypeId,   
                      VSM.MainType, VSM.Title AS Setup, A.ReferSourceId, CASE A.PatientSourceTypeId WHEN 95 THEN ISNULL(EJD.EmployeeStoreLocationId, 0)   
                      WHEN 1001 THEN ISNULL(EJD1.EmployeeStoreLocationId, 0) END AS EmployeeStoreLocationId,  
                      A.CauseId,A.OtherName,A.FollowupRemark,A.CompliantRemark,isnull(A.Age,0) as Age,isnull(A.Months,0) as Months,  
                      isnull(A.GenderId,0) as GenderId,  
                      isnull(A.ExaminationId,0) as ExaminationId,  
       (Left(convert(varchar,TSM.FromTime,108),5) + '-' + Left(convert(varchar,TSM.ToTime,108),5)) as TimeSlot,  
       A.ApprovalStatusId,ISNULL(A.AppointmentType,0) as AppointmentType,
	   ISNULL(A.AppointmentFlag,'New Appointment')AS AppointmentFlag
FROM         sAppointment.tAppointment AS A  
       LEFT JOIN sHrm.tEmployeeFamilyDetails AS EFD ON A.PatientSourceId = EFD.Id AND A.PatientSourceTypeId = 1001  
                      LEFT JOIN sHrm.tEmployeeMaster AS EM2 ON EM2.Id = EFD.EmployeeId AND A.PatientSourceTypeId = 1001  
                      LEFT JOIN sHrm.tEmployeeMaster AS EM ON (EM.Id = A.PatientSourceId OR EM.Id = EFD.EmployeeId) AND A.PatientSourceTypeId = 95  
                      LEFT JOIN sHrm.tCsrBenefiterMaster AS CSB ON CSB.Id = A.PatientSourceId AND A.PatientSourceTypeId = 1009  
                      LEFT JOIN sHrm.tEmployeePersonalDetail AS EPD ON EPD.EmployeeId = EM.Id  
                      LEFT JOIN sCommon.tGenderMaster AS GM ON GM.Id = EPD.GenderId  
                      LEFT JOIN sCommon.tGenderMaster AS GM2 ON GM.Id = CSB.GenderId  
                      LEFT JOIN sCommon.tStatusMaster AS SM ON SM.Id = A.StatusId  
                      LEFT JOIN sHrm.tEmployeeMaster AS EM1 ON EM1.Id = A.DoctorEmployeeId  
                      LEFT JOIN sCommon.tRelationshipMaster AS RM ON RM.Id = EFD.RelationshipId  
                      LEFT JOIN sHrm.tEmployeeJobDetail AS EJD ON EJD.EmployeeId = EM.Id  
                      LEFT JOIN sHrm.tEmployeeJobDetail AS EJD1 ON EJD1.EmployeeId = EFD.EmployeeId  
                      LEFT JOIN sCommon.tOrganizationDepartmentMaster AS ODM ON ODM.Id = EJD.OrganizationDepartmentId  
                      INNER JOIN sIp.tStoreLocationMaster AS SLM ON SLM.Id = A.StoreLocationId  
                      INNER JOIN sExamination.vExtSetupMaster AS VSM ON VSM.Id = A.SetupId  
       LEFT JOIN sAppointment.tTimeSlotMaster TSM On TSM.Id=A.TimeslotId  
GO

GO


ALTER FUNCTION [sCommon].[fn_ConvertToIST]
(
    @DateTime DATETIME
)
RETURNS NVARCHAR(20)
AS
BEGIN
    DECLARE @ISTDateTime DATETIME

    -- Add 5 hours 30 minutes to convert UTC to IST
    SET @ISTDateTime = DATEADD(MINUTE, 330, @DateTime)

    -- Return formatted string yyyy-MM-dd HH:mm:ss
    RETURN ISNULL(
        CONVERT(NVARCHAR(20), @ISTDateTime, 120), -- 120 = ODBC canonical yyyy-mm-dd hh:mi:ss
        '-'
    )
END

GO


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

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


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

	-----

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

    
    -- Clean up
    DROP TABLE #tempTable;
    DROP TABLE #tempFuntionTable;
    DROP TABLE #tmpMenzerIndex;
    DROP TABLE #tempDiabeticProfileServiceValues;
    DROP TABLE #tempFBSTable;
END

GO


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

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

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

-- Execute the dynamic SQL
EXEC sp_executesql @SQL;

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

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

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

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

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

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

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

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

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

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




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

GO


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

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

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

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

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

	    END as RestAdviseStatus,

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

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

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

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

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

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

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

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

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

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

GO


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

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

DECLARE @FinalSelectColumns NVARCHAR(MAX);

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

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

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

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

GO

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

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

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

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

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

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

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

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

    ORDER BY [Date of Use];

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

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

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

    ORDER BY [Date of Use];

END

GO


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

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

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

   DECLARE @rIsDiabetic bit = 0, @rIsDiabeticExisting bit = 0, @rIsHypertension bit = 0 , @rIsHypertensionExisting bit = 0;
	 set @rIsDiabetic = (select top 1 1 from @tbltmpDiagnosis where d_DiagnosisRemark = 'Diabetic' and d_ExaminationId = @lExaminationId)
	 set @rIsDiabeticExisting = (select top 1 1 from @tbltmpDiagnosis where d_DiagnosisRemark = 'Diabetic ( Existing )' and d_ExaminationId = @lExaminationId)
	 set @rIsHypertension = (select top 1 1 from @tbltmpDiagnosis where (d_DiagnosisRemark = 'Hypertension' or d_DiagnosisRemark = 'Stage I HTN' or d_DiagnosisRemark = 'Stage II HTN' 
																		or d_DiagnosisRemark = 'Stage III HTN' or d_DiagnosisRemark = 'Hypertension Crisis') and d_ExaminationId = @lExaminationId)
	 set @rIsHypertensionExisting = (select top 1 1 from @tbltmpDiagnosis where d_DiagnosisRemark = 'Hypertension ( Existing )' and d_ExaminationId = @lExaminationId)

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

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

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

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

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

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

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

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

GO


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

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

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

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

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

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

	--DROP TABLE #dummy;

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

GO


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

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

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

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

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

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

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

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

  Declare @lAudiometryResultRemarkManualConf nvarchar(10);

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

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

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

GO


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

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

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

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

GO

ALTER PROCEDURE [sHospitalization].[pGetDoctorHospitalizationDataForDashboard]  
    @rFromDate NVARCHAR(50) = NULL,  
    @rToDate NVARCHAR(50) = NULL,  
    @rDoctorId NVARCHAR(50) = NULL,  
    @rStatus NVARCHAR(50) = NULL,  
 @rState NVARCHAR(50) = NULL,  
    @rOrgId BIGINT = NULL  
AS  
BEGIN  
    SET NOCOUNT ON;  
    
    -------------------------------------------------------------  
    -- 🔄 STEP 0: Convert Empty Strings ('') to NULL  
    -------------------------------------------------------------  
    IF @rFromDate = '' SET @rFromDate = NULL;  
    IF @rToDate = '' SET @rToDate = NULL;  
    IF @rDoctorId = '' OR @rDoctorId = '0' SET @rDoctorId = NULL;  
    IF @rStatus = '' SET @rStatus = NULL;  
 IF @rState = '' SET @rState = NULL;     
  
   -- IF @rOrgId IS NULL SET @rOrgId = 9999;  
  
    -------------------------------------------------------------  
    -- 🔄 STEP 1: Convert NVARCHAR date inputs to DATE  
    -------------------------------------------------------------  
    --DECLARE @FromDateConverted DATE = TRY_CAST(@rFromDate AS DATE);  
    --DECLARE @ToDateConverted DATE = TRY_CAST(@rToDate AS DATE);  
    --DECLARE @DoctorIdConverted BIGINT = TRY_CAST(@rDoctorId AS BIGINT);  
  
 -------------------------------------------------------------  
-- STEP 1: Convert NVARCHAR date inputs to DATE (dd/MM/yyyy)  
-------------------------------------------------------------  
DECLARE @FromDateConverted DATE = NULL;  
DECLARE @ToDateConverted DATE = NULL;  
DECLARE @DoctorIdConverted BIGINT = TRY_CAST(@rDoctorId AS BIGINT);  
  
-- Convert FromDate  
IF (@rFromDate IS NOT NULL AND @rFromDate <> '')  
BEGIN  
    SET @FromDateConverted = CONVERT(DATE, @rFromDate, 103);  
END  
  
-- Convert ToDate  
IF (@rToDate IS NOT NULL AND @rToDate <> '')  
BEGIN  
    SET @ToDateConverted = CONVERT(DATE, @rToDate, 103);  
END  
  
-- Swap if reversed  
IF (@FromDateConverted IS NOT NULL AND @ToDateConverted IS NOT NULL  
    AND @FromDateConverted > @ToDateConverted)  
BEGIN  
    DECLARE @tmp DATE = @FromDateConverted;  
    SET @FromDateConverted = @ToDateConverted;  
    SET @ToDateConverted = @tmp;  
END  
  
  
    -------------------------------------------------------------  
    -- 🧹 STEP 2: Prepare base data  
    -------------------------------------------------------------  
    IF OBJECT_ID('tempdb..#BaseData') IS NOT NULL  
        DROP TABLE #BaseData;  
  
    SELECT   
        TD.Id,  
        TD.OrgId,  
        TD.BeneficiaryName,  
        TD.DateOfIntimation,  
        TD.DateOfAdmission,  
		  CASE 
        WHEN TD.ParticipantSourceId IS NULL 
         AND TD.ParticipantSourceTypeId IS NULL 
            THEN 'Non-Oracle'
        ELSE 'Oracle'
    END AS OracleNonOracleType,

        TD.DateOfDischarge,  
        TD.ClaimType,  
        TD.IntimationNumber,  
        TD.StatusOfIntimation,  
        TD.NetworkCity,  
        TD.State,  
        SM.StateName,  
        TD.HospitalName,  
        TD.Age,  
        TD.Relation,  
        TD.ProposerName,  
        TD.NatureOfIllness,  
        TD.TicketStatus,  
        TD.AssignedDoctorId,  
        ISNULL(  
            CASE   
                WHEN ISNULL(EM.EmployeePrefix, '') = ''   
                    THEN EM.FirstName + ' ' + ISNULL(EM.LastName, '')  
                ELSE EM.EmployeePrefix + ' ' + EM.FirstName + ' ' + ISNULL(EM.LastName, '')  
            END,   
        'Unassigned') AS DoctorName,  
        TD.TicketNumber,  
        TD.TicketOpenDate,  
        TD.ModeOfStatus,  
        TD.Grade,  
        TD.GroupCode,  
        TD.AdmissionType,  
        CASE   
            WHEN TD.EstimatedAmount IS NOT NULL   
                 AND TD.EstimatedAmount != ''  
                 AND ISNUMERIC(REPLACE(REPLACE(TD.EstimatedAmount, ',', ''), '.', '')) = 1  
            THEN TRY_CAST(REPLACE(TD.EstimatedAmount, ',', '') AS DECIMAL(18,2))  
            ELSE NULL   
        END AS EstimatedAmount,  
        TD.NetworkStatus,  
        TD.IsObsolete,  
        TD.Remarks,  
        TD.CreatedDateTime,  
		  SCT.Title AS Business,
        DATEDIFF(DAY, TD.TicketOpenDate, ISNULL(TD.DateOfDischarge, GETDATE())) AS AgeingDays,  
        CASE   
            WHEN TD.TicketStatus = 'Close' THEN 'Close'  
       WHEN TD.TicketStatus = 'New'   THEN 'New'  
            ELSE 'Open'  
        END AS StatusCategory  
    INTO #BaseData  
    FROM sHospitalization.tIntimationDetails TD  
    LEFT JOIN sHospitalization.tStateMaster SM  
        ON SM.StateName = TD.State AND SM.OrgId = TD.OrgId  
    LEFT JOIN sHrm.tEmployeeMaster EM  
        ON EM.Id = TD.AssignedDoctorId  
		        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD   
            ON ECD.EmployeeId = EM.Id  
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD   
            ON EJD.EmployeeId = EM.Id  
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM   
            ON ETM.Id = EJD.EmployeeTypeId  
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM   
            ON ECM.Id = EJD.EmployeeCompanyId  
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM   
            ON CGM.Id = ECM.CompanyGroupId  
        LEFT JOIN [sHrm].[tVerticalMaster] VTM   
            ON VTM.Id = CGM.VerticalId  
        LEFT JOIN [sHrm].[tSectorMaster] SCT   
            ON SCT.Id = VTM.SectorId  
        Left JOIN [sCommon].[tLocationMaster] LM   
            ON LM.Id = EJD.EmployeeLocationId  
    WHERE   
        TD.OrgId = @rOrgId  
        AND TD.IsObsolete = 0  
AND (  
        @FromDateConverted IS NULL   
        OR CAST(TD.DateOfIntimation AS DATE) >= @FromDateConverted  
    )  
AND (  
        @ToDateConverted IS NULL   
        OR CAST(TD.DateOfIntimation AS DATE) <= @ToDateConverted  
    )  
  
  
        AND (@DoctorIdConverted IS NULL OR TD.AssignedDoctorId = @DoctorIdConverted)  
        AND (@rStatus IS NULL OR @rStatus = '0' OR TD.TicketStatus = @rStatus)  
   And (@rState IS NULL OR @rState = '0' OR TD.State = @rState)  
  
  
  
-- select @rState  
  
    -------------------------------------------------------------  
    -- 🧾 STEP 3: Summary Data  
    -------------------------------------------------------------  
    IF OBJECT_ID('tempdb..#SummaryData') IS NOT NULL  
        DROP TABLE #SummaryData;  
  
    SELECT   
        COUNT(DISTINCT Id) AS TotalCases,  
        COUNT(DISTINCT AssignedDoctorId) AS TotalDoctors,  
        COUNT(DISTINCT State) AS TotalStates,  
        COUNT(DISTINCT HospitalName) AS TotalHospitals,  
        SUM(CASE WHEN StatusCategory = 'Close' THEN 1 ELSE 0 END) AS ClosedCases,  
        SUM(CASE WHEN StatusCategory = 'Open' THEN 1 ELSE 0 END) AS OpenCases,  
        CAST(AVG(EstimatedAmount) AS DECIMAL(18,2)) AS AverageEstimatedAmount,  
        CAST(SUM(EstimatedAmount) AS DECIMAL(18,2)) AS TotalEstimatedAmount,  
        CAST(SUM(CASE WHEN StatusCategory = 'Close' THEN 1 ELSE 0 END) * 100.0 / NULLIF(COUNT(DISTINCT Id), 0) AS DECIMAL(5,2)) AS ClosureRate  
    INTO #SummaryData  
    FROM #BaseData;  
  
  
    -------------------------------------------------------------  
    -- 📊 STEP 4: Result Sets  
    -------------------------------------------------------------  
  
    -- 1️⃣ Monthly Trend Data  
    SELECT   
        FORMAT(DateOfIntimation, 'yyyy-MM') AS MonthYear,  
        FORMAT(DateOfIntimation, 'MMM yyyy') AS MonthYearDisplay,  
        COUNT(Id) AS CaseCount  
    FROM #BaseData  
    WHERE DateOfIntimation IS NOT NULL  
    GROUP BY FORMAT(DateOfIntimation, 'yyyy-MM'), FORMAT(DateOfIntimation, 'MMM yyyy')  
    ORDER BY MonthYear;  
  
    -- 2️⃣ Status Summary (Pie Chart)  
    SELECT   
        TicketStatus,  
        COUNT(Id) AS StatusCount,  
        CASE   
            WHEN TicketStatus = 'New' THEN '#36A2EB'  
            WHEN TicketStatus = 'Open' THEN '#FF6384'  
            WHEN TicketStatus = 'Close' THEN '#4BC0C0'  
            ELSE '#9966FF'  
        END AS ColorCode  
    FROM #BaseData  
    GROUP BY TicketStatus  
    ORDER BY StatusCount DESC;  
  
    -- 3️⃣ Doctor-wise Beneficiary Count  
    SELECT   
        DoctorName,  
        COUNT(Id) AS BeneficiaryCount  
    FROM #BaseData  
    WHERE DoctorName IS NOT NULL  
    GROUP BY DoctorName  
    ORDER BY BeneficiaryCount DESC;  
  
   -- 4️⃣ Open Cases Ageing Analysis (0-7, 8-15, 16-30 Days)
SELECT
    AgeingCategory,
    TotalCases
FROM (
    SELECT
        CASE
            WHEN AgeingDays <= 7  THEN '0-7 Days'
            WHEN AgeingDays <= 15 THEN '8-15 Days'
            WHEN AgeingDays <= 30 THEN '16-30 Days'
            ELSE 'Above 30 Days'
        END AS AgeingCategory,
        COUNT(*) AS TotalCases,
        CASE
            WHEN AgeingDays <= 7  THEN 1
            WHEN AgeingDays <= 15 THEN 2
            WHEN AgeingDays <= 30 THEN 3
            ELSE 4
        END AS SortOrder
    FROM #BaseData
    WHERE StatusCategory = 'Open'
    GROUP BY
        CASE
            WHEN AgeingDays <= 7  THEN '0-7 Days'
            WHEN AgeingDays <= 15 THEN '8-15 Days'
            WHEN AgeingDays <= 30 THEN '16-30 Days'
            ELSE 'Above 30 Days'
        END,
        CASE
            WHEN AgeingDays <= 7  THEN 1
            WHEN AgeingDays <= 15 THEN 2
            WHEN AgeingDays <= 30 THEN 3
            ELSE 4
        END
) AS AgedData
ORDER BY SortOrder;

  
    -- 5️⃣ Summary Statistics  
    SELECT   
        TotalCases,  
        TotalDoctors,  
        TotalStates,  
        TotalHospitals,  
        ClosedCases,  
        OpenCases,  
        ClosureRate,  
        AverageEstimatedAmount,  
        TotalEstimatedAmount  
    FROM #SummaryData;  
  
    -- 6️⃣ State-wise Distribution  
    SELECT   
        ISNULL(StateName, 'Unknown') AS StateName,  
        COUNT(Id) AS CaseCount  
    FROM #BaseData  
    GROUP BY ISNULL(StateName, 'Unknown')  
    ORDER BY CaseCount DESC;  
  
    -- 7️⃣ Hospital-wise Distribution  
    SELECT   
        ISNULL(HospitalName, 'Unknown') AS HospitalName,  
        COUNT(Id) AS CaseCount  
    FROM #BaseData  
    GROUP BY ISNULL(HospitalName, 'Unknown')  
    ORDER BY CaseCount DESC;  
  
    -- 8️⃣ Claim Type Distribution  
    SELECT   
        ISNULL(ClaimType, 'Unknown') AS ClaimType,  
        COUNT(Id) AS CaseCount  
    FROM #BaseData  
    GROUP BY ISNULL(ClaimType, 'Unknown')  
    ORDER BY CaseCount DESC;  

     
     -- 8️⃣ Oracle vs Non-Oracle Distribution
     SELECT   
         OracleNonOracleType AS OracleandNonOracleChartType,
         COUNT(Id) AS CaseCount
     FROM #BaseData
     GROUP BY OracleNonOracleType
     ORDER BY CaseCount DESC;

      -- 9️⃣ Business-wise Distribution
      SELECT   
          ISNULL(Business, 'Unknown') AS Business,
          COUNT(Id) AS CaseCount
      FROM #BaseData
      GROUP BY ISNULL(Business, 'Unknown')
      ORDER BY CaseCount DESC;
      
  
  
    -------------------------------------------------------------  
    -- 🧹 Clean up  
    -------------------------------------------------------------  
    DROP TABLE #BaseData;  
    DROP TABLE #SummaryData;  
  
END;

GO

ALTER PROCEDURE [sHospitalization].[pIntimationDetailsListReviewGet]      
(      
    @rOrgId SMALLINT,      
    @rFromDate NVARCHAR(50) = NULL,      
    @rToDate NVARCHAR(50) = NULL,      
    @rDoctorId BIGINT = 0,      
    @rStatusId VARCHAR(50) = 0,      
    @rCodeLike NVARCHAR(MAX) = ''      
)      
AS      
BEGIN      
    SET NOCOUNT ON;      
    SET DATEFORMAT dmy;      
      
    DECLARE       
        @FromDate DATETIME = NULL,      
        @ToDate DATETIME = NULL;      
      
DECLARE @StatusIds TABLE (Id INT);      
      
INSERT INTO @StatusIds (Id)      
SELECT T.X.value('.', 'INT')      
FROM (      
    SELECT CAST(      
        '<x>' + REPLACE(@rStatusId, ',', '</x><x>') + '</x>'      
        AS XML      
    ) AS XmlData      
) A      
CROSS APPLY XmlData.nodes('/x') AS T(X);      
      
      
      
    -- Map rStatusId to text      
    --DECLARE @StatusText NVARCHAR(20) = NULL;      
    --IF @rStatusId = 1 SET @StatusText = 'New';      
    --IF @rStatusId = 2 SET @StatusText = 'Open';      
    --IF @rStatusId = 3 SET @StatusText = 'Close';      
 --IF @rStatusId = 4 SET @StatusText = 'New & Open';      
      
    -----------------------------------------      
    -- ✅ SQL 2008/2012 SAFE DATE CONVERSION      
    -----------------------------------------      
    IF (@rFromDate IS NOT NULL AND @rFromDate <> '')      
        SET @FromDate = CONVERT(DATETIME, @rFromDate, 103);  -- FORCES DD/MM/YYYY      
      
    IF (@rToDate IS NOT NULL AND @rToDate <> '')      
        SET @ToDate = DATEADD(DAY, 1, CONVERT(DATETIME, @rToDate, 103));  -- include full day      
      
    -----------------------------------------      
    -- If no code, make it empty      
    -----------------------------------------      
    IF (ISNULL(@rCodeLike, '') = '') SET @rCodeLike = '';      
      
    BEGIN TRY      
        SELECT       
            TD.Id AS IntimationId,      
            TD.EmpCode AS EmployeeCode,      
            TD.BeneficiaryName,      
            TD.Relation,      
            --TD.Age,      
       CASE       
        WHEN UPPER(ISNULL(TD.Relation, '')) = 'SELF'      
             AND VEMDS.EmployeeId = TD.ParticipantSourceId      
            THEN ISNULL(VEMDS.Age, TD.Age)      
        ELSE TD.Age      
    END AS Age,      
            TD.HospitalName,      
            TD.NetworkCity,      
            TD.State,      
            TD.StatusOfIntimation,      
            TD.TypeOfIntimation,      
            TD.FIRNo,      
            TD.CreatedDateTime,      
            TD.TicketStatus AS StatusName,      
            TD.Grade AS Grade,      
            TD.NatureOfIllness,      
            TD.IntimationNumber,      
            TD.ClaimType,      
            TD.DateOfIntimation,      
            TD.DateOfAdmission,      
            TD.DateOfDischarge,      
            TD.TicketNumber,      
            TD.Remarks,      
      
            ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS AssignedDoctor,      
            --AD.DesignationId,      
   EMDS.id as DesignationId,      
          -- ISNULL(VEMDS.FirstName, '') + ' ' + ISNULL(VEMDS.LastName, '') AS EmployeeName,      
    CASE       
    WHEN (ISNULL(VEMDS.FirstName, '') = '' AND ISNULL(VEMDS.LastName, '') = '')      
         THEN TD.ProposerName      
    ELSE ISNULL(VEMDS.FirstName, '') + ' ' + ISNULL(VEMDS.LastName, '')      
END AS EmployeeName,      
      
            ISNULL(ECD.CompanyEmail, '') AS CompanyEmail,      
       --    ISNULL(VEMDS1.MobileNumber, '') AS OracleMobile,      
    ISNULL(VEMDS.MobileNumber, '') AS OracleMobile,      
   ISNULL(TD.Mobile1, '') AS ApiMobile,      
      
            SCT.Title AS Business,      
            VTM.Title AS Vertical,      
            CGM.Title AS CompanyGroup,      
            ECM.Title AS Company,      
            LM.Title AS Location,      
            DGM.Title AS DepartmentGroup,      
            ODM.Title AS Department,      
            ETM.Title AS EmployeeType,      
            GRD.Title AS GradeTitle,      
   VEMDS.Designation as DesignationName,      
      
            AD.UpdatedDateTime AS LastActionDate,      
            TD.AssignedDoctorId AS DoctorEmployeeId,      
   TD.ParticipantSourceId as EmployeeId,      
      
ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS AssignDoctor,      
ISNULL(VEMDS1.ExtensionNo,'') DoctorExtension,      
ISNULL(VEMDS1.MobileNumber,'') DoctorMobileNumber,      
CASE       
   WHEN TD.TicketStatus != 'New'       
       THEN ISNULL(VEMDS2.FirstName, '') + ' ' + ISNULL(VEMDS2.LastName, '')      
   ELSE 'System'      
END AS AssignBYDoctor,      
  
      
      
            STUFF((SELECT ', ' + R.Remark      
                FROM sHospitalization.tIntimationRemark R      
                WHERE R.HospitalizationIntimationDetailId = TD.Id      
                ORDER BY R.CreatedDateTime DESC      
                FOR XML PATH(''), TYPE      
            ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS AllRemarks,      
      
            (      
                SELECT       
                    R.Id,      
                    R.Remark,      
                    R.CreatedDateTime,      
                    R.CreatedUserId      
                FROM sHospitalization.tIntimationRemark R      
                WHERE R.HospitalizationIntimationDetailId = TD.Id      
                ORDER BY R.CreatedDateTime DESC      
                FOR JSON PATH      
            ) AS RemarkHistoryJSON      
      
        FROM [sHospitalization].[tIntimationDetails] TD      
        INNER JOIN [sHospitalization].[tIntimationAssignedDoctor] AD       
            ON  TD.IntimationAssignedDoctorId = AD.Id      
        Left JOIN [sHrm].[tEmployeeMaster] EMD       
            ON EMD.Id = AD.DoctorEmployeeId      
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP       
            ON EMP.Id = TD.ParticipantSourceId      
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD       
            ON ECD.EmployeeId = EMP.Id      
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD       
            ON EJD.EmployeeId = EMP.Id      
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM       
            ON ETM.Id = EJD.EmployeeTypeId      
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM       
            ON ECM.Id = EJD.EmployeeCompanyId      
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM       
            ON CGM.Id = ECM.CompanyGroupId      
        LEFT JOIN [sHrm].[tVerticalMaster] VTM       
            ON VTM.Id = CGM.VerticalId      
        LEFT JOIN [sHrm].[tSectorMaster] SCT       
            ON SCT.Id = VTM.SectorId      
        Left JOIN [sCommon].[tLocationMaster] LM       
            ON LM.Id = EJD.EmployeeLocationId      
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM       
            ON DGM.Id = EJD.OrganizationDepartmentId      
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM       
            ON ODM.Id = EJD.OrganizationDepartmentId      
      
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS       
            ON EMDS.Id = EJD.EmployeeDesignationId      
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS       
            ON VEMDS.EmployeeId = TD.ParticipantSourceId      
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1       
            ON VEMDS1.EmployeeId = TD.AssignedDoctorId      
     LEFT JOIN [sHrm].[vExtEmployeeMaster]    VEMDS2      
            ON VEMDS2.UserId = TD.UpdatedUserId      
        LEFT JOIN [sHrm].[tGradeMaster] GRD       
            ON GRD.Id = VEMDS.GradeId      
      
        WHERE       
            TD.OrgId = @rOrgId      
            AND (TD.AssignedDoctorId = @rDoctorId OR @rDoctorId = 0)      
            -----------------------------------------      
            -- ✅ CORRECT DATE FILTER (NO 2025 LEAK)      
            -----------------------------------------      
            AND (      
                    (@FromDate IS NULL OR TD.CreatedDateTime >= @FromDate)      
                AND (@ToDate   IS NULL OR TD.CreatedDateTime <  @ToDate)      
            )      
      
            AND (                      EXISTS (      
                    SELECT 1      
                    FROM sCommon.fnsplit(@rCodeLike, ',') AS SplitValues      
                    WHERE       
                        (CHARINDEX(',', @rCodeLike) = 0 AND TD.EmpCode LIKE SplitValues.item + '%')      
                        OR      
                        (CHARINDEX(',', @rCodeLike) > 0 AND TD.EmpCode = SplitValues.item)      
                )      
                OR @rCodeLike = ''      
            )      
            AND (      
       
               --    (@rStatusId <> 4 AND TD.TicketStatus = @StatusText)      
               -- OR (@rStatusId = 4 AND TD.TicketStatus IN ('New', 'Open'))      
      
                --TD.TicketStatus = @StatusText      
      
                   @rStatusId = '0'      
                   OR TD.TicketStatus IN (      
             SELECT      
                           CASE Id      
                               WHEN 1 THEN 'New'      
                               WHEN 2 THEN 'Open'      
                               WHEN 3 THEN 'Close'      
                           END      
                       FROM @StatusIds      
                   )      
            )      
      
        ORDER BY TD.CreatedDateTime DESC;      
    END TRY      
      
    BEGIN CATCH      
        DECLARE @ErrMsg NVARCHAR(MAX) = ERROR_MESSage();      
        INSERT INTO [sHospitalization].[tErrorLog]      
        (      
            ErrorMessage,       
            StoredProcedure,       
            ErrorDateTime,       
            UserId,       
            OrgId      
        )      
        VALUES      
        (      
            @ErrMsg,       
            'pIntimationDetailsListReviewGet',       
            GETUTCDATE(),       
            NULL,       
            @rOrgId      
        );      
    END CATCH      
END;

GO

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

GO

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

GO


ALTER proc [sSupport].[pDropDownsGet]
@rStoreLocationId int
as
begin
	declare @tblYears table(tid int identity(1,1),y_id varchar(10),y_title varchar(10));
	DECLARE @CurrentYear INT = YEAR(sCommon.fGetDate());

	insert into @tblYears
	SELECT 
    CAST(Y AS varchar(4)) AS [Value],
    CAST(Y AS varchar(4)) AS [Text]
	FROM (
		SELECT @CurrentYear AS Y UNION ALL
		SELECT @CurrentYear - 1 UNION ALL
		SELECT @CurrentYear - 2 UNION ALL
		SELECT @CurrentYear - 3 UNION ALL
		SELECT @CurrentYear - 4 UNION ALL
		SELECT @CurrentYear - 5
	) A
	ORDER BY Y;
	
	declare @lAmbulanceRes varchar(max)='',@lMonthRes varchar(max)='',@lYearRes varchar(max)=''
	select @lAmbulanceRes = @lAmbulanceRes + '<option value="0"> -- Select -- </option>'
	select @lAmbulanceRes = @lAmbulanceRes + '<option value="' + convert(varchar,Id) + '">' + AmbulanceCode + '</option>'
	from sSupport.tAmbulanceMaster where IsObsolete = 0 and StoreLocationId = @rStoreLocationId
	order by AmbulanceCode
	
	select @lMonthRes = @lMonthRes + '<option value="0"> -- Select -- </option>'
	select @lMonthRes = @lMonthRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sCommon.tMonthMaster where IsObsolete = 0 order by Id
	
	select @lYearRes = @lYearRes + '<option value="0"> -- Select -- </option>'
	select @lYearRes = @lYearRes + '<option value="' + y_id + '">' + y_title + '</option>'
	from @tblYears order by y_id
	
	select @lAmbulanceRes as AmbulanceRes,@lMonthRes as MonthRes,@lYearRes as YearRes
end

GO

ALTER FUNCTION [dbo].[fn_ParseDateString] (@DateStr NVARCHAR(100))
RETURNS DATE
AS
BEGIN
    DECLARE @ParsedDate DATE;

    IF @DateStr IS NULL OR LTRIM(RTRIM(@DateStr)) = ''
        RETURN NULL;

    -- Case 1: dd/MM/yyyy
    IF @DateStr LIKE '[0-3][0-9]/[0-1][0-9]/[1-2][0-9][0-9][0-9]'
    BEGIN
        IF ISDATE(
            SUBSTRING(@DateStr, 7, 4) + '-' +
            SUBSTRING(@DateStr, 4, 2) + '-' +
            SUBSTRING(@DateStr, 1, 2)
        ) = 1
        BEGIN
            SET @ParsedDate = CONVERT(
                DATE,
                SUBSTRING(@DateStr, 7, 4) + '-' +
                SUBSTRING(@DateStr, 4, 2) + '-' +
                SUBSTRING(@DateStr, 1, 2),
                23
            );
        END
    END
    ELSE
    BEGIN
        -- Case 2: yyyy-mm-dd or yyyy-mm-dd hh:mm:ss
        IF ISDATE(@DateStr) = 1
        BEGIN
            SET @ParsedDate = CONVERT(DATE, @DateStr, 120);
        END
    END

    RETURN @ParsedDate;
END;

GO


ALTER PROCEDURE [sHospitalization].[pIntimationDetailsInsert]
    @rHospitalName NVARCHAR(255) = NULL,
    @rPatientName NVARCHAR(255) = NULL,
    @rEmpCode NVARCHAR(100) = NULL,
    @rMobile1 NVARCHAR(20) = NULL,
    @rOrgId INT = NULL,
    -- Raw Excel Columns
    @rRawEmployeeNo NVARCHAR(100) = NULL,
    @rRawBeneficiaryName NVARCHAR(255) = NULL,
    @rRawAge NVARCHAR(10) = NULL,
    @rRawRelation NVARCHAR(100) = NULL,
    @rRawNatureOfIllness NVARCHAR(500) = NULL,
    @rRawProposerName NVARCHAR(255) = NULL,
    @rRawContact1 NVARCHAR(20) = NULL,
    @rRawHospitalName NVARCHAR(255) = NULL,
    @rRawNetworkCity NVARCHAR(100) = NULL,
    @rRawState NVARCHAR(100) = NULL,
    @rRawTreatingDoctor NVARCHAR(255) = NULL,
    @rRawLikelyDateOfAdmission NVARCHAR(200) = NULL,
    @rRawDateOfDischarge NVARCHAR(200) = NULL,
    @rRawStatusOfIntimation NVARCHAR(100) = NULL,
    @rRawTypeOfIntimation NVARCHAR(100) = NULL,
    @rRawFIRNo NVARCHAR(100) = NULL,
    @rRawDateOfFileReceived NVARCHAR(200) = NULL,
    @rRawClaimType NVARCHAR(200) = NULL,
    @rRawIntimationNo NVARCHAR(100) = NULL,
    @rRawDateOfIntimation NVARCHAR(200) = NULL,
    @rRawTPACardNo NVARCHAR(100) = NULL,
    @rRawGrade NVARCHAR(200) = NULL,
    @rRawGroupCode NVARCHAR(200) = NULL,
    @rRawModeOfStatus NVARCHAR(200) = NULL,
    @rRawTAT NVARCHAR(200) = NULL,
    @rRawAdmissionType NVARCHAR(200) = NULL,
    @rRawEstimatedAmount NVARCHAR(200) = NULL,
    @rRawNetworkStatus NVARCHAR(200) = NULL,
    @rRawTAT_Godi NVARCHAR(200) = NULL,
    @rRawTAT_Band_Godi NVARCHAR(200) = NULL,
    @rCreatedUserId BIGINT = NULL,
    @rIsObsolete BIT = 0,
    @AssignedDoctorId BIGINT = NULL,
	@IntimationAssignedDoctorId INT = NULL
    
AS
BEGIN
    SET nocount ON;
	DECLARE @NewRecordId BIGINT ;
    BEGIN try
        DECLARE @EmployeeId BIGINT = NULL,
                @PreviousDoctorId BIGINT = NULL,
                @TicketStatus NVARCHAR(50) = 'New',
                @CurrentDateTime DATETIME = Getutcdate(),
                @TicketNumber NVARCHAR(50) = NULL,
                @AssignTypeId BIGINT = NULL,
                @AssignSubTypeId BIGINT = NULL,
                @DesignationId BIGINT = NULL,
                @ParsedDateOfAdmission DATE,
                @ParsedDateOfDischarge DATE,
                @ParsedDateOfIntimation DATE,
                @ParsedEstimatedAmount DECIMAL(18, 2),
                @ParsedAge INT,
                @lNextNumber BIGINT,
                @FIRNo_num NUMERIC(18, 0) = NULL,
                @TPACardNo_num NUMERIC(18, 0) = NULL,
                @EstimatedAmount_num DECIMAL(18, 2) = NULL,
                @TAT_Godi_int INT = NULL,
                @ParticipantSourceTypeId BIGINT = NULL;
				
        ---------------------------------------------------------------------
        -- Generate new RowId
        ---------------------------------------------------------------------
        EXEC scommon.ptablerowidget @rOrgId = @rOrgId,
                                    @rTableTitle = 'sHospitalization.tIntimationDetails',
                                    @rIsCurrentNumber = 0,
                                    @rSeed = 1,
                                    @rIncrement = 1,
                                    @outNextNumber = @lNextNumber output;
        SET @NewRecordId = @lNextNumber;
        ---------------------------------------------------------------------
        -- Resolve EmployeeId (if present)
        ---------------------------------------------------------------------
        ---------------------------------------------------------------------
        -- Resolve EmployeeId (if present)
        ---------------------------------------------------------------------
        IF ISNULL(LTRIM(RTRIM(@rRawEmployeeNo)), '') <> ''
        BEGIN
            SELECT @EmployeeId = Id
            FROM [sHrm].[tEmployeeMaster]
            WHERE Code = @rRawEmployeeNo
                  AND IsObsolete = 0;

            IF @EmployeeId IS NOT NULL
            BEGIN

                SET @ParticipantSourceTypeId = 95;
            END
            ELSE
            BEGIN

                SET @ParticipantSourceTypeId = NULL;
            END
        END
        ELSE
        BEGIN

            SET @ParticipantSourceTypeId = NULL;
        END

        ---------------------------------------------------------------------
        -- Doctor assignment placeholder logic (currently manual or external)
        ---------------------------------------------------------------------
        -- ASSIGNDOCTORDONE:
        ---------------------------------------------------------------------
        -- Generate Ticket Number
        ---------------------------------------------------------------------
        -- SET @TicketNumber = 'TKT-' + Format(Getutcdate(), 'yyyyMMdd') + '-' + RIGHT('00000' + Cast(Abs(Checksum(Newid())) % 100000 AS NVARCHAR(5)), 5);
        -- Generate sequential TicketNumber (e.g. TKT-20251105-00001)
        ---------------------------------------------------------------------
        -- Generate sequential TicketNumber like TKT-20251105-00001
        ---------------------------------------------------------------------
        DECLARE @NextNumber INT;

        SELECT @NextNumber = ISNULL(MAX(CAST(RIGHT(TicketNumber, 5) AS INT)), 0) + 1
        FROM [sHospitalization].[tIntimationDetails]
        WHERE TicketNumber LIKE 'TKT-' + FORMAT(GETUTCDATE(), 'yyyyMMdd') + '%';

        SET @TicketNumber
            = 'TKT-' + FORMAT(GETUTCDATE(), 'yyyyMMdd') + '-' + RIGHT('00000' + CAST(@NextNumber AS NVARCHAR(5)), 5);


        ---------------------------------------------------------------------
        -- Parse / normalize fields
        ---------------------------------------------------------------------
        SET @ParsedDateOfAdmission = dbo.Fn_parsedatestring(@rRawLikelyDateOfAdmission);
        SET @ParsedDateOfDischarge = dbo.Fn_parsedatestring(@rRawDateOfDischarge);
        SET @ParsedDateOfIntimation = dbo.Fn_parsedatestring(@rRawDateOfIntimation);
        -- Normalize estimated amount
        IF Isnull(Ltrim(Rtrim(@rRawEstimatedAmount)), '') <> ''
        BEGIN
            SET @rRawEstimatedAmount = Replace(Replace(Ltrim(Rtrim(@rRawEstimatedAmount)), ',', ''), ' ', '');
            SET @ParsedEstimatedAmount = try_cast(@rRawEstimatedAmount as decimal(18, 2));
        END
        ELSE
            SET @ParsedEstimatedAmount = NULL;
        SET @ParsedAge = try_cast(@rRawAge as int);
        ---------------------------------------------------------------------
        -- Validate numeric fields BEFORE INSERT
        ---------------------------------------------------------------------
        -- FIRNo
        IF Isnull(Ltrim(Rtrim(@rRawFIRNo)), '') <> ''
        BEGIN
            SET @FIRNo_num = try_cast(Replace(Ltrim(Rtrim(@rRawFIRNo)), ' ', '') as numeric(18, 0));
            IF @FIRNo_num IS NULL
                RAISERROR('Invalid FIRNo: cannot convert [%s] to numeric', 16, 1, @rRawFIRNo);
        END
        ELSE
            SET @FIRNo_num = NULL;
        -- TPACardNo
        IF Isnull(Ltrim(Rtrim(@rRawTPACardNo)), '') <> ''
        BEGIN
            SET @TPACardNo_num = try_cast(Replace(Ltrim(Rtrim(@rRawTPACardNo)), ' ', '') as numeric(18, 0));
            IF @TPACardNo_num IS NULL
                RAISERROR('Invalid TPACardNo: cannot convert [%s] to numeric', 16, 1, @rRawTPACardNo);
        END
        ELSE
            SET @TPACardNo_num = NULL;
        -- EstimatedAmount
        IF Isnull(Ltrim(Rtrim(@rRawEstimatedAmount)), '') <> ''
        BEGIN
            IF @ParsedEstimatedAmount IS NULL
                RAISERROR('Invalid EstimatedAmount: cannot convert [%s] to decimal', 16, 1, @rRawEstimatedAmount);
            ELSE
                SET @EstimatedAmount_num = @ParsedEstimatedAmount;
        END
        ELSE
            SET @EstimatedAmount_num = NULL;
        -- TAT_Godi
        IF Isnull(Ltrim(Rtrim(@rRawTAT_Godi)), '') <> ''
        BEGIN
            SET @TAT_Godi_int = try_cast(Ltrim(Rtrim(@rRawTAT_Godi)) as int);
            IF @TAT_Godi_int IS NULL
                RAISERROR('Invalid TAT_Godi: cannot convert [%s] to int', 16, 1, @rRawTAT_Godi);
        END
        ELSE
            SET @TAT_Godi_int = NULL;


			        ---------------------------------------------------------------------
        -- Insert / Update State Master
        ---------------------------------------------------------------------
        IF ISNULL(LTRIM(RTRIM(@rRawState)), '') <> ''
        BEGIN
            DECLARE @lStateId BIGINT;

            -- Check if state already exists
            SELECT @lStateId = Id
            FROM [sHospitalization].[tStateMaster]
            WHERE StateName = @rRawState
                  AND OrgId = @rOrgId
                  AND IsObsolete = 0;

            -- If not found, insert new
            IF @lStateId IS NULL
            BEGIN
                EXEC scommon.ptablerowidget 
                    @rOrgId = @rOrgId,
                    @rTableTitle = 'sHospitalization.tStateMaster',
                    @rIsCurrentNumber = 0,
                    @rSeed = 1,
                    @rIncrement = 1,
                    @outNextNumber = @lStateId OUTPUT;

                INSERT INTO [sHospitalization].[tStateMaster]
                (
                    Id,
                    OrgId,
                    StateName,
                    CreatedUserId,
                    CreatedDateTime,
                    UpdatedUserId,
                    UpdatedDateTime,
                    IsObsolete
                )
                VALUES
                (
                    @lStateId,
                    @rOrgId,
                    @rRawState,
                    @rCreatedUserId,
                    @CurrentDateTime,
                    @rCreatedUserId,
                    @CurrentDateTime,
                    0
                );
            END
        END

        ---------------------------------------------------------------------
        -- All validations passed — perform insert inside a transaction
        ---------------------------------------------------------------------
        BEGIN TRANSACTION;
        INSERT INTO [sHospitalization].[tIntimationDetails]
        (
            id,
            orgid,
            participantsourceid,
            participantsourcetypeid,
            empcode,
            beneficiaryname,
            dateofintimation,
            dateofadmission,
            dateofdischarge,
            claimtype,
            intimationnumber,
            natureofillness,
            status,
            hospitalname,
            networkcity,
            state,
            age,
            mobile1,
            assigneddoctorid,
			IntimationAssignedDoctorId,
            ticketnumber,
            ticketstatus,
            ticketopendate,
            relation,
            proposername,
            statusofintimation,
            typeofintimation,
            firno,
            tpacardno,
            grade,
            groupcode,
            modeofstatus,
            tat,
            admissiontype,
            estimatedamount,
            networkstatus,
            tat_godi,
            tat_band_godi,
            isobsolete,
            createddatetime,
            createduserid,
            updateddatetime,
            updateduserid
        )
        VALUES
        (@NewRecordId,
         Isnull(@rOrgId, 0),
         @EmployeeId,
         @ParticipantSourceTypeId,
         @rRawEmployeeNo,
         @rRawBeneficiaryName,
         @ParsedDateOfIntimation,
         @ParsedDateOfAdmission,
         @ParsedDateOfDischarge,
         @rRawClaimType,
         @rRawIntimationNo,
         @rRawNatureOfIllness,
         @rRawStatusOfIntimation,
         @rRawHospitalName,
         @rRawNetworkCity,
         @rRawState,
         @ParsedAge,
         @rRawContact1,
         @AssignedDoctorId,
		 @IntimationAssignedDoctorId,
         @TicketNumber,
         @TicketStatus,
         @CurrentDateTime,
         @rRawRelation,
         @rRawProposerName,
         @rRawStatusOfIntimation,
         @rRawTypeOfIntimation,
         @FIRNo_num,
         @TPACardNo_num,
         @rRawGrade,
         @rRawGroupCode,
         @rRawModeOfStatus,
         @rRawTAT,
         @rRawAdmissionType,
         @EstimatedAmount_num,
         @rRawNetworkStatus,
         @TAT_Godi_int,
         @rRawTAT_Band_Godi,
         @rIsObsolete,
         @CurrentDateTime,
         @rCreatedUserId,
         @CurrentDateTime,
         @rCreatedUserId
        );

        ---------------------------------------------------------------------
        -- Insert doctor assignment log
        ---------------------------------------------------------------------
        IF @AssignedDoctorId IS NOT NULL
        BEGIN
            DECLARE @lAssignLogId BIGINT;
            EXEC scommon.ptablerowidget @rOrgId = @rOrgId,
                                        @rTableTitle = 'sHospitalization.tIntimationDoctorAssignmentLog',
                                        @rIsCurrentNumber = 0,
                                        @rSeed = 1,
                                        @rIncrement = 1,
                                        @outNextNumber = @lAssignLogId output;
            INSERT INTO [sHospitalization].[tIntimationDoctorAssignmentLog]
            (
                id,
                orgid,
                hospitalizationintimationdetailid,
                previousdoctoremployeeid,
                newdoctoremployeeid,
                assigneddate,
                ticketnumber,
                createduserid,
                createddatetime,
                updateduserid,
                updateddatetime,
				Status
            )
            VALUES
            (@lAssignLogId,
             Isnull(@rOrgId, 0),
             @NewRecordId,
             @PreviousDoctorId,
             @AssignedDoctorId,
             @CurrentDateTime,
             @TicketNumber,
             @rCreatedUserId,
             @CurrentDateTime,
             @rCreatedUserId,
             @CurrentDateTime,
			 'New'
            );

        END
        COMMIT TRANSACTION;
		---------------------------------------------------------------------
-- Insert default remark entry with Status = 'New'
---------------------------------------------------------------------
--IF @AssignedDoctorId IS NOT NULL
--BEGIN
--    DECLARE @lRemarkId BIGINT;

--    EXEC scommon.ptablerowidget 
--        @rOrgId = @rOrgId,
--        @rTableTitle = 'sHospitalization.tIntimationRemark',
--        @rIsCurrentNumber = 0,
--        @rSeed = 1,
--        @rIncrement = 1,
--        @outNextNumber = @lRemarkId OUTPUT;

--    INSERT INTO [sHospitalization].[tIntimationRemark]
--    (
--        Id,
--        OrgId,
--        HospitalizationIntimationDetailId,
--        DoctorEmployeeId,
--        Remark,
--        CreatedUserId,
--        CreatedDateTime,
--        UpdatedUserId,
--        UpdatedDateTime,
--        Status
--    )
--    VALUES
--    (
--        @lRemarkId,
--        @rOrgId,
--        @NewRecordId,
--        @AssignedDoctorId,
--        NULL,                     -- Remark initially empty
--        @rCreatedUserId,
--        @CurrentDateTime,
--        @rCreatedUserId,
--        @CurrentDateTime,
--        'New'                     -- Default Status
--    );
--END

        ---------------------------------------------------------------------
        -- Return newly created record id
        ---------------------------------------------------------------------
        SELECT @NewRecordId AS newrecordid;

        RETURN;
    END try
    BEGIN catch
        -- Ensure rollback
        IF @@TRANCOUNT > 0
            ROLLBACK TRANSACTION;
        DECLARE @ErrorMessage NVARCHAR(4000) = Error_message();
        DECLARE @lErrorId BIGINT;
        EXEC scommon.ptablerowidget @rOrgId = @rOrgId,
                                    @rTableTitle = 'sHospitalization.tErrorLog',
                                    @rIsCurrentNumber = 0,
                                    @rSeed = 1,
                                    @rIncrement = 1,
                                    @outNextNumber = @lErrorId output;
        INSERT INTO [sHospitalization].[tErrorLog]
        (
            id,
            errormessage,
            storedprocedure,
            errordatetime,
            userid,
            orgid
        )
        VALUES
        (@lErrorId, @ErrorMessage, 'sHospitalization.pIntimationDetailsInsert', Getutcdate(), @rCreatedUserId, @rOrgId);

        SET @NewRecordId = -1;
        RAISERROR(@ErrorMessage, 16, 1);
        RETURN;
    END catch
END;

GO


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

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

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

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

	DECLARE @DiagnosisHeader NVARCHAR(MAX)='';

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

	DECLARE @FinalDiagnosisHeader NVARCHAR(MAX);

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

	DECLARE @CreateSQL NVARCHAR(MAX);

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

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

	EXEC sp_executesql @CreateSQL;

	DECLARE @DiagnosisSQL NVARCHAR(MAX);

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

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

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

		DECLARE @T1Columns NVARCHAR(MAX);

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

		DECLARE @SQL NVARCHAR(MAX);

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

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

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

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

IF OBJECT_ID('tempdb..##tmpDiagnosis') IS NOT NULL  
BEGIN  
  DROP TABLE ##tmpDiagnosis  
END
IF OBJECT_ID('tempdb..##tempTable') IS NOT NULL  
BEGIN  
  DROP TABLE ##tempTable  
END
IF OBJECT_ID('tempdb..##tempTable1') IS NOT NULL  
BEGIN  
  DROP TABLE ##tempTable1  
END
IF OBJECT_ID('tempdb..##tempTable2') IS NOT NULL  
BEGIN  
  DROP TABLE ##tempTable2 
END
 
 IF OBJECT_ID('tempdb..#temp_GroupingWithPercentage') IS NOT NULL  
BEGIN  
  DROP TABLE #temp_GroupingWithPercentage  
 END  
  
 IF OBJECT_ID('tempdb..#temp_EmployeeDetails') IS NOT NULL  
BEGIN  
  DROP TABLE #temp_EmployeeDetails  
END  
  
 IF OBJECT_ID('tempdb..#temp_EmployeeDemographicsDetails') IS NOT NULL  
BEGIN  
  DROP TABLE #temp_EmployeeDemographicsDetails  
END  
  
 IF OBJECT_ID('tempdb..#temp_EmployeeAgeGrouping') IS NOT NULL  
BEGIN  
  DROP TABLE #temp_EmployeeAgeGrouping  
END  
  
  
END  

GO

IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 108)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('108', '199', 'Hospitalization Follow-Up', '', '', '[RecipientName],[DoctorName],[Relationship],[Extension],[MobileNumber],[BeneficiaryName]', '0', '0', NULL, 'Wellness Call – Hospitalization Follow-Up', '1', '0');
END
ELSE
BEGIN
    SELECT '108 Already Exists';
END

IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 109)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('109', '199', 'Hospitalization Intimation Ticket Assigned ', '', '', '[RecipientName],[DoctorName],[Relationship],[Extension],[MobileNumber],[BeneficiaryName]', '0', '0', NULL, 'Hospitalization Intimation Ticket Assigned – Action Required', '1', '0');
END
ELSE
BEGIN
    SELECT '108 Already Exists';
END

GO

alter PROCEDURE [sHospitalization].[pIntimationDetailsListReviewGet]      
(      
    @rOrgId SMALLINT,      
    @rFromDate NVARCHAR(50) = NULL,      
    @rToDate NVARCHAR(50) = NULL,      
    @rDoctorId BIGINT = 0,      
    @rStatusId VARCHAR(50) = 0,      
    @rCodeLike NVARCHAR(MAX) = ''      
)      
AS      
BEGIN      
    SET NOCOUNT ON;      
    SET DATEFORMAT dmy;      
      
    DECLARE       
        @FromDate DATETIME = NULL,      
        @ToDate DATETIME = NULL;      
      
DECLARE @StatusIds TABLE (Id INT);      
      
INSERT INTO @StatusIds (Id)      
SELECT T.X.value('.', 'INT')      
FROM (      
    SELECT CAST(      
        '<x>' + REPLACE(@rStatusId, ',', '</x><x>') + '</x>'      
        AS XML      
    ) AS XmlData      
) A      
CROSS APPLY XmlData.nodes('/x') AS T(X);      
      
      
      
    -- Map rStatusId to text      
    --DECLARE @StatusText NVARCHAR(20) = NULL;      
    --IF @rStatusId = 1 SET @StatusText = 'New';      
    --IF @rStatusId = 2 SET @StatusText = 'Open';      
    --IF @rStatusId = 3 SET @StatusText = 'Close';      
 --IF @rStatusId = 4 SET @StatusText = 'New & Open';      
      
    -----------------------------------------      
    -- ✅ SQL 2008/2012 SAFE DATE CONVERSION      
    -----------------------------------------      
    IF (@rFromDate IS NOT NULL AND @rFromDate <> '')      
        SET @FromDate = CONVERT(DATETIME, @rFromDate, 103);  -- FORCES DD/MM/YYYY      
      
    IF (@rToDate IS NOT NULL AND @rToDate <> '')      
        SET @ToDate = DATEADD(DAY, 1, CONVERT(DATETIME, @rToDate, 103));  -- include full day      
      
    -----------------------------------------      
    -- If no code, make it empty      
    -----------------------------------------      
    IF (ISNULL(@rCodeLike, '') = '') SET @rCodeLike = '';      
      
    BEGIN TRY      
        SELECT       
            TD.Id AS IntimationId,      
            TD.EmpCode AS EmployeeCode,      
            TD.BeneficiaryName,      
            TD.Relation,      
            --TD.Age,      
       CASE       
        WHEN UPPER(ISNULL(TD.Relation, '')) = 'SELF'      
             AND VEMDS.EmployeeId = TD.ParticipantSourceId      
            THEN ISNULL(VEMDS.Age, TD.Age)      
        ELSE TD.Age      
    END AS Age,      
            TD.HospitalName,      
            TD.NetworkCity,      
            TD.State,      
            TD.StatusOfIntimation,      
            TD.TypeOfIntimation,      
            TD.FIRNo,      
            TD.CreatedDateTime,      
            TD.TicketStatus AS StatusName,      
            TD.Grade AS Grade,      
            TD.NatureOfIllness,      
            TD.IntimationNumber,      
            TD.ClaimType,      
            TD.DateOfIntimation,      
            TD.DateOfAdmission,      
            TD.DateOfDischarge,      
            TD.TicketNumber,      
            TD.Remarks,      
      
            ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS AssignedDoctor,      
            --AD.DesignationId,      
   EMDS.id as DesignationId,      
          -- ISNULL(VEMDS.FirstName, '') + ' ' + ISNULL(VEMDS.LastName, '') AS EmployeeName,      
    CASE       
    WHEN (ISNULL(VEMDS.FirstName, '') = '' AND ISNULL(VEMDS.LastName, '') = '')      
         THEN TD.ProposerName      
    ELSE ISNULL(VEMDS.FirstName, '') + ' ' + ISNULL(VEMDS.LastName, '')      
END AS EmployeeName,      
      
            ISNULL(ECD.CompanyEmail, '') AS CompanyEmail,      
       --    ISNULL(VEMDS1.MobileNumber, '') AS OracleMobile,      
    ISNULL(VEMDS.MobileNumber, '') AS OracleMobile,      
   ISNULL(TD.Mobile1, '') AS ApiMobile,      
      
            SCT.Title AS Business,      
            VTM.Title AS Vertical,      
            CGM.Title AS CompanyGroup,      
            ECM.Title AS Company,      
            LM.Title AS Location,      
            DGM.Title AS DepartmentGroup,      
            ODM.Title AS Department,      
            ETM.Title AS EmployeeType,      
            GRD.Title AS GradeTitle,      
   VEMDS.Designation as DesignationName,      
      
            AD.UpdatedDateTime AS LastActionDate,      
            TD.AssignedDoctorId AS DoctorEmployeeId,      
   TD.ParticipantSourceId as EmployeeId,      
      
ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS AssignDoctor,      
ISNULL(VEMDS1.ExtensionNo,'') DoctorExtension,      
ISNULL(VEMDS1.MobileNumber,'') DoctorMobileNumber,      
CASE       
   WHEN TD.TicketStatus != 'New'       
       THEN ISNULL(VEMDS2.FirstName, '') + ' ' + ISNULL(VEMDS2.LastName, '')      
   ELSE 'System'      
END AS AssignBYDoctor,      
  
      
      
            STUFF((SELECT ', ' + R.Remark      
                FROM sHospitalization.tIntimationRemark R      
                WHERE R.HospitalizationIntimationDetailId = TD.Id      
                ORDER BY R.CreatedDateTime DESC      
                FOR XML PATH(''), TYPE      
            ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS AllRemarks,      
      
            (      
                SELECT       
                    R.Id,      
                    R.Remark,      
                    R.CreatedDateTime,      
                    R.CreatedUserId      
                FROM sHospitalization.tIntimationRemark R      
                WHERE R.HospitalizationIntimationDetailId = TD.Id      
                ORDER BY R.CreatedDateTime DESC      
                FOR JSON PATH      
            ) AS RemarkHistoryJSON      
      
        FROM [sHospitalization].[tIntimationDetails] TD      
        INNER JOIN [sHospitalization].[tIntimationAssignedDoctor] AD       
            ON  TD.IntimationAssignedDoctorId = AD.Id      
        Left JOIN [sHrm].[tEmployeeMaster] EMD       
            ON EMD.Id = AD.DoctorEmployeeId      
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP       
            ON EMP.Id = TD.ParticipantSourceId      
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD       
            ON ECD.EmployeeId = EMP.Id      
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD       
            ON EJD.EmployeeId = EMP.Id      
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM       
            ON ETM.Id = EJD.EmployeeTypeId      
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM       
            ON ECM.Id = EJD.EmployeeCompanyId      
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM       
            ON CGM.Id = ECM.CompanyGroupId      
        LEFT JOIN [sHrm].[tVerticalMaster] VTM       
            ON VTM.Id = CGM.VerticalId      
        LEFT JOIN [sHrm].[tSectorMaster] SCT       
            ON SCT.Id = VTM.SectorId      
        Left JOIN [sCommon].[tLocationMaster] LM       
            ON LM.Id = EJD.EmployeeLocationId      
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM       
            ON DGM.Id = EJD.OrganizationDepartmentId      
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM       
            ON ODM.Id = EJD.OrganizationDepartmentId      
      
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS       
            ON EMDS.Id = EJD.EmployeeDesignationId      
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS       
            ON VEMDS.EmployeeId = TD.ParticipantSourceId      
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1       
            ON VEMDS1.EmployeeId = TD.AssignedDoctorId      
     LEFT JOIN [sHrm].[vExtEmployeeMaster]    VEMDS2      
            ON VEMDS2.UserId = TD.UpdatedUserId      
        LEFT JOIN [sHrm].[tGradeMaster] GRD       
            ON GRD.Id = VEMDS.GradeId      
      
        WHERE       
            TD.OrgId = @rOrgId      
            AND (TD.AssignedDoctorId = @rDoctorId OR @rDoctorId = 0)      
            -----------------------------------------      
            -- ✅ CORRECT DATE FILTER (NO 2025 LEAK)      
            -----------------------------------------      
            AND (      
                    (@FromDate IS NULL OR TD.CreatedDateTime >= @FromDate)      
                AND (@ToDate   IS NULL OR TD.CreatedDateTime <  @ToDate)      
            )      
      
            AND (                      EXISTS (      
                    SELECT 1      
                    FROM sCommon.fnsplit(@rCodeLike, ',') AS SplitValues      
                    WHERE       
                        (CHARINDEX(',', @rCodeLike) = 0 AND TD.EmpCode LIKE SplitValues.item + '%')      
                        OR      
                        (CHARINDEX(',', @rCodeLike) > 0 AND TD.EmpCode = SplitValues.item)      
                )      
                OR @rCodeLike = ''      
            )      
            AND (      
       
               --    (@rStatusId <> 4 AND TD.TicketStatus = @StatusText)      
               -- OR (@rStatusId = 4 AND TD.TicketStatus IN ('New', 'Open'))      
      
                --TD.TicketStatus = @StatusText      
      
                   @rStatusId = '0'      
                   OR TD.TicketStatus IN (      
             SELECT      
                           CASE Id      
                               WHEN 1 THEN 'New'      
                               WHEN 2 THEN 'Open'      
                               WHEN 3 THEN 'Close'      
                           END      
                       FROM @StatusIds      
                   )      
            )      
      
        ORDER BY TD.CreatedDateTime DESC;      
    END TRY      
      
    BEGIN CATCH      
        DECLARE @ErrMsg NVARCHAR(MAX) = ERROR_MESSage();      
        INSERT INTO [sHospitalization].[tErrorLog]      
        (      
            ErrorMessage,       
            StoredProcedure,       
            ErrorDateTime,       
            UserId,       
            OrgId      
        )      
        VALUES      
        (      
            @ErrMsg,       
            'pIntimationDetailsListReviewGet',       
            GETUTCDATE(),       
            NULL,       
            @rOrgId      
        );      
    END CATCH      
END;

GO


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

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

GO

IF NOT EXISTS (
    SELECT 1
    FROM [sSecurity].[tTask]
    WHERE [Id] = 21033
)
BEGIN
    INSERT INTO [sSecurity].[tTask]
    (
        [Id],
        [Title],
        [TitleResourceKeyId],
        [IsObsolete],
        [ModuleId],
        [AvailablePermission],
        [OrderIndex],
        [ResourceTypeId],
        [IsClientSpecific]
    )
    VALUES
    (
        21033,
        'OPD - Mobile',
        0,
        0,
        217,
        15,
        60,
        5,
        0
    );
END
ELSE
BEGIN
     SELECT '21033 Already Exist'
END

GO

CREATE OR ALTER FUNCTION [dbo].[fAbnormalFindingsHealthIndicator]
(
    @rExaminationId BIGINT
)
RETURNS TABLE
AS
RETURN
(
    SELECT
        EXM.Id AS ExaminationId,

        (
            CASE 
                WHEN
                    CAST(ISNULL(DV.BMI,0) AS FLOAT) >= 36 THEN
                    '<b>BMI-' + CAST(DV.BMI AS NVARCHAR(20)) + '</b><br/>'
                WHEN
                    CAST(ISNULL(DV.BloodPressureSystolic,0) AS FLOAT) > 160
                    OR CAST(ISNULL(DV.BloodPressureDiastolic,0) AS FLOAT) > 110 THEN
                    '<b>BP(Sys/Dia)-' + CAST(DV.BloodPressureSystolic AS NVARCHAR(20)) + '/' +
                    CAST(DV.BloodPressureDiastolic AS NVARCHAR(20)) + '</b><br/>'
                WHEN
                    CAST(ISNULL(D.HB,0) AS FLOAT) < 8 AND CAST(ISNULL(D.HB,0) AS FLOAT) > 0 THEN
                    '<b>HB-' + CAST(D.HB AS NVARCHAR(20)) + '</b><br/>'
                WHEN
                    CAST(ISNULL(D.HBA1C,0) AS FLOAT) > 10 THEN
                    '<b>HBA1C-' + CAST(D.HBA1C AS NVARCHAR(20)) + '</b><br/>'
                WHEN
                    LTRIM(RTRIM(D.ECG)) = 'Abnormal' THEN '<b>ECG-Abnormal</b><br/>'
                WHEN
                    LTRIM(RTRIM(D.ECHO)) = 'Abnormal' THEN '<b>ECHO-Abnormal</b><br/>'
                WHEN
                    LTRIM(RTRIM(D.TMT)) = 'Positive' THEN '<b>TMT-Positive</b><br/>'
                ELSE ''
            END
        ) + CHAR(13) + CHAR(10) +
        +
        'BMI-' + CAST(ISNULL(DV.BMI,0) AS NVARCHAR(20))
        + ', BP(Sys/Dia)-' + CAST(ISNULL(DV.BloodPressureSystolic,0) AS NVARCHAR(20))
        + '/' + CAST(ISNULL(DV.BloodPressureDiastolic,0) AS NVARCHAR(20))
        + ', HB-' + ISNULL(CAST(D.HB AS NVARCHAR(20)),'')
        + ', HBA1C-' + ISNULL(CAST(D.HBA1C AS NVARCHAR(20)),'')
        + ', SERUM CREATININE-' + ISNULL(CAST(D.[SERUM CREATININE] AS NVARCHAR(20)),'')
        + ', SERUM URIC ACID-' + ISNULL(CAST(D.[SERUM URIC ACID] AS NVARCHAR(20)),'')
        + ', TRIGLYCERIDE-' + ISNULL(CAST(D.[TRIGLYCERIDE] AS NVARCHAR(20)),'')
        + ', LDL-' + ISNULL(CAST(D.LDL AS NVARCHAR(20)),'')
        + ', TSH-' + ISNULL(CAST(D.TSH AS NVARCHAR(20)),'')
        + ', PSA-' + ISNULL(CAST(D.PSA AS NVARCHAR(20)),'')
        + ', TMT-' + ISNULL(D.TMT,'')
        + ', ECHO-' + ISNULL(D.ECHO,'')
        + ', ECG-' + ISNULL(D.ECG,'')
        + ', SONOGRAPHY-' + ISNULL(D.SONOGRAPHY,'')
        + ', XRAY-' + ISNULL(D.XRAY,'')
        AS AbnormalFindingHtml

    FROM sExamination.tExamination EXM

    LEFT JOIN sExamination.tVital DV
        ON DV.SourceId = EXM.Id

    LEFT JOIN
    (
        SELECT *
        FROM
        (
            SELECT
                TR.SourceId AS ExaminationId,
                SPM.Title,
                TRD.ServiceValue
            FROM sOrderEntry.tStaticTestParameterMaster SPM
            INNER JOIN sOrderEntry.tTestParameterMaster TPM ON TPM.StaticTestParameterId = SPM.Id
            INNER JOIN sOrderEntry.tTestDetail TTD ON TTD.TestParameterId = TPM.Id
            INNER JOIN sExamination.tTestRequestDetail TRD ON TRD.TestDetailId = TTD.Id
            INNER JOIN sExamination.tTestRequest TR ON TR.Id = TRD.TestRequestId
            WHERE SPM.Id IN
            (3,5,19,20,21,25,31,32,33,34,38,107,104,105,109,108,2,27,49,166,54,58)
        ) X
        PIVOT
        (
            MIN(ServiceValue) FOR Title IN
            (
                [HB],[HBA1C],[SERUM CREATININE],[SERUM URIC ACID],
                [TRIGLYCERIDE],[LDL],[TSH],[PSA],
                [TMT],[ECHO],[ECG],[SONOGRAPHY],[XRAY]
            )
        ) P
    ) D ON D.ExaminationId = EXM.Id

    WHERE EXM.Id = @rExaminationId
);
GO

IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 108)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('108', '199', 'Hospitalization Follow-Up', '', '', '[RecipientName],[DoctorName],[Relationship],[Extension],[MobileNumber],[BeneficiaryName]', '0', '0', NULL, 'Wellness Call – Hospitalization Follow-Up', '1', '0');
END
ELSE
BEGIN
    SELECT '108 Already Exists';
END

IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 109)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('109', '199', 'Hospitalization Intimation Ticket Assigned ', '', '', '[RecipientName],[DoctorName],[Relationship],[Extension],[MobileNumber],[BeneficiaryName]', '0', '0', NULL, 'Hospitalization Intimation Ticket Assigned – Action Required', '1', '0');
END
ELSE
BEGIN
    SELECT '108 Already Exists';
END

GO

alter PROCEDURE [sHospitalization].[pIntimationDetailsListReviewGet]          
(          
    @rOrgId SMALLINT,          
    @rFromDate NVARCHAR(50) = NULL,          
    @rToDate NVARCHAR(50) = NULL,          
    @rDoctorId BIGINT = 0,          
    @rStatusId VARCHAR(50) = 0,          
    @rCodeLike NVARCHAR(MAX) = ''          
)          
AS          
BEGIN          
    SET NOCOUNT ON;          
    SET DATEFORMAT dmy;          
          
    DECLARE           
        @FromDate DATETIME = NULL,          
        @ToDate DATETIME = NULL;          
          
DECLARE @StatusIds TABLE (Id INT);          
          
INSERT INTO @StatusIds (Id)          
SELECT T.X.value('.', 'INT')          
FROM (          
    SELECT CAST(          
        '<x>' + REPLACE(@rStatusId, ',', '</x><x>') + '</x>'          
        AS XML          
    ) AS XmlData          
) A          
CROSS APPLY XmlData.nodes('/x') AS T(X);          
          
          
          
    -- Map rStatusId to text          
    --DECLARE @StatusText NVARCHAR(20) = NULL;          
    --IF @rStatusId = 1 SET @StatusText = 'New';          
    --IF @rStatusId = 2 SET @StatusText = 'Open';          
    --IF @rStatusId = 3 SET @StatusText = 'Close';          
 --IF @rStatusId = 4 SET @StatusText = 'New & Open';          
          
    -----------------------------------------          
    -- ✅ SQL 2008/2012 SAFE DATE CONVERSION          
    -----------------------------------------          
    IF (@rFromDate IS NOT NULL AND @rFromDate <> '')          
        SET @FromDate = CONVERT(DATETIME, @rFromDate, 103);  -- FORCES DD/MM/YYYY          
          
    IF (@rToDate IS NOT NULL AND @rToDate <> '')          
        SET @ToDate = DATEADD(DAY, 1, CONVERT(DATETIME, @rToDate, 103));  -- include full day          
          
    -----------------------------------------          
    -- If no code, make it empty          
    -----------------------------------------          
    IF (ISNULL(@rCodeLike, '') = '') SET @rCodeLike = '';          
          
    BEGIN TRY          
        SELECT           
            TD.Id AS IntimationId,          
            TD.EmpCode AS EmployeeCode,          
            TD.BeneficiaryName,          
            TD.Relation,          
            --TD.Age,          
       CASE           
        WHEN UPPER(ISNULL(TD.Relation, '')) = 'SELF'          
             AND VEMDS.EmployeeId = TD.ParticipantSourceId          
            THEN ISNULL(VEMDS.Age, TD.Age)          
        ELSE TD.Age          
    END AS Age,          
            TD.HospitalName,          
            TD.NetworkCity,          
            TD.State,          
            TD.StatusOfIntimation,          
            TD.TypeOfIntimation,          
            TD.FIRNo,          
            TD.CreatedDateTime,          
            TD.TicketStatus AS StatusName,          
            TD.Grade AS Grade,          
            TD.NatureOfIllness,          
            TD.IntimationNumber,          
            TD.ClaimType,          
            TD.DateOfIntimation,          
            TD.DateOfAdmission,          
            TD.DateOfDischarge,          
            TD.TicketNumber,          
            TD.Remarks,          
          
            ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS AssignedDoctor,          
            --AD.DesignationId,          
   EMDS.id as DesignationId,          
          -- ISNULL(VEMDS.FirstName, '') + ' ' + ISNULL(VEMDS.LastName, '') AS EmployeeName,          
    CASE           
    WHEN (ISNULL(VEMDS.FirstName, '') = '' AND ISNULL(VEMDS.LastName, '') = '')          
         THEN TD.ProposerName          
    ELSE ISNULL(VEMDS.FirstName, '') + ' ' + ISNULL(VEMDS.LastName, '')          
END AS EmployeeName,          
          
            ISNULL(ECD.CompanyEmail, '') AS CompanyEmail,          
       --    ISNULL(VEMDS1.MobileNumber, '') AS OracleMobile,          
    ISNULL(VEMDS.MobileNumber, '') AS OracleMobile,          
   ISNULL(TD.Mobile1, '') AS ApiMobile,          
      
            SCT.Title AS Business,          
            VTM.Title AS Vertical,          
            CGM.Title AS CompanyGroup,          
            ECM.Title AS Company,          
            LM.Title AS Location,          
            DGM.Title AS DepartmentGroup,          
            ODM.Title AS Department,          
            ETM.Title AS EmployeeType,          
            GRD.Title AS GradeTitle,          
   VEMDS.Designation as DesignationName,          
          
            AD.UpdatedDateTime AS LastActionDate,          
            TD.AssignedDoctorId AS DoctorEmployeeId,          
   TD.ParticipantSourceId as EmployeeId,          
          
ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS AssignDoctor,          
ISNULL(VEMDS1.ExtensionNo,'') DoctorExtensionNo,          
ISNULL(VEMDS1.MobileNumber,'') DoctorMobileNumber,          
CASE

    WHEN TDLog.PreviousDoctorEmployeeId IS NOT NULL
        THEN ISNULL(VEMDS2.FirstName, '') + ' ' + ISNULL(VEMDS2.LastName, '')
    ELSE 'System'
END AS AssignBYDoctor
,          
      
          
          
            STUFF((SELECT ', ' + R.Remark          
                FROM sHospitalization.tIntimationRemark R          
                WHERE R.HospitalizationIntimationDetailId = TD.Id          
                ORDER BY R.CreatedDateTime DESC          
                FOR XML PATH(''), TYPE          
            ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS AllRemarks,          
          
            (          
                SELECT           
                    R.Id,          
                    R.Remark,          
                    R.CreatedDateTime,          
                    R.CreatedUserId          
                FROM sHospitalization.tIntimationRemark R          
                WHERE R.HospitalizationIntimationDetailId = TD.Id          
                ORDER BY R.CreatedDateTime DESC          
                FOR JSON PATH          
            ) AS RemarkHistoryJSON          
          
        FROM [sHospitalization].[tIntimationDetails] TD          
        INNER JOIN [sHospitalization].[tIntimationAssignedDoctor] AD           
            ON  TD.IntimationAssignedDoctorId = AD.Id          
        Left JOIN [sHrm].[tEmployeeMaster] EMD           
            ON EMD.Id = AD.DoctorEmployeeId          
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP           
            ON EMP.Id = TD.ParticipantSourceId          
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD           
            ON ECD.EmployeeId = EMP.Id          
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD           
            ON EJD.EmployeeId = EMP.Id          
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM           
            ON ETM.Id = EJD.EmployeeTypeId          
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM           
            ON ECM.Id = EJD.EmployeeCompanyId          
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM           
            ON CGM.Id = ECM.CompanyGroupId          
        LEFT JOIN [sHrm].[tVerticalMaster] VTM           
            ON VTM.Id = CGM.VerticalId          
        LEFT JOIN [sHrm].[tSectorMaster] SCT           
            ON SCT.Id = VTM.SectorId          
        Left JOIN [sCommon].[tLocationMaster] LM           
            ON LM.Id = EJD.EmployeeLocationId          
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM           
            ON DGM.Id = EJD.OrganizationDepartmentId          
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM           
            ON ODM.Id = EJD.OrganizationDepartmentId          
          
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS           
            ON EMDS.Id = EJD.EmployeeDesignationId          
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS           
            ON VEMDS.EmployeeId = TD.ParticipantSourceId          
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1           
            ON VEMDS1.EmployeeId = TD.AssignedDoctorId          
     LEFT JOIN [sHrm].[vExtEmployeeMaster]    VEMDS2          
            ON VEMDS2.UserId = TD.UpdatedUserId          
        LEFT JOIN [sHrm].[tGradeMaster] GRD           
            ON GRD.Id = VEMDS.GradeId     
OUTER APPLY
(
    SELECT TOP 1 *
    FROM sHospitalization.tIntimationDoctorAssignmentLog L
    WHERE L.HospitalizationIntimationDetailId = TD.Id
    ORDER BY L.AssignedDate DESC
) TDLog

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

GO


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

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

GO

CREATE OR ALTER FUNCTION [dbo].[fAbnormalFindingsHealthIndicator]
(
    @rExaminationId BIGINT
)
RETURNS TABLE
AS
RETURN
(
    WITH DataCTE AS
(
    SELECT
        EXM.Id AS ExaminationId,
		PA.HealthIndicatorId,
        DV.BMI,
        DV.BloodPressureSystolic,
        DV.BloodPressureDiastolic,

        -- Explicit columns from Pivot (NO ExaminationId here)
        D.HB,
        D.HBA1C,
        D.[SERUM CREATININE],
        D.[SERUM URIC ACID],
        D.[TRIGLYCERIDE],
        D.LDL,
        D.TSH,
        D.PSA,
        D.TMT,
        D.ECHO,
        D.ECG,
        D.SONOGRAPHY,
        D.XRAY
    FROM sSupport.tProviderAppointment AS PA
	INNER JOIN sExamination.tExamination EXM ON EXM.ParticipantSourceId = PA.PatientSourceId AND EXM.SetupId = PA.SetupId
    LEFT JOIN sExamination.tVital DV
        ON DV.SourceId = EXM.Id
    LEFT JOIN
    (
        SELECT *
        FROM
        (
            SELECT
                TR.SourceId AS ExaminationId,
                SPM.Title,
                TRD.ServiceValue
            FROM sOrderEntry.tStaticTestParameterMaster SPM
            INNER JOIN sOrderEntry.tTestParameterMaster TPM 
                ON TPM.StaticTestParameterId = SPM.Id
            INNER JOIN sOrderEntry.tTestDetail TTD 
                ON TTD.TestParameterId = TPM.Id
            INNER JOIN sExamination.tTestRequestDetail TRD 
                ON TRD.TestDetailId = TTD.Id
            INNER JOIN sExamination.tTestRequest TR 
                ON TR.Id = TRD.TestRequestId
            WHERE SPM.Id IN
            (
                3,5,19,20,21,25,31,32,33,34,
                38,107,104,105,109,108,2,
                27,49,166,54,58
            )
        ) X
        PIVOT
        (
            MIN(ServiceValue) FOR Title IN
            (
                [HB],[HBA1C],[SERUM CREATININE],
                [SERUM URIC ACID],[TRIGLYCERIDE],
                [LDL],[TSH],[PSA],
                [TMT],[ECHO],[ECG],
                [SONOGRAPHY],[XRAY]
            )
        ) P
    ) D ON D.ExaminationId = EXM.Id
    WHERE EXM.Id = @rExaminationId
	),
    AbnormalCTE AS
    (
        SELECT *,
        CASE
            /* ================= SEVERE ================= */
            WHEN CAST(BMI AS FLOAT) >= 36 THEN 'BMI'
            WHEN CAST(BloodPressureSystolic AS FLOAT) > 160 THEN 'BPSys'
            WHEN CAST(BloodPressureDiastolic AS FLOAT) > 110 THEN 'BPDia'
            WHEN CAST(HB AS FLOAT) < 8 AND CAST(HB AS FLOAT) > 0 THEN 'HB'
            WHEN CAST(HBA1C AS FLOAT) > 10 THEN 'HBA1C'
            WHEN CAST([SERUM CREATININE] AS FLOAT) > 2 THEN 'SERUM CREATININE'
            WHEN CAST([SERUM URIC ACID] AS FLOAT) > 9.5 THEN 'SERUM URIC ACID'
            WHEN CAST([TRIGLYCERIDE] AS FLOAT) > 500 THEN 'TRIGLYCERIDE'
            WHEN CAST(LDL AS FLOAT) > 200 THEN 'LDL'
            WHEN CAST(TSH AS FLOAT) > 50 THEN 'TSH'
            WHEN CAST(PSA AS FLOAT) > 10 THEN 'PSA'
            WHEN HealthIndicatorId = 607 AND LTRIM(RTRIM(TMT)) = 'Positive' THEN 'TMT'
            WHEN HealthIndicatorId = 607 AND LTRIM(RTRIM(ECHO)) = 'Abnormal' THEN 'ECHO'
            WHEN HealthIndicatorId = 607 AND LTRIM(RTRIM(ECG)) = 'Abnormal' THEN 'ECG'
            WHEN HealthIndicatorId = 607 AND LTRIM(RTRIM(SONOGRAPHY)) = 'Abnormal' THEN 'SONOGRAPHY'
            WHEN HealthIndicatorId = 607 AND LTRIM(RTRIM(XRAY)) = 'Abnormal' THEN 'XRAY'

            /* ================= MODERATE ================= */
            WHEN CAST(BMI AS FLOAT) BETWEEN 30 AND 35 THEN 'BMI'
            WHEN CAST(BloodPressureSystolic AS FLOAT) BETWEEN 150 AND 160 THEN 'BPSys'
            WHEN CAST(BloodPressureDiastolic AS FLOAT) BETWEEN 100 AND 110 THEN 'BPDia'
            WHEN CAST(HB AS FLOAT) BETWEEN 8 AND 9.99 THEN 'HB'
            WHEN CAST(HBA1C AS FLOAT) BETWEEN 8 AND 10 THEN 'HBA1C'
            WHEN CAST([SERUM CREATININE] AS FLOAT) BETWEEN 1.5 AND 2 THEN 'SERUM CREATININE'
            WHEN CAST([SERUM URIC ACID] AS FLOAT) BETWEEN 7.7 AND 9.4 THEN 'SERUM URIC ACID'
            WHEN CAST([TRIGLYCERIDE] AS FLOAT) BETWEEN 200 AND 500 THEN 'TRIGLYCERIDE'
            WHEN CAST(LDL AS FLOAT) BETWEEN 150 AND 200 THEN 'LDL'
            WHEN CAST(TSH AS FLOAT) BETWEEN 11 AND 50 THEN 'TSH'
            WHEN CAST(PSA AS FLOAT) > 5 THEN 'PSA'

            /* ================= MILD ================= */
            WHEN CAST(BMI AS FLOAT) BETWEEN 26 AND 29.99 THEN 'BMI'
            WHEN CAST(BloodPressureSystolic AS FLOAT) BETWEEN 140 AND 149 THEN 'BPSys'
            WHEN CAST(BloodPressureDiastolic AS FLOAT) BETWEEN 90 AND 99 THEN 'BPDia'
            WHEN CAST(HB AS FLOAT) BETWEEN 10 AND 11.99 THEN 'HB'
            WHEN CAST(HBA1C AS FLOAT) BETWEEN 6.5 AND 7.99 THEN 'HBA1C'
            WHEN CAST([SERUM CREATININE] AS FLOAT) BETWEEN 1.3 AND 1.49 THEN 'SERUM CREATININE'
            WHEN CAST([SERUM URIC ACID] AS FLOAT) BETWEEN 6.5 AND 7.69 THEN 'SERUM URIC ACID'
            WHEN CAST([TRIGLYCERIDE] AS FLOAT) BETWEEN 150 AND 199.99 THEN 'TRIGLYCERIDE'
            WHEN CAST(LDL AS FLOAT) BETWEEN 101 AND 149.99 THEN 'LDL'
            WHEN CAST(TSH AS FLOAT) BETWEEN 5.6 AND 10.99 THEN 'TSH'
            ELSE ''
        END AS AbnormalKey
        FROM DataCTE
    )
    SELECT
        ExaminationId,
        (
            /* ===== BOLD ABNORMAL TEST ===== */
            CASE AbnormalKey
                WHEN 'BMI' THEN '<b>BMI-' + CAST(BMI AS NVARCHAR(20)) + '</b>,<br/>'
				WHEN 'BPSys' THEN '<b>BP(Sys/Dia)-' + ISNULL(CAST(BloodPressureSystolic AS NVARCHAR(50)),'') + '/' + ISNULL(CAST(BloodPressureDiastolic AS NVARCHAR(50)),'') + '</b>,<br/>'
				WHEN 'BPDia' THEN '<b>BP(Sys/Dia)-' + ISNULL(CAST(BloodPressureSystolic AS NVARCHAR(50)),'') + '/' + ISNULL(CAST(BloodPressureDiastolic AS NVARCHAR(50)),'') + '</b>,<br/>'
                WHEN 'HB' THEN '<b>HB-' + CAST(HB AS NVARCHAR(20)) + '</b>,<br/>'
                WHEN 'HBA1C' THEN '<b>HBA1C-' + CAST(HBA1C AS NVARCHAR(20)) + '</b>,<br/>'
                WHEN 'SERUM CREATININE' THEN '<b>SERUM CREATININE-' + CAST([SERUM CREATININE] AS NVARCHAR(20)) + '</b>,<br/>'
                WHEN 'SERUM URIC ACID' THEN '<b>SERUM URIC ACID-' + CAST([SERUM URIC ACID] AS NVARCHAR(20)) + '</b>,<br/>'
                WHEN 'TRIGLYCERIDE' THEN '<b>TRIGLYCERIDE-' + CAST([TRIGLYCERIDE] AS NVARCHAR(20)) + '</b>,<br/>'
                WHEN 'LDL' THEN '<b>LDL-' + CAST(LDL AS NVARCHAR(20)) + '</b>,<br/>'
                WHEN 'TSH' THEN '<b>TSH-' + CAST(TSH AS NVARCHAR(20)) + '</b>,<br/>'
                WHEN 'PSA' THEN '<b>PSA-' + CAST(PSA AS NVARCHAR(20)) + '</b>,<br/>'
                WHEN 'TMT' THEN '<b>TMT-Positive</b>,<br/>'
                WHEN 'ECHO' THEN '<b>ECHO-Abnormal</b>,<br/>'
                WHEN 'ECG' THEN '<b>ECG-Abnormal</b>,<br/>'
                WHEN 'SONOGRAPHY' THEN '<b>SONOGRAPHY-Abnormal</b>,<br/>'
                WHEN 'XRAY' THEN '<b>XRAY-Abnormal</b>,<br/>'
                ELSE ''
            END
			+
            /* ===== DETAILS (EXCLUDE BOLD ONE) ===== */
			STUFF(
            CASE WHEN AbnormalKey <> 'BMI' THEN ', BMI-' + ISNULL(CAST(BMI AS NVARCHAR(20)), '') ELSE '' END
            + CASE WHEN AbnormalKey NOT IN ('BPSys','BPDia') 
                THEN ', BP(Sys/Dia)-' + ISNULL(CAST(BloodPressureSystolic AS NVARCHAR(20)), '') + '/' 
                          + ISNULL(CAST(BloodPressureDiastolic AS NVARCHAR(20)), '') ELSE '' END
            + CASE WHEN AbnormalKey <> 'HB' THEN ', HB-' + ISNULL(CAST(HB AS NVARCHAR(20)), '') ELSE '' END
            + CASE WHEN AbnormalKey <> 'HBA1C' THEN ', HBA1C-' + ISNULL(CAST(HBA1C AS NVARCHAR(20)), '') ELSE '' END
            + CASE WHEN AbnormalKey <> 'SERUM CREATININE' THEN ', SERUM CREATININE-' + ISNULL(CAST([SERUM CREATININE] AS NVARCHAR(20)), '') ELSE '' END
            + CASE WHEN AbnormalKey <> 'SERUM URIC ACID' THEN ', SERUM URIC ACID-' + ISNULL(CAST([SERUM URIC ACID] AS NVARCHAR(20)), '') ELSE '' END
            + CASE WHEN AbnormalKey <> 'TRIGLYCERIDE' THEN ', TRIGLYCERIDE-' + ISNULL(CAST([TRIGLYCERIDE] AS NVARCHAR(20)), '') ELSE '' END
            + CASE WHEN AbnormalKey <> 'LDL' THEN ', LDL-' + ISNULL(CAST(LDL AS NVARCHAR(20)), '') ELSE '' END
            + CASE WHEN AbnormalKey <> 'TSH' THEN ', TSH-' + ISNULL(CAST(TSH AS NVARCHAR(20)), '') ELSE '' END
            + CASE WHEN AbnormalKey <> 'PSA' THEN ', PSA-' + ISNULL(CAST(PSA AS NVARCHAR(20)), '') ELSE '' END
            + CASE WHEN AbnormalKey <> 'TMT' THEN ', TMT-' + ISNULL(TMT,'') ELSE '' END
            + CASE WHEN AbnormalKey <> 'ECHO' THEN ', ECHO-' + ISNULL(ECHO,'') ELSE '' END
            + CASE WHEN AbnormalKey <> 'ECG' THEN ', ECG-' + ISNULL(ECG,'') ELSE '' END
            + CASE WHEN AbnormalKey <> 'SONOGRAPHY' THEN ', SONOGRAPHY-' + ISNULL(SONOGRAPHY,'') ELSE '' END
            + CASE WHEN AbnormalKey <> 'XRAY' THEN ', XRAY-' + ISNULL(XRAY,'') ELSE '' END, 
			1, 2, ''
			)
        ) AS AbnormalFindingHtml
    FROM AbnormalCTE
);

GO


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

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

GO


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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

GO


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

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

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

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

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

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

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

	--DROP TABLE #dummy;

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

GO

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

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

GO


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

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

GO


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

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

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

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

GO


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

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


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

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

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

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

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

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

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

 SELECT @res = @res + '</table></div>'  
 SELECT @res AS result  
END  
  
GO


INSERT INTO [sSecurity].[tTask]
(
    Id,
    Title,
    TitleResourceKeyId,
    IsObsolete,
    ModuleId,
    AvailablePermission,
    OrderIndex,
    ResourceTypeId,
    IsClientSpecific
)
SELECT 21037, 'Claim Assign Doctor', 0, 0, 199, 2, 5, 5, 0
WHERE NOT EXISTS (SELECT 1 FROM [sSecurity].[tTask] WHERE Id = 21037);


INSERT INTO [sSecurity].[tTask]
(
    Id,
    Title,
    TitleResourceKeyId,
    IsObsolete,
    ModuleId,
    AvailablePermission,
    OrderIndex,
    ResourceTypeId,
    IsClientSpecific
)
SELECT 21038, 'Claim API Call', 0, 0, 199, 2, 6, 5, 0
WHERE NOT EXISTS (SELECT 1 FROM [sSecurity].[tTask] WHERE Id = 21038);

GO

ALTER TABLE sAlert.tAlertLog
ADD ClaimIntimationDetailId BIGINT NULL;

GO


IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 108)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('108', '199', 'Hospitalization Follow-Up', '', '', '[RecipientName],[DoctorName],[Relationship],[Extension],[MobileNumber],[BeneficiaryName]', '0', '0', NULL, 'Wellness Call – Hospitalization Follow-Up', '1', '0');
END
ELSE
BEGIN
    SELECT '108 Already Exists';
END

IF NOT EXISTS (SELECT * FROM [sAlert].[tEventMaster] WHERE Id = 109)
BEGIN
    INSERT INTO [sAlert].[tEventMaster] 
    (Id, ModuleId, Title, Remark, ViewName, Fields, IsShowRoleBasedOnFunctionality, IsObsolete, Template, MailSubject, IsAllowAutoSend, IsSubscribe) 
    VALUES 
    ('109', '199', 'Hospitalization Intimation Ticket Assigned ', '', '', '[RecipientName],[DoctorName],[Relationship],[Extension],[MobileNumber],[BeneficiaryName],[NewAssignedCount] ,[OpenFrom]', '0', '0', NULL, 'Hospitalization Intimation Ticket Assigned – Action Required', '1', '0');
END
ELSE
BEGIN
    SELECT '109 Already Exists';
END

GO

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

GO

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

GO

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

GO

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

GO

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

GO

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

GO

CREATE OR ALTER PROCEDURE [sHospitalization].[pIntimationDetailsListReviewGet]  
(              
    @rOrgId SMALLINT,              
    @rFromDate NVARCHAR(50) = NULL,              
    @rToDate NVARCHAR(50) = NULL,              
    @rDoctorId BIGINT = 0,              
    @rStatusId VARCHAR(50) = 0,              
    @rCodeLike NVARCHAR(MAX) = ''              
)              
AS              
BEGIN              
    SET NOCOUNT ON;              
    SET DATEFORMAT dmy;              
              
    DECLARE               
        @FromDate DATETIME = NULL,              
        @ToDate DATETIME = NULL;              
              
DECLARE @StatusIds TABLE (Id INT);        
  
              
INSERT INTO @StatusIds (Id)              
SELECT T.X.value('.', 'INT')              
FROM (              
    SELECT CAST(              
        '<x>' + REPLACE(@rStatusId, ',', '</x><x>') + '</x>'              
        AS XML              
    ) AS XmlData              
) A              
CROSS APPLY XmlData.nodes('/x') AS T(X);              
              
              
       
    -- Map rStatusId to text              
    --DECLARE @StatusText NVARCHAR(20) = NULL;              
    --IF @rStatusId = 1 SET @StatusText = 'New';              
    --IF @rStatusId = 2 SET @StatusText = 'Open';              
    --IF @rStatusId = 3 SET @StatusText = 'Close';              
 --IF @rStatusId = 4 SET @StatusText = 'New & Open';              
              
    -----------------------------------------              
    -- ✅ SQL 2008/2012 SAFE DATE CONVERSION              
    -----------------------------------------              
    IF (@rFromDate IS NOT NULL AND @rFromDate <> '')              
        SET @FromDate = CONVERT(DATETIME, @rFromDate, 103);  -- FORCES DD/MM/YYYY              
              
    IF (@rToDate IS NOT NULL AND @rToDate <> '')              
        SET @ToDate = DATEADD(DAY, 1, CONVERT(DATETIME, @rToDate, 103));  -- include full day              
              
    -----------------------------------------              
    -- If no code, make it empty              
    -----------------------------------------              
    IF (ISNULL(@rCodeLike, '') = '') SET @rCodeLike = '';              
              
    BEGIN TRY              
        SELECT               
            TD.Id AS IntimationId,              
            TD.EmpCode AS EmployeeCode,              
            TD.BeneficiaryName,              
            TD.Relation,              
            --TD.Age,              
       CASE               
        WHEN UPPER(ISNULL(TD.Relation, '')) = 'SELF'              
             AND VEMDS.EmployeeId = TD.ParticipantSourceId              
            THEN ISNULL(VEMDS.Age, TD.Age)              
        ELSE TD.Age              
    END AS Age,              
            TD.HospitalName,              
            TD.NetworkCity,              
            TD.State,              
            TD.StatusOfIntimation,              
            TD.TypeOfIntimation,              
            TD.FIRNo,              
            TD.CreatedDateTime,              
            TD.TicketStatus AS StatusName,              
            TD.Grade AS Grade,              
            TD.NatureOfIllness,              
            TD.IntimationNumber,              
            TD.ClaimType,              
            TD.DateOfIntimation,              
            TD.DateOfAdmission,              
            TD.DateOfDischarge,              
            TD.TicketNumber,              
            TD.Remarks,              
              
            ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS AssignedDoctor,              
            --AD.DesignationId,              
   EMDS.id as DesignationId,              
          -- ISNULL(VEMDS.FirstName, '') + ' ' + ISNULL(VEMDS.LastName, '') AS EmployeeName,              
    CASE               
    WHEN (ISNULL(VEMDS.FirstName, '') = '' AND ISNULL(VEMDS.LastName, '') = '')              
         THEN TD.ProposerName              
    ELSE ISNULL(VEMDS.FirstName, '') + ' ' + ISNULL(VEMDS.LastName, '')              
END AS EmployeeName,              
              
            ISNULL(ECD.CompanyEmail, '') AS CompanyEmail,        
       --    ISNULL(VEMDS1.MobileNumber, '') AS OracleMobile,              
    ISNULL(VEMDS.MobileNumber, '') AS OracleMobile,              
   ISNULL(TD.Mobile1, '') AS ApiMobile,              
          
            SCT.Title AS Business,              
            VTM.Title AS Vertical,              
            CGM.Title AS CompanyGroup,              
            ECM.Title AS Company,              
            LM.Title AS Location,              
            DGM.Title AS DepartmentGroup,              
            ODM.Title AS Department,              
            ETM.Title AS EmployeeType,              
            GRD.Title AS GradeTitle,              
   VEMDS.Designation as DesignationName,              
              
            AD.UpdatedDateTime AS LastActionDate,              
            TD.AssignedDoctorId AS DoctorEmployeeId,              
   TD.ParticipantSourceId as EmployeeId,              
              
ISNULL(VEMDS1.FirstName, '') + ' ' + ISNULL(VEMDS1.LastName, '') AS AssignDoctor,              
ISNULL(VEMDS1.ExtensionNo,'') DoctorExtensionNo,              
ISNULL(VEMDS1.MobileNumber,'') DoctorMobileNumber,              
CASE    
    
    WHEN TDLog.PreviousDoctorEmployeeId IS NOT NULL    
        THEN ISNULL(VEMDS2.FirstName, '') + ' ' + ISNULL(VEMDS2.LastName, '')    
    ELSE 'System'    
END AS AssignBYDoctor    
,            AL.CreatedDate,  
          
              
              
            STUFF((SELECT ', ' + R.Remark              
                FROM sHospitalization.tIntimationRemark R              
                WHERE R.HospitalizationIntimationDetailId = TD.Id              
                ORDER BY R.CreatedDateTime DESC              
                FOR XML PATH(''), TYPE              
            ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS AllRemarks,              
              
            (              
                SELECT               
                    R.Id,              
                    R.Remark,              
                    R.CreatedDateTime,              
                    R.CreatedUserId              
                FROM sHospitalization.tIntimationRemark R              
                WHERE R.HospitalizationIntimationDetailId = TD.Id              
                ORDER BY R.CreatedDateTime DESC              
                FOR JSON PATH              
            ) AS RemarkHistoryJSON              
              
        FROM [sHospitalization].[tIntimationDetails] TD              
        INNER JOIN [sHospitalization].[tIntimationAssignedDoctor] AD               
            ON  TD.IntimationAssignedDoctorId = AD.Id              
        Left JOIN [sHrm].[tEmployeeMaster] EMD               
            ON EMD.Id = AD.DoctorEmployeeId              
        LEFT JOIN [sHrm].[tEmployeeMaster] EMP               
            ON EMP.Id = TD.ParticipantSourceId              
        LEFT JOIN [sHrm].[tEmployeeCommunications] ECD               
            ON ECD.EmployeeId = EMP.Id              
        LEFT JOIN [sHrm].[tEmployeeJobDetail] EJD               
            ON EJD.EmployeeId = EMP.Id              
        LEFT JOIN [sHrm].[tEmployeeTypeMaster] ETM               
            ON ETM.Id = EJD.EmployeeTypeId              
        LEFT JOIN [sHrm].[tEmployeeCompanyMaster] ECM               
            ON ECM.Id = EJD.EmployeeCompanyId              
        LEFT JOIN [sHrm].[tCompanyGroupMaster] CGM               
            ON CGM.Id = ECM.CompanyGroupId              
        LEFT JOIN [sHrm].[tVerticalMaster] VTM               
            ON VTM.Id = CGM.VerticalId              
        LEFT JOIN [sHrm].[tSectorMaster] SCT               
            ON SCT.Id = VTM.SectorId              
        Left JOIN [sCommon].[tLocationMaster] LM               
            ON LM.Id = EJD.EmployeeLocationId              
        LEFT JOIN [sCommon].[tDepartmentGroupMaster] DGM               
            ON DGM.Id = EJD.OrganizationDepartmentId              
        LEFT JOIN [sCommon].[tOrganizationDepartmentMaster] ODM               
            ON ODM.Id = EJD.OrganizationDepartmentId              
              
     LEFT JOIN [sHrm].[tEmployeeDesignationMaster] EMDS               
            ON EMDS.Id = EJD.EmployeeDesignationId              
     LEFT JOIN [sHrm].[vExtEmployeeMaster]  VEMDS               
            ON VEMDS.EmployeeId = TD.ParticipantSourceId              
        LEFT JOIN [sHrm].[vEmployeeCommonDetail]  VEMDS1               
            ON VEMDS1.EmployeeId = TD.AssignedDoctorId              
     LEFT JOIN [sHrm].[vExtEmployeeMaster]    VEMDS2              
            ON VEMDS2.UserId = TD.UpdatedUserId              
        LEFT JOIN [sHrm].[tGradeMaster] GRD               
            ON GRD.Id = VEMDS.GradeId         
  
OUTER APPLY    
(    
    SELECT TOP 1 *    
    FROM sHospitalization.tIntimationDoctorAssignmentLog L    
    WHERE L.HospitalizationIntimationDetailId = TD.Id    
    ORDER BY L.AssignedDate DESC    
) TDLog    
OUTER APPLY (  
    SELECT TOP 1  
        CreatedDateTime AS CreatedDate  
    FROM sAlert.tAlertLog  
    WHERE ClaimIntimationDetailId = TD.Id  
    ORDER BY CreatedDateTime DESC  
) AL  
  
              
        WHERE               
            TD.OrgId = @rOrgId              
            AND (TD.AssignedDoctorId = @rDoctorId OR @rDoctorId = 0)              
            -----------------------------------------              
            -- ✅ CORRECT DATE FILTER (NO 2025 LEAK)              
            -----------------------------------------              
            AND (              
                    (@FromDate IS NULL OR TD.CreatedDateTime >= @FromDate)              
                AND (@ToDate   IS NULL OR TD.CreatedDateTime <  @ToDate)              
            )              
              
            AND (                      EXISTS (              
                    SELECT 1              
                    FROM sCommon.fnsplit(@rCodeLike, ',') AS SplitValues              
                    WHERE               
                        (CHARINDEX(',', @rCodeLike) = 0 AND TD.EmpCode LIKE SplitValues.item + '%')              
                        OR              
                        (CHARINDEX(',', @rCodeLike) > 0 AND TD.EmpCode = SplitValues.item)              
                )              
                OR @rCodeLike = ''              
            )              
            AND (              
               
               --    (@rStatusId <> 4 AND TD.TicketStatus = @StatusText)              
               -- OR (@rStatusId = 4 AND TD.TicketStatus IN ('New', 'Open'))              
              
                --TD.TicketStatus = @StatusText              
              
                   @rStatusId = '0'              
                   OR TD.TicketStatus IN (              
             SELECT              
                           CASE Id              
                               WHEN 1 THEN 'New'              
                               WHEN 2 THEN 'Open'              
                               WHEN 3 THEN 'Close'              
                           END              
                       FROM @StatusIds              
                   )              
            )              
              
        ORDER BY TD.CreatedDateTime DESC;              
    END TRY              
              
    BEGIN CATCH              
        DECLARE @ErrMsg NVARCHAR(MAX) = ERROR_MESSage();              
        INSERT INTO [sHospitalization].[tErrorLog]              
        (              
            ErrorMessage,               
            StoredProcedure,               
            ErrorDateTime,               
            UserId,               
            OrgId              
        )              
        VALUES              
        (              
            @ErrMsg,               
            'pIntimationDetailsListReviewGet',               
            GETUTCDATE(),               
            NULL,               
            @rOrgId              
        );              
    END CATCH              
END;    

GO

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

GO

ALTER TABLE [sHospitalization].[tIntimationDetails]
ADD [Flag] BIT NOT NULL DEFAULT (0);

GO

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

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

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

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

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

GO

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

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

GO

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


