

INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('24.01.16',240116,'BEGIN','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO



PRINT N'Altering Table [sAdmission].[tAdmissionForm]...';


GO
ALTER TABLE [sAdmission].[tAdmissionForm]
    ADD [WhatsappContactNo] NVARCHAR (20) NULL;


GO
PRINT N'Altering Table [sAlert].[tEventTemplate]...';


GO
ALTER TABLE [sAlert].[tEventTemplate]
    ADD [DefaultAlertToEUId] NVARCHAR (MAX) NULL;


GO
PRINT N'Altering Table [sAssessment].[tTempAllExam]...';


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [PermanentStreetOne]   NVARCHAR (150) NULL,
        [PermanentStreetTwo]   NVARCHAR (150) NULL,
        [PermanentStreetThree] NVARCHAR (150) NULL,
        [CasteCategory]        NVARCHAR (50)  NULL;


GO
PRINT N'Altering Table [sHrm].[tEmployeeMaster]...';


GO
ALTER TABLE [sHrm].[tEmployeeMaster]
    ADD [EUId] BIGINT NULL;


GO
PRINT N'Creating Table [sStudent].[tTempDigitalFormScopeHistory]...';


GO
CREATE TABLE [sStudent].[tTempDigitalFormScopeHistory] (
    [DigitalFormId] INT      NOT NULL,
    [SourceTypeId]  SMALLINT NOT NULL,
    [SourceId]      BIGINT   NOT NULL,
    CONSTRAINT [UK_tTempDigitalFormScopeHistory] UNIQUE NONCLUSTERED ([DigitalFormId] ASC, [SourceTypeId] ASC, [SourceId] ASC) WITH (FILLFACTOR = 85)
);


GO
PRINT N'Creating Table [sStudent].[tTempStudent11]...';


GO
CREATE TABLE [sStudent].[tTempStudent11] (
    [StudentId6]           BIGINT         NOT NULL,
    [IsFatherExStudent]    VARCHAR (3)    NOT NULL,
    [IsMotherExStudent]    VARCHAR (3)    NOT NULL,
    [FatherOrganization]   NVARCHAR (200) NULL,
    [FatherDesignation]    NVARCHAR (100) NULL,
    [MotherOrganization]   NVARCHAR (200) NULL,
    [MotherDesignation]    NVARCHAR (100) NULL,
    [RelativeOrganization] NVARCHAR (200) NULL,
    [RelativeDesignation]  NVARCHAR (100) NULL
);


GO



ALTER VIEW [sStudent].[vStudentColumnName]  
AS 
SELECT 	
	  --SA.AcademicId,	  
	  --SA.ClassId,
	  --SA.DivisionId,
	  SA.RollNo,
	  --SA.OrgId,
	  --SA.BatchId,
	  OM.Title AS Organization,
	  BM.Title AS Batch,
	  DM.Title AS Department,
	  --SA.StudentId,
	  SA.SUId,
	  SA.Code AS [ID No],
	  SA.Code AS [GR No],
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  --SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      SO.DateOfBirth,
      SO.BirthdateInWord,
      --SO.TransportModeId,
      TM.Title AS TransportMode,
      --SO.GenderId,
      GM.Title AS Gender,
      --SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast As FamilyCaste,
      --SO.FamilySubCast,
      --SO.CastCategoryId,
      
      CCM.Title AS CasteCategory,
      --SO.ReligionId,
      RM.Title AS Religion,
      --SO.HouseId,
      HM.Title AS House,
      --SO.MotherTongueId,
      MTM.Title AS MotherTongue,
      --SO.NationalityId,
      NM.Title AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity AS IsPhysicalDeformity,
      SH.PysicalDeformityRemark AS PhysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
    STUFF(
        COALESCE(',' + NULLIF(SC.PresentStreetOne, ''), '')  + 
        COALESCE(',' + NULLIF(SC.PresentStreetTwo, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentStreetThree, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentCountry, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentState, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentCity, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentZipCode, ''), '') +
        COALESCE(',' + NULLIF(SC.PresentContactNo, ''), ''),
        1, 1, '') AS PresentAddress,
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
	   STUFF(
           COALESCE(',' + NULLIF(SC.PermanentStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.PermanentStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentStreetThree, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentCity, ''), '') +
            COALESCE(',' + NULLIF(SC.PermanentZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.PermanentContactNo, ''), ''),
           1, 1, '') AS PermanentAddress ,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
	   
      STUFF(
           COALESCE(',' + NULLIF(SC.EmergencyStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.EmergencyStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyStreetThree, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyState, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyCity, ''), '') +
            COALESCE(',' + NULLIF(SC.EmergencyZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.EmergencyContactNo, ''), ''),
           1, 1, '') AS EmergencyAddress ,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  --AR.PickupDestinationId AS BusRouteDestinationId,
	  BDM.Title AS BusRouteDestination,
	  SF.FatherName,
	  SF.FatherDateOfBirth,	 
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeContactNo,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome AS FatherAnnualIncome,	-- MantisId : 0029214
	  SF.MotherName,
	  SF.MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
	  SF.MotherOfficeContactNo,
      SF.MotherOfficeAddress,
      SF.MotherIncome AS MotherAnnualIncome,	-- MantisId : 0029214   
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  SAD.AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
      SAD.InactiveDate,
	  SAD.InActiveReason,
	  SAD.LCBook,
	  SAD.LeftStandardId AS LeftStandard,
	  SAD.LeftDate,
	  SAD.LCDate,
	  SAD.LCCopy,
	  SAD.LeftReason,
	  SAD.LCProgress,
	  SAD.LCConduct,
	  SAD.LCRemark,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.BankAccountNumber,
	  AD.BankName,
	  AD.BankBranch,
	  AD.BankIFSCCode,
	  AD.BankAccountHolderName,
	  BSM.Title AS StudentBatchStatus,
	  AD.Class9BoardRegistrationNumber,
	  AD.Class11BoardRegistrationNumber,
	  AD.PassportNumber,
	  AD.PassportType,
	  AD.PassportCountryCode,
	  AD.PassportIssueDate,
	  AD.PassportExpiryDate,
	  SS.SiblingName1,
	  SS.SiblingInstitue1,
	  SS.SiblingClass1,
	  SS.SiblingAge1,
	  SS.SiblingRelation1,
	  SS.SiblingName2,
	  SS.SiblingInstitue2,
	  SS.SiblingClass2,
	  SS.SiblingAge2,
	  SS.SiblingRelation2,
	  SS.SiblingName3,
	  SS.SiblingInstitue3,
	  SS.SiblingClass3,
	  SS.SiblingAge3,
	  SS.SiblingRelation3,
	  CD.SSCBoard,
	  CD.SSCSchool,
	  CD.SSCPassingYear,
	  CD.SSCObtainMarks,
	  CD.SSCOutOfMarks,
	  CD.SSCPercentage,
	  CD.SSCMathMarks,
	  CD.SSCMathOutOfMarks,
	  CD.HSCBoard,
	  CD.HSCSchool,
	  CD.HSCPassingYear,
	  CD.HSCObtainMarks,
	  CD.HSCOutOfMarks,
	  CD.HSCPercentage,
	  
	  CD.HSCBiologyMarks,
	  CD.HSCBiologyOutOfMarks,
	 
	  CD.HSCChemistryMarks,
	  CD.HSCChemistryOutOfMarks,
	  CD.HSCMathMarks,
	  CD.HSCMathOutOfMarks,
	  cd.HSCPhysicsMarks,
	  CD.HSCPhysicsOutOfMarks,
	  CD.PCMMarks,
	  CD.PCBMarks,
	  CD.JEERollNo,
	  CD.JEEMeritNo,
	  CD.JEEMeritMarks,
	  CD.JEEOutOfMarks,
	  CD.DiplomaBoard,
	  CD.DiplomaCollege,
	  CD.DiplomaPassingYear,
	  CD.DiplomaObtainMarks,
	  CD.DiplomaOutOfMarks,
	  CD.DiplomaPercentage,
	  CD.ApplicationNo,
	  CD.AdmissionRound,
	  CD.MaritalStatusId,
	  ISNULL(HHM.Title,'') AS HostelName,
	  ISNULL(HRM.Title,'') AS Room,
	  ISNULL(HBM.Title,'') AS BuildingName,
	  ISNULL(HAR.BedNumber,'') AS BedNumber,
	  ISNULL(SGM.Title,'') AS StudentGroup,
	  ISNULL(SGMO.Title,'') AS StudentOtherGroup,
	  SO.BirthState,
	  SO.BirthCountry,
	  ISNULL(BDM.PickupTime,'') AS PickupTime,
	  ISNULL(BDM.DropTime,'') AS DropTime,
	  ISNULL(BRM.Title,'') AS BusRoute,
	  ISNULL(SAD.PreviousStandard,'') AS PreviousStandard,
	  ISNULL(So.ReferenceRemark,'') AS ReferenceRemark,
	  ISNULL(SAD.LCNumber,'') AS LCNumber,
	  CM.Title AS AdmissionStandard,
	  SF.IsFatherExStudent,
	  SF.IsMotherExStudent,
	  SF.FatherOrganization,
	  SF.FatherDesignation,
	  SF.MotherOrganization,
	  SF.MotherDesignation,
	  SF.RelativeOrganization,
	  SF.RelativeDesignation,
	  SH.IsAllergy,
      SH.AllergyRemark,
      SO.FamilySubCast,
      SF.RelativeName,
      SF.RelativeDateOfBirth,
      SF.RelativeOccupation,
      SF.RelativeQualification,
      SF.RelativeContactNo,
      SF.RelativeMail,
      SF.RelativeOfficeAddress,      
      SF.RelativeIncome AS RelativeAnnualIncome,		-- MantisId : 0029214
     
    
		STUFF( (SELECT DISTINCT ',' + CTM.Title FROM sStudent.tStudentCustomTag SCT INNER JOIN sStudent.tCustomTagMaster CTM ON SCT.CustomTagId=CTM.Id 
							WHERE SCT.StudentId = SA.StudentId FOR XML PATH ('')), 1, 1, '')  AS CustomTag,
		STM.Title AS RecordTag,
		SC.WhatsAppContactNo,
        SC.IsStopApplicationAccess,
		CASE WHEN ISNULL(SO.DateOfBirth, '') = '' THEN '' ELSE (SELECT [sCommon].[fGetDateOfBirthInWord](SO.DateOfBirth)) END AS Age,
		BDM.Title AS PickupPoint 
  FROM sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SAD.AdmissionStandardId
	INNER JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	INNER JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	INNER JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	INNER JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	INNER JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	INNER JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	INNER JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	INNER JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId
	INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	INNER JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	INNER JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	INNER JOIN sStudent.tStudentadditional AD ON AD.StudentId= SA.StudentId
	INNER JOIN sStudent.tStudentBatchStatus SBS ON SBS.AcademicId = SA.AcademicId
	INNER JOIN sStudent.tBatchStatusMaster BSM ON BSM.Id = SBS.BatchStatusId
	INNER JOIN sStudent.tStudentSibling SS ON SS.StudentId= SA.StudentId
	INNER JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	INNER JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SA.StudentId
	INNER JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	INNER JOIN sHostel.tBuildingMaster HBM ON HBM.HostelId = HRM.HostelId
	INNER JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	INNER JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SA.StudentGroupId
	INNER JOIN sStudent.tStudentOtherGroupMaster SGMO ON SGMO.Id = SA.StudentOtherGroupId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
	INNER JOIN sCommon.tStatusMaster STM ON STM.Id = SA.RecordStatusId AND STM.StatusTypeId=102
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
GO
PRINT N'Altering View [sStudent].[vStudentCustomSearch]...';


GO

ALTER VIEW [sStudent].[vStudentCustomSearch]  
  
AS  
  
SELECT 	
	  SA.AcademicId,	  
	  SA.ClassId,
	  SA.DivisionId,
	  SA.RollNo,
	  SA.OrgId,
	  OM.Title AS Organization,
	  SA.BatchId,
	  BM.Title AS Batch,
	  BM.OrgGroupBatchId,
	  SA.DepartmentId,
	  DM.Title AS Department,
	  SA.StudentId,
	  SA.SUId,
	  SA.Code,
	  SA.Number,
	  SA.FirstName,
	  SA.MiddleName,
	  SA.LastName,
	  SA.Name,
	  --SA.DepartmentId,
	  SA.StatusId,
	  SA.ClassName,
	  SA.DivisionName,
	  SA.StatusName,
	  SO.UIDNumber,
	  SO.AdhaarNumber,
      CONVERT(VARCHAR(10), SO.DateOfBirth, 111) AS DateOfBirth,
      SO.BirthdateInWord,
      SO.TransportModeId,
      TM.Title AS TransportMode,
      SO.GenderId,
      GM.Title AS Gender,
      SO.BloodGroupId,
      BGM.Title AS BloodGroup,
      SO.BirthPlace,
      SO.BirthTaluka,
      SO.BirthDistrict,
      SO.FamilyCast AS FamilyCaste,
      SO.FamilySubCast,
      
      
      SO.CastCategoryId,
      CCM.Title AS CasteCategory,
      SO.ReligionId,
      RM.Title AS Religion,
      SO.HouseId,
      HM.Title AS House,
      SO.MotherTongueId,
     SO.MotherTongue AS MotherTongue,
      SO.NationalityId,
      NM.Nationality AS Nationality,
      SO.Hobby,
      SH.IdentificationMark1,
      SH.IdentificationMark2,
      SH.IsPysicalDeformity,
      SH.PysicalDeformityRemark,
      SH.IsMajorIllness,
      SH.MajorIllnessRemark,
      SH.FamilyDoctorName,
      SH.FamilyDoctorContactNo,
      
	  SC.PresentStreetOne,
      SC.PresentStreetTwo,
      SC.PresentStreetThree,
      SC.PresentCountry,
      SC.PresentState,
      SC.PresentCity,
      SC.PresentZipCode,
      SC.PresentContactNo,
      SC.PermanentStreetOne,
      SC.PermanentStreetTwo,
      SC.PermanentStreetThree,
      SC.PermanentCountry,
      SC.PermanentState,
      SC.PermanentCity,
      SC.PermanentZipCode,
      SC.PermanentContactNo,
      SC.EmergencyStreetOne,
      SC.EmergencyStreetTwo,
      SC.EmergencyStreetThree,
      SC.EmergencyCountry,
      SC.EmergencyState,
      SC.EmergencyCity,
      SC.EmergencyZipCode,
      SC.EmergencyContactNo,
      SC.ParentContactNo,
      SC.ParentEmail,
      SC.StudentContactNo,
      SC.StudentEmail,
	  ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
	  RT.BusRouteDestinationId AS BusRouteDestinationId,
	  RT.BusRouteDestination AS BusRouteDestination,
	  SF.FatherName,
	  CONVERT(VARCHAR(10), SF.FatherDateOfBirth, 111)AS FatherDateOfBirth,
	  SF.FatherQualification,
	  SF.FatherOccupation,
	  SF.FatherContactNo,
	  SF.FatherMail,
	  SF.FatherOfficeAddress,
	  SF.FatherIncome AS FatherAnnualIncome,	-- MantisId : 0029214
	  SF.FatherOfficeContactNo,
	  SF.MotherName,
	 CONVERT(VARCHAR(10),  SF.MotherDateOfBirth,111) AS MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
	  SF.MotherOfficeContactNo,
      SF.MotherOfficeAddress,
      SF.MotherIncome AS MotherAnnualIncome,    -- MantisId : 0029214  
	  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
	  AC.Title AS AdmissionCategory,
	  SAD.PreviousSchool,
	  CONVERT(VARCHAR(10), SAD.AdmissionDate, 111) AS AdmissionDate,
	  SAD.AdmissionFormNumber,
	  SAD.AdmissionNumber,
	  SAD.IsTransfer,
	  SAD.TransferFrom,
	  SAD.PassingYear,
	  SAD.IsTFWS,
	  SAD.IsCertificateHolder,
	  SAD.CertificateName,
	  AQM.Title AS AdmissionQuota,
	  CONVERT(VARCHAR(10),SAD.LeftDate, 111) AS LeftDate,
	  SA.IsBlackList,
	  SA.BlackListReason,
	  SA.DivisionOrder,
	  SA.ClassOrderIndex,
	  AD.RepeatCount,
	  ADI.BankAccountNumber,
	  ADi.BankBranch,
	  ADI.BankIFSCCode,
	  ADI.BankName,
	  ADI.BankAccountHolderName,
	  ESM.Title AS StudentBatchStatus,
	  EnrollmentStatusId AS StudentStatusId,
	  ADI.Class9BoardRegistrationNumber,
	  ADI.Class11BoardRegistrationNumber,
	  ADI.PassportNumber,
	  ADI.PassportType,
	  ADI.PassportCountryCode,
	CONVERT(VARCHAR(10),ADI.PassportIssueDate,111) AS PassportIssueDate,
	  ADI.PassportExpiryDate,
	  ISNULL(SS.SiblingName1,'') As SiblingName1,
	  ISNULL(SS.SiblingInstitue1,'') As SiblingInstitue1,
	  ISNULL(SS.SiblingClass1,'') As SiblingClass1,
	  ISNULL(SS.SiblingAge1,'') As SiblingAge1,
	  ISNULL(SS.SiblingRelation1,'') As SiblingRelation1,
	  ISNULL(SS.SiblingName2,'') As SiblingName2,
	  ISNULL(SS.SiblingInstitue2,'') As SiblingInstitue2,
	  ISNULL(SS.SiblingClass2,'') As SiblingClass2,
	  ISNULL(SS.SiblingAge2,'') As SiblingAge2,
	  ISNULL(SS.SiblingRelation2,'') As SiblingRelation2,
	  ISNULL(SS.SiblingName3,'') As SiblingName3,
	  ISNULL(SS.SiblingInstitue3,'') As SiblingInstitue3,
	  ISNULL(SS.SiblingClass3,'') As SiblingClass3,
	  ISNULL(SS.SiblingAge3,'') As SiblingAge3,
	  ISNULL(SS.SiblingRelation3,'') As SiblingRelation3,
	  ISNULL(HHM.Title,'') AS HostelName,
	  ISNULL(HRM.Title,'') AS Room,
	  ISNULL(HBM.Title,'') AS BuildingName,
	  ISNULL(HAR.BedNumber,'') AS BedNumber,
	  
	  ISNULL(SM.StudentGroupId,0) AS StudentGroupId,
	  ISNULL(SM.StudentOtherGroupId,0) AS StudentOtherGroupId,
	  
	  SGM.Title AS StudentGroup,
	  SOGM.Title AS StudentOtherGroup,
	  SO.BirthState,
	  So.BirthCountry,
	  ISNULL(RT.BusRouteId,0) AS BusRouteId,
	  ISNULL(RT.PickupTime,'') AS PickupTime,
	  ISNULL(RT.Droptime,'') AS Droptime,
	  ISNULL(RT.BusRoute,'' )AS BusRoute,
	   CD.SSCBoard,
	   CD.SSCSchool,
	  CD.SSCPassingYear,
	  CD.SSCObtainMarks,
	  CD.SSCOutOfMarks,
	  CD.SSCPercentage,
	  CD.SSCMathMarks,
	  CD.SSCMathOutOfMarks,
	  CD.HSCBoard,
	  CD.HSCSchool,
	  CD.HSCPassingYear,
	  CD.HSCObtainMarks,
	  CD.HSCOutOfMarks,
	  CD.HSCPercentage,
	  
	  CD.HSCBiologyMarks,
	  CD.HSCBiologyOutOfMarks,
	 
	  CD.HSCChemistryMarks,
	  CD.HSCChemistryOutOfMarks,
	  CD.HSCMathMarks,
	  CD.HSCMathOutOfMarks,
	  cd.HSCPhysicsMarks,
	  CD.HSCPhysicsOutOfMarks,
	  CD.PCMMarks,
	  CD.PCBMarks,
	  CD.JEERollNo,
	  CD.JEEMeritNo,
	  CD.JEEMeritMarks,
	  CD.JEEOutOfMarks,
	  CD.DiplomaBoard,
	  CD.DiplomaCollege,
	  CD.DiplomaPassingYear,
	  CD.DiplomaObtainMarks,
	  CD.DiplomaOutOfMarks,
	  CD.DiplomaPercentage,
	  CD.ApplicationNo,
	  CD.AdmissionRound,
	  CD.MaritalStatusId,
	  EX.Id As ExemptionTypeId,
	  SAD.PreviousStandard,
	  SO.ReferenceRemark,
	  SAD.LCNumber,
	  CM.Title AS AdmissionStandard,
	  SH.IsAllergy,
      SH.AllergyRemark,
      SF.RelativeName,
      SF.RelativeDateOfBirth,
      SF.RelativeOccupation,
      SF.RelativeQualification,
      SF.RelativeContactNo,
      SF.RelativeMail,
      SF.RelativeOfficeAddress,      
      SF.RelativeIncome AS RelativeAnnualIncome,		-- MantisId : 0029214
      STUFF(
           COALESCE(',' + NULLIF(SC.PresentStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.PresentStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentStreetThree, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PresentCity, ''), '') +
            COALESCE(',' + NULLIF(SC.PresentZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.PresentContactNo, ''), ''),
           1, 1, '') AS PresentAddress,
      STUFF(
           COALESCE(',' + NULLIF(SC.PermanentStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.PermanentStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentStreetThree, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentState, ''), '') +
           COALESCE(',' + NULLIF(SC.PermanentCity, ''), '') +
            COALESCE(',' + NULLIF(SC.PermanentZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.PermanentContactNo, ''), ''),
           1, 1, '') AS PermanentAddress ,
      STUFF(
           COALESCE(',' + NULLIF(SC.EmergencyStreetOne, ''), '')  + 
           COALESCE(',' + NULLIF(SC.EmergencyStreetTwo, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyStreetThree, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyCountry, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyState, ''), '') +
           COALESCE(',' + NULLIF(SC.EmergencyCity, ''), '') +
            COALESCE(',' + NULLIF(SC.EmergencyZipCode, ''), '') +
            COALESCE(',' + NULLIF(SC.EmergencyContactNo, ''), ''),
           1, 1, '') AS EmergencyAddress ,
	  (SELECT STUFF( (SELECT DISTINCT ',' + CTM.Title FROM sStudent.tStudentCustomTag SCT INNER JOIN sStudent.tCustomTagMaster CTM ON SCT.CustomTagId=CTM.Id 
							WHERE SCT.StudentId = SA.StudentId FOR XML PATH ('')), 1, 1, '')  AS CustomTag FROM sStudent.tStudentMaster SM1 WHERE SM1.Id = SM.Id GROUP BY SM1.Id) AS CustomTag,
		STM.Title AS RecordTag,
		SC.IsStopApplicationAccess,
		CASE WHEN ISNULL(SO.DateOfBirth, '') = '' THEN '' ELSE (SELECT [sCommon].[fGetDateOfBirthInWord](SO.DateOfBirth)) END AS Age,
		RT.PickupPoint as PickupPoint

  FROM sStudent.vStudentAcademic SA
    INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SAD.AdmissionStandardId
	LEFT JOIN sCommon.tAdmissionQuotaMaster AQM ON AQM.Id = SAD.AdmissionQuotaId
	LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	--LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId
	LEFT JOIN sCommon.tTransportModeMaster TM ON TM.Id=SO.TransportModeId
	LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
	LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
	LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id=SO.CastCategoryId
	LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
	LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
	LEFT JOIN sCommon.tMotherTongueMaster MTM ON MTM.Id=SO.MotherTongueId
	LEFT JOIN sCommon.tCountryMaster NM ON NM.Id=SO.NationalityId
	--LEFT JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId
	LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId=SA.StudentId
	LEFT JOIN sStudent.tAdmissionCategoryMaster AC ON AC.Id=SA.AdmissionCategoryId
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId = SA.AcademicId
	LEFT JOIN sStudent.tStudentadditional ADI ON ADI.StudentId = SA.StudentId
	LEFT JOIN sStudent.tEnrollmentStatusMaster ESM ON ESM.Id = SM.EnrollmentStatusId
	LEFT JOIN sStudent.tStudentSibling SS ON SS.StudentId = SA.StudentId
	LEFT JOIN sHostel.tAssignRoom HAR ON HAR.SourceId = SM.Id AND HAR.OrgGroupBatchId = SA.OrgGroupBatchId
	LEFT JOIN sHostel.tRoomMaster HRM ON HRM.Id = HAR.RoomId
	LEFT JOIN sHostel.tBuildingMaster HBM ON HRM.BuildingId = HBM.Id 
	LEFT JOIN sHostel.tHostelMaster HHM ON HHM.Id = HRM.HostelId
	
	LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id=SM.StudentGroupId
	LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id=SM.StudentOtherGroupId
	--LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId
	LEFT JOIN sStudent.tCollegeDetail CD ON CD.StudentId = SA.StudentId
	LEFT JOIN sFee.tExemptionTypeMaster EX ON Ex.Id=SA.ExemptionTypeId
   LEFT JOIN
	(SELECT AR.SourceId,AR.DropDestinationId AS BusRouteDestinationId,BDM2.Title AS BusRouteDestination,AR.PickupDestinationId AS BusRoutePickupDestinationId,BDM.Title AS PickupPoint, ISNULL(BRM.Id,0) AS BusRouteId,
	  ISNULL(BDM.PickupTime,'') AS PickupTime,
	  ISNULL(BDM.Droptime,'') AS Droptime,
	  ISNULL(BRM.Title,'' )AS BusRoute,BRM.OrgGroupBatchId FROM sTransport.tAssignRoute AR 
    INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id=AR.PickupDestinationId
	LEFT JOIN sTransport.tBusRouteDestinationMaster BDM2 ON BDM2.Id=AR.DropDestinationId
    INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BDM.BusRouteId AND  AR.SourceTypeId=2003  )  RT 
    ON RT.SourceId = SA.StudentId     AND RT.OrgGroupBatchId =SA.OrgGroupBatchId
	INNER JOIN sCommon.tStatusMaster STM ON STM.Id = SA.RecordStatusId AND STM.StatusTypeId=102
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = SA.DepartmentId
GO

PRINT N'Creating Function [sCommon].[fConvertDateTimeToDifferentTimeZone]...';


GO

CREATE FUNCTION [sCommon].[fConvertDateTimeToDifferentTimeZone](@rDateTime datetime)
RETURNS [datetime] WITH EXECUTE AS CALLER
AS 
BEGIN
		DECLARE @lConfigValue nvarchar(50),@date datetime
		

		DECLARE @lTimeZoneConfigValue nvarchar(max), @lConfigValueId int
		
		Select @lConfigValueId = CV.Id FROM sConfig.tConfigurationSetup CS 
		INNER JOIN sConfig.tConfigurationValue CV ON CS.ConfigurationId = CV.ConfigurationId AND CS.ItemValue = CV.ItemValue
		WHERE CS.ConfigurationId = 234

		--@lConfigValueId = 60 for (UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi
		--@lConfigValueId = 61 for (UTC+00:00) Dublin, Edinburgh, Lisbon, London
		--@lConfigValueId = 72 for (UTC+03:00) Nairobi


		----SELECT @lConfigValueId

		----for (UTC+00:00) Dublin, Edinburgh, Lisbon, London
		IF(@rDateTime = '')
		BEGIN
			SELECT @date = @rDateTime
		END
		ELSE IF(@lConfigValueId = 61)
		BEGIN
		    SELECT @date = DATEADD(MINUTE, -330, @rDateTime)
			--SELECT @date = '2023-10-01 00:00:00.000'
		END
		--for (UTC+03:00) Nairobi and (UTC+03:00) Kuwait , Riyadh
		ELSE IF(@lConfigValueId = 72 OR @lConfigValueId = 203)
		BEGIN
			SELECT @date = CONVERT(DATETIME,SWITCHOFFSET(CONVERT(DATETIMEOFFSET, (DATEADD(MINUTE, -330, @rDateTime))), '+03:00'))
		END
		--for (UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi
		ELSE
		BEGIN
			SELECT @date = @rDateTime
		END

		RETURN @date

END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionFormGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionFormGet]

	 @rAdmissionFormId bigint = 0,
	 @rFormNo int,
	 @rForClassId int,
	 @rBatchId int=0,
	 @rStatusId smallint='',
	 @rOrgId int,
	 @rFirstName nvarchar(100),
	 @rLastName nvarchar(100),
	 @rMeritMarks decimal(10,2),
	 @rFromDate datetime= '1900-01-01',
	 @rToDate datetime = '9990-12-31',
	 @rDepartmentId int=0,
	 @rIsTransportFilter int=2,
	 @rIsHostelFilter int=2,
	 @rDataEntryStatusId smallint=0,
	 @rIsCommonSearch bit=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	SET @rToDate = DATEADD(d,1,@rToDate)		 

BEGIN 
		--IF @rIsSearch = 1
		BEGIN
		SET @rFirstName = ISNULL(@rFirstName,'')
		SET @rLastName = ISNULL(@rLastName,'')
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	
	SELECT 
			 AF.Id
			,AF.FormNo
			,AF.FirstName
			,AF.MiddleName
			,AF.LastName

			--,AF.FirstName+' '+AF.LastName as Name
			,[sStudent].[fStudentNameGet](AF.FirstName , ISNULL(AF.MiddleName,'') , AF.LastName,OM.StudentNameFormatId ) AS Name

			,AF.ForClassId
			,AF.BatchId
			,CM.Title AS ClassName
			,AF.ForBatch
			,ISNULL(AF.DateOfBirth,'') AS DateOfBirth
			,AF.DateOfBirthInWord
			,AF.StatusId
			,SM.Title as StatusName
			,ISNULL(ASM.Title,'') AS FormStatus
			,AF.StreetOne
			,AF.StreetTwo
			,AF.StreetThree
			,AF.Country
			,AF.State
			,AF.City
			,AF.ZipCode
			,AF.ContactNo
			,AF.ContactEmail
			,AF.Remark
			,AF.PreviousSchool
			,AF.MeritMarks
			,AF.MeritGrade
			,AF.GenderId
			,ISNULL(GM.Title,'') AS Gender
			,ISNULL(AF.ReligionId,0) AS ReligionId
			,AF.FamilyCast
			,AF.FamilySubCast
			,ISNULL(AF.CastCategoryId,0) AS CastCategoryId
			,AF.CreatedDateTime AS AdmissionFormDate
			,ISNULL(AF.StudentId,0) AS StudentId
			,ISNULL(AF.AdmissionDate,'') AS AdmissionDate
			--,AF.StudentPhoto,
			,(CASE WHEN @rIsCommonSearch=0 THEN ISNULL(AF.StudentPhoto,0) ELSE NULL END) AS StudentPhoto
			
			,ISNULL(AFFD.FatherName,'') AS FatherName,
			Isnull(AFFD.FatherDateOfBirth,'') AS FatherDateOfBirth,
			Isnull(AFFD.FatherOccupation,'') AS FatherOccupation,
			Isnull(AFFD.FatherQualification,'') AS FatherQualification,
			Isnull(AFFD.FatherContactNo,'') AS FatherContactNo,
			Isnull(AFFD.FatherMail,'') AS FatherMail,
			Isnull(AFFD.FatherOfficeAddress,'') As FatherOfficeAddress,
			isnull(AFFD.FatherOrganization,'') as FatherOrganization,
			isnull(AFFD.FatherDesignation,'') as FatherDesignation,
			Isnull(AFFD.FatherIncome,'') as FatherIncome,
			Isnull(AFFD.MotherName,'') AS MotherName,
			iSNULL(AFFD.MotherDateOfBirth,'')AS MotherDateOfBirth,
			isnull(AFFD.MotherOccupation,'') AS MotherOccupation,
			isnull(AFFD.MotherQualification,'') AS MotherQualification,
			isnull(AFFD.MotherContactNo,'') as MotherContactNo,
			isnull(AFFD.MotherMail,'') As MotherMail,
			isnull(AFFD.MotherOfficeAddress,'') as MotherOfficeAddress,
			isnull(AFFD.MotherOrganization,'') as MotherOrganization,
			isnull(AFFD.MotherDesignation,'') as MotherDesignation,
			isnull(AFFD.MotherIncome,'') as MotherIncome,
			AF.MotherTongue AS MotherTongue,
		 
			isnull(AFFD.RelationshipName,'') as RelationshipName,
			isnull(AFFD.RelativeName,'')  AS GuardianName ,
			isnull(AFFD.RelativeDateOfBirth ,'')AS GuardianDateOfBirth,
			isnull(AFFD.RelativeOccupation,'') AS GuardianOccupation,
			isnull(AFFD.RelativeQualification,'') AS GuardianQualification,
			isnull(AFFD.RelativeContactNo,'') AS GuardianContactNo,
			isnull(AFFD.RelativeMail,'')  AS GuardianMail,
			isnull(AFFD.RelativeOfficeAddress,'') AS GuardianOfficeAddress,
			isnull(AFFD.RelativeOrganization,'') as RelativeOrganization,
			isnull(AFFD.RelativeDesignation,'') as RelativeDesignation,
			isnull(AFFD.RelativeIncome,'') AS GuardianIncome  ,
			isnull(AF.IsHostelRequired,0) AS IsHostelRequired  ,
			isnull(AF.IsTransportRequired,0) AS IsTransportRequired,
			isnull(AF.BirthPlace,'') AS BirthPlace,
			isnull(AF.BirthTaluka,'') AS BirthTaluka,
			isnull(AF.BirthDistrict,'') AS BirthDistrict,
			isnull(AF.BloodGroupId,0) AS BloodGroupId,
			isnull(AF.AdhaarNumber,'') AS AdhaarNumber,
			isnull(AF.IsPysicalDeformity,0) AS IsPysicalDeformity,
			isnull(AF.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			isnull(AF.IsMajorIllness,0) AS IsMajorIllness,
			isnull(AF.MajorIllnessRemark,'') AS MajorIllnessRemark,
			isnull(AF.IsAllergy,0) AS IsAllergy,
			isnull(AF.AllergyRemark,'') AS AllergyRemark,
			isnull(AF.BirthState,'') AS BirthState,
			isnull(AF.BirthCountry,'') AS BirthCountry,
			isnull(SA.PreviousStandard,'') As PreviousStandard,
	        isnull(AFFD.LiveWithId,0) AS LiveWithId,
			--isnull(ASB.SiblingName,'') AS SiblingName,
			--isnull(ASB.SiblingRelation,'')AS SiblingRelation,
			
			--isnull(ASB.SiblingStandard,'') AS SiblingStandard,
			--isnull(ASB.SiblingSchool,'')AS SiblingSchool
			
			 ISNULL(AF.CustomField1Answer,'') AS CustomField1Answer,
			 ISNULL(AF.CustomField2Answer,'') AS CustomField2Answer,
			 ISNULL(AF.CustomField3Answer,'') AS CustomField3Answer,
			 SM1.Title AS DataEntryStatus,
			 AF.Nationality,
			 ISNULL(AFFD.FatherAdhaarNumber,'') AS FatherAdhaarNumber,
			 AF.CreatedDateTime AS AdmissionFormDate,
			 ISNULL(AFFD.MotherAadhaarNumber,'') AS MotherAadhaarNumber,
			 ISNULL(AFFD.RelativeAadhaarNumber,'') AS RelativeAadhaarNumber,
			 ISNULL(AFFD.FatherOfficePhone,'') AS FatherOfficePhone,
			 ISNULL(AFFD.MotherOfficePhone,'') AS MotherOfficePhone,
			 CASE WHEN AF.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode,
			 ISNULL(AF.WhatsappContactNo,'') AS WhatsappContactNo		--add for 29511 mantis
			 
  FROM 
            sAdmission.tAdmissionForm AF
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AF.StatusId
			INNER JOIN sCommon.tStatusMaster SM1 ON SM1.Id=AF.DataEntryStatusId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AF.ForClassId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AF.GenderId
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFFD ON AFFD.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = AF.StudentId
			 --LEFT JOIN sAdmission.tAdmissionFormSibling ASB ON ASB.AdmissionFormId = AF.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentID=AF.StudentID
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
		AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))
		AND ((AF.FirstName like @rFirstName) OR (@rFirstName=''))
		AND ((AF.LastName like @rLastName) OR (@rLastName=''))
		--AND ((AF.CreatedDateTime>= @rFromDate) OR (@rFromDate=''))
		AND ((Cast(AF.AdmissionDate as datetime)>= @rFromDate) OR (@rFromDate=''))
		--AND ((AF.AdmissionDate is not null AND Cast(AF.AdmissionDate as datetime)>= @rFromDate) or (AF.AdmissionDate is null AND AF.CreatedDateTime>= @rFromDate) or (@rFromDate=''))
		--AND ((AF.CreatedDateTime < @rToDate) OR (@rToDate=''))
		AND ((Cast(AF.AdmissionDate as datetime)<= @rToDate) OR (@rToDate=''))
		--AND ((AF.AdmissionDate is not null AND Cast(AF.AdmissionDate as datetime)< @rToDate) or (AF.AdmissionDate is null AND AF.CreatedDateTime< @rToDate) or (@rToDate=''))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AF.ForClassId=@rForClassId) OR (@rForClassId=0)) 
		AND ((AF.BatchId=@rBatchId) OR (@rBatchId=0)) 
		--AND ((AF.MeritMarks=@rMeritMarks) OR (@rMeritMarks=0))
		AND ((AF.StatusId=@rStatusId) OR (@rStatusId = ''))
		AND ((AF.DataEntryStatusId=@rDataEntryStatusId) OR (@rDataEntryStatusId = 0))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId = 0))
		AND AF.OrgId=@rOrgId
        AND ((ISnull(AF.IsHostelRequired,0)=@rIsHostelFilter ) OR   (ISNULL(@rIsHostelFilter,2)=2) )
	   AND ((ISNUll(AF.IsTransportRequired,0)=@rIsTransportFilter) OR (isnull(@rIsTransportFilter,0) = 2))
	  
 order by AF.FormNo
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionFormAdd]...';


GO


ALTER PROCEDURE [sAdmission].[pAdmissionFormAdd]
		 @rId bigint
		,@rFormNo int
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName	nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int		 
		,@rDateOfBirth date
		,@rDateOfBirthInWord nvarchar(100)
		,@rOrgId smallint
		,@rBatchId int
		,@rStatusId	smallint
		,@rStreetOne nvarchar(50)
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode	nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10, 2)
		,@rMeritGrade nvarchar(20)
		,@rGenderId	int
		,@rReligionId int
		,@rFamilyCast nvarchar(100)
		,@rFamilySubCast nvarchar(100)
		,@rCastCategoryId int
		,@rCreatedUserId bigint
		,@rFormPassword nvarchar(100)=''
		,@rDataEntryModeId smallint
		,@rDataEntryStatusId smallint
		,@rStudentPhoto varbinary(max),
		 @rNationality nvarchar(150),
		 @rMotherTongue nvarchar(150),
		 @rOtherInformation nvarchar(150),
		 @rIsPysicalDeformity bit,
		 @rPysicalDeformityRemark nvarchar(200),
         @rIsMajorIllness bit,
         @rMajorIllnessRemark nvarchar(200),
         @rIsAllergy bit,
         @rAllergyRemark nvarchar(200),
         @rBirthPlace nvarchar(150),
         @rBirthTaluka nvarchar(150),
         @rBirthDistrict nvarchar(150),
         @rBloodGroupId tinyint,
         @rAdhaarNumber nvarchar(20),
         @rIsHostelRequired bit=0,
		 @rIsTransportRequired bit=0,
		 @rBirthState nvarchar(150)='',
		 @rBirthCountry nvarchar(150)='',
		 @rCustomField1Answer nvarchar(200)='',
		 @rCustomField2Answer nvarchar(200)='',
		 @rCustomField3Answer nvarchar(200)='',
		 --@rFatherAdhaarNumber nvarchar(50) ,
		 @OutAdmissionFormId BIGINT = NULL OUTPUT,
		 @rOriginalStudentPhoto varbinary(max) = null,
		 @rAdmissionDate date='',
		 @rWhatsappContactNo nvarchar(20) = '' -- Added column of WhatsappContact for mantis : 29772
		
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--BEGIN TRY
	

	
 BEGIN TRANSACTION	
 DECLARE @lNextNumber BIGINT
 DECLARE @lBIGID BIGINT
 DECLARE @lSMALLID INT
 
 IF(@rId = 0)	
	BEGIN
	
	
	
		IF Exists(select FormNo from sAdmission.tAdmissionForm where FormNo=@rFormNo AND BatchId=@rBatchId)
			BEGIN
			select -101 as Result
			RETURN
		END 
	
	--EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2006,@rStoreLocationId = 0, @rNextNumber  = @rFormNo OUTPUT

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

	--	IF @rFormNo = '-300'
	--  BEGIN
	--	SELECT -300 AS Result, '' AS Number, 0 AS Id 
	--	RETURN
	--  END
	IF(@rFormNo = 0)
	BEGIN
	SELECT @rFormNo = ISNULL(MAX(FormNo),0) + 1 FROM sAdmission.tAdmissionForm WHERE BatchId=@rBatchId
	
	END
	
	IF(@rFormPassword = '')
	BEGIN
	SELECT @rFormPassword = @rFormNo
	
	END
	
	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionForm', 0, 1, 1,@outNextNumber = @lNextNumber output
	
--SET	 @lBIGID  = @lNextNumber
--SET	 @lSMALLID  = CONVERT(int, @lBIGID)
	-- IF(@rFormNo = 0)
	-- BEGIN
	-- select convert(int,@lNextNumber)
	--SET @rFormNo = ISNULL(@rFormNo,@lNextNumber)
	--END
	INSERT INTO sAdmission.tAdmissionForm
		(
			 Id
			,FormNo
			,FirstName
			,MiddleName
			,LastName
			,ForClassId			 
			,ForBatchId
			,DateOfBirth
			,DateOfBirthInWord
			,OrgId
			,BatchId
			,StatusId
			,StreetOne
			,StreetTwo
			,StreetThree
			,Country
			,State
			,City
			,ZipCode
			,ContactNo
			,ContactEmail
			,Remark
			,PreviousSchool
			,MeritMarks
			,MeritGrade
			,GenderId
			,ReligionId
			,FamilyCast
			,FamilySubCast
			,CastCategoryId
			,CreatedUserId
			,CreatedDateTime
			,FormPassword
			,DataEntryModeId
			,DataEntryStatusId
			,StudentPhoto,
			Nationality,
			MotherTongue,
			OtherInformation,
			IsPysicalDeformity,
           PysicalDeformityRemark,
           IsMajorIllness,
           MajorIllnessRemark,
           IsAllergy,
           AllergyRemark,
           BirthPlace,
         BirthTaluka,
         BirthDistrict,
         BloodGroupId,
         AdhaarNumber,
         IsHostelRequired,
         IsTransportRequired,
         BirthState,
         BirthCountry,
         CustomField1Answer,
         CustomField2Answer,
         CustomField3Answer,
		 OriginalStudentPhoto,
		 AdmissionDate,
		 WhatsappContactNo -- Added column of WhatsappContact for mantis : 29772
         --FatherAdhaarNumber
			
		)
	VALUES
		(
			 @lNextNumber
			,@rFormNo
			,@rFirstName
			,@rMiddleName
			,@rLastName
			,@rForClassId			 
			,@rForBatchId
			,@rDateOfBirth
			,@rDateOfBirthInWord
			,@rOrgId
			,@rBatchId
			,@rStatusId
			,@rStreetOne
			,@rStreetTwo
			,@rStreetThree
			,@rCountry
			,@rState
			,@rCity
			,@rZipCode
			,@rContactNo
			,@rContactEmail
			,@rRemark
			,@rPreviousSchool
			,@rMeritMarks
			,@rMeritGrade
			,@rGenderId
			,@rReligionId
			,@rFamilyCast
			,@rFamilySubCast
			,@rCastCategoryId
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rFormPassword
			,@rDataEntryModeId
			,@rDataEntryStatusId
			,@rStudentPhoto,
			@rNationality,
			@rMotherTongue,
			@rOtherInformation,
			@rIsPysicalDeformity,
			   @rPysicalDeformityRemark,
			   @rIsMajorIllness,
			   @rMajorIllnessRemark,
			   @rIsAllergy,
			   @rAllergyRemark,
			  @rBirthPlace,
			 @rBirthTaluka,
			 @rBirthDistrict,
			 @rBloodGroupId,
			 @rAdhaarNumber,
			 @rIsHostelRequired,
			 @rIsTransportRequired,
			 @rBirthState,
			@rBirthCountry,
			 @rCustomField1Answer,
			 @rCustomField2Answer,
			 @rCustomField3Answer,
			 @rOriginalStudentPhoto,
			 @rAdmissionDate,
			 @rWhatsappContactNo -- Added column of WhatsappContact for mantis : 29772
			 --@rFatherAdhaarNumber
		)
		             
	END	 
	 ELSE
	 BEGIN
	 
	 
	 
	 	IF Exists(select FormNo from sAdmission.tAdmissionForm where FormNo=@rFormNo AND BatchId=@rBatchId And Id <> @rId)
			BEGIN
			select -101 as Result
			RETURN
		END 
	
	 
	 
	 SET @lNextNumber = @rId
	    UPDATE  sAdmission.tAdmissionForm
	    SET
	        FormNo = @rFormNo
			,FirstName=@rFirstName
			,MiddleName=@rMiddleName
			,LastName=@rLastName
			,ForClassId=@rForClassId			
			,DateOfBirth=@rDateOfBirth
			,DateOfBirthInWord=@rDateOfBirthInWord
			,StatusId=@rStatusId
			,StreetOne=@rStreetOne
			,StreetTwo=@rStreetTwo
			,StreetThree=@rStreetThree
			,Country=@rCountry
			,State=@rState
			,City=@rCity
			,ZipCode=@rZipCode
			,ContactNo=@rContactNo
			,ContactEmail=@rContactEmail
			,Remark=@rRemark
			,PreviousSchool=@rPreviousSchool
			,MeritMarks=@rMeritMarks
			,MeritGrade=@rMeritGrade
			,GenderId=@rGenderId
			,ReligionId=@rReligionId
			,FamilyCast=@rFamilyCast
			,FamilySubCast=@rFamilySubCast
			,CastCategoryId=@rCastCategoryId
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
			--,DataEntryModeId = @rDataEntryModeId
			--,DataEntryStatusId = @rDataEntryStatusId
			,StudentPhoto = @rStudentPhoto,
			Nationality =@rNationality,
			MotherTongue=@rMotherTongue,
			OtherInformation=@rOtherInformation,
			IsPysicalDeformity=@rIsPysicalDeformity,
           PysicalDeformityRemark=@rPysicalDeformityRemark,
           IsMajorIllness=@rIsMajorIllness,
           MajorIllnessRemark=@rMajorIllnessRemark,
           IsAllergy=@rIsAllergy,
           AllergyRemark=@rAllergyRemark,
           BirthPlace=@rBirthPlace,
		   BirthTaluka=@rBirthTaluka,
			BirthDistrict=@rBirthDistrict,
			BloodGroupId=@rBloodGroupId,
			AdhaarNumber=@rAdhaarNumber,
			IsHostelRequired= @rIsHostelRequired,
			IsTransportRequired=@rIsTransportRequired,
			BirthState=@rBirthState,
			BirthCountry=@rBirthCountry,
			CustomField1Answer=@rCustomField1Answer,
			CustomField2Answer=@rCustomField2Answer,
			CustomField3Answer=@rCustomField3Answer,
			OriginalStudentPhoto=@rOriginalStudentPhoto,
			AdmissionDate=@rAdmissionDate,
			WhatsappContactNo = @rWhatsappContactNo  -- Added column of WhatsappContact for mantis : 29772
			--FatherAdhaarNumber = @rFatherAdhaarNumber
	      WHERE Id = @rId 	   
	 END  
		SELECT @lNextNumber AS Result
	SET @OutAdmissionFormId=@lNextNumber
		COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionFormConfirmGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionFormConfirmGet]
	 @rAdmissionFormId bigint = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
		
	SELECT 
			iSNULL(AF.Id,0) as Id,
			AF.FormNo,
			AF.FirstName,
			AF.MiddleName,
			AF.LastName,
			AF.ForClassId,
			iSNULL(AF.ForBatchId, 0) as ForBatchId,
			AF.ForBatch,
			AF.DateOfBirth,
			AF.DateOfBirthInWord,
			AF.OrgId,
			AF.BatchId,
			AF.StatusId,
			AF.StreetOne,
			AF.StreetTwo,
			AF.StreetThree,
			AF.Country,
			AF.State,
			AF.City,
			AF.ZipCode,
			AF.ContactNo,
			AF.ContactEmail,
			AF.Remark,
			AF.PreviousSchool,
			AF.MeritMarks,
			AF.MeritGrade,
			iSNULL(AF.GenderId,0) as GenderId,
			iSNULL(AF.ReligionId,0) as ReligionId ,
			AF.FamilyCast,
			AF.FamilySubCast,
			iSNULL(AF.CastCategoryId,0) as CastCategoryId,
			AF.CreatedUserId,
			AF.CreatedDateTime,
			iSNULL(AF.UpdatedUserId,0) aS UpdatedUserId,
			AF.UpdatedDateTime,
			iSNULL(AF.StudentId,0) as StudentId,
			AF.FormPassword,
			iSNULL(AF.DataEntryModeId,0) as DataEntryModeId,
			iSNULL(AF.DataEntryStatusId,0) as DataEntryStatusId,
			AF.StudentPhoto,
			iSNULL(AF.AdmissionCategoryId,0) AS AdmissionCategoryId,
			AF.Nationality,
			AF.MotherTongue,
			AF.OtherInformation,
			iSNULL(AF.IsPysicalDeformity,0) aS IsPysicalDeformity ,
			AF.PysicalDeformityRemark,
			iSNULL(AF.IsMajorIllness,0) aS IsMajorIllness ,
			AF.MajorIllnessRemark,
			iSNULL(AF.IsAllergy,0) aS IsAllergy,
			AF.AllergyRemark,
			AF.BirthPlace,
			AF.BirthTaluka,
			AF.BirthDistrict,
			iSNULL(AF.BloodGroupId,0) AS  BloodGroupId,
			AF.AdhaarNumber,
			iSNULL(AF.IsHostelRequired,0) as IsHostelRequired,
			iSNULL(AF.IsTransportRequired,0) as IsTransportRequired,
			AF.BirthState,
			AF.BirthCountry,
			OM.Title AS SchoolName,
			BM.Title AS BatchName,
			CM.Title AS ClassName,
			GM.Title AS Gender,
			RM.Title AS ReligionName,
			CCM.Title AS CastCategoryName,
			BGM.Title AS BloodGroup,
			ISNULL(AF.CustomField1Answer,'') AS CustomField1Answer,
			ISNULL(AF.CustomField2Answer,'') AS CustomField2Answer,
			ISNULL(AF.CustomField3Answer,'') AS CustomField3Answer,
			AF.WhatsappContactNo -- Change done for mantis 29772
			
  FROM
   sAdmission.tAdmissionForm AF
   LEFT JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 
   LEFT JOIN sSetup.tBatchMaster BM ON AF.BatchId=BM.Id 
   LEFT JOIN sSetup.tClassMaster CM ON AF.ForClassId = CM.Id 
   LEFT JOIN sCommon.tGenderMaster GM ON AF.GenderId = GM.Id
    LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = AF.ReligionId 
    LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = AF.CastCategoryId 
    LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = AF.BloodGroupId
  WHERE 
  
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))
       
 
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionFormOnlineGet]...';


GO

ALTER PROCEDURE [sAdmission].[pAdmissionFormOnlineGet]  
  @rAdmissionFormId bigint = 0,  
  @rFormNo int,  
  @rOrgId int  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
    
 SELECT   
   iSNULL(Id,0) as id,  
   FormNo,  
   FirstName,  
   MiddleName,  
   LastName,  
   ForClassId,  
   iSNULL(ForBatchId, 0) as ForBatchId,  
   ForBatch,  
   DateOfBirth,  
   DateOfBirthInWord,  
   OrgId,  
   BatchId,  
   StatusId,  
   StreetOne,  
   StreetTwo,  
   StreetThree,  
   Country,  
   State,  
   City,  
   ZipCode,  
   ContactNo,  
   ContactEmail,  
   Remark,  
   PreviousSchool,  
   MeritMarks,  
   MeritGrade,  
   iSNULL(GenderId,0) as GenderId,  
   iSNULL(ReligionId,0) as ReligionId ,  
   FamilyCast,  
   FamilySubCast,  
   iSNULL(CastCategoryId,0) as CastCategoryId,  
   CreatedUserId,  
   CreatedDateTime,  
   iSNULL(UpdatedUserId,0) aS UpdatedUserId,  
   UpdatedDateTime,  
   iSNULL(StudentId,0) as StudentId,  
   FormPassword,  
   iSNULL(DataEntryModeId,0) as DataEntryModeId,  
   iSNULL(DataEntryStatusId,0) as DataEntryStatusId,  
   StudentPhoto,  
   iSNULL(AdmissionCategoryId,0) AS AdmissionCategoryId,  
   Nationality,  
   MotherTongue,  
   OtherInformation,  
   iSNULL(IsPysicalDeformity,0) aS IsPysicalDeformity ,  
   PysicalDeformityRemark,  
   iSNULL(IsMajorIllness,0) aS IsMajorIllness ,  
   MajorIllnessRemark,  
   iSNULL(IsAllergy,0) aS IsAllergy,  
   AllergyRemark,  
   BirthPlace,  
   BirthTaluka,  
   BirthDistrict,  
   iSNULL(BloodGroupId,0) AS  BloodGroupId,  
   AdhaarNumber,  
   iSNULL(IsHostelRequired,0) as IsHostelRequired,  
   iSNULL(IsTransportRequired,0) as IsTransportRequired,  
   BirthState,  
   BirthCountry,  
   ISNULL(AF.CustomField1Answer,'') AS CustomField1Answer,  
   ISNULL(AF.CustomField2Answer,'') AS CustomField2Answer,  
   ISNULL(AF.CustomField3Answer,'') AS CustomField3Answer,
   WhatsappContactNo -- Change done for mantis 29772
  FROM   
           sAdmission.tAdmissionForm AF  
  WHERE   
    
      ((AF.Id = @rAdmissionFormId) OR (@rAdmissionFormId = 0))  
  AND ((AF.FormNo=@rFormNo) OR (@rFormNo=0))  
  AND AF.OrgId=@rOrgId  
         
 order by AF.FormNo  
END
GO
PRINT N'Altering Procedure [sAdmission].[pAdmissionGenerateReport]...';


GO

ALTER PROCEDURE [sAdmission].[pAdmissionGenerateReport]
 
	@rId bigint,
	@rClassId int,
	@rClassIds nvarchar(max)='',
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rFormNo [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rFatherName nvarchar(50)='',
	@rMotherName nvarchar(50)='',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rMotherTongue nvarchar(max) = '',
	@rNationality nvarchar(max) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rBatchId int = 0,
	@rFromFormNo nvarchar(20), 
	@rToFormNo nvarchar(20),
	@rContactNo nvarchar(50) = '',
	@rReportName nvarchar(50) ='',
	@rPageIndex int,
	@rCreatedUserId bigint,
	@rIsCommon bit = 0,
	@rIsCommonForOrg bit = 0,
	@rSavedReport nvarchar(max) = ''
	

AS
BEGIN
	 
	SET NOCOUNT ON;

    IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate='0001-01-01'
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate='9990-12-31'
	IF(@rDOAFromDate IS NULL)
		SET @rDOAFromDate='0001-01-01'
	IF(@rDOAToDate IS NULL)
		SET @rDOAToDate='9990-12-31'

	If @rDOBToDate <> '9999-12-31'
		SET @rDOBToDate = DATEADD(d,1,@rDOBToDate)
	If @rDOAToDate <> '9999-12-31'
		SET @rDOAToDate = DATEADD(d,1,@rDOAToDate)
		
		IF(@rReportName != '' AND @rId = 0)
		BEGIN
			DECLARE @lNextNumber BIGINT, @query  AS NVARCHAR(MAX), @lColumnValue nvarchar(max) 
			declare @lColumnName nvarchar(max), @lClmNm nvarchar(max)
			declare @lOrderBy nvarchar(max), @lOrdBy nvarchar(max)
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
			--PRINT(@lNextNumber)
			--Removing Table Alias while Inserting in Table
			SET @lColumnName = @rColumnName
			SET @lClmNm = Replace(@lColumnName,'AT.','')
			SET @lClmNm = Replace(@lClmNm,'ACF.','')
			
			SET @lOrderBy = @rOrderBy
			SET @lOrdBy = Replace(@lOrderBy,'AT.','')
			SET @lOrdBy = Replace(@lOrdBy,'ACF.','')
			--print(@lOrdBy)
			--print(@lClmNm)
			INSERT INTO sAdmission.tAdmissionCustomSearch
			(
				Id,Title,ColumnName,OrderBy,OrgId,BatchId, ClassId, FormNo, FromFormNo, ToFormNo,StatusId,ClassIds,FirstName,LastName,FatherName, 
				MotherName, DOBFromDate,DOBToDate,DOAFromDate,DOAToDate,Country,State,City,ContactNo,GenderId,ReligionId,CastCategoryId,
				Nationality,BloodGroupId,MotherTongueId,PreviousSchool,FatherQualification,MotherQualification,FatherOccupation,MotherOccupation,
				IsCommonUsers,IsCommonForOrg, CreatedUserId,CreatedDateTime
			)
			VALUES
			(
				@lNextNumber,@rReportName,@lClmNm,@lOrdBy,@rOrgId,@rBatchId,@rClassId,@rFormNo,@rFromFormNo,@rToFormNo,@rStatusId,@rClassIds,@rFirstName,@rLastName,
				@rFatherName,@rMotherName,@rDOBFromDate,@rDOBToDate,@rDOAFromDate,@rDOAToDate,@rCountry,@rState,
				@rCity,@rContactNo,@rGenderId,@rReligionId,@rCastCategoryId,@rNationality,@rBloodGroupId,@rMotherTongue,
				@rPreviousSchool,@rFatherQualification,@rMotherQualification,@rFatherOccupation,@rMotherOccupation,
				@rIsCommon,@rIsCommonForOrg,@rCreatedUserId,sCommon.fGetDate()
			)
		END
		--IF(@rId > 0)
		--BEGIN
		--	Select @rColumnName=ColumnName,@rOrderBy=OrderBy,@rOrgId=OrgId,@rBatchId=BatchId,@rClassId=ClassId,@rFormNo=FormNo,
		--	@rFromFormNo=FromFormNo,@rToFormNo=ToFormNo,@rStatusId=StatusId,@rClassIds=ClassIds,@rFirstName=FirstName,@rLastName=LastName,
		--	@rFatherName=FatherName,@rMotherName=MotherName,@rDOBFromDate=DOBFromDate,@rDOBToDate=DOBToDate,@rDOAFromDate=DOAFromDate,
		--	@rDOAToDate=DOAToDate,@rCountry=Country,@rState=State,@rCity=City,@rContactNo=ContactNo,@rGenderId=GenderId,@rReligionId=ReligionId,
		--	@rCastCategoryId=CastCategoryId,@rNationality=Nationality,@rBloodGroupId=BloodGroupId,@rMotherTongue=MotherTongueId,@rPreviousSchool=PreviousSchool,
		--	@rFatherQualification=FatherQualification,@rMotherQualification=MotherQualification,@rFatherOccupation=FatherOccupation,@rMotherOccupation=MotherOccupation
		--	FROM sAdmission.tAdmissionCustomSearch WHERE Id=@rId
		--END

		DECLARE @Sql nvarchar(MAX)= ''
		
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rFatherName = sCommon.fSearchStringGet(@rFatherName)
		SET @rMotherName = sCommon.fSearchStringGet(@rMotherName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		SET @rCity = sCommon.fSearchStringGet(@rCity)
		SET @rNationality = sCommon.fSearchStringGet(@rNationality)
		SET @rMotherTongue = sCommon.fSearchStringGet(@rMotherTongue)
		SET @rPreviousSchool = sCommon.fSearchStringGet(@rPreviousSchool)
		SET @rFatherQualification = sCommon.fSearchStringGet(@rFatherQualification)
		SET @rMotherQualification = sCommon.fSearchStringGet(@rMotherQualification)
		SET @rFatherOccupation = sCommon.fSearchStringGet(@rFatherOccupation)
		SET @rMotherOccupation = sCommon.fSearchStringGet(@rMotherOccupation)
		
		






	SELECT * INTO #MyAdmissionSearchTable 
	FROM
	(SELECT  CASE 
			WHEN AF.BloodGroupId = 1 THEN 'A+'
			WHEN AF.BloodGroupId = 2 THEN 'A-'
			WHEN AF.BloodGroupId = 3 THEN 'B+'
			WHEN AF.BloodGroupId = 4 THEN 'B-'
			WHEN AF.BloodGroupId = 5 THEN 'O+'
			WHEN AF.BloodGroupId = 6 THEN 'O-'
			WHEN AF.BloodGroupId = 7 THEN 'AB+'
			WHEN AF.BloodGroupId = 8 THEN 'AB-'
			WHEN AF.BloodGroupId = 9 THEN '-'
		END AS BloodGroup, 
		CASE 
			WHEN AFD.LiveWithId = 1 THEN 'Both'
			WHEN AFD.LiveWithId = 2 THEN 'Father'
			WHEN AFD.LiveWithId = 3 THEN 'Mother'
			WHEN AFD.LiveWithId = 4 THEN 'Guardian'
		END AS LiveWith,
		CASE 
			WHEN AF.GenderId = 1 THEN 'Male'
			WHEN AF.GenderId = 2 THEN 'Female'
		END AS Gender,
		AF.Id,
		AF.FormNo as FormNo,
		AF.FirstName,
		AF.MiddleName,
		AF.LastName as SurName,
		AF.FirstName + ' '+  AF.LastName AS StudentName,
		AF.DateOfBirth,
		AF.OrgId,
		AF.BatchId,
		AF.StatusId,
		AF.StreetOne,
		AF.StreetTwo,
		AF.StreetThree,
		AF.Country,
		AF.State,
		AF.City,
	   AF.ZipCode,
	   AF.ContactNo,
	   AF.ContactEmail,
	   AF.Remark,
	   AF.PreviousSchool,
	   AF.MeritMarks,
	   AF.MeritGrade,
	   AF.GenderId,
	   AF.ReligionId,
	   AF.FamilyCast,
	   AF.FamilySubCast,
	   AF.CastCategoryId,
	   AF.StudentId,
	   AF.FormPassword,
	   AF.Nationality,
	   AF.MotherTongue,
	   AF.IsPysicalDeformity,
	   AF.PysicalDeformityRemark,
	   AF.IsMajorIllness,
	   AF.MajorIllnessRemark,
	   AF.IsAllergy,
	   AF.AllergyRemark,
	   AF.BirthPlace,
	   AF.BirthTaluka,
	   AF.BirthDistrict,
	   AF.BloodGroupId,
	   AF.AdhaarNumber,
	   AF.BirthState,
	   AF.BirthCountry,
	   AF.OriginalStudentPhoto,
	   AF.OtherInformation as OtherInformation,
	   AF.AdmissionDate AS AdmissionFormDate,
	   CASE WHEN AF.IsHostelRequired = 0 THEN 'No' WHEN AF.IsHostelRequired = 1 THEN 'Yes' END AS HostelRequired,
	   CASE WHEN AF.IsTransportRequired = 0 THEN 'No' WHEN AF.IsTransportRequired = 1 THEN 'Yes' END AS TransportRequired,
	   OM.Title as Organization, 
	   OM.AffiliationId,
	   BM.Title as Batch, 
	   BM.FromDate, 
	   BM.ToDate, 
	   SM.Title as Status,
	   CM.Id as ClassId,
	   CM.Title as Class,
	   RM.Title AS Religion,
	   APA1.AcademicYear as FatherAcademicYear,
	   APA1.AdmissionClass as FatherAdmissionClass,
	   APA1.InstituteName as FatherInstituteName,
	   APA1.InstituteCity as FatherInstituteCity,
	   APA1.InstituteAffiliaton as FatherInstituteAffiliation,
	   APA1.Language as FatherMediumOfStudy,
	   APA2.AcademicYear as MotherAcademicYear,
	   APA2.AdmissionClass as MotherAdmissionClass,
	   APA2.InstituteName as MotherInstituteName,
	   APA2.InstituteCity as MotherInstituteCity,
	   APA2.InstituteAffiliaton as MotherInstituteAffiliation,
	   APA2.Language as MotherMediumOfStudy,
	   APA3.AcademicYear as GuardianAcademicYear, 
	   APA3.AdmissionClass as GuardianAdmissionClass,
	   APA3.InstituteName as GuardianInstituteName,
	   APA3.InstituteCity as GuardianInstituteCity,
	   APA3.InstituteAffiliaton as GuardianInstituteAffiliation,
	   APA3.Language as GuardianMediumOfStudy,
	   RSM.Title,
	   (STUFF((SELECT ',' + ReferenceDetail FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceDetail,
	   (STUFF((SELECT ',' + ReferenceName FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceName,
	   (STUFF((SELECT ',' + ReferenceRelation FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceRelation,
	   (STUFF((SELECT ',' + ReferenceContactNo FROM sAdmission.tAdmissionFormReference WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS ReferenceContactNo,
	   AFSA.AcademicYear as StudentAcademicYear,
	   AFSA.AdmissionClass as StudentAdmissionClass,
	   (STUFF((SELECT ',' + SiblingName FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingName,
	   (STUFF((SELECT ',' + SiblingRelation FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingRelation,
	   (STUFF((SELECT ',' + SiblingStandard FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingStandard,
	   (STUFF((SELECT ',' + SiblingSchool FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS SiblingSchool,
	   (STUFF((SELECT ',' + Code FROM sAdmission.tAdmissionFormSibling WHERE AdmissionFormId = AF.Id FOR XML PATH ('')), 1, 1, '')) AS Code,
	   AFSA.InstituteName as StudentInstituteName,
	   AFSA.InstituteCity as StudentInstituteCity,
	   AFSA.InstituteAffiliaton as StudentInstituteAffiliation, 
	   AFSA.Result, 
	   AFSA.Language,
	   AFD.FatherName, 
	   AFD.FatherDateOfBirth,
	   AFD.FatherOccupation,
	   AFD.FatherQualification,
	   AFD.FatherContactNo,
	   AFD.FatherMail,
	   AFD.FatherOfficeAddress,
	   AFD.FatherIncome AS FatherAnnualIncome, -- MantisId : 0029214 Changed label FatherIncome to FatherAnnualIncome
	   AFD.MotherName,
	   AFD.MOtherDateOfBirth,
	   AFD.MotherOccupation,
	   AFD.MotherQualification,
	   AFD.MotherContactNo,
	   AFD.MotherMail,
	   AFD.MotherOfficeAddress, 
	   AFD.MotherIncome AS MotherAnnualIncome, -- MantisId : 0029214 Changed label MotherIncome to MotherAnnualIncome
	   AFD.RelationshipName,
	   AFD.RelativeName,
	   AFD.RelativeDateOfBirth,
	   AFD.RelativeOccupation,
	   AFD.RelativeQualification,
	   AFD.RelativeContactNo,
	   AFD.RelativeMail,
	   AFD.RelativeOfficeAddress,
	   AFD.RelativeIncome AS RelativeAnnualIncome,	-- MantisId : 0029214 Changed label RelativeIncome to RelativeAnnualIncome
	   AFD.FatherPhoto,
	   AFD.MotherPhoto,
	   AFD.RelativePhoto,
	   AFD.FatherOrganization,
	   AFD.FatherDesignation,
	   AFD.FatherOfficePhone,
	   AFD.MotherOrganization,
	   AFD.MotherDesignation,
	   AFD.MotherOfficePhone,
	   AFD.RelativeOrganization,
	   AFD.RelativeDesignation,
	   AFD.RelativeOfficePhone,
	   AFD.IsFatherExStudent,
	   AFD.FatherPassOutYear,
	   AFD.IsMotherExStudent,
	   AFD.MotherPassOutYear, 
	   AFD.IsRelativeExStudent,
	   AFD.RelativePassOutYear,
	   AFD.FatherAdhaarNumber,
	   AFD.OriginalFatherPhoto,
	   AFD.OriginalMotherPhoto,
	   AFD.OriginalRelativePhoto,
	   AFD.MotherAadhaarNumber,
	   AFD.RelativeAadhaarNumber,
	   U.LoginTitle As AdmissionHandledBy,
	   SM1.CreatedDateTime AS AdmissionFormConvertedDate
		from sAdmission.tAdmissionForm AF
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
		INNER JOIN  sCommon.tStatusMaster SM ON AF.StatusId = SM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
		INNER JOIN sSecurity.tUser U ON U.Id = AF.CreatedUserId
		LEFT JOIN  sStudent.tStudentAdmission SA ON SA.AdmissionFormId = AF.Id
		LEFT JOIN  sStudent.tStudentMaster SM1 ON SM1.Id = AF.StudentId AND AF.StatusId=208
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id = AF.ReligionId
		LEFT JOIN sAdmission.tAdmissionFormParentAcademic APA1 ON APA1.AdmissionFormId = AF.Id AND APA1.RelationShipId = 1
		LEFT JOIN sAdmission.tAdmissionFormParentAcademic APA2 ON APA2.AdmissionFormId = AF.Id AND APA2.RelationShipId = 2
		LEFT JOIN sAdmission.tAdmissionFormParentAcademic APA3 ON APA3.AdmissionFormId = AF.Id AND APA3.RelationShipId = 7
		LEFT JOIN sCommon.tRelationshipMaster RSM ON RSM.Id = APA1.RelationshipId
		LEFT JOIN sCommon.tRelationshipMaster RSM1 ON RSM1.Id = APA2.RelationshipId
		LEFT JOIN sCommon.tRelationshipMaster RSM2 ON RSM2.Id = APA3.RelationshipId
		--LEFT JOIN sAdmission.tAdmissionFormReference AFR ON AFR.AdmissionFormId = AF.Id
		--LEFT JOIN sAdmission.tAdmissionFormSibling AFS ON AFS.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionFormStudentAcademic AFSA ON AFSA.AdmissionFormId = AF.Id
		LEFT JOIN sAdmission.tAdmissionFormFamilyDetail AFD ON AFD.AdmissionFormId = AF.Id
		WHERE ((AF.OrgId = @rOrgId ) OR (@rOrgId = 0))
				AND ((AF.BatchId = @rBatchId) OR (@rBatchId = 0))
				AND ((AF.ForClassId = @rClassId) OR (@rClassId = 0))
			    AND ((ISNULL(AF.ForClassId,0) IN (SELECT cast(item as int) FROM sCommon.fnsplit(@rClassIds,',')) OR (@rClassIds='')))
				AND ((AF.FormNo = @rFormNo) OR (@rFormNo = ''))
				AND ((AF.FormNo  >= @rFromFormNo) OR (ISNULL(@rFromFormNo,'') = ''))
				AND ((AF.FormNo  <= @rToFormNo) OR (ISNULL(@rToFormNo,'') = ''))
			    AND (AF.StatusId = @rStatusId)
				AND ((AF.FirstName Like @rFirstName) OR (@rFirstName = ''))
				AND ((AF.LastName Like @rLastName)OR(@rLastName = ''))
				AND ((AFD.FatherName like @rFatherName) OR (@rFatherName=''))
				AND ((AFD.MotherName like @rMotherName) OR (@rMotherName=''))
				AND (( AF.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
				AND (( AF.DateOfBirth  <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
				--AND (( CAST(AF.CreatedDateTime AS Date)  >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
				--AND (( CAST(AF.CreatedDateTime AS Date)  <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
				AND ((Convert(nvarchar(12),AF.CreatedDateTime) >=  @rDOAFromDate) OR (@rDOAFromDate=''))
			    AND ((Convert(nvarchar(12),AF.CreatedDateTime) <=  @rDOAToDate) OR (@rDOAToDate=''))
				AND ((ISNULL(AF.Country,'') Like @rCountry )OR(@rCountry = ''))
				AND ((ISNULL(AF.State,'') Like @rState)OR(@rState = ''))
				AND ((ISNULL(AF.City,'') Like @rCity)OR(@rCity = ''))
				AND ((AF.ContactNo=@rContactNo) OR (@rContactNo=0))
				AND (ISNULL(AF.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
				AND (ISNULL(AF.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
				AND (ISNULL(AF.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
				AND ((AF.Nationality Like @rNationality) OR (@rNationality = ''))
				AND (ISNULL(AF.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
				AND ((AF.MotherTongue Like @rMotherTongue) OR (@rMotherTongue = ''))
				AND ((AF.PreviousSchool Like  @rPreviousSchool) OR (@rPreviousSchool = ''))
				AND ((AFD.FatherQualification Like  @rFatherQualification) OR (@rFatherQualification = ''))
				AND ((AFD.MotherQualification Like @rMotherQualification) OR (@rMotherQualification = ''))
				AND ((AFD.FatherOccupation Like @rFatherOccupation) OR (@rFatherOccupation = ''))
				AND ((AFD.MotherOccupation Like @rMotherOccupation) OR (@rMotherOccupation = '')) 
				) AS AdmissionReportGeneration
				
		  --SELECT * FROM #MyAdmissionSearchTable

		  --AdmissionCriteriaFields
		  DECLARE @cols AS NVARCHAR(MAX),@criteriaquery  AS NVARCHAR(MAX)
			-- CTE for Admission Form Field
			;WITH AdmissionCriteriaFormCTE AS (SELECT  DISTINCT FieldRemark FROM sAdmission.tAdmissionCriteriaForm ACF
			LEFT JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
			--WHERE (ACF.BatchId = @rBatchId OR @rBatchId = 0) AND (ACF.ClassId = @rClassId OR @rClassId = 0)
			GROUP BY Id,FieldRemark,ClassId,BatchId
			)
			SELECT @cols = STUFF((SELECT  ',' + QUOTENAME(FieldRemark) FROM AdmissionCriteriaFormCTE
			GROUP BY FieldRemark
			ORDER BY FieldRemark FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')
			

			IF object_id('tempdb..##tempAdmissionCriteriaForm') IS NOT NULL 
			BEGIN
			--print('Hi')
			   DROP TABLE ##tempAdmissionCriteriaForm 
			END
			IF(@cols IS NOT NULL)
			BEGIN 
				SET @criteriaquery = 'SELECT DISTINCT AdmissionFormId,' + @cols + ' INTO ##tempAdmissionCriteriaForm FROM 
							 (
								SELECT DISTINCT  AFF.AdmissionFormId,AdmissionFormFieldResponse, FieldRemark
								FROM 
								sAdmission.tAdmissionCriteriaForm ACF
								INNER JOIN sAdmission.tAdmissionFormField AFF ON ACF.Id = AFF.AdmissionCriteriaFormId
								WHERE ((ACF.BatchId = '+CONVERT(nvarchar(10),@rBatchId)+') OR (' +CONVERT(nvarchar(10),@rBatchId)+' = 0)) AND ((ACF.ClassId = '+CONVERT(nvarchar(10),@rClassId)+') OR ('+CONVERT(nvarchar(10),@rClassId)+' = 0))
							) x
							PIVOT
							(
								MAX(AdmissionFormFieldResponse)
								FOR FieldRemark IN (' + @cols + ')
							) p' 
				print(@criteriaquery)
				exec (@criteriaquery)
				
				  --SELECT * FROM #MyAdmissionSearchTable
				--SELECT * FROM ##tempAdmissionCriteriaForm ACF
			END
			IF(@cols IS NULL)
				Declare @lSQLAlt nvarchar(max)=''
				IF(@rOrderBy = '' OR @rOrderBy = NULL)
				BEGIN
					SET @lSQLAlt = @lSQLAlt + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT '
					print(@lSQLAlt)
					exec(@lSQLAlt)
				END
				ELSE
				BEGIN
				print(@rOrderBy)
				SET @lSQLAlt = @lSQLAlt + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT GROUP BY ' +@rColumnName+ ',' +@rOrderBy+ ' ORDER BY ' +@rOrderBy+ ';'
				print(@lSQLAlt)
				exec (@lSQLAlt)
				END

		  --
		IF(@cols IS NOT NULL)
		Declare @lSQL nvarchar(max) ='', @lqry nvarchar(max)=''
		IF(@rOrderBy = '' OR @rOrderBy = NULL)
		BEGIN
			--SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT'
			SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT LEFT JOIN ##tempAdmissionCriteriaForm ACF ON AT.Id = ACF.AdmissionFormId'
			print(@lSQL)
			exec(@lSQL)
		END
		ELSE
		BEGIN
		print(@rOrderBy)
			SET @lSQL = @lSQL + 'SELECT ' + @rColumnName + ' FROM #MyAdmissionSearchTable AT LEFT JOIN ##tempAdmissionCriteriaForm ACF ON AT.Id = ACF.AdmissionFormId ORDER BY ' +@rOrderBy+ ';'
			print(@lSQL)
			exec (@lSQL)
			IF OBJECT_ID(N'dbo.MyTable0', N'U') IS NOT NULL 
			 DROP Table ##tempAdmissionCriteriaForm
		END
		
END
GO
PRINT N'Altering Procedure [sAlert].[pOnlineAdmissionGet]...';


GO
ALTER PROCEDURE [sAlert].[pOnlineAdmissionGet]
	
	@rAdmissionFormId bigint,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
SELECT 
		
AF.Id AS AdmissionFormId,
		
AF.FirstName+' '+AF.MiddleName+' '+AF.LastName AS Name,
		
AF.ContactNo AS MobileNo,	
		
AF.ContactEmail AS EmailId,
REPLACE (    
REPLACE (
		
REPLACE (
		
REPLACE (
		
REPLACE (
		
REPLACE (
		
REPLACE(@rTemplate,'[Name]',AF.FirstName+' '+AF.MiddleName+' '+AF.LastName),'[Organization]',ISNULL(OM.DisplayTitle,'')),
		'[ForClass]',ISNULL(CM.Title,'')),'[AdmissionFormNo]',ISNULL(AF.FormNo,0)),'[BatchName]',ISNULL(BM.Title,'')),'[Amount]',ISNULL(AC.FormFeeAmount,0)),'[FormPassword]',ISNULL(AF.FormPassword,''))	AS MsgText,
		
@rSubject AS [Subject],
0 As ReceiverSourceId,
0 As ReceiverSourceTypeId,
AF.WhatsappContactNo AS WhatsAppContactNo,		--add for 29511 mantis
ISNULL(AF.FormNo,0) AS AdmissionFormNo,
ISNULL(OM.DisplayTitle,'') AS Organization,
ISNULL(CM.Title,'') AS ForClass,
ISNULL(BM.Title,'') AS BatchName,
ISNULL(AC.FormFeeAmount,0) AS Amount,
ISNULL(AF.FormPassword,'') AS FormPassword


FROM sAdmission.tAdmissionForm AF
INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
LEFT JOIN sAdmission.tAdmissionCriteria AC ON AC.ClassId = CM.Id  AND AC.BatchId= BM.Id
INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = AF.OrgId
WHERE	
		
AF.Id = @rAdmissionFormId

END
GO
PRINT N'Altering Procedure [sAlert].[pCheckEventTemplateGet]...';


GO

 
ALTER PROCEDURE [sAlert].[pCheckEventTemplateGet]

	@rOrgId smallint,
	@rEventId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	SELECT 
			AlertModeId,
			ISNULL(IsAutoSend,'false') AS IsAutoSend,
			Template,
			MailSubject,
			ISNULL(DefaultAlertTo,'') AS DefaultAlertTo,
			EMailCC,
			EMailBCC,
			ISNULL(WhatsAppTemplate,'') AS WhatsAppTemplate,
			ISNULL(WhatsAppTemplateLanguage,'') AS WhatsAppTemplateLanguage,
			ISNULL(DefaultAlertToEUId,'') AS DefaultAlertToEUId
	FROM 
			sAlert.tEventTemplate
	WHERE	
			EventId=@rEventId
			AND OrgId=@rOrgId
	ORDER BY AlertModeId
END
GO
PRINT N'Altering Procedure [sAlert].[pEventTemplateAdd]...';


GO
 
ALTER PROCEDURE [sAlert].[pEventTemplateAdd]
	 
	
	@rEventTemplateDetailXml [nvarchar](max),
	--@rAcademicId bigint,
	@rAlertModeId int,
	@rOrgId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rEventTemplateDetailXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN	
	 DELETE FROM sAlert.tEventTemplate
				 WHERE AlertModeId =@rAlertModeId  AND OrgId=@rOrgId
	
 
	 INSERT INTO sAlert.tEventTemplate
		(
			OrgId,
			EventId,
			MailSubject,
			Template,
			AlertModeId,
			IsAutoSend,
			DefaultAlertTo,
			SMSTemplateID,
			EMailCC,
			EMailBCC,
			WhatsAppTemplate,
			WhatsAppTemplateLanguage,
			DefaultAlertToEUId
			)
		SELECT
		
			OrgId,
			EventId,
			MailSubject,
			Template,
			AlertModeId,
			IsAutoSend,
			DefaultAlertTo,
			SMSTemplateID,
			EMailCC,
			EMailBCC,
			WhatsAppTemplate,
			WhatsAppTemplateLanguage,
			DefaultAlertToEUId
			
		FROM OPENXML (@loDoc, '/Table/EventTemplateDetail', 1)
		WITH ( 
				OrgId int,
				EventId bigint,
				AlertModeId int,
				MailSubject nvarchar(100),
				Template nvarchar(max),
				IsAutoSend bit,
				DefaultAlertTo nvarchar(500),
				SMSTemplateID nvarchar(100),
				EMailCC nvarchar(500),
				EMailBCC nvarchar(500),
				WhatsAppTemplate nvarchar(100),
				WhatsAppTemplateLanguage nvarchar(100),
				DefaultAlertToEUId nvarchar(max)
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAlert].[pEventTemplateListGet]...';


GO
ALTER PROCEDURE [sAlert].[pEventTemplateListGet]

	@rAlertModeId int,
	@rOrgGroupId smallint,
	@rOrgId int,
	@rIsAutoSend bit
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SELECT 
			EM.Title AS EventName,
			ISNULL(ET.Template,ISNULL(EM.Template,'')) AS TemplateName,
			EM.Id,
			ISNULL(ET.AlertModeId,0) AS AlertModeId,
			ISNULL(IsAutoSend,0) AS IsAutoSend,
			EM.Fields AS FieldName,
			MM.Title AS ModuleName,
			MM.Id AS ModuleId,
			ISNULL(ET.MailSubject,ISNULL(EM.MailSubject,'')) AS MailSubject,
			ISNULL(EM.IsAllowAutoSend,0) AS IsAllowAutoSend,
			ISNULL(ET.DefaultAlertTo,'') AS DefaultAlertTo,
			ISNULL(EM.IsAssignDefaultAlert,0) AS IsAssignDefaultAlert,
			ISNULL(ET.SMSTemplateID,'')AS SMSTemplateID,
			ISNULL(ET.EMailCC,'') AS EMailCC,
			ISNULL(ET.EMailBCC,'') AS EMailBCC,
			ISNULL(ET.WhatsAppTemplate,'') AS WhatsAppTemplate,
			ISNULL(ET.WhatsAppTemplateLanguage,'') AS WhatsAppTemplateLanguage,
			ISNULL(ET.DefaultAlertToEUId,'') AS DefaultAlertToEUId
	FROM 
			 sAlert.tEventMaster EM
			 INNER JOIN sCommon.tModuleMaster MM ON MM.Id=EM.ModuleId
			 LEFT JOIN sAlert.tEventTemplate ET ON ET.EventId=EM.Id AND ET.OrgId=@rOrgId AND ((ET.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			 INNER JOIN sSecurity.tModulePermission MP ON MP.OrgGroupId=@rOrgGroupId AND MP.ModuleId=EM.ModuleId 
			 --AND MP.ModuleId!=162
	WHERE	
			(EM.IsObsolete=0)
			ORDER BY ModuleName

END
GO
PRINT N'Altering Procedure [sEMeeting].[pEventTemplateGet]...';


GO

ALTER PROCEDURE [sHrm].[pXMLEmployeeMasterAdd]
	(
		@rXmlDoc nvarchar(MAX),
		@rOrgId int
	)
AS

SET NOCOUNT ON

BEGIN
SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
DECLARE @lInterrorCode INT,
			@intDoc INT
DECLARE @lNextNumber BIGINT			
BEGIN TRY
BEGIN TRANSACTION	
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	select 1
	-----------------------
	INSERT INTO sSetup.tDepartmentMaster
	(
		OrgId,
		Id,
		Code,
		Title,
		DisplayTitle,
		IsObsolete,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime
	)
	SELECT TOP(1)
		A.OrgId,
		sCommon.fGetIntIdForOrg(1,A.OrgId),
		'Default Department',
		'Default Department',
		'Default Department',
		0,
		9999000000003,
		sCommon.fGetDate(),
		9999000000003,
		sCommon.fGetDate()	
	
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		OrgId smallint '@OrgId'
	)A Left Join sSetup.tDepartmentMaster DM ON DM.Id = sCommon.fGetIntIdForOrg(1,A.OrgId)
	Where DM.Id is null 
	
	SELECT @lNextNumber = MAX(ID) FROM sSetup.tDepartmentMaster Where OrgId=@rOrgId
    EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sSetup.tDepartmentMaster', @rCurrentNumber = @lNextNumber 

	-- Update EmployeeMaster
	UPDATE sHrm.tEmployeeMaster
	SET
		FirstName=A.FirstName,
		MiddleName=A.MiddleName,
		LastName=A.LastName,
		StatusId=A.StatusId,
		UpdatedUserId=9999000000003,
		UpdatedDateTime=sCommon.fGetDate()
	FROM
	(
		SELECT
			Id,
			OrgId,
			FirstName,
			MiddleName,
			LastName,
			CASE WHEN StatusId = 1 THEN 7 ELSE 9 END AS StatusId
		
		FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
		WITH
		(
			Id int '@Id' ,
			Code nvarchar(10) '@Code',
			FirstName nvarchar(100) '@FirstName',
			LastName nvarchar(100) '@LastName',
			MiddleName nvarchar(100) '@MiddleName',	
			StatusId tinyint '@StatusId',
			OrgId smallint '@OrgId'
		))A INNER JOIN sHRM.tEmployeeMaster E ON E.ID= sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId) AND  ISNULL(E.IsOtherUser,0) = 0
	
	-- Insert Employee Master
	INSERT INTO sHrm.tEmployeeMaster
	(
		OrgID,
		Id,
		Code,
		FirstName,
		MiddleName,
		LastName,
		StatusId,
		IsObsolete,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,
		EUId				-- MantisId : 	0029269
	)
	SELECT
		A.OrgId,
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId),
		A.Code,
		A.FirstName,
		A.MiddleName,
		A.LastName,
		CASE WHEN A.StatusId = 1 THEN 7 ELSE 9 END,
		0,
		9999000000003,
		sCommon.fGetDate(),
		9999000000003,
		sCommon.fGetDate(),
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId)
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,
		Code nvarchar(10) '@Code',
		FirstName nvarchar(100) '@FirstName',
		LastName nvarchar(100) '@LastName',
		MiddleName nvarchar(100) '@MiddleName',	
		StatusId tinyint '@StatusId',
		OrgId smallint '@OrgId'
	)A LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),@rOrgId) AND  ISNULL(EM.IsOtherUser,0) = 0
	WHERE EM.Id IS NULL
	
	SELECT @lNextNumber = MAX(ID) FROM sHrm.tEmployeeMaster Where OrgId=@rOrgId AND  ISNULL(IsOtherUser,0) = 0
    EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sHrm.tEmployeeMaster', @rCurrentNumber = @lNextNumber 

	-- Update PersonalDetail
	UPDATE sHrm.tEmployeePersonalDetail
	SET
		DateOfBirth=A.DateOfBirth,
		GenderId=A.GenderId,
		MaritalStatusId=A.MaritalStatusId,
		BloodGroupId=A.BloodGroupId,
		Qualification=A.Qualification,
		UpdatedUserId=9999000000003,
		UpdatedDateTime=sCommon.fGetDate()
	FROM
	(	
	SELECT
		OrgId,
		Id,
		CASE WHEN DateOfBirth = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(DateOfBirth, 8)) END AS DateOfBirth,
		CASE WHEN GenderId = 101 OR GenderId = 1 THEN 1 ELSE 2 END AS GenderId,
		CASE WHEN MaritalStatusId  =1 THEN 2 ELSE 1 END AS MaritalStatusId,
		CASE WHEN BloodGroupId =1 THEN 1
			 WHEN BloodGroupId =2 THEN 8
			 WHEN BloodGroupId =3 THEN 5
			 WHEN BloodGroupId =4 THEN 3
			 WHEN BloodGroupId =5 THEN 4
			 WHEN BloodGroupId =6 THEN 2
			 WHEN BloodGroupId =7 THEN 7
			 WHEN BloodGroupId =8 THEN 6 ELSE 9 END AS BloodGroupId,
		Qualification
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id bigint '@Id' ,	
		DateOfBirth int '@dateofbirth',
		GenderId int '@genderId',
		MaritalStatusId int '@MaritalStatusId',
		BloodGroupId int '@BloodGroupId',
		Qualification nvarchar(50) '@Qualification',	
		OrgId smallint '@OrgId'
	))A  INNER JOIN sHRM.tEmployeePersonalDetail EP ON EP.EmployeeId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId) 
	
	
	
	-- Insert PersonalDetail
	INSERT INTO sHrm.tEmployeePersonalDetail
	(
		OrgId,		
		EmployeeId,
		DateOfBirth,
		GenderId,
		MaritalStatusId,
		BloodGroupId,
		Qualification,
		UpdatedUserId,
		UpdatedDateTime
	)
	
	SELECT
		A.OrgId,
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId),
		CASE WHEN A.DateOfBirth = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(A.DateOfBirth, 8)) END,
		CASE WHEN A.GenderId = 101 OR A.GenderId = 1 THEN 1 ELSE 2 END,
		CASE WHEN A.MaritalStatusId  =1 THEN 2 ELSE 1 END,
		CASE WHEN A.BloodGroupId =1 THEN 1
			 WHEN A.BloodGroupId =2 THEN 8
			 WHEN A.BloodGroupId =3 THEN 5
			 WHEN A.BloodGroupId =4 THEN 3
			 WHEN A.BloodGroupId =5 THEN 4
			 WHEN A.BloodGroupId =6 THEN 2
			 WHEN A.BloodGroupId =7 THEN 7
			 WHEN A.BloodGroupId =8 THEN 6 ELSE 9 END,
		A.Qualification,
		9999000000003,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id bigint '@Id' ,	
		DateOfBirth int '@dateofbirth',
		GenderId int '@genderId',
		MaritalStatusId int '@MaritalStatusId',
		BloodGroupId int '@BloodGroupId',
		Qualification nvarchar(50) '@Qualification',	
		OrgId smallint '@OrgId'
	)A LEFT JOIN sHrm.tEmployeePersonalDetail EP ON EP.EMPLOYEEID = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),@rOrgId) 
	WHERE EP.EmployeeId is null
	
	-- Update Job Detail
	UPDATE sHrm.tEmployeeJobDetail
	SET
		DateOfJoining = A.DateOfJoining,		
		EmployeeDesignationId = A.EmployeeDesignationId,
		EmployeeGroupId = A.EmployeeGroupId,
		UpdatedUserId=9999000000003,
		UpdatedDateTime=sCommon.fGetDate()
	FROM
	(
	SELECT
		OrgId,
		Id,
		EmployeeGroupId,
		CASE WHEN DateOfJoining = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(DateOfJoining, 8)) END AS DateOfJoining,
		sCommon.fGetIntIdForOrg(EmployeeDesignationId,OrgId) AS EmployeeDesignationId
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,	
		DateOfJoining int '@DateOfJoining',
		OrgId smallint '@OrgId',
		EmployeeGroupId smallint '@EmployeeGroupId',
		EmployeeDesignationId int '@EmployeeDesignationId'
	))A  INNER JOIN sHRM.tEmployeeJobDetail EJ ON EJ.EmployeeId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId)  
	
	
	-- Insert Job Detail
	INSERT INTO sHrm.tEmployeeJobDetail
	(
		OrgId,
		--Id,
		EmployeeId,
		OrganizationDepartmentId,
		DateOfJoining,		
		EmployeeTypeId,
		EmployeeGroupId,
		EmployeeDesignationId,
		EmployeeGradeId,	
		UpdatedUserId,
		UpdatedDateTime
	)
	SELECT
		A.OrgId,
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),A.OrgId),
		sCommon.fGetIntIdForOrg(1,A.OrgId),
		CASE WHEN A.DateOfJoining = 0 THEN 01/01/1900 ELSE Convert(DATETIME, LEFT(A.DateOfJoining, 8)) END,
		sCommon.fGetIntIdForOrg(1,A.OrgId),
		A.EmployeeGroupId,
		sCommon.fGetIntIdForOrg(A.EmployeeDesignationId,A.OrgId),
		0,	
		9999000000003,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,	
		DateOfJoining int '@DateOfJoining',
		OrgId smallint '@OrgId',
		EmployeeGroupId smallint '@EmployeeGroupId',
		EmployeeDesignationId int '@EmployeeDesignationId'
	)A Left Join sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),@rOrgId)
	where EJ.EmployeeId is null
	


	-- Update Communication Detail
	UPDATE sHrm.tEmployeeCommunications
	SET
		MobileNumber = A.MobileNumber,
		PersonalEmail = A.PersonalEmail,
		PresentStreetOne = A.PresentStreetOne,
		PresentStreetTwo = A.PresentStreetTwo,
		PresentCity = A.PresentCity,
		PresentZipCode = A.PresentZipCode,
		PresentContactNo = A.PresentContactNo,
		PermanentStreetOne =A.PermanentStreetOne,
		PermanentStreetTwo=A.PermanentStreetTwo,
		PermanentCity=A.PermanentCity,
		PermanentZipCode=A.PermanentZipCode
	FROM
	(
	SELECT
		Id,
		MobileNumber,
		PersonalEmail,
		PresentStreetOne,
		PresentStreetTwo,
		PresentCity,
		PresentZipCode,
		PresentContactNo,
		PermanentStreetOne,
		PermanentStreetTwo,
		PermanentCity,
		PermanentZipCode
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,
		MobileNumber nvarchar(20) '@MobileNumber',
		PersonalEmail nvarchar(100) '@PersonalEmail',
		OrgId smallint '@OrgId',
		PresentStreetOne NVARCHAR(50) '@PresentStreetOne',
		PresentStreetTwo NVARCHAR(50) '@PresentStreetTwo',
		PresentCity NVARCHAR(50) '@PresentCity',
		PresentZipCode NVARCHAR(50) '@PresentZipCode',
		PresentContactNo NVARCHAR(20) '@PresentContactNo',
		PermanentStreetOne NVARCHAR(50) '@PermanentStreetOne',
		PermanentStreetTwo NVARCHAR(50) '@PermanentStreetTwo',
		PermanentCity NVARCHAR(50) '@PermanentCity',
		PermanentZipCode NVARCHAR(50) '@PermanentZipCode'
	))A INNER JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId =sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),@rOrgId) 
	
	-- Insert Communication Detail
	INSERT INTO sHrm.tEmployeeCommunications
	(
		EmployeeId,
		MobileNumber,
		PersonalEmail,
		PresentStreetOne,
		PresentStreetTwo,
		PresentCity,
		PresentZipCode,
		PresentContactNo,
		PermanentStreetOne,
		PermanentStreetTwo,
		PermanentCity,
		PermanentZipCode,
		CreatedUserId,
		CreatedDateTime
	)
	SELECT
		sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),@rOrgId),
		A.MobileNumber,
		A.PersonalEmail,
		A.PresentStreetOne,
		A.PresentStreetTwo,
		A.PresentCity,
		A.PresentZipCode,
		A.PresentContactNo,
		A.PermanentStreetOne,
		A.PermanentStreetTwo,
		A.PermanentCity,
		A.PermanentZipCode,
		9999000000003,
		sCommon.fGetDate()
				
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id int '@Id' ,
		MobileNumber nvarchar(20) '@MobileNumber',
		PersonalEmail nvarchar(100) '@PersonalEmail',
		OrgId smallint '@OrgId',
		PresentStreetOne NVARCHAR(50) '@PresentStreetOne',
		PresentStreetTwo NVARCHAR(50) '@PresentStreetTwo',
		PresentCity NVARCHAR(50) '@PresentCity',
		PresentZipCode NVARCHAR(50) '@PresentZipCode',
		PresentContactNo NVARCHAR(20) '@PresentContactNo',
		PermanentStreetOne NVARCHAR(50) '@PermanentStreetOne',
		PermanentStreetTwo NVARCHAR(50) '@PermanentStreetTwo',
		PermanentCity NVARCHAR(50) '@PermanentCity',
		PermanentZipCode NVARCHAR(50) '@PermanentZipCode'

	)A LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = sCommon.fGetBigIntIdForOrg(convert(bigint,RIGHT(A.Id,5)),@rOrgId) 
	WHERE EC.EmployeeId IS null



	IF NOT EXISTS (SELECT ID FROM sHrm.tEmployeeGradeMaster WHERE ID = 1)
	BEGIN
		INSERT INTO sHrm.tEmployeeGradeMaster (Id,Code,Title,
		IsObsolete,CreatedUserId,CreatedDateTime) VALUES
		(1,'Default Grade','Default Grade',0,9999000000003,sCommon.fGetDate())
	END

	EXEC sp_xml_removedocument @intDoc
	COMMIT TRANSACTION
	SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rFromObtain decimal(5,2)=0,
	 @rToObtain decimal(5,2)=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)='' 
	
	 --,@rcolumn_visible bit
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExam
 IF(@rOrgGroupBatchId=0)
	SELECT @rOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id=@rBatchId  
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

Select @GradeStringHtml = GradeStringHtml from sAssessment.tGradeSetMaster where Id =@GradeSetId
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

Declare @lDecimalConfig nvarchar(20)='', @lOrgId int
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
SELECT @lDecimalConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @lOrgId

DECLARE @lAbsentRemarkConfig nvarchar(20) = ''
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId


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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(100),
		StudCode NVarchar(20),
		StudentName Nvarchar(300),
		RollNo int,
		ResultStatus Nvarchar(50),	
		ClassName NVarchar(100),		
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(5,2),
		RankNumber int,
		ResultGrade NVarchar(10),
		
		MaximumMark1 decimal(10,2),		
		SubjectGrade1 NVarchar(10),
		Obtain1 decimal(5,2) Default 0,
		ExamMaximum1 decimal(10,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(10,2),	
		SubjectGrade2 NVarchar(10),
		Obtain2 decimal(5,2) Default 0,
		ExamMaximum2 decimal(10,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(10,2),
		SubjectGrade3 NVarchar(10),
		Obtain3 decimal(5,2) Default 0,
		ExamMaximum3 decimal(10,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(10,2),	
		SubjectGrade4 NVarchar(10),
		Obtain4 decimal(5,2) Default 0,
		ExamMaximum4 decimal(10,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(10,2),		
		SubjectGrade5 NVarchar(10),
		Obtain5 decimal(5,2) Default 0,
		ExamMaximum5 decimal(10,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(10,2),		
		SubjectGrade6 NVarchar(10),
		Obtain6 decimal(5,2) Default 0,
		ExamMaximum6 decimal(10,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(10,2),		
		SubjectGrade7 NVarchar(10),
		Obtain7 decimal(5,2) Default 0,
		ExamMaximum7 decimal(10,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(10,2),	
		SubjectGrade8 NVarchar(10),
		Obtain8 decimal(5,2) Default 0,
		ExamMaximum8 decimal(10,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(10,2),		
		SubjectGrade9 NVarchar(10),
		Obtain9 decimal(5,2) Default 0,
		ExamMaximum9 decimal(10,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(10,2),		
		SubjectGrade10 NVarchar(10),
		Obtain10 decimal(5,2) Default 0,
		ExamMaximum10 decimal(10,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(10,2),		
		SubjectGrade11 NVarchar(10),
		Obtain11 decimal(5,2) Default 0,
		ExamMaximum11 decimal(10,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(10,2),		
		SubjectGrade12 NVarchar(10),
		Obtain12 decimal(5,2) Default 0,
		ExamMaximum12 decimal(10,2),
		IsPresent12 bit,
		
		MaximumMark13 decimal(10,2),		
		SubjectGrade13 NVarchar(10),
		Obtain13 decimal(5,2) Default 0,
		ExamMaximum13 decimal(10,2),
		IsPresent13 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(10),
		SubjectGradeTerm2 NVarchar(10),
		SubjectGradeTerm3 NVarchar(10),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(300),
		Remark3 nvarchar(300),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(5,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(10),
		PercentileTerm1 decimal(5,2),
		ResultStatusTerm1 Nvarchar(50),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(5,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(10),
		PercentileTerm2 decimal(5,2),
		ResultStatusTerm2 Nvarchar(50), 
		TotalMarkTerm3 	decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(5,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(10),
		PercentileTerm3 decimal(5,2),
		ResultStatusTerm3 Nvarchar(50), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(10),
		SubjectName NVarchar(100),
		SubjectCode Nvarchar(20),	
		SubjectMinimum decimal(10,2),		
		SubjectMaximum decimal(10,2),
		SubjectObtain  decimal(5,2),
		
		Exam1Name Nvarchar(100),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(5,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(10),
		Percentile1 decimal(5,2),
		ResultStatus1 Nvarchar(50),
		Exam1CombineExamName Nvarchar(100),
				
		Exam2Name nvarchar(100),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(5,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(10),
		Percentile2 decimal(5,2),
		ResultStatus2 Nvarchar(50),
		Exam2CombineExamName Nvarchar(100),
		
		Exam3Name nvarchar(100),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(5,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(10),
		Percentile3 decimal(5,2),		
		ResultStatus3 Nvarchar(50),
		Exam3CombineExamName Nvarchar(100),
		
		Exam4Name nvarchar(100),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(5,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(10),
		Percentile4 decimal(5,2),
		ResultStatus4 Nvarchar(50),
		Exam4CombineExamName Nvarchar(100),
		
		Exam5Name nvarchar(100),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(5,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(10),
		Percentile5 decimal(5,2),
		ResultStatus5 Nvarchar(50),
		Exam5CombineExamName Nvarchar(100),
		
		Exam6Name nvarchar(100),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(5,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(10),
		Percentile6 decimal(5,2),
		ResultStatus6 Nvarchar(50),
		Exam6CombineExamName Nvarchar(100),
		
		Exam7Name nvarchar(100),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(5,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(10),
		Percentile7 decimal(5,2),
		ResultStatus7 Nvarchar(50),
		Exam7CombineExamName Nvarchar(100),
		
		Exam8Name nvarchar(100),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(5,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(10),
		Percentile8 decimal(5,2),
		ResultStatus8 Nvarchar(50),
		Exam8CombineExamName Nvarchar(100),
		
		
		Exam9Name nvarchar(100),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(5,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(10),
		Percentile9 decimal(5,2),
		ResultStatus9 Nvarchar(50),
		Exam9CombineExamName Nvarchar(100),
		
		Exam10Name nvarchar(100),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(5,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(10),
		Percentile10 decimal(5,2),
		ResultStatus10 Nvarchar(50),
		Exam10CombineExamName Nvarchar(100),
		
		Exam11Name nvarchar(100),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(5,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(10),
		Percentile11 decimal(5,2),
		ResultStatus11 Nvarchar(50),
		Exam11CombineExamName Nvarchar(100),
		
		Exam12Name nvarchar(100),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(5,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(10),
		Percentile12 decimal(5,2),
		ResultStatus12 Nvarchar(50),
		Exam12CombineExamName Nvarchar(100),

		Exam13Name nvarchar(100),	
		TotalMarks13 decimal(8,2),
		TotalObtain13 decimal(8,2),
		Percentage13 decimal(5,2),
		RankNumber13 int,
		ResultGrade13 NVarchar(10),
		Percentile13 decimal(5,2),
		ResultStatus13 Nvarchar(50),
		Exam13CombineExamName Nvarchar(100),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		Exam13Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(100),
		LastName nvarchar(100),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(50),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(100),
		SubjectGroupCode nvarchar(20),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(100),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(5,2),	
		SubjectObtainTerm2 decimal(5,2),
		SubjectObtainTerm3  decimal(5,2),
		SubjectMaxTerm1 decimal(10,2),
		SubjectMaxTerm2 decimal(10,2),
		SubjectMaxTerm3 decimal(10,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(20),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		TotalDays13 decimal(6,2),
		PresentDays13 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(1000),
		GeneralRemarkTerm2 nvarchar(1000),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(6,2),
		SR_WeightTerm1 decimal(6,2),
		SR_HeightTerm2 decimal(6,2),
		SR_WeightTerm2 decimal(6,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIdNumber nvarchar(50),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(50),
		MotherMail nvarchar(50),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(10),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(100) ,
		FatherOccupation nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		IsDecimal bit,
		IsAbsentRemark bit,
		FinalAbsentRemark nvarchar(100),
		AbsentRemark1 nvarchar(100),
		AbsentRemark2 nvarchar(100),
		AbsentRemark3 nvarchar(100),
		AbsentRemark4 nvarchar(100),
		AbsentRemark5 nvarchar(100),
		AbsentRemark6 nvarchar(100),
		AbsentRemark7 nvarchar(100),
		AbsentRemark8 nvarchar(100),
		AbsentRemark9 nvarchar(100),
		AbsentRemark10 nvarchar(100),
		AbsentRemark11 nvarchar(100),
		AbsentRemark12 nvarchar(100),
		AbsentRemark13 nvarchar(100),
		ExamMaximumTerm1 decimal(6,2),
		ExamMaximumTerm2 decimal(6,2),
		ExamMaximumTerm3 decimal(6,2),
		--add for 29923 mantis
		PermanentStreetOne nvarchar(150),
		PermanentStreetTwo nvarchar(150),
		PermanentStreetThree nvarchar(150),
		CasteCategory nvarchar(50)
		)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	
	ExamCode,
	
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	MarksheetHeaderA4,
	IsImageHeader,
	MyGoal,
	AreaOfInterest,
	Responsibility,
	MyInterestHobby,
	MyStrength,
	Achievements, 
	
	DentalHygiene,
	VisionLeft,
	VisionRight,
	IsDetail,
	SubjectGroupId,
	SubjectGroupTitle,
	SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	KrupaMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
    IsShowWithDetail,
    IsPresent,
    GradeTitle,
	
	SubjectHighestDivisionGrade,
	SubjectHighestDivisionMark,
	
	AchievementsTerm1,
	AchievementsTerm2,
	GeneralRemarkTerm1,
	GeneralRemarkTerm2,
	ResultRemark1Term1,
	ResultRemark2Term1,
	ResultRemark1Term2,
	ResultRemark2Term2,
	SR_HeightTerm1,
	SR_WeightTerm1,
	SR_HeightTerm2,
	SR_WeightTerm2,
	SR_PresentDaysTerm1,
	SR_PresentDaysTerm2,
	SR_TotalDaysTerm1,
	SR_TotalDaysTerm2,
	HouseName,
	HouseId,
	AdhaarNumber,
	UIdNumber,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail ,
	MotherMail ,
	Gender,
	CoordinatorEmployeeSign,
	StudentAddress,
	SUId,
	HighestDivisionMark,
	HighestDivisionGrade,
	StreamTitle,
	AdmissionNo,
	AdmissionDate,
	MiddleName ,
	FatherOccupation,
	ResultSheetAdditionalTitle,
	IsDecimal,
	IsAbsentRemark,
	FinalAbsentRemark,
	--add for 29923 mantis
	PermanentStreetOne,
	PermanentStreetTwo,
	PermanentStreetThree,
	CasteCategory
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		Convert(nvarchar(50),@rClassId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,


		EM.IsMarksInDecimal,
		
				
		1,
		--RD.Obtain,
		R.Percentile,
		--SM.Title AS ClassSubject,
		RD.Id AS ResultDetailId,
		R.Id AS ResultId,

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
		SI.StudentPhoto
		ELSE NULL END)AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN
		--	OI.CertificateHeaderA4 
		--	ELSE NULL END)AS  MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		@rIsDetail AS IsDetail,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		RD.KrupaMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(Sr.HouseRemark,'') As HouseRemark,
		ISNULL(BGM.Title,'') AS BloodGroup,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		
		'' AS AchievementsTerm1,
		'' AS AchievementsTerm2,
		'' AS GeneralRemarkTerm1,
		'' AS GeneralRemarkTerm2,
		'' AS ResultRemark1Term1,
		'' AS ResultRemark2Term1, 
		'' AS ResultRemark1Term2,
		'' AS ResultRemark2Term2,
		SR.StudentHeight AS SR_HeightTerm1,
		SR.StudentWeight AS SR_WeightTerm1,
		SR.StudentHeight AS SR_HeightTerm2,
		SR.StudentWeight AS SR_WeightTerm2,
		ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm1,
	    ISNULL(SR.PresentDays,0) AS SR_PresentDaysTerm2,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm1,
	    ISNULL(SR.TotalDays,0) AS SR_TotalDaysTerm2,
	    HM.Title As HouseName,HM.Id as HouseId,
	    ISNULL(SO.AdhaarNumber,'') As AdhaarNumber,
	    ISNULL(SO.UIdNumber,'') As UIdNumber,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		(SC.PresentStreetOne +' '+ SC.PresentStreetTwo +' '+ SC.PresentStreetThree +' '+ SC.PresentCity +' '+ SC.PermanentState) AS StudentAddress,
		ISNULL(Stum.SUId,'') AS SUId,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,
		ISNULL(StM.Title,'') AS StreamTitle,
		ISNULL(StuA.AdmissionNumber,0) AS AdmissionNo,
		ISNULL(StuA.AdmissionDate,'') AS AdmissionDate,
		Stum.MiddleName ,
		ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
		ISNULL(EM.ResultSheetAdditionalTitle, '') AS ResultSheetAdditionalTitle,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
		ISNULL(RD.AbsentRemark,'') AS FinalAbsentRemark,
		--add for 29923 mantis
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		CSM.Title As CasteCategory      --Mantis 0030303
				
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tStreamMaster StM ON CM.StreamId = Stm.Id
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId AND  ISNULL(EMP.IsOtherUser,0) = 0
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
	Left JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	
	LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=StuM.Id AND AR.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId 
= AR.OrgGroupBatchId)) 
    LEFT JOIN
	(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = StuM.Id 
	LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId		  
	--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId        --Mantis 0030303
	 WHERE
		R.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClassId) OR (@rClassId=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		AND ((R.TotalObtain>=@rFromObtain) OR (@rFromObtain=0))
		AND ((R.TotalObtain<=@rToObtain) OR (@rToObtain=0))
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    )
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
	AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	    
	Order By ED.DisplayOrder

 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.ExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	--print ('tempcombine')
	--SELECT * FROM #tempcombineExam
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int
  
	Select @lCount = MAX(Id) from #tempcombineExam
	--SET @lCount1 = @lCount+1
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T SET
					 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
					 Obtain' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.Obtain,0),
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
					 AbsentRemark' + convert(nvarchar(15),@lCount)+'= ISNULL(RD.AbsentRemark,' + CHAR(39)+CHAR(39) + '),
					 		
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays										
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--print(@query)
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.ExamSubGroupDisplayTitle,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		Declare @lCombineExamId int
			SELECT @lCombineExamId = EC.ExamId  FROM [sAssessment].[tExamMaster] EM 
										INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId  
										INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (SELECT SubExamId  FROM sAssessment.tExamCombine WHERE examid=@rExamId) 
										WHERE   (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId AND EM.Id = @lSubExamId
			--SELECT @lSubCombineExamName
		set @query ='update T set 
					 Exam' + convert(nvarchar(15),@lCount)+ 'CombineExamName =  EM.DisplayTitle
					  From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lCombineExamId) 
				
				--Print @query		
		execute(@query)
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code,
					AchievementsTerm1 = SR.Achievements,
					GeneralRemarkTerm1 = SR.GeneralRemark,
					ResultRemark1Term1 = SR.ResultRemark1,
					ResultRemark2Term1 = SR.ResultRemark2,
					SR_HeightTerm1 = SR.StudentHeight,
					SR_WeightTerm1 = SR.StudentWeight,
					SR_PresentDaysTerm1 = SR.PresentDays,
					SR_TotalDaysTerm1 = SR.TotalDays,
					ExamMaximumTerm1 = EM.ExamMaximum
					
					From
					 
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum,
					AchievementsTerm2 = SR.Achievements,
					GeneralRemarkTerm2 = SR.GeneralRemark,
					ResultRemark1Term2 = SR.ResultRemark1,
					ResultRemark2Term2 = SR.ResultRemark2,
					SR_HeightTerm2 = SR.StudentHeight,
					SR_WeightTerm2 = SR.StudentWeight,
					SR_PresentDaysTerm2 = SR.PresentDays,
					SR_TotalDaysTerm2 = SR.TotalDays
									 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code,
					ExamMaximumTerm2 = EM.ExamMaximum			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code,
					ExamMaximumTerm3 = EM.ExamMaximum			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END
	
	
	
	
	
	--WHILE (@lCount1 <= 6)
	--BEGIN
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN MaximumMark' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Exam' + convert(nvarchar(150),@lCount1)+ 'Name'
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN SubjectGrade' + convert(nvarchar(150),@lCount1)
	--	execute(@query)		
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN Obtain' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	set @query ='ALTER TABLE #TempAllExam DROP COLUMN ExamMaximum' + convert(nvarchar(15),@lCount1)
	--	execute(@query)
	--	SET @lCount1 = @lCount1 + 1
	--END
	
	SELECT @rBuilder1,@rBuilder2, T.*
	FROM #TempAllExam T
	
	--INNER JOIN SSETUP.TCLASSSUBJECT CS ON CS.ID = T.CLASSSUBJECTID
	--WHERE
	--	((T.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	--	AND ((T.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	--	AND ((T.RankNumber >= @rFromRank) OR (@rFromRank=0))
	--	AND ((T.RankNumber <= @rToRank) OR (@rToRank=0))
	--	AND ((T.ResultGrade = @rGrade) OR (@rGrade=''))
	--	AND ((T.StudCode=@rCode) OR (@rCode=''))		
		--order by T.RollNo,CS.ORDERINDEX
	--SELECT * FROM #TempAllExam	
	drop table #tempcombineExam
	Drop table #TempAllExam
	
	--Select
	--	'' As Builder1,
	--	'' As Builder2,
	--    '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
	--	'' As IsDisplayMonthlyAttendanceText,
	--    '' AS ClassIdText,
	--	0 As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	0 As TotalMark ,
	--	0 As TotalObtain,
	--	0 As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
 --       '' As IsMarksInDecimal,
 --             0 As column_visible,

 --             0 As Percentile ,

 --            0 As ResultDetailId, 
 --            0 As ResultId,

	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	0 As IsRankNo , 
	--	0 As IsGrade ,
	--	0 As IsPercentile ,
	--	0 As IsPercentage ,
	--	0 As IsSubjectPercentile ,
	--	0 As IsProcessResult ,
	--	0 As IsNegativeMarks ,
	--	0 As IsIncludeCoScholastic ,
	--	0 As IsOnPrePrinted ,
	--	0 As IsDisplayPhoto ,
	--	0 As IsDisplayBirthDate ,
	--	0 As IsLockForEdit ,
	--	0 As IsDisplaySchoolName ,			
	--	0 As IsDisplayAttendance ,
	--	0 As IsDisplayHeightWeight ,
	--	0 As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	'' As DateOfBirth ,
	--	0 As HeightTerm1 ,
	--	0 As WeightTerm1 ,
	--	0 As HeightTerm2,
	--	0 As WeightTerm2 ,
	--	0 As HeightAnnual ,
	--	0 As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	0 As TermScopeId ,		 
	--	0x As StudentPhoto ,
	--	'' As GradeString,
	--	0 As IsDisplayGradeString ,		 
	--	0 As IsDisplayInMarksheet ,
	--	0 As IsShowSubjectGrade ,
	--	0 As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	0 As SubjectMinimum ,		
	--	0 As SubjectMaximum ,
	--	0 As SubjectObtain ,
	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,

	--	0 As TotalDays ,
	--	0 As PresentDays ,
	--	0 As StudentHeight,
	--	0 As StudentWeight ,
	--	'' As ExamSeatNo ,
	--    0 As ExamId ,

 --       '' AS ExamCode,

	--	0 As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	0 As IsShowSubjectMark , 
	--	0 As IsOptionalSubject ,
	--	0 As CoScholasticScopeId ,
	--	0 As IsDisplayPrincipalSign ,
	--	0 As IsDisplayTeacherSign ,
	--	0x As EmployeeSign,
 --            '' As Batch,
 --            '' As ClassTeacherName,
 --      '' AS FirstName,
 --      '' AS LastName,
 --            0 As IsDisplayMonthlyAttendance,
	--	0x As MarksheetHeaderA4 ,
	--	0 As IsImageHeader ,
 --            '' As    MyGoal,
 --       '' As  AreaOfInterest,
 --       '' As Responsibility,
 --       '' As MyInterestHobby,
 --       '' As MyStrength,
 --       '' As Achievements,

	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
 --             0 As IsDetail,
 --             0 AS   SubjectGroupId,
 --             ''   AS SubjectGroupTitle,
 --        '' AS SubjectGroupCode,
 --        '' AS DecimalFormat,
 --        '' AS SubjectRemark,
 --               0 As GraceMark,
 --               0 As KrupaMark,
 --                '' As GradeStringHtml,
 --          '' As ResultRemark3,
 --         0 As IsDisplayTotalMark,
 --         ''  As ContactNo,
	--	'' As PresentAddress ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
 --       '' As ImprovementArea,
 --       '' As ProgressArea,
 --       '' As GeneralRemark,
 --              '' As MyActivity,
 --        ''  As ClassTeacherRemark,

 --        '' As HouseRemark,
	--	  '' As BloodGroup ,
 --         '' As BatchIdText,
 --                0 As IsShowWithDetail,
 --                0 As IsPresent,
 --                ''  As GradeTitle,

 --         '' As SubjectHighestDivisionGrade,
 --                 0  As SubjectHighestDivisionMark,

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign ,	
 --			'' As FatherOccupation ,
 --			0 AS IsDecimal,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm1,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm2,
 --			CONVERT(decimal(6,2),0) AS ExamMaximumTerm3

-- SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering Procedure [sBiometric].[pTimeSheetListGet]...';


GO
ALTER PROCEDURE [sBiometric].[pTimeSheetListGet]
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,  
  @rStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rEmployeeName nvarchar(50) = '',
  @rStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @rOrgGroupDepartmentId int = 0
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
  
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20),
 ShiftName nvarchar(25)  
 )  
    Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		DECLARE @lBatchID int
		DECLARE @lForYear nvarchar(20),@lForMonth nvarchar(20)
		Set @lForYear = Year(@rFromDate)
		
		Set @lForMonth = Month(@rFromDate)
		
		Set @ldate= CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@lForMonth,@lForYear)
		
		set @Firstdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @Lastdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), @Days)

		SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1
   
 INSERT INTO #TempMonthTrans  
   
 	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END
	--Mantis Id:28837 Start to check from amd to date month contain 31 days
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
	END

	IF NOT EXISTS (SELECT * FROM #TempMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) AND Attn_Date=@rToDate)	--Mantis Id 30042, only "if" condition will be added
	BEGIN
		IF Month(@rToDate) NOT IN (2,4,6,9,11)
		BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND  ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)
		END
	END
	--Mantis Id:28837 End


 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),1,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),1,0,0,@rOrgId) else D01 end as D01,  
 --D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),2,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),2,0,0,@rOrgId) else D02 end as D02,  
 --D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),3,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),3,0,0,@rOrgId) else D03 end as D03,  
 --D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),4,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),4,0,0,@rOrgId) else D04 end as D04,  
 --D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),5,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),5,0,0,@rOrgId) else D05 end as D05,  
 --D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),6,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),6,0,0,@rOrgId) else D06 end as D06,  
 --D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),7,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),7,0,0,@rOrgId) else D07 end as D07,  
 --D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),8,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),8,0,0,@rOrgId) else D08 end as D08,  
 --D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime), case When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),9,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),9,0,0,@rOrgId) else D09 end as D09,  
 --D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),10,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),10,0,0,@rOrgId) else D10 end as D10,  
 --D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),11,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),11,0,0,@rOrgId) else D11 end as D11,  
 --D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),12,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),12,0,0,@rOrgId) else D12 end as D12,  
 --D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),13,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),13,0,0,@rOrgId) else D13 end as D13,  
 --D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),14,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),14,0,0,@rOrgId) else D14 end as D14,  
 --D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),15,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),15,0,0,@rOrgId) else D15 end as D15,  
 --D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),16,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),16,0,0,@rOrgId) else D16 end as D16,  
 --D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),17,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),17,0,0,@rOrgId) else D17 end as D17,  
 --D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),18,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),18,0,0,@rOrgId) else D18 end as D18,  
 --D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),19,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),19,0,0,@rOrgId) else D19 end as D19,  
 --D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),20,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),20,0,0,@rOrgId) else D20 end as D20,  
 --D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),21,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),21,0,0,@rOrgId) else D21 end as D21,  
 --D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),22,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),22,0,0,@rOrgId) else D22 end as D22,  
 --D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),23,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),23,0,0,@rOrgId) else D23 end as D23,  
 --D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),24,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),24,0,0,@rOrgId) else D24 end as D24,  
 --D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),25,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),25,0,0,@rOrgId) else D25 end as D25,  
 --D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),26,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),26,0,0,@rOrgId) else D26 end as D26,  
 --D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),27,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),27,0,0,@rOrgId) else D27 end as D27,  
 --D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --UNION ALL  
  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),28,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),28,0,0,@rOrgId) else D28 end as D28,  
 --D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 --IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))   
 --BEGIN  
 -- INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),29,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),29,0,0,@rOrgId) else D29 end as D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
   
 --IF Month(@rFromDate) <> 2  
 --BEGIN  
 --INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),30,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),30,0,0,@rOrgId) else D30 end as D30,  
 --D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  
   
 --IF Month(@rFromDate) NOT IN (2,4,6,9,11)  
 --BEGIN  
 --INSERT INTO #TempMonthTrans  
 --SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),CASE When sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),31,0,0,@rOrgId)<>'-' then  
 --sHrm.fWeekHOffGetBio(EmployeeId,YEAR(attn_dt),MONTH(attn_dt),31,0,0,@rOrgId) else D31 end as D31,  
 --D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 --AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 --END  

 --SELECT * FROM #TempMonthTrans
 --SELECT TM.*,
 
       
		
 SELECT TM.Id,TM.EmployeeId,TM.Attn_Date,TM.PresentStatus AS OldPresentStatus,OGD.Title AS [Organization Group Department],
 
 CASE When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='PW')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW'
  When ((TM.PresentStatus='XX')AND (Cast(TM.Attn_Date as date)<GETDATE()) And (cast(EJD.DateOfJoining as date)<= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfJoining,'')='')AND (EJD.DateOfleaving>= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfleaving,'')='') AND (TM.FirstIn ='00:00'))  then 'A'
 ELSE
 TM.PresentStatus END as PresentStatus,
 TM.FirstIn,TM.LastOut,TM.OverTime,TM.LateBy,TM.Duration,TM.EarlyBy,TM.ShiftName, MT.Tot_Attn,
 MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,  
 Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode ,   
 [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,   
 [sBiometric].[fEmployeeLeaveTypePendingGet](TM.ATTN_DATE,TM.EmployeeId) AS LeavePendingStatus,   
 [sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel,  
 ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
 ISNULL(SM.Id,0) AS StatusId,  
 ISNULL(SM.Title,'') AS Status  
 FROM #TempMonthTrans TM   
 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId  
 LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)  
 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId  
 --INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(EJD.DateOfJoining,'1900/01/01'))
 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(cast(rtrim(YEAR(EJD.DateOfJoining) *10000+ Month(EJD.DateOfJoining) *100+ 01) as datetime),'1900/01/01'))
 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
 LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
 WHERE   
 TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate    
 AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
 AND (( @rStatus = '1' AND (TM.Duration < '09:30')) OR ( @rStatus != '1' AND ((PresentStatus = @rStatus OR @rStatus='0'))))
 AND EM.OrgId = @rOrgId 
 AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
 AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
 AND (EM.FirstName + ' ' + EM.LastName like '%' + @rEmployeeName + '%' or @rEmployeeName = '')
 AND  ISNULL(EM.IsOtherUser,0) = 0
 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
 --AND (TM.Duration < '09:30')
 Order By TM.EmployeeId,TM.Attn_Date


 


END
GO
PRINT N'Altering Procedure [sSetup].[pPortalEmployeeMasterUpdate]...';


GO


ALTER PROCEDURE [sSetup].[pPortalEmployeeMasterUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	

	 BEGIN	
	
	UPDATE sHrm.tEmployeeMaster
		SET
			OrgID = A.OrgID,
			Code = A.Code,
			FirstName = sSetup.fPortalXMLTagsReplaceReverse(A.FirstName),
			MiddleName = sSetup.fPortalXMLTagsReplaceReverse(A.MiddleName),
			LastName = sSetup.fPortalXMLTagsReplaceReverse(A.LastName),
			ShortName = sSetup.fPortalXMLTagsReplaceReverse(A.ShortName),
			StatusId = A.StatusId,
			IsObsolete = A.IsObsolete,
			CreatedUserId = A.CreatedUserId,
			CreatedDateTime = A.CreatedDateTime,
			UpdatedUserId = A.UpdatedUserId,
			UpdatedDateTime = A.UpdatedDateTime
		 FROM
		 (
		SELECT		
			OrgID,
			Id,
			Code,
			FirstName,
			MiddleName,
			LastName,
			ShortName,
			StatusId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,		
			UpdatedDateTime
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
			[OrgID] [smallint],
			[Id] [bigint],
			[Code] [nvarchar](20),
			[FirstName] [nvarchar](100),
			[MiddleName] [nvarchar](100),
			[LastName] [nvarchar](100),
			[ShortName] [nvarchar](50),
			[StatusId] [smallint],
			[IsObsolete] [bit],
			[CreatedUserId] [bigint],
			[CreatedDateTime] [datetime],
			[UpdatedUserId] [bigint],
			[UpdatedDateTime] [datetime]
			  )) A
			  WHERE sHrm.tEmployeeMaster.Id = A.Id AND ISNULL(IsOtherUser,0) = 0
		
		
		
		 INSERT INTO sHrm.tEmployeeMaster
		(
			OrgID,
			Id,
			Code,
			FirstName,
			MiddleName,
			LastName,
			ShortName,
			StatusId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,		
			UpdatedDateTime,
			EUId					-- MantisId : 	0029269
			)
		SELECT		
			A.OrgID,
			A.Id,
			A.Code,
			sSetup.fPortalXMLTagsReplaceReverse(A.FirstName),
			sSetup.fPortalXMLTagsReplaceReverse(A.MiddleName),
			sSetup.fPortalXMLTagsReplaceReverse(A.LastName),
			sSetup.fPortalXMLTagsReplaceReverse(A.ShortName),
			A.StatusId,
			A.IsObsolete,
			A.CreatedUserId,
			A.CreatedDateTime,
			A.UpdatedUserId,		
			A.UpdatedDateTime,
			A.Id				-- MantisId : 	0029269
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[OrgID] [smallint],
				[Id] [bigint],
				[Code] [nvarchar](20),
				[FirstName] [nvarchar](100),
				[MiddleName] [nvarchar](100),
				[LastName] [nvarchar](100),
				[ShortName] [nvarchar](50),
				[StatusId] [smallint],
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime]
			  ) A LEFT JOIN sHrm.tEmployeeMaster EM
			  ON A.Id = EM.Id WHERE EM.Id IS NULL AND ISNULL(EM.IsOtherUser,0) = 0
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rSubjectId int = 0,
	 @rBatchId int=0,
	 @rClass int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rOrgId int=0,
	 @rMultiCode nvarchar(max)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 	

 --Select * from   sAssessment.tTempAllExamSubjectActivity
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(1000),
@GradeSetId int , @IsIncludeSubExam bit
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
SELECT @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

Declare @lDecimalConfig nvarchar(20)=''
SELECT @lDecimalConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		
		ResultStatus Nvarchar(50),	
		
		ClassName NVarchar(100),
				
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		--MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		--Obtain1 decimal(8,2),
		--ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		
		Remark2 nvarchar(300),
		Remark3 nvarchar(300),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		SubActivityGrade1 nvarchar(50),
		ActivityGrade1 nvarchar(50),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		SubActivityGrade2 nvarchar(50),
		ActivityGrade2 nvarchar(50),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		SubActivityGrade3 nvarchar(50),
		ActivityGrade3 nvarchar(50),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		SubActivityGrade4 nvarchar(50),
		ActivityGrade4 nvarchar(50),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		SubActivityGrade5 nvarchar(50),
		ActivityGrade5 nvarchar(50),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		SubActivityGrade6 nvarchar(50),
		ActivityGrade6 nvarchar(50),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		--SubActivityGrade7 nvarchar(10),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		TotalDays decimal(6, 2),
		PresentDays decimal(6, 2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		IsDisplayParentName bit,
		
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		
		ActivityName nvarchar(200),
		SubActivityName nvarchar(200),
		SubActivityId int,
		ActivityId Int,
		 SubActivityGrade nvarchar(50),
		 ActivityGrade nvarchar(50),
		SubActivityGradeIndicator nvarchar(50),
		SubActivityDescriptiveIndicator nvarchar(200),
		SubjectActivityOrderIndex Smallint,
		SubActivityOrderIndex smallint,
		ColumnSubjectCount SmallInt,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		Height1 decimal(6,2),
		Height2 decimal(6,2),
		Height3 decimal(6,2),
		Height4 decimal(6,2),
		Height5 decimal(6,2),
		Height6 decimal(6,2),
		Weight1 decimal(6,2),
		Weight2 decimal(6,2),
		Weight3 decimal(6,2),
		Weight4 decimal(6,2),
		Weight5 decimal(6,2),
		Weight6 decimal(6,2),
		TotalDays1 decimal(6, 2),
		PresentDays1 decimal(6, 2),
		TotalDays2 decimal(6, 2),
		PresentDays2 decimal(6, 2),
		TotalDays3 decimal(6, 2),
		PresentDays3 decimal(6, 2),
		TotalDays4 decimal(6, 2),
		PresentDays4 decimal(6, 2),
		TotalDays5 decimal(6, 2),
		PresentDays5 decimal(6, 2),
		TotalDays6 decimal(6, 2),
		PresentDays6 decimal(6, 2),
		MyActivity1 nvarchar(200),
		MyActivity2 nvarchar(200),
		MyActivity3 nvarchar(200),
		MyActivity4 nvarchar(200),
		MyActivity5 nvarchar(200),
		MyActivity6 nvarchar(200),
		GeneralRemark1 nvarchar(200),
		GeneralRemark2 nvarchar(200),
		GeneralRemark3 nvarchar(200),
		GeneralRemark4 nvarchar(200),
		GeneralRemark5 nvarchar(200),
		GeneralRemark6 nvarchar(200),
		PresentAddress nvarchar(500) ,
		MobileNo nvarchar(50),
		House nvarchar(100),
		 
		AttendanceTerm1 decimal(6, 2) ,
		AttendanceTerm2 decimal(6, 2),
		WorkingDaysTerm1 decimal(6, 2),
		WorkingDaysTerm2 decimal(6, 2),
		
		BloodGroup nvarchar(20),
		GradeSetIdText nvarchar(50),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ParentEmail nvarchar(500),
		MyGoal nvarchar(200),
		MyStrength nvarchar(200),
		MyInterestHobby nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		Achievements nvarchar(1000),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		ClassTeacherName Nvarchar(100),
		HouseRemark nvarchar(1000),
		GeneralRemark nvarchar(1000),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		IsDecimal bit,
		Name nvarchar(150),
		--mantis 0029914
		PermanentStreetOne nvarchar(150),
		PermanentStreetTwo nvarchar(150),
		PermanentStreetThree nvarchar(150),
		AdmissionNo nvarchar(50),
		StudentContactNo nvarchar(50)
	)	
	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	IsIncludeCoScholastic,
	IsOnPrePrinted,
	IsDisplayPhoto,
	IsDisplayBirthDate,
	IsLockForEdit,
	IsDisplaySchoolName,			
	IsDisplayAttendance,
	IsDisplayHeightWeight,
	IsResultStatus,
	FooterAdjustmentText,
	DetailAdjustmentText,
	FooterAdjustment,
	DetailAdjustment,
	ResultRemark,
	DateOfBirth,
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	TermScopeId,
	StudentPhoto,
	GradeString,
	IsDisplayGradeString,	 
	IsDisplayInMarksheet,
	IsShowSubjectGrade,
	IsIncludeInTotal,
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	IsDisplayParentName,
	FatherName,
	MotherName,
	IsShowSubjectMark,
	IsOptionalSubject,
	CoScholasticScopeId,
	IsDisplayPrincipalSign,
	IsDisplayTeacherSign,
	EmployeeSign,
	SubActivityGrade,
	ActivityGrade,
	ActivityName,
	SubActivityName,
	SubActivityId,
	ActivityId,
	SubActivityGradeIndicator,
	SubActivityDescriptiveIndicator,
	SubjectActivityOrderIndex,
	SubActivityOrderIndex,
	ColumnSubjectCount,
	MarksheetHeaderA4,
	IsImageHeader,
	PresentAddress,
 	MobileNo,
	House,
	AttendanceTerm1   ,
	AttendanceTerm2  ,
	WorkingDaysTerm1  ,
	WorkingDaysTerm2  ,
	BloodGroup,
	GradeSetIdText,
	IsDisplayMonthlyAttendanceText,
	DentalHygiene,
	VisionLeft,
	VisionRight,
	TeacherSignCaption,
	PrincipalSignCaption,ParentSignCaption,
	ParentEmail,
	MyGoal ,
	MyStrength ,
	MyInterestHobby ,
	AreaOfInterest ,
	Responsibility ,
	Achievements ,
	ImprovementArea ,
	ProgressArea ,
	MyActivity ,
	ClassTeacherRemark ,
	ClassTeacherName ,
	HouseRemark ,
	GeneralRemark ,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail,
	MotherMail,
	IsDecimal,
	Name,
	-- mantis-0029914
	PermanentStreetOne,
	PermanentStreetTwo,
	PermanentStreetThree,
	AdmissionNo,
	StudentContactNo
	)
	
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS StudentName,
		A.RollNo,
		R.ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,


		EM.IsMarksInDecimal,
		1,
		--RD.Obtain,
		R.Percentile,
		--SM.Title AS ClassSubject,
		RD.Id AS ResultDetailId,
		R.Id AS ResultId,

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
		EM.TermScopeId,
		CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto,
		CASE @GradeStringRemark WHEN '' THEN @GradeString ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
	    SAM.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		ISNULL(SR.TotalDays,0)AS TotalDays,
		ISNULL(SR.PresentDays,0)AS PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		--EMP.FirstName
		(CASE ISNULL(OS.AcademicId,0)
		WHEN 0 THEN 0
		ELSE 1 END) AS IsOptionalSubject,
		EM.CoScholasticScopeId,
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		SSA.Grade AS SubActivityGrade,
		ISNULL(SAS.Grade,'') AS ActivityGrade,
		SAM.Title AS ActivityName,
		SSAM.Title AS SubActivityName,
		SSA.SubjectSubActivityId AS SubActivityId,
		SAM.Id AS ActivityId,
		SSA.GradeIndicator AS SubActivityGradeIndicator,
		SSA.DescriptiveIndicator AS SubActivityDescriptiveIndicator,
		SAM.OrderIndex AS SubjectActivityOrderIndex,
		SSAM.OrderIndex AS SubActivityOrderIndex,
		CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
				ELSE 1 END   AS   ColumnSubjectCount,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.MarksheetHeaderA4
			ELSE NULL END)AS  MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader	,
		ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		 SC.ParentContactNo,
		ISNULL(HM.Title,'') AS House,
		ISNULL(CCER.AttendanceTerm1,0) AS AttendanceTerm1,
		ISNULL(CCER.AttendanceTerm2,0) AS AttendanceTerm2,
		ISNULL(CCER.WorkingDaysTerm1,0) AS WorkingDaysTerm1,
		ISNULL(CCER.WorkingDaysTerm2,0) AS WorkingDaysTerm2,
		ISNULL(BGM.Title,'') AS BloodGroup,
		CONVERT (nvarchar(50),EM.GradeSetId) AS GradeSetIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		--CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EM.TeacherSignCaption ELSE NULL END AS TeacherSignCaption,
		--CASE WHEN EM.IsDisplayPrincipalSign = 1 THEN EM.PrincipalSignCaption ELSE NULL END AS PrincipalSignCaption,
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(ParentSignCaption,'') AS ParentSignCaption,
		SC.ParentEmail As ParentEmail,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		SF.FatherContactNo,
		SF.MotherContactNo,
		SF.FatherMail,
		SF.MotherMail,
		CONVERT(bit,@lDecimalConfig) AS IsDecimal,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		-- mantis-0029914
		SC.PermanentStreetOne,
		SC.PermanentStreetTwo,
		SC.PermanentStreetThree,
		StuA.AdmissionNumber,
		SC.StudentContactNo
		
	FROM 
		sAssessment.tCCESubjectSubActivityExamScore SSA
		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
		INNER JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
		LEFT JOIN sAssessment.tCCESubjectActivityExamScore SAS ON SAS.SubjectActivityId= SAM.Id AND SSA.AcademicId = SAS.AcademicId AND SSA.ExamId = SAS.ExamId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId	
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
		INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = SAM.ClassSubjectId
		--INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
    	INNER JOIN sStudent.tAcademic  A ON   SSA.AcademicId = A.Id
		LEFT JOIN sAssessment.tCCEResult CCER    ON  CCER.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = A.Id AND OS.ClassSubjectId = ED.ClassSubjectId  
		LEFT JOIN sAssessment.tResult R ON R.AcademicId = SSA.AcademicId AND R.ExamId = SSA.ExamId
		LEFT JOIN sAssessment.tResultDetail RD  ON R.Id = RD.ResultId AND ED.ID = RD.ExamDetailId 
		LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = StuM.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =Stum.ID
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
		--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
		--0029914
		LEFT JOIN sStudent.tStudentAdmission StuA ON StuM.Id = StuA.StudentId
	
	 WHERE
		SSA.ExamId = @rExamId 
		AND ((A.DivisionId =  @rDivisionId) OR (@rDivisionId=0))
		AND ((A.ClassId =  @rClass) OR (@rClass=0))		 
		AND ((A.BatchId =  @rBatchId) OR (@rBatchId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		--AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		--AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		--AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((StuM.Code=@rCode) OR (@rCode=''))	
		--AND ((R.Id = @rResultId) OR (@rResultId = 0))	
		--AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))
		--AND ((CS.SubjectId=@rSubjectId) OR(@rSubjectId=0) ) 
		 AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	 
	Order By ED.DisplayOrder
 
	
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.SubExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	 
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int  
	Select @lCount = MAX(Id) from #tempcombineExam	
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		set @query ='update T SET
					
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
					 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
					 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
					 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark 
					 									
					 From
						 
						 sAssessment.tResult R 
						INNER JOIN  sAssessment.tResultDetail RD ON RD.ResultId = R.Id						
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 							
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
 
	 set @query ='update T SET
					
					 
					 SubActivityGrade' + convert(nvarchar(15),@lCount)+ '=SSA.Grade	
					 						
					 From
						sAssessment.tCCESubjectSubActivityExamScore SSA				
						inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	 					
						WHERE SSA.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
 
  set @query ='update T SET
					
					  ActivityGrade' + convert(nvarchar(15),@lCount)+ '=SAS.Grade	
					 						
					 From
						sAssessment.tCCESubjectActivityExamScore SAS				
						inner JOIN 	#TempAllExam  T ON T.ActivityId = SAS.SubjectActivityId And T.AcademicId = SAS.AcademicId	 					
						WHERE SAS.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
	-- set @query ='update T SET
					
	--				 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
	--				 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
	--				 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
	--				 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
	--				 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
	--				 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark
	--				 From
	--					sAssessment.tCCESubjectSubActivityExamScore SSA
						
	--					inner JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	--					inner JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	--					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	--					inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	
	--					LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 					
	--					WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
 ----PRINT(@QUERY)	
 --  EXECUTE(@query)
	
						
		/*	set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	execute(@query)*/
		
		
	set @lCount = @lCount -1
	end
	SELECT @rBuilder1 , T.*
	FROM #TempAllExam T
	
	
		
	drop table #tempcombineExam
	Drop table #TempAllExam

	--Select 
	-- '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
		
	--	CONVERT(bigint , 0) As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	CONVERT(decimal , 0) As TotalMark ,
	--	CONVERT(decimal , 0) As TotalObtain,
	--	CONVERT(decimal , 0) As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
		
	--	--MaximumMark1 decimal(8,2),		
	--	'' As SubjectGrade1 ,
	--	--Obtain1 decimal(8,2),
	--	--ExamMaximum1 decimal(8,2),
	--	CONVERT(bit , 0) As IsPresent1,
						
	--	CONVERT(decimal , 0) As MaximumMark2 ,	
	--	'' As SubjectGrade2 ,
	--	CONVERT(decimal , 0) As Obtain2 ,
	--	CONVERT(decimal , 0) As ExamMaximum2 ,
	--	CONVERT(bit , 0) As IsPresent2,
				
	--	CONVERT(decimal , 0) As MaximumMark3 ,
	--	'' As SubjectGrade3 ,
	--	CONVERT(decimal , 0) As Obtain3 ,
	--	CONVERT(decimal , 0) As ExamMaximum3 ,
	--	CONVERT(bit , 0) As IsPresent3 ,		
		
	--	CONVERT(decimal , 0) As MaximumMark4 ,	
	--	'' As SubjectGrade4 ,
	--	CONVERT(decimal , 0) As Obtain4 ,
	--	CONVERT(decimal , 0) As ExamMaximum4 ,
	--	CONVERT(bit , 0) As IsPresent4 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark5 ,		
	--	'' As SubjectGrade5 ,
	--	CONVERT(decimal , 0) As Obtain5 ,
	--	CONVERT(decimal , 0) As ExamMaximum5 ,
	--	CONVERT(bit , 0) As IsPresent5 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark6 ,		
	--	'' As SubjectGrade6,
	--	CONVERT(decimal , 0) As Obtain6 ,
	--	CONVERT(decimal , 0) As ExamMaximum6 ,
	--	CONVERT(bit , 0) As IsPresent6 ,	
		
	--	CONVERT(decimal , 0) As MaximumMark7 ,		
	--	'' As SubjectGrade7,
	--	CONVERT(decimal , 0) As Obtain7 ,
	--	CONVERT(decimal , 0) As ExamMaximum7 ,
	--	CONVERT(bit , 0) As IsPresent7 ,	
	
	--	CONVERT(decimal , 0) As MaximumMark8 ,	
	--	'' As SubjectGrade8,
	--	CONVERT(decimal , 0) As Obtain8 ,
	--	CONVERT(decimal , 0) As ExamMaximum8 ,
	--	CONVERT(bit , 0) As IsPresent8 ,	
		
	--	'' As SubjectGradeTerm1,
	--	'' As SubjectGradeTerm2 ,
	--	CONVERT(bit , 0) As IsMarksInDecimal ,
	--	CONVERT(bit , 0) As column_visible ,
	--	--Obtain decimal(5,2),
	--	CONVERT(decimal , 0) As Percentile,
	--	--ClassSubject nvarchar(100),
	--	CONVERT(bigint , 0) As ResultDetailId ,
	--	CONVERT(bigint , 0) As ResultId ,	
	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	CONVERT(bit , 0) As IsRankNo , 
	--	CONVERT(bit , 0) As IsGrade ,
	--	CONVERT(bit , 0) As IsPercentile ,
	--	CONVERT(bit , 0) As IsPercentage ,
	--	CONVERT(bit , 0) As IsSubjectPercentile ,
	--	CONVERT(bit , 0) As IsProcessResult ,
	--	CONVERT(bit , 0) As IsNegativeMarks ,
	--	CONVERT(bit , 0) As IsIncludeCoScholastic ,
	--	CONVERT(bit,0) As IsOnPrePrinted ,
	--	CONVERT(bit , 0) As IsDisplayPhoto ,
	--	CONVERT(bit , 0) As IsDisplayBirthDate ,
	--	CONVERT(bit , 0) As IsLockForEdit ,
	--	CONVERT(bit , 0) As IsDisplaySchoolName ,			
	--	CONVERT(bit , 0) As IsDisplayAttendance ,
	--	CONVERT(bit , 0) As IsDisplayHeightWeight ,
	--	CONVERT(bit , 0) As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	CONVERT(Date , null) As DateOfBirth ,
	--	CONVERT(decimal , 0) As HeightTerm1 ,
	--	CONVERT(decimal , 0) As WeightTerm1 ,
	--	CONVERT(decimal , 0) As HeightTerm2,
	--	CONVERT(decimal , 0) As WeightTerm2 ,
	--	CONVERT(decimal , 0) As HeightAnnual ,
	--	CONVERT(decimal , 0) As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	CONVERT(decimal , 0) As TotalMarkTerm1 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm1 ,
	--	CONVERT(decimal , 0) As PercentageTerm1,
	--	0 As RankNumberTerm1 ,
	--	'' As ResultGradeTerm1,
	--	CONVERT(decimal , 0) As PercentileTerm1 ,
	--	'' As ResultStatusTerm1,		   
	--	CONVERT(decimal , 0) As TotalMarkTerm2 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm2 ,
	--	CONVERT(decimal , 0) As PercentageTerm2 ,
	--	0 As RankNumberTerm2 ,
	--	'' As ResultGradeTerm2 ,
	--	CONVERT(decimal , 0) As PercentileTerm2 ,
	--	'' As ResultStatusTerm2 , 
	--	CONVERT(tinyInt , 0) As TermScopeId ,		 
	--	Convert (varbinary(max) , '') As StudentPhoto ,
	--	'' As GradeString,
	--	CONVERT(bit , 0) As IsDisplayGradeString ,		 
	--	CONVERT(bit , 0) As IsDisplayInMarksheet ,
	--	CONVERT(bit , 0) As IsShowSubjectGrade ,
	--	CONVERT(bit , 0) As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	CONVERT(decimal , 0) As SubjectMinimum ,		
	--	CONVERT(decimal , 0) As SubjectMaximum ,
	--	CONVERT(decimal , 0) As SubjectObtain ,
		
	--	'' As Exam1Name ,		
	--	CONVERT(decimal , 0) As TotalMarks1 ,		
	--	CONVERT(decimal , 0) As TotalObtain1 ,
	--	CONVERT(decimal , 0) As Percentage1 ,
	--	0 As RankNumber1 ,
	--	'' As ResultGrade1,
	--	CONVERT(decimal , 0) As Percentile1 ,
	--	'' As ResultStatus1 ,
		
	--	'' As SubActivityGrade1,
	--	'' As ActivityGrade1,
		
	--	'' As Exam2Name ,	
	--	CONVERT(decimal , 0) As TotalMarks2 ,
	--	CONVERT(decimal , 0) As TotalObtain2 ,
	--	CONVERT(decimal , 0) As Percentage2 ,
	--	0 As RankNumber2 ,
	--	'' As ResultGrade2 ,
	--	CONVERT(decimal , 0) As Percentile2 ,
	--	'' As ResultStatus2 ,
		
	--	'' As SubActivityGrade2,
	--	'' As ActivityGrade2 ,
		
	--	'' As Exam3Name ,	
	--	CONVERT(decimal , 0) As TotalMarks3 ,
	--	CONVERT(decimal , 0) As TotalObtain3 ,
	--	CONVERT(decimal , 0) As Percentage3 ,
	--	0 As RankNumber3 ,
	--	'' As ResultGrade3 ,
	--	CONVERT(decimal , 0) As Percentile3 ,		
	--	'' As ResultStatus3,
		
	--	'' As SubActivityGrade3 ,
	--	'' As ActivityGrade3 ,
		
	--	'' As Exam4Name ,	
	--	CONVERT(decimal , 0) As TotalMarks4 ,
	--	CONVERT(decimal , 0) As TotalObtain4,
	--	CONVERT(decimal , 0) As Percentage4 ,
	--	0 As RankNumber4 ,
	--	'' As ResultGrade4 ,
	--	CONVERT(decimal , 0) As Percentile4 ,
	--	'' As ResultStatus4 ,
		
	--	'' As SubActivityGrade4,
	--	'' As ActivityGrade4 ,
		
	--	'' As Exam5Name ,		
	--	CONVERT(decimal , 0) As TotalMarks5 ,
	--	CONVERT(decimal , 0) As TotalObtain5 ,
	--	CONVERT(decimal , 0) As Percentage5 ,
	--	0 As RankNumber5 ,
	--	'' As ResultGrade5 ,
	--	CONVERT(decimal , 0) As Percentile5 ,
	--	'' As ResultStatus5 ,
		
	--	'' As SubActivityGrade5 ,
	--	'' As ActivityGrade5 ,
		
	--	'' As Exam6Name ,	
	--	CONVERT(decimal , 0) As TotalMarks6 ,
	--	CONVERT(decimal , 0) As TotalObtain6,
	--	CONVERT(decimal , 0) As Percentage6 ,
	--	0 As RankNumber6 ,
	--	'' As ResultGrade6 ,
	--	CONVERT(decimal , 0) As Percentile6 ,
	--	'' As ResultStatus6 ,
		
	--	'' As SubActivityGrade6 ,
	--	'' As ActivityGrade6 ,
		
	--	'' As Exam7Name ,		
	--	CONVERT(decimal , 0) As TotalMarks7 ,
	--	CONVERT(decimal , 0) As TotalObtain7,
	--	CONVERT(decimal , 0) As Percentage7 ,
	--	0 As RankNumber7 ,
	--	'' As ResultGrade7,
	--	CONVERT(decimal , 0) As Percentile7 ,
	--	'' As ResultStatus7 ,
		
	--	--SubActivityGrade7 nvarchar(10),
		
	--	'' As Exam8Name,
	--	CONVERT(decimal , 0) As TotalMarks8 ,
	--	CONVERT(decimal , 0) As TotalObtain8 ,
	--	CONVERT(decimal , 0) As Percentage8,
	--	0 As RankNumber8 ,
	--	'' As ResultGrade8 ,
	--	CONVERT(decimal , 0) As Percentile8,
	--	'' As ResultStatus8,
	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,
	--	CONVERT(decimal , 0) As TotalDays ,
	--	CONVERT(decimal , 0) As PresentDays ,
	--	CONVERT(decimal , 0) As StudentHeight,
	--	CONVERT(decimal , 0) As StudentWeight ,
	--	'' As ExamSeatNo ,
	--	0 As ExamId ,
	--	CONVERT(bit , 0) As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	CONVERT(bit , 0) As IsShowSubjectMark , 
	--	CONVERT(bit , 0) As IsOptionalSubject ,
	--	CONVERT(tinyInt , 0) As CoScholasticScopeId ,
	--	CONVERT(bit , 0) As IsDisplayPrincipalSign ,
	--	CONVERT(bit , 0) As IsDisplayTeacherSign ,
	--	Convert (varbinary(max) , '') As EmployeeSign,
		
	--	'' As ActivityName ,
	--	'' As SubActivityName ,
	--	0 As SubActivityId ,
	--	0 As ActivityId ,
	--	 '' As SubActivityGrade,
	--	 '' As ActivityGrade ,
	--	'' As SubActivityGradeIndicator ,
	--	'' As SubActivityDescriptiveIndicator,
	--	0 As SubjectActivityOrderIndex ,
	--	0 As SubActivityOrderIndex ,
	--	0 As ColumnSubjectCount ,
	--	Convert (varbinary(max) , '') As MarksheetHeaderA4 ,
	--	CONVERT(bit,0) As IsImageHeader ,
	--	CONVERT(decimal , 0) As Height1 ,
	--	CONVERT(decimal , 0) As Height2 ,
	--	CONVERT(decimal , 0) As Height3,
	--	CONVERT(decimal , 0) As Height4 ,
	--	CONVERT(decimal , 0) As Height5,
	--	CONVERT(decimal , 0) As Height6 ,
	--	CONVERT(decimal , 0) As Weight1 ,
	--	CONVERT(decimal , 0) As Weight2 ,
	--	CONVERT(decimal , 0) As Weight3 ,
	--	CONVERT(decimal , 0) As Weight4,
	--	CONVERT(decimal , 0) As Weight5 ,
	--	CONVERT(decimal , 0) As Weight6 ,
	--	CONVERT(decimal , 0) As TotalDays1 ,
	--	CONVERT(decimal , 0) As PresentDays1 ,
	--	CONVERT(decimal , 0) As TotalDays2 ,
	--	CONVERT(decimal , 0) As PresentDays2 ,
	--	CONVERT(decimal , 0) As TotalDays3 ,
	--	CONVERT(decimal , 0) As PresentDays3 ,
	--	CONVERT(decimal , 0) As TotalDays4 ,
	--	CONVERT(decimal , 0) As PresentDays4 ,
	--	CONVERT(decimal , 0) As TotalDays5 ,
	--	CONVERT(decimal , 0) As PresentDays5 ,
	--	CONVERT(decimal , 0) As TotalDays6 ,
	--	CONVERT(decimal , 0) As PresentDays6 ,
	--	'' As MyActivity1,
	--	'' As MyActivity2 ,
	--	'' As MyActivity3,
	--	'' As MyActivity4 ,
	--	'' As MyActivity5,
	--	'' As MyActivity6,
	--	'' As GeneralRemark1,
	--	'' As GeneralRemark2 ,
	--	'' As GeneralRemark3 ,
	--	'' As GeneralRemark4,
	--	'' As GeneralRemark5,
	--	'' As GeneralRemark6,
	--	'' As PresentAddress ,
	--	'' As  MobileNo,
	--	'' As House ,
		 
	--	CONVERT(decimal , 0) As AttendanceTerm1  ,
	--	CONVERT(decimal , 0) As AttendanceTerm2 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm1 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm2 ,
	--	  '' As BloodGroup ,
	--	  '' As GradeSetIdText ,
	--	  '' As IsDisplayMonthlyAttendanceText ,
	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
	--	'' As ParentEmail ,
	--  '' AS MyGoal,
	--	'' AS MyStrength,
	--	'' AS MyInterestHobby,
	--	'' AS AreaOfInterest,
	--	'' AS Responsibility,
	--	'' AS Achievements,
	--	'' As ImprovementArea,
	--	'' AS ProgressArea,
	--	'' AS MyActivity,
	--	'' As ClassTeacherRemark,
	--	'' AS ClassTeacherName,
	--	'' As HouseRemark,
	--	'' As GeneralRemark,
	--	'' AS FatherContactNo,
	--	'' AS MotherContactNo,
	--	'' AS FatherMail,
	--	'' AS MotherMail,
	--  CONVERT(bit , 0) As IsDecimal,
	--  '' As Name,
	--'' AS PermanentStreetOne,
	--'' AS PermanentStreetTwo,
	--'' AS PermanentStreetThree,
	--'' AS AdmissionNo,
	--'' AS StudentContactNo
	--END


end
/*
 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
					
					--sAssessment.tCCESubjectActivityMaster SAM 	
	--		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.SubjectActivityId=SAM.Id  
	--		INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	--		INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
	--		 INNER JOIN sStudent.vStudentAcademic  A ON   A.ClassId = CS.ClassId AND  A.StatusId = 1
	--		 LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SSA ON SSA.AcademicId = A.AcademicId AND SSA.SubjectSubActivityId= SSAM.Id  	
			  */
GO
PRINT N'Altering Procedure [sSetup].[pPortalEmployeeDetailAdd]...';


GO
ALTER PROCEDURE [sSetup].[pPortalEmployeeDetailAdd]
	(
		@rStrXml nvarchar(MAX),
		@rOrgId int
	)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT,
			@intDoc INT
BEGIN
	BEGIN TRY
		
		EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml			
		SET @rStrXml=REPLACE(@rStrXml,'&','AND')
		
		BEGIN TRANSACTION	
			BEGIN
	
	--DELETE FROM sHrm.tEmployeeMaster WHERE OrgID = @rOrgId	
	INSERT INTO sHrm.tEmployeeMaster
	(
		OrgID,
		Id,
		Code,
		FirstName,
		MiddleName,
		LastName,
		StatusId,
		IsObsolete,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,
		EUId				-- MantisId : 	0029269 
	)
	SELECT
		OrgId,
		Id,
		Code,
		FirstName,
		MiddleName,
		LastName,
		StatusId,
		IsObsolete,
		CreatedUserId,
		sCommon.fGetDate(),
		UpdatedUserId,
		UpdatedDateTime,
		Id				-- MantisId : 	0029269
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id BIGINT '@Id' ,
		Code nvarchar(10) '@Code',
		FirstName nvarchar(100) '@FirstName',
		LastName nvarchar(100) '@LastName',
		MiddleName nvarchar(100) '@MiddleName',
		StatusId tinyint '@StatusId',
		IsObsolete bit '@IsObsolete',
		CreatedUserId Bigint '@CreatedUserId',
		UpdatedUserId bigint '@UpdatedUserId',
		UpdatedDateTime DateTime '@UpdatedDateTime',
		OrgId smallint '@OrgId'
	)
	
	
	
	--DELETE FROM sHrm.tEmployeePersonalDetail WHERE OrgId= @rOrgId		
	INSERT INTO sHrm.tEmployeePersonalDetail
	(
		OrgId,
		EmployeeId,
		DateOfBirth,
		GenderId,
		MaritalStatusId,
		BloodGroupId,
		Qualification,
		UpdatedUserId,
		UpdatedDateTime
	)
	
	SELECT
		OrgId,
		EmployeeId,
		DateOfBirth,
		GenderId,
		MaritalStatusId,
		BloodGroupId,
		Qualification,
		UpdatedUserId,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id BIGINT '@PersonalDetailId',
		EmployeeId BIGINT '@Id',
		DateOfBirth DATE '@DateOfBirth',
		GenderId TINYINT '@GenderId',
		MaritalStatusId TINYINT '@MaritalStatusId',
		BloodGroupId TINYINT '@BloodGroupId',
		Qualification NVARCHAR(50) '@Qualification',
		UpdatedUserId BIGINT '@UpdatedUserId',
		OrgId SMALLINT '@OrgId'
	)

	
	--DELETE FROM sHrm.tEmployeeJobDetail WHERE OrgId = @rOrgId
	INSERT INTO sHrm.tEmployeeJobDetail
	(
		OrgId,
		EmployeeId,
		OrganizationDepartmentId,
		DateOfJoining,		
		EmployeeTypeId,
		EmployeeGroupId,
		EmployeeDesignationId,
		EmployeeGradeId,	
		UpdatedUserId,
		UpdatedDateTime
	)
	SELECT
		OrgId,
		EmployeeId,
		OrganizationDepartmentId,
		DateOfJoining,
		EmployeeTypeId,
		EmployeeGroupId,
		EmployeeDesignationId,
		EmployeeGradeId,	
		UpdatedUserId,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id BIGint '@JobDetailId' ,
		EmployeeId bigint '@Id',
		OrganizationDepartmentId int '@OrganizationDepartmentId',
		DateOfJoining Date '@DateOfJoining',
		OrgId smallint '@OrgId',
		EmployeeTypeId int '@EmployeeTypeId',
		EmployeeGroupId tinyint '@EmployeeGroupId',
		EmployeeDesignationId int '@EmployeeDesignationId',
		EmployeeGradeId int '@EmployeeGradeId',
		UpdatedUserId bigint '@UpdatedUserId'
	)
	
	
	--DELETE FROM sHrm.tEmployeeCommunication WHERE OrgId = @rOrgId
	INSERT INTO sHrm.tEmployeeCommunications
	(
		EmployeeId,
		MobileNumber,
		PersonalEmail,
		UpdatedUserId,
		UpdatedDateTime
	)
	SELECT
		EmployeeId,
		MobileNumber,
		PersonalEmail,
		UpdatedUserId,
		sCommon.fGetDate()
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		Id BIGint '@CommunicationId' ,
		EmployeeId bigint '@Id',		
		MobileNumber nvarchar(20) '@MobileNumber',
		PersonalEmail nvarchar(100) '@PersonalEmail',
		OrgId smallint '@OrgId',
		UpdatedUserId bigint '@UpdatedUserId'
	)
	
	
		INSERT INTO sHrm.tEmployeeImages
	(
		EmployeeId,
		EmployeePhoto 
	)
	SELECT
		EmployeeId,
		[sCommon].[Base64Decode](EmployeePhoto)	
		 
		
	FROM OPENXML (@intDoc, '/Table/EmployeeMaster', 1)
	WITH
	(
		 
		EmployeeId bigint '@Id',		
		EmployeePhoto nvarchar(max) '@EmployeePhoto' 
	)
	
	
	IF NOT EXISTS (SELECT ID FROM sHrm.tEmployeeGradeMaster WHERE ID = 1)
	BEGIN
		INSERT INTO sHrm.tEmployeeGradeMaster (Id,Code,Title,IsObsolete,CreatedUserId,CreatedDateTime) VALUES
		(1,'Default Grade','Default Grade',0,9999000000003,sCommon.fGetDate())
	END
	END	
			EXEC sp_xml_removedocument @intDoc
		COMMIT TRANSACTION	
		SELECT 1
	END TRY
	BEGIN CATCH
	SELECT -1
	END CATCH

END
GO
PRINT N'Altering Procedure [sEMeeting].[pOnlineMeetingGet]...';


GO

ALTER PROCEDURE [sHrm].[pRptEmployeeAttendanceRegisterGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rEmployeeName nvarchar(200),
		@rEmployeeCode nvarchar (200),
		@rEmployeeId bigint,
		@rDepartmentId int,
		@rEmployeeGradeId int,
		@rForYear  smallint,
		@rForMonth tinyint,
		@rBatchId int,
		@rOrgId int,
		@rStatusId smallint=0,
		@rEmployeeStatusId int = 0,
		@rFromNumber int = NULL,
		@rToNumber int = NULL
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

DECLARE @li int 
SET @li=1
Declare @ldate datetime,@lDays int
declare @Days int
Declare @Firstdate datetime
Declare @Lastdate datetime

		
Set @ldate= CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
		
set @Firstdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), 01)
set @Lastdate=CONVERT(nvarchar(10), @rForYear)+ '-' +  CONVERT(nvarchar(10), @rForMonth) + '-' + CONVERT(nvarchar(10), @Days)
		
CREATE Table #EmployeeAttendanceRegistertempTable
(
	 
	EmployeeCode nvarchar(50),
	EmployeeId bigint,
	EmployeeName nvarchar(100),
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(100),
	DepartmentId int,
	DepartmentName nvarchar(50),
	IsPresent bit,
	DayPart int,
	AttendanceDate date,
	DateOfJoining date,
	DateOfLeaving  date,
	AttendanceTagId int ,
	Number int ,
	IsOtherUser smallint,
	EmployeeGrade nvarchar(500),
	Code nvarchar(200),
	LeaveCount decimal(12,2)
 
)
Insert INTO #EmployeeAttendanceRegistertempTable
(	
	EmployeeCode ,
	EmployeeId ,
	EmployeeName,
	ForYear ,
	ForMonth,
	ForMonthInWord,
	DepartmentId ,
	DepartmentName ,
	IsPresent ,
	DayPart ,
	AttendanceDate ,
	DateOfJoining ,
	DateOfLeaving ,
	AttendanceTagId,
	Number,
	IsOtherUser,
	EmployeeGrade,
	Code,
	LeaveCount
)
SELECT  
		EM.Code AS EmployeeCode,
		EM.EmployeeId AS EmployeeId,
		EM.EmployeeName,
		YEAR(EAR.AttendanceDate) AS ForYear,
		MONTH(EAR.AttendanceDate) AS ForMonth,
		DATENAME(month, EAR.AttendanceDate) AS ForMonthInWord,
		EM.DepartmentId,
		EM.DepartmentName,
		EAR.IsPresent,
		day(EAR.AttendanceDate) AS DayPart,
		EAR.AttendanceDate,
		EJD.DateOfJoining,
		EJD.DateOfLeaving,
			EAR.AttendancetagId,
		EM.Number,
		EM.IsOtherUser,
		EM.EmployeeGrade,
		LTM.Code,
		(SELECT ISNULL(SUM(CONVERT(decimal(12,2),  '.'+PARSENAME(NoOfLeave,1))),0) FROM sHrm.tLeave WHERE LeaveTypeId = LTM.Id AND FromDate BETWEEN @FirstDate AND @LastDate AND StatusId!=551 AND OrgId = @rOrgId AND BatchId = @rBatchId AND EmployeeId = EM.EmployeeId) AS LeaveCount

	FROM 

		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.EmployeeId AND (EAR.BatchId = @rBatchId)
		AND MONTH(EAR.AttendanceDate)=@rForMonth AND YEAR(EAR.AttendanceDate)=@rForYear
		INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId AND LTM.IsObsolete=0	
	WHERE 
			EM.OrgID = @rOrgId 
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rStatusId) OR (@rStatusId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
    		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
			AND EM.IsOtherUser = 0
			AND (EM.Number >= @rFromNumber OR @rFromNumber IS NULL) AND (EM.Number <= @rToNumber OR @rToNumber IS NULL)
			ORDER BY EM.Number

CREATE TABLE #TempDaysTempTable
(
 DayPart int
 )
WHILE @li<=@Days

BEGIN

INSERT INTO #TempDaysTempTable
(
	DayPart 
)

SELECT 
@li AS DayPart
SET @li = @li + 1

END

		
			SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2, 
			Number,
			isnull(EmployeeCode,'') as EmployeeCode,
			PivotTable.EmployeeId,
			isnull(EmployeeName,'') as EmployeeName,   
			DepartmentName,
			EmployeeGrade,      
		   	sCommon.fGetDaysInMonth (@rForMonth,@rForYear) AS TotalDays,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'01',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-01')),DateOfJoining,DateOfLeaving,[1]) AS P1,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'02',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-02')),DateOfJoining,DateOfLeaving,[2]) AS P2,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'03',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-03')),DateOfJoining,DateOfLeaving,[3]) AS P3,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'04',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-04')),DateOfJoining,DateOfLeaving,[4])  AS P4,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'05',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-05')),DateOfJoining,DateOfLeaving,[5]) AS P5,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'06',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-06')),DateOfJoining,DateOfLeaving,[6]) AS P6,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'07',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-07')),DateOfJoining,DateOfLeaving,[7])  AS P7,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'08',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-08')),DateOfJoining,DateOfLeaving,[8]) As P8,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'09',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-09')),DateOfJoining,DateOfLeaving,[9]) AS P9,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'10',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-10')),DateOfJoining,DateOfLeaving,[10]) AS P10,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'11',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-11')),DateOfJoining,DateOfLeaving,[11]) AS P11,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'12',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-12')),DateOfJoining,DateOfLeaving,[12]) AS P12,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'13',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-13')),DateOfJoining,DateOfLeaving,[13]) AS P13,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'14',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-14')),DateOfJoining,DateOfLeaving,[14]) AS P14,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'15',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-15')),DateOfJoining,DateOfLeaving,[15]) AS P15,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'16',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-16')),DateOfJoining,DateOfLeaving,[16])  AS P16,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'17',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-17')),DateOfJoining,DateOfLeaving,[17]) AS P17,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'18',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-18')),DateOfJoining,DateOfLeaving,[18])  AS P18,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'19',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-19')),DateOfJoining,DateOfLeaving,[19])  AS P19,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'20',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-20')),DateOfJoining,DateOfLeaving,[20])  AS P20,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'21',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-21')),DateOfJoining,DateOfLeaving,[21]) AS P21,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'22',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-22')),DateOfJoining,DateOfLeaving,[22]) AS P22,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'23',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-23')),DateOfJoining,DateOfLeaving,[23]) AS P23,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'24',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-24')),DateOfJoining,DateOfLeaving,[24]) AS P24,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'25',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-25')),DateOfJoining,DateOfLeaving,[25]) AS P25,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'26',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-26')),DateOfJoining,DateOfLeaving,[26]) AS P26,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'27',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-27')),DateOfJoining,DateOfLeaving,[27]) AS P27,
			[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'28',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-28')),DateOfJoining,DateOfLeaving,[28]) AS P28,
			CASE WHEN @Days>=29 THEN[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'29',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-29')),DateOfJoining,DateOfLeaving,[29]) end AS P29,
			CASE WHEN @Days>=30 THEN[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'30',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-30')),DateOfJoining,DateOfLeaving,[30])end AS P30,
			CASE WHEN @Days>=31 THEN[sHrm].[fAttendanceWithApproveLeaveGet](PivotTable.EmployeeId,@rForYear,@rForMonth,'31',@rBatchId,DepartmentId,@rOrgId,CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-31')),DateOfJoining,DateOfLeaving,[31])end AS P31,
			Code,
			LeaveCount
			FROM
(
	Select  
		EmployeeCode,
		EmployeeId,
		EmployeeName,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		DepartmentId,
		DepartmentName,
		(
			CASE 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LA' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'ED' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		DateOfLeaving,		 
		DateOfJoining,
		Number,
		EmployeeGrade,
		Code,
		LeaveCount	
	 FROM 
		#EmployeeAttendanceRegistertempTable ST 
		LEFT JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE 
		  ((DateOfLeaving >= @FirstDate) OR ISNULL(DateOfLeaving,'') = '')
		  AND IsOtherUser = 0
	   -- WHERE 
	   -- ForYear=@rForYear AND ForMonth=@rForMonth
) AS SourceTable 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  EmployeeId AS EmployeeId, COUNT(1) AS TCount 
		   FROM  
				#EmployeeAttendanceRegistertempTable
				WHERE AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
		     GROUP BY  EmployeeId 
    ) TC ON TC.EmployeeId = PivotTable.EmployeeId 
	LEFT JOIN
	(
		Select EmployeeId AS EmployeeId, COUNT(1) AS ACount 
		   FROM  #EmployeeAttendanceRegistertempTable
		    WHERE   IsPresent = 0	 	 
		      AND AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			GROUP BY  EmployeeId
    ) AC ON AC.EmployeeId = PivotTable.EmployeeId
	LEFT JOIN
	(
		SELECT EJD.EmployeeId, COUNT(1) AS PCount  FROM 
		
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = EM.EmployeeId AND (EAR.BatchId = @rBatchId)
		AND MONTH(EAR.AttendanceDate)=@rForMonth AND YEAR(EAR.AttendanceDate)=@rForYear
	   
			WHERE   
	
	    ((EM.OrgId=@rOrgId) OR (@rOrgId= 0))
	       AND ((EM.DepartmentId = @rDepartmentId)OR (@rDepartmentId=0))
	       AND ((EAR.BatchId=@rBatchId) OR (@rBatchId= 0))
	       AND EAR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
		   AND EM.IsOtherUser = 0
	 GROUP BY EJD.EmployeeId 
    ) PC ON PC.EmployeeId = PivotTable.EmployeeId
		
	Order By PivotTable.Number	
			--FROM
			--sHrm.vEmployeeCommonDetail EM
			--INNER JOIN sHrm.tEmployeeMaster E ON E.Id = EM.EmployeeId				
			--INNER JOIN sHrm.tLeaveTypeMaster LTM ON E.OrgID=LTM.OrgId						
			
   -- 		WHERE 
   -- 		EM.OrgID = @rOrgId 
   -- 		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
   -- 		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
   -- 		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
   -- 		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
   -- 		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
   -- 		AND ((EM.EmployeeStatusId=@rStatusId) OR (@rStatusId=0))
   -- 		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
   -- 		AND (EM.DateOfJoining<= @Lastdate OR ISNULL(EM.DateOfJoining,'')='')
   -- 		AND (EM.DateOfleaving>= @Firstdate OR ISNULL(EM.DateOfleaving,'')='')
   -- 		--AND ((ISNULL(EM.DateOfJoining,''))<=CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'-'+CONVERT(NVARCHAR(2),@rForMonth)+'-'+CONVERT(NVARCHAR(2),IN(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31)))))			
			--AND EM.IsOtherUser = 0
			--AND E.Number>=@rFromNumber AND E.Number<=@rToNumber

		--	SELECT [Builder1]
  --    ,[Builder2]
	 -- ,[Number]
  --    ,[EmployeeCode]
  --    ,[EmployeeId]
  --    ,[EmployeeName]
  --    ,[DepartmentName]
  --    ,[EmployeeGrade]
  --    ,[TotalDays]
  --    ,[P1]
  --    ,[P2]
  --    ,[P3]
  --    ,[P4]
  --    ,[P5]
  --    ,[P6]
  --    ,[P7]
  --    ,[P8]
  --    ,[P9]
  --    ,[P10]
  --    ,[P11]
  --    ,[P12]
  --    ,[P13]
  --    ,[P14]
  --    ,[P15]
  --    ,[P16]
  --    ,[P17]
  --    ,[P18]
  --    ,[P19]
  --    ,[P20]
  --    ,[P21]
  --    ,[P22]
  --    ,[P23]
  --    ,[P24]
  --    ,[P25]
  --    ,[P26]
  --    ,[P27]
  --    ,[P28]
  --    ,[P29]
  --    ,[P30]
  --    ,[P31]
  --    ,[Code]
  --    ,[LeaveCount]
  --FROM [sHrm].[tTempEmployeeAttendanceRegister]
drop table #EmployeeAttendanceRegistertempTable	  
drop table #TempDaysTempTable
END
GO
PRINT N'Altering Procedure [sHrm].[pTransferEmployee]...';


GO
ALTER PROCEDURE [sHrm].[pTransferEmployee]
		   
		   @rFromOrgId int,
		   @rToOrgId int,
		   @rToDepartmentId int,
		   @rToEmployeeTypeId int,
		   @rToEmployeeGradeId int,
		   @rToEmployeeDesignationId int,
		   @rEmployeeId bigint,
		   @rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF EXISTS(SELECT 1 FROM sHrm.tEmployeeMaster WHERE OrgId = @rToOrgId AND ReferenceEmployeeId = @rEmployeeId AND  ISNULL(IsOtherUser,0) = 0) 
	BEGIN
		SELECT -101
		RETURN
	END
	
	BEGIN TRY
		BEGIN TRANSACTION
		
		
		
		
		DECLARE @lNextNumber BIGINT
		EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sHrm.tEmployeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		-- Employee Master 
		INSERT INTO sHrm.tEmployeeMaster
		(OrgID,Id,Code,FirstName,MiddleName,LastName,ShortName,StatusId,IsObsolete,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,ShiftId,PunchId,ReferenceEmployeeId,EUId)		-- MantisId : 	0029269 Add EUID
		SELECT @rToOrgId,@lNextNumber,@lNextNumber,FirstName,MiddleName,LastName,ShortName,StatusId,IsObsolete,@rUserId,sCommon.fGetDate(),@rUserId,sCommon.fGetDate(),ShiftId,PunchId,Id,@lNextNumber FROM sHrm.tEmployeeMaster WHERE OrgId = @rFromOrgId AND Id = @rEmployeeId AND  ISNULL(IsOtherUser,0) = 0
		
		-- Employee Job Detail
		INSERT INTO sHrm.tEmployeeJobDetail
		(OrgID,EmployeeId,EmployeeDesignationId,OrganizationDepartmentId,DateOfJoining,UpdatedUserId,UpdatedDateTime,EmployeeTypeId,DateOfleaving,ReasonOfleaving,EmployeeGroupId,EmployeeGradeId,JobRemark,EmployeeManagerId,ProbationDays,ReferenceRemark,EmployeeBusinessHeadId,Subjects,OrgGroupDepartmentId)
		SELECT @rToOrgId,@lNextNumber,@rToEmployeeDesignationId,@rToDepartmentId,DateOfJoining,@rUserId,sCommon.fGetDate(),@rToEmployeeTypeId,DateOfleaving,ReasonOfleaving,EmployeeGroupId,EmployeeGradeId,JobRemark,NULL,ProbationDays,ReferenceRemark,NULL,Subjects,OrgGroupDepartmentId FROM sHrm.tEmployeeJobDetail WHERE OrgId = @rFromOrgId AND EmployeeId = @rEmployeeId
		
		-- Employee Personal Detail
		INSERT INTO sHrm.tEmployeePersonalDetail
		(OrgID,EmployeeId,UIDNumber,DateOfBirth,GenderId,ReligionId,MaritalStatusId,IdentificationMark1,BloodGroupId,Qualification,UpdatedUserId,UpdatedDateTime,FamilyCast,CastCategoryId,AdhaarNumber)
		SELECT @rToOrgId,@lNextNumber,UIDNumber,DateOfBirth,GenderId,ReligionId,MaritalStatusId,IdentificationMark1,BloodGroupId,Qualification,@rUserId,sCommon.fGetDate(),FamilyCast,CastCategoryId,AdhaarNumber FROM sHrm.tEmployeePersonalDetail WHERE OrgId = @rFromOrgId AND EmployeeId = @rEmployeeId
		
		-- Employee Communications
		INSERT INTO sHrm.tEmployeeCommunications
		(EmployeeId,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,PresentState,PresentCity,PresentZipCode,PresentContactNo,
		PermanentStreetOne,PermanentStreetTwo,PermanentStreetThree,PermanentCountry,PermanentState,PermanentCity,PermanentZipCode,PermanentContactNo,
		EmergencyStreetOne,EmergencyStreetTwo,EmergencyStreetThree,EmergencyCountry,EmergencyState,EmergencyCity,EmergencyZipCode,EmergencyContactNo,
		PhoneNoCompany,ExtensionNo,CompanyEmail ,PersonalEmail,MobileNumber,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime)
		SELECT @lNextNumber,PresentStreetOne,PresentStreetTwo,PresentStreetThree,PresentCountry,PresentState,PresentCity,PresentZipCode,PresentContactNo,
		PermanentStreetOne,PermanentStreetTwo,PermanentStreetThree,PermanentCountry,PermanentState,PermanentCity,PermanentZipCode,PermanentContactNo,
		EmergencyStreetOne,EmergencyStreetTwo,EmergencyStreetThree,EmergencyCountry,EmergencyState,EmergencyCity,EmergencyZipCode,EmergencyContactNo,
		PhoneNoCompany,ExtensionNo,CompanyEmail ,PersonalEmail,MobileNumber,@rUserId,sCommon.fGetDate(),@rUserId,sCommon.fGetDate() 
		FROM sHrm.tEmployeeCommunications EC INNER JOIN sHrm.tEmployeeMaster EM ON EC.EmployeeId = EM.Id
		WHERE EM.OrgId = @rFromOrgId AND EC.EmployeeId = @rEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
		
		-- Employee Statutory And Other
		INSERT INTO sHrm.tEmployeeStatutoryAndOther
		([EmployeeId],[EPFNumber],[IsVPFDeduction],[VPFContributionId],[VPFContributionEffectiveFrom],[VPFPercentage]
        ,[VPFAmount],[ESINumber],[BankName],[Branch],[AccountNumber],[IFSCNumber],[PanNumber],[IncomeTaxStatusId]
        ,[UpdatedUserId],[UpdatedDateTime],[IncrementDate],[BasicPay],[PayrollId],[PayrollGroupId]
        ,[Payscale],[EPFJoinDate],[UAN],[RetirementDate])
		SELECT 
		@lNextNumber,[EPFNumber],[IsVPFDeduction],[VPFContributionId],[VPFContributionEffectiveFrom],[VPFPercentage]
        ,[VPFAmount],[ESINumber],[BankName],[Branch],[AccountNumber],[IFSCNumber],[PanNumber],[IncomeTaxStatusId]
        ,@lNextNumber,sCommon.fGetDate(),[IncrementDate],[BasicPay],NULL,NULL
        ,[Payscale],[EPFJoinDate],[UAN],[RetirementDate]
		FROM sHrm.tEmployeeStatutoryAndOther ESO INNER JOIN sHrm.tEmployeeMaster EM ON ESO.EmployeeId = EM.Id
		WHERE EM.OrgId = @rFromOrgId AND ESO.EmployeeId = @rEmployeeId AND  ISNULL(EM.IsOtherUser,0) = 0
		
		SELECT 1
		COMMIT TRANSACTION			
	END TRY
		
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering Procedure [sAcademic].[pClassworkGet]...';


GO
ALTER PROCEDURE [sAcademic].[pClassworkGet]

	 @rId bigint=0,	 
	 @rSubjectId int=0,
	 @rClassId int=0,
	 @rEmployeeId bigint=0,
	 @rDivisionid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rOrgId int=0,
     --@rBatchId int
     @rOrgGroupBatchId int=0,
    @rUserId bigint =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	IF(@rEmployeeId = -1)
	BEGIN
		SET @rEmployeeId = 0
	END

	if(@rId = 0)
		BEGIN
			SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			--comment above line due to mantisid - 0029607 - for different time zone
			--[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(AC.CreatedDateTime,'')) AS CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework,
			AC.Id AS ClassworkId
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
	order by 
			AC.HomeWorkEndDate DESC
		END 
	ELSE
		BEGIN
		SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			--comment above line due to mantisid - 0029607 - for different time zone
			--[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(AC.CreatedDateTime,'')) AS CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId,
			ISNULL(AC.IsSubmitHomework,0) AS IsSubmitHomework,
			AC.Id AS ClassworkId
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			GROUP BY AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ClassworkStatusId,
			HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			AC.HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title,
		  vTSD.SubjectName,
		    EM.FirstName,  EM.LastName,
		    vTSD.ClassTitle,
		   vTSD.DivisionTitle,
		    BM.OrgId,
		    OM.DisplayTitle,
		     AC.ClassWorkDate, AC.DivisionId,AC.SubjectId
			 ,AC.IsSubmitHomework
	order by 
			AC.HomeWorkEndDate DESC
		END
	
END
GO
PRINT N'Altering Procedure [sHrm].[pDigitalFormFieldApprove]...';


GO
ALTER PROCEDURE [sHrm].[pDigitalFormFieldApprove]
			@rId BIGINT = 0,
			@rUpdateFieldId INT=0,
			@rOldValue NVARCHAR(500)='',
			@rNewValue NVARCHAR(500)='',
			@rActionRemark NVARCHAR(500) = '',
			@rActionUserId BIGINT,
			@rActionDateTime DATETIME,
			@rStatusId INT,
			@rRequestId INT =0,
			@rOldValueImage VARBINARY(MAX) = 0x00000000,
			@rNewValueImage VARBINARY(MAX) = 0x00000000
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

		IF EXISTS(SELECT 1 FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rId)
		BEGIN
		    
			DECLARE @lResult INT
			DECLARE @lDataTypeId NVARCHAR(1)
			SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Id=@rUpdateFieldId

			IF(@lDataTypeId = 4)
			BEGIN
				SET @rNewValue = CONVERT(DATETIME,@rNewValue,104)
				SET @rOldValue = CONVERT(DATETIME,@rOldValue,104)
			END

			DECLARE @lUpdateField NVARCHAR(100)
			DECLARE @lUpdateFieldImage VARBINARY(MAX)
			DECLARE @lSubFunctionality NVARCHAR(100)
			DECLARE @lEmployeeId BIGINT

			SET @lUpdateField = (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)

			SET @lSubFunctionality = (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)
			SET @lEmployeeId = (SELECT EmployeeId FROM sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rId)

			IF(@lUpdateField = 'Gender' OR @lUpdateField = 'Religion' OR @lUpdateField = 'MaritalStatus' OR @lUpdateField = 'BloodGroup' 
			 OR @lUpdateField = 'EmployeeDesignation' OR @lUpdateField = 'OrganizationDepartment' OR @lUpdateField = 'EmployeeType' 
			 OR @lUpdateField = 'EmployeeGroup' OR @lUpdateField = 'EmployeeGrade' OR @lUpdateField = 'OrgGroupDepartment' 
			 OR @lUpdateField = 'EmployeeManager'  OR @lUpdateField = 'Payroll' OR  @lUpdateField = 'PayrollGroup' OR @lUpdateField = 'Tribe')
			
			BEGIN
			SET @lUpdateField =@lUpdateField + 'Id'
			END
			IF(@lUpdateField = 'OrganizationHeadManager' )
			BEGIN
				SET @lUpdateField = 'EmployeeBusinessHeadId'
			END
			IF(@lUpdateField = 'CasteCategory' )
			BEGIN
			SET @lUpdateField = REPLACE(@lUpdateField,'Caste','Cast') + 'Id'
			END
			
			IF(@lUpdateField = 'FamilyCast' )
			BEGIN
				SET @lUpdateField = REPLACE(@lUpdateField,'Caste','Cast') 
			END
	
			Declare @Sql nvarchar(MAX)

			IF OBJECT_ID('ListofEmpData') IS NOT NULL	
			BEGIN 
				DROP TABLE ListofEmpData
			END	
			
			--Select @lSubFunctionality	
			IF(@rStatusId = 550)
			BEGIN
				
				IF(@lSubFunctionality = 'EmployeeImage')
				-----------------EmployeeImage--------------
					BEGIN
						IF(@lUpdateField = 'EmployeeImage')
						BEGIN
							SET @lUpdateField = 'EmployeePhoto'
						END

						CREATE TABLE ListofData(Id BIGINT,EmployeeId BIGINT,SubCategory VARBINARY(MAX),UpdatedUserId BIGINT,IsExist BIT);
						INSERT INTO ListofData VALUES (@rId,@lEmployeeId,@rNewValueImage,@rActionUserId,0)

						UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeImages)

						SET @sql='INSERT INTO sHrm.tEmployeeImages 
								(EmployeeId,'+@lUpdateField+',EmployeeSign,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,Ld.SubCategory,sCommon.fGetDate()
								FROM
									ListofData LD WHERE LD.IsExist=1'
					
						PRINT @sql		
						EXEC sp_executesql @sql
						SET  @sql='UPDATE sHrm.tEmployeeImages  set '+@lUpdateField+' = LD.SubCategory,
									EmployeeSign = LD.SubCategory,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeImages  EI 
									INNER JOIN ListofData LD ON EI.EmployeeId=LD.EmployeeId AND IsExist=0'
		
						EXEC sp_executesql @sql

						DROP TABLE ListofData
						SET @lResult = 1;
					END

				ELSE

				BEGIN

					CREATE TABLE ListofEmpData(Id BIGINT,EmployeeId BIGINT,SubCategory NVARCHAR(150),UpdatedUserId BIGINT,IsExist BIT);
					INSERT INTO ListofEmpData VALUES (@rId,@lEmployeeId,@rNewValue,@rActionUserId,0)
		
					IF(@lSubFunctionality = 'EmployeeCommunication')  ----EmployeeCommunication
						BEGIN
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications)
								SET @sql='INSERT INTO sHrm.tEmployeeCommunications 
											(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
											SELECT
												LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
											FROM
												ListofEmpData LD WHERE LD.IsExist=1'
									
								PRINT @sql		
								EXEC sp_executesql @sql
								SET @sql='UPDATE sHrm.tEmployeeCommunications set '+@lUpdateField+' = LD.SubCategory,
											UpdatedUserId=LD.UpdatedUserId,
											UpdatedDateTime=sCommon.fGetDate()  
											from sHrm.tEmployeeCommunications EC 
											INNER JOIN ListofEmpData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
								EXEC sp_executesql @sql
	
		
								DROP TABLE ListofEmpData
									 SET @lResult = 1;
						END
						
					ELSE IF(@lSubFunctionality = 'EmployeeOther')         -------EmployeeOther
						BEGIN
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
			
								IF(@lUpdateField = 'DateOfBirth')
								BEGIN			
									SET @sql='INSERT INTO sHrm.tEmployeePersonalDetail 
											(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
											SELECT
												LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
											FROM
												ListofEmpData LD WHERE LD.IsExist=1'
									EXEC sp_executesql @sql				
			 							
									SET @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
												UpdatedUserId=LD.UpdatedUserId,
												UpdatedDateTime=sCommon.fGetDate()  
												from sHrm.tEmployeePersonalDetail EPD 
												INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'			
									EXEC sp_executesql @sql
									SET @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
									EXEC sp_executesql @sql
								END
								ELSE
								BEGIN
									SET @sql='INSERT INTO sHrm.tEmployeePersonalDetail
												(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
												SELECT
													LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
												FROM
													ListofEmpData LD WHERE LD.IsExist=1'
									EXEC sp_executesql @sql				
			 							
									SET @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
												UpdatedUserId=LD.UpdatedUserId,
												UpdatedDateTime=sCommon.fGetDate()  
												from sHrm.tEmployeePersonalDetail EPD 
												INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'
									
									EXEC sp_executesql @sql
									
								END
								DROP TABLE ListofEmpData
									 SET @lResult = 1;
						END	
							
					ELSE IF(@lSubFunctionality = 'JobDetail')		--------JobDetail
						BEGIN
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeJobDetail) 
							IF(@lUpdateField = 'DateOfJoining')
							BEGIN			
								SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
								EXEC sp_executesql @sql				
			 						
								SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
											UpdatedUserId=LD.UpdatedUserId,
											UpdatedDateTime=sCommon.fGetDate()  
											from sHrm.tEmployeeJobDetail  EJD 
											INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
								EXEC sp_executesql @sql
								SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfJoining=''1900-01-01'''
								EXEC sp_executesql @sql
							END
					ELSE IF(@lUpdateField = 'DateOfleaving')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfleaving=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'ProbationUptoDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE ProbationUptoDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'AhdocUptoDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
							 		UpdatedUserId=LD.UpdatedUserId,
							 		UpdatedDateTime=sCommon.fGetDate()  
							 		from sHrm.tEmployeeJobDetail  EJD 
							 		INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE AhdocUptoDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'PermanentDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE PermanentDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE
					BEGIN
						SET  @sql='INSERT INTO sHrm.tEmployeeJobDetail
							 		(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET  @sql='UPDATE sHrm.tEmployeeJobDetail set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'
			
						EXEC sp_executesql @sql
					END
					DROP TABLE ListofEmpData
						 SET @lResult = 1;
					END	

					ELSE IF(@lSubFunctionality = 'EmployeeGeneral')			---------EmployeeGeneral
						BEGIN
						
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT Id FROM sHrm.tEmployeeMaster) 
							-- MantisId : 	0029269 Add EUID
							SET  @sql='INSERT INTO sHrm.tEmployeeMaster
										(Id,'+@lUpdateField+',CreatedUserId,CreatedDateTime,EUId)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate(),LD.EmployeeId
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'				 
							EXEC sp_executesql @sql
							SET  @sql='UPDATE sHrm.tEmployeeMaster set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeMaster EM 
										INNER JOIN ListofEmpData LD ON EM.Id=LD.EmployeeId AND IsExist=0'
		
							EXEC sp_executesql @sql
					
							DROP TABLE ListofEmpData
								 SET @lResult = 1;
						END

					ELSE IF(@lSubFunctionality = 'Statutory')	   ----------Statutory
						BEGIN
							UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
							SET @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'				
							EXEC sp_executesql @sql
							
							SET @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@lUpdateField+' = LD.SubCategory,
											UpdatedUserId=LD.UpdatedUserId,
											UpdatedDateTime=sCommon.fGetDate()  
											from sHrm.tEmployeeStatutoryAndOther ES 
											INNER JOIN ListofEmpData LD ON ES.EmployeeId=LD.EmployeeId AND IsExist=0'

							EXEC sp_executesql @sql
							 
							DROP TABLE ListofEmpData
							 SET @lResult = 1;
						END
				END	

				IF(@lResult = 1)
				BEGIN
					UPDATE sHrm.tDigitalFormEmployee
					SET
						StatusId = @rStatusId
						,ActionRemark = @rActionRemark
						,ActionUserId = @rActionUserId
						,ActionDateTime = @rActionDateTime
					WHERE 
						AutoId = @rRequestId
				END
			
				SELECT 1 AS Result
			END

			ELSE IF(@rStatusId = 551)
			IF(@lSubFunctionality = 'EmployeeImage')
				BEGIN
					IF(@lUpdateField = 'EmployeeImage')
						BEGIN
							SET @lUpdateField = 'EmployeePhoto'
						END

					CREATE TABLE ListofData(Id BIGINT,EmployeeId BIGINT,SubCategory VARBINARY(MAX),UpdatedUserId BIGINT,IsExist BIT);
					INSERT INTO ListofData VALUES (@rId,@lEmployeeId,@rOldValueImage,@rActionUserId,0)

					UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeImages)

					SET @sql='INSERT INTO sHrm.tEmployeeImages 
						(EmployeeId,'+@lUpdateField+',EmployeeSign,UpdatedDateTime)
						SELECT
							LD.EmployeeId,Ld.SubCategory,Ld.SubCategory,sCommon.fGetDate()
						FROM
							ListofData LD WHERE LD.IsExist=1'

					EXEC sp_executesql @sql

					DROP TABLE ListofData
					SET @lResult = 1;
				END

			ELSE
			BEGIN

				CREATE TABLE ListofEmpData(Id BIGINT,EmployeeId BIGINT,SubCategory NVARCHAR(150),UpdatedUserId BIGINT,IsExist BIT);
				INSERT INTO ListofEmpData VALUES (@rId,@lEmployeeId,@rNewValue,@rActionUserId,0)

			--UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications)
			
				IF(@lSubFunctionality = 'EmployeeCommunication')  ----EmployeeCommunication
					BEGIN
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications)
							SET  @sql='INSERT INTO sHrm.tEmployeeCommunications 
										(EmployeeId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
								
							PRINT @sql		
							EXEC sp_executesql @sql
							SET  @sql='UPDATE sHrm.tEmployeeCommunications set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeCommunications EC 
										INNER JOIN ListofEmpData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
							EXEC sp_executesql @sql
	
		
							DROP TABLE ListofEmpData
								 SET @lResult = 1;
						END
					
				ELSE IF(@lSubFunctionality = 'EmployeeOther')         -------EmployeeOther
					BEGIN
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
							IF(@lUpdateField = 'DateOfBirth')
							BEGIN			
								SET @sql='INSERT INTO sHrm.tEmployeePersonalDetail 
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
								EXEC sp_executesql @sql				
			 						
								SET @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
											UpdatedUserId=LD.UpdatedUserId,
											UpdatedDateTime=sCommon.fGetDate()  
											from sHrm.tEmployeePersonalDetail EPD 
											INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'			
								EXEC sp_executesql @sql
								SET @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
								EXEC sp_executesql @sql
						END
					ELSE
						BEGIN
							SET @sql='INSERT INTO sHrm.tEmployeePersonalDetail
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
							EXEC sp_executesql @sql				
			 					
							SET @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeePersonalDetail EPD 
										INNER JOIN ListofEmpData LD ON EPD.EmployeeId=LD.EmployeeId'
			
							EXEC sp_executesql @sql
						END
						DROP TABLE ListofEmpData
							 SET @lResult = 1;
						END	

				Else IF(@lSubFunctionality = 'JobDetail')		--------JobDetail
					BEGIN
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeJobDetail) 
						IF(@lUpdateField = 'DateOfJoining')
						BEGIN			
							SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
									(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
							EXEC sp_executesql @sql				
			 					
							SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeJobDetail  EJD 
										INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
							EXEC sp_executesql @sql
							SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfJoining=''1900-01-01'''
							EXEC sp_executesql @sql
					END

					ELSE IF(@lUpdateField = 'DateOfleaving')
						BEGIN			
							SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
									(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'
							EXEC sp_executesql @sql				
			 					
							SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeJobDetail  EJD 
										INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
							EXEC sp_executesql @sql
							SET  @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE DateOfleaving=''1900-01-01'''
							EXEC sp_executesql @sql
						END

					ELSE IF(@lUpdateField = 'ProbationUptoDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE ProbationUptoDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'AhdocUptoDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE AhdocUptoDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE IF(@lUpdateField = 'PermanentDate')
					BEGIN			
						SET @sql='INSERT INTO sHrm.tEmployeeJobDetail 
								(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofEmpData LD WHERE LD.IsExist=1'
						EXEC sp_executesql @sql				
			 				
						SET @sql='UPDATE sHrm.tEmployeeJobDetail  set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeJobDetail  EJD 
									INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'			
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@lUpdateField+' = null WHERE PermanentDate=''1900-01-01'''
						EXEC sp_executesql @sql
					END
					ELSE
						BEGIN
							SET @sql='INSERT INTO sHrm.tEmployeeJobDetail
										(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
										SELECT
											LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
										FROM
											ListofEmpData LD WHERE LD.IsExist=1'
							EXEC sp_executesql @sql				
			 					
							SET @sql='UPDATE sHrm.tEmployeeJobDetail set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeJobDetail EJD 
										INNER JOIN ListofEmpData LD ON EJD.EmployeeId=LD.EmployeeId'
			
							EXEC sp_executesql @sql
						END
					DROP TABLE ListofEmpData
						 SET @lResult = 1;
					END	

				ELSE IF(@lSubFunctionality = 'EmployeeGeneral')			---------EmployeeGeneral
					BEGIN
					
						UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT Id FROM sHrm.tEmployeeMaster) 
						-- MantisId : 	0029269 Add EUID									
						SET @sql='INSERT INTO sHrm.tEmployeeMaster
									(Id,'+@lUpdateField+',CreatedUserId,CreatedDateTime,EUId)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate(),LD.EmployeeId
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'				
						EXEC sp_executesql @sql
						SET @sql='UPDATE sHrm.tEmployeeMaster set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sHrm.tEmployeeMaster EM 
									INNER JOIN ListofEmpData LD ON EM.Id=LD.EmployeeId AND IsExist=0'
		
						EXEC sp_executesql @sql
						
						DROP TABLE ListofEmpData
							 SET @lResult = 1;
					END

				 Else IF(@lSubFunctionality = 'Statutory')	   ----------Statutory
					BEGIN
						 UPDATE ListofEmpData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
						 SET @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
									(EmployeeId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
									SELECT
										LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofEmpData LD WHERE LD.IsExist=1'				
						 EXEC sp_executesql @sql
						 
						 SET @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sHrm.tEmployeeStatutoryAndOther ES 
										INNER JOIN ListofEmpData LD ON ES.EmployeeId=LD.EmployeeId AND IsExist=0'

						EXEC sp_executesql @sql
						  
						DROP TABLE ListofEmpData
							SET @lResult = 1;
					END
				
			END

			IF(@lResult = 1)
			BEGIN
				UPDATE sHrm.tDigitalFormEmployee
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 2 AS Result
		END

		ELSE
		BEGIN
		   SELECT -101 As Result
		END
		
		COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
		SELECT ERROR_MESSAGE() AS Error
	END CATCH
		
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeMasterAdd]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeMasterAdd]
    
    @rOrgId smallint,
	@rCode [nvarchar](100),
	@rFirstName [nvarchar](100),
	@rMiddleName [nvarchar](100),
	@rLastName [nvarchar](100),
    @rEmployeeTypeId int,
	@rDepartmentId int,
	@rDateOfBirth Date,
	@rDateOfJoining Date,
	@rGenderId int,
	@rReligionId int=null,--
	@rStatusId [int],
	@rIsObsolete [bit],
	@rCreatedUserId [bigint],
	@OutEmployeeId bigint = null output,--
	@rEmployeeDesignationId INT,
	@rBloodGroupId TINYINT = 0,--
	@rQualification nvarchar(150) = '',
	@rEmployeeGradeId int,
	@rEmployeeGroupId int,
	@rShortName nvarchar(50),
	@rEmployeeManagerId bigint=0,
	@rFamilyCast nvarchar(150) = '',
	@rCastCategoryId int  =null,
	@rNumber bigint=0,
	@rProbationUptoDate date = null,
	@rAhdocUptoDate date = null,
	@rPermanentDate date= null,
	@rIsOtherUser smallint = 0,
	@rDateOfResignation date = null,
	@rDateOfLeaving Date = null,
	@rTribeId int = null,
	@rAdhaarNumber nvarchar(40)='',
	@rMaritalStatusId TINYINT = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	DECLARE @lNextNumber BIGINT
	
	DECLARE @loEmpNumber Nvarchar(100)
	DECLARE @lEmpPrefixResult Int
    

	IF EXISTS(SELECT Id FROM sHrm.tEmployeeMaster WHERE Code=@rCode AND OrgId=@rOrgId AND ISNULL(IsOtherUser,0) = 0 )
		BEGIN
		SELECT -101 as Result
		RETURN
	END 
 

		
    
 --   IF((@rCode = Null) OR (@rCode = ''))
 --   BEGIN
	--	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 94,@rStoreLocationId = 0, @rNextNumber = @loEmpNumber OUTPUT	
	--	SET @loEmpNumber = ISNULL(@loEmpNumber, '-300')
	--	SET @lEmpPrefixResult = '-300'	
	--END
	--ELSE
	--  BEGIN
 --       SET	@loEmpNumber = @rCode
 --     END
            		
	--IF (@loEmpNumber <> '-300')
	--BEGIN
	
	--BEGIN TRY
 --	BEGIN TRANSACTION
	
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
				
		INSERT INTO sHrm.tEmployeeMaster
			(
				Id,
				Code,
				FirstName,
				MiddleName,
				LastName,
				ShortName,
				StatusId,
				IsObsolete,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime,
				OrgId,
				Number,
				IsOtherUser,
				EUId			-- MantisId : 	0029269
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rFirstName,
				@rMiddleName,
				@rLastName,
				@rShortName,
				@rStatusId,
				@rIsObsolete,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrgId,
				@rNumber,
				@rIsOtherUser,
				@lNextNumber		-- MantisId : 	0029269
			)
	    
		 
				
		SELECT Id AS RESULT, @loEmpNumber AS EmpCode FROM sHrm.tEmployeeMaster WHERE  Id = @lNextNumber
		SET @OutEmployeeId = @lNextNumber -- added for import employee
		
		BEGIN 
        Execute sHrm.pEmployeeJobDetailAdd  
	       @rOrgId,@lNextNumber,@rEmployeeDesignationId,@rDepartmentId,@rDateOfJoining,@rCreatedUserId,
	       @rEmployeeTypeId,@rEmployeeGradeId,@rEmployeeGroupId,'',@rEmployeeManagerId,NULL,NULL,0,@rProbationUptoDate,@rAhdocUptoDate,@rPermanentDate,@rDateOfResignation,@rDateOfLeaving
	          
	     Execute sHrm.pEmployeePersonalDetailAdd @rOrgId,@lNextNumber,'',@rDateOfBirth,@rGenderId,@rReligionId,
	     @rMaritalStatusId,'',@rBloodGroupId,@rQualification,@rCreatedUserId,@rFamilyCast,@rCastCategoryId,@rTribeId,@rAdhaarNumber

	      
		END	

		--COMMIT TRANSACTION
	 
		--END TRY
		
		--BEGIN CATCH
		--ROLLBACK TRANSACTION 
 
		--	RAISERROR ('Error saving employee Master', -- Message text.
  --             16, -- Severity.
  --             1 -- State.
  --             );           
		 
 
		--END CATCH			
 
	
	 
END
GO
PRINT N'Altering Procedure [sHrm].[pEmployeeMasterGet]...';


GO

ALTER PROCEDURE [sHrm].[pEmployeeMasterGet]
	 
	 @rOrgId smallint,
	 @rId [bigint] = 0,
	 @rCode nvarchar(50) = ''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 --  IF @rCode <> ''
		--BEGIN			
		--SET @rCode = sCommon.fSearchStringGet(@rCode)
		--END
	 SELECT 
				EM.Id,
				EM.Id AS EmployeeId,
				EM.Code,
				EM.FirstName,
				EM.MiddleName,
				EM.LastName,
				EM.ShortName AS EmpShortName,
				EM.StatusId,
				EM.IsObsolete,
				EM.FirstName+' '+EM.LastName As EmployeeFullName,
				EJD.OrganizationDepartmentId AS DepartmentId,
				EJD.DateOfJoining,
				EJD.EmployeeTypeId,
				EPD.DateOfBirth,
				EPD.GenderId,
				EJD.EmployeeDesignationId,
				ISNULL(DM.Title,'') AS EmployeeDesignation,
				EJD.EmployeeGradeId,
				EJD.EmployeeGroupId,
				DEP.title AS EmployeeDepartment,
				EM.Number As Number,
				EJD.ProbationUptoDate,
				EJD.AhdocUptoDate,
				EJD.PermanentDate,
				EJD.DateOfResignation,
				CAST(ISNULL(EJD.DateOfleaving,'01-01-0001') as nvarchar(50)) As DateOfleaving,
				CAST(EM.IsOtherUser as int) As IsOtherUser,
				EM.EUId
	
   FROM 
				sHrm.tEmployeeMaster EM 
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
		   INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId 
		   LEFT JOIN sHrm.tEmployeeDesignationMaster DM	ON DM.Id  = EJD.EmployeeDesignationId
		   LEFT JOIN [sSetup].[tDepartmentMaster] DEP ON DEP.id=EJD.OrganizationDepartmentId
	WHERE 
			    EM.OrgId = @rOrgId
		   AND ((EM.Id = @rId) OR (@rId = 0))
		   AND ((EM.Code= @rCode) OR (@rCode = ''))
		   --AND ISNULL(EM.IsOtherUser,0) = 0 
END
GO
PRINT N'Altering Procedure [sLibrary].[pRptReaderBookListGet]...';


GO

ALTER PROCEDURE [sLibrary].[pRptReaderBookListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rReaderSourceTypeId smallint,
	 --@rReaderSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rFromLogDate date,
	 @rToLogDate date,
	 @rLibraryId int,
	 @rCode nvarchar(20) = ''  --added
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
If(@rReaderSourceTypeId=2003)
BEGIN
	SELECT 
	     
	        @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,
			BL.StatusId ,
			SM.Title AS Status,
			SA.Name,
			SA.RollNo,
			SA.Code,
			SA.ClassName,
			SA.DivisionName,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2
			
			
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005
			INNER JOIN sSetup.tBatchMaster B ON SA.BatchId = B.Id --AND B.IsActive = 1
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
		AND (SA.ClassId=@rClassId OR @rClassId=0)
		AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND (BL.StatusId=523) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		AND (SA.Code=@rCode OR @rCode='') --added
END
ELSE If(@rReaderSourceTypeId=95)
BEGIN
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BM.BookSubject,
			BL.LogDate,
			BL.DueDate,
			IS1.NoOfBookIssuable,			
			BL.StatusId,
			SM.Title AS Status,
			BL.IsCurrentStatus ,
			EM.FirstName+' '+EM.LastName AS Name,
			EM.Code,
			ODM.Title AS EmpDept,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2
	FROM 
			sLibrary.tBookLog BL
			LEFT JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId	
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId=2004
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
				WHERE 
			((BL.ReaderSourceTypeId=@rReaderSourceTypeId) OR (@rReaderSourceTypeId=0))
		--AND (BL.ReaderSourceId=@rReaderSourceId OR @rReaderSourceId=0)
		AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND (BL.StatusId=523)
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND (BL.LibraryId=@rLibraryId)
		AND  ISNULL(EM.IsOtherUser,0) = 0
END
END
GO
PRINT N'Altering Procedure [sPayroll].[pRptEmployeePaybillDetail]...';


GO
ALTER PROCEDURE [sPayroll].[pRptEmployeePaybillDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rDepartmentId int,
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0,
	 -- mantis 29994
	 @rBankName nvarchar(200)=''
	  
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END
	 
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1

	SET @rEmployeeCode = sCommon.fSearchStringGet(@rEmployeeCode)
    SET @rEmployeeName = sCommon.fSearchStringGet(@rEmployeeName)
	-- mantis-29994
	SET @rBankName = sCommon.fSearchStringGet(@rBankName)


	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		PPE.TotalEarning,
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		MM.Title AS MonthName,
		ISNULL(PPE.WorkingDays,0) AS WorkingDays,
		(ISNULL(PPE.WorkingDays,0) - ISNULL(PPE.Lwp,0)) AS PresentDays,
		--ISNULL(PPE.Lwp,0) AS AbsentDays,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		tEM.FirstName,
		tEm.LastName,
		ISNULL(ESO.AccountHolderName,'')AS AccountHolderName,
		tEM.Number,
		EM.EmployeeDesignation,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId

		
	FROM sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth	
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
	INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
where 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0) 
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
	  --mantis- 29994
	  AND ((ESO.BankName Like '%' + @rBankName  + '%') OR (@rBankName = ''))
END
GO
PRINT N'Altering Procedure [sPayroll].[pRptPFDetail]...';


GO
ALTER PROCEDURE [sPayroll].[pRptPFDetail]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rEmployeeId bigint,
	 @rEmployeeCode nvarchar(200),
	 @rEmployeeName nvarchar(200),
	 @rForMonth int,
	 @rForYear int,
	 @rPayrollId int,
	 @rPayrollGroupId int,
	 @rPayrollYearId int,
	 @rOrderByField nvarchar(20)='',
	 @rOrgId int = 0,
	 @rDepartmentId int = 0,
	 @rStatusId int = 0,
	 @rEmployeeGroupId int = 0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	IF(@rForMonth!=0 and @rForYear!=0)
	BEGIN
		SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
		SET @lLasteDate=DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))
	END

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

	--DECLARE @lConfigValue nvarchar(50) = ''
	--DECLARE @lIsOnPrePrinted bit = 0
	--DECLARE @lIsDisplayImageHeader bit=0

	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 469 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Blank')
	--BEGIN
	--SET @lIsOnPrePrinted = 1
	--SET @lIsDisplayImageHeader = 0
	--END
	--ELSE IF (@lConfigValue = 'Image')
	--BEGIN
	--SET @lIsOnPrePrinted = 0
	--SET @lIsDisplayImageHeader = 1
	--END

	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PFS.PfSalaryLimit,
		PFS.FpsSalaryLimit,
		PFS.EmployeePfPercent,
		PFS.EmployerPfPercent,
		PFS.EmployerFpsPercent,
		PFS.AdminChargesPercent,
		PFS.EdliPercent,
		PFS.InspectionChargesPercent,
		PFPro.PayProcessElementId,
		PFPro.EmployeePfAmount,
		PFPro.EmployerPfAmount,
		PFPro.EmployerFpsAmount,
		PFPro.AdminChargesAmount,
		PFPro.EdliChargesAmount,
		PFPro.InspectionChargesAmount,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS WorkingDays,
	   (SELECT ISNULL(SUM(PPE.Amount),0) FROM sPayroll.tPayProcessElement PPE INNER JOIN sPayroll.tPayElement P  
	    ON PPE.PayElementId =  P.ID  WHERE PPE.PayProcessEmployeeId = PE.PayProcessEmployeeId AND PayElementId IN 
		(SELECT DependentPayElementId FROM sPayroll.tPaySetupDependent PD INNER JOIN sPayroll.tPaySetup PS ON  PD.PaySetupId = PS.ID
		INNER JOIN sPayroll.tPayElement PE ON PS.PayElementId = PE.ID WHERE PS.PayrollId = @rPayrollId AND PS.PayrollYearId = @rPayrollYearId 
		AND PE.PayElementDefaultId = 56 AND ((PS.SourceTypeId=2020 AND ESO.PayrollGroupId=PS.SourceId) OR (PS.SourceTypeId=95 AND tEM.Id=PS.SourceId)))
		) 
		AS Salary,
	    ISNULL(ESO.UAN,'') AS UAN,
	    PPE.TotalEarning,
	    EM.FirstName,
		EM.LastName,
		tEM.Number,
		--@lIsOnPrePrinted AS IsOnPrePrinted,
		--@lIsDisplayImageHeader AS IsDisplayImageHeader,
		--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId

	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPfProcess PFPro ON PFPro.PayProcessElementId=PE.ID
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sPayroll.tPfSetup PFS ON PFS.PayrollYearId = PY.Id 
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		--INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.ForMonth=@rForMonth AND AT.ForYear =@rForYear
		--INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = 0) OR (0 = 0))  AND ((AT.ForYear = 0) OR (0 = 0)) 
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = @rForMonth) OR (@rForMonth = 0))  AND ((AT.ForYear = @rForYear) OR (@rForYear = 0)) 
		LEFT JOIN 
		(
		SELECT PE.Amount,PPE.WorkingDays,PPE.PayProcessId,PPE.EmployeeId, PPE.PayrollGroupId
		FROM sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.PayElementDefaultId = 1
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		) A ON A.PayProcessId = PPE.PayProcessId AND A.EmployeeId = PPE.EmployeeId  AND A.PayrollGroupId =  PPE.PayrollGroupId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '' OR ISNULL(@lFirstDate,'')='')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '' OR ISNULL(@lLasteDate,'')='')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering Procedure [sStudent].[pGetUploadBulkPhotoData]...';


GO


ALTER PROCEDURE [sStudent].[pGetUploadBulkPhotoData]
@rSourceTypeId int,
@rPageIndex int
 AS

 SET NOCOUNT ON
 BEGIN

	DECLARE @lPageSize int = 20	

	IF OBJECT_ID('tempdb..#tUploadBulkPhotoData') IS NOT NULL DROP TABLE #tUploadBulkPhotoData
	CREATE TABLE #tUploadBulkPhotoData
	(
		Id bigint identity,	
		SourceId Bigint,
		Code nvarchar(20),
		Name nvarchar(300),
		RollNo Int,
		Photo varbinary(max)
	)

	IF(@rSourceTypeId = 2003)

	BEGIN

	INSERT INTO #tUploadBulkPhotoData
	SELECT 
			SM.Id AS SourceId,
			SM.Code,
			(FirstName +' '+ MiddleName +' '+ LastName) AS Name, 
			SA.RollNo,
			SI.StudentPhoto AS Photo
			FROM [sStudent].[tStudentMaster] SM 
			
			INNER JOIN sStudent.tAcademic SA ON SM.Id=SA.StudentId 
			INNER Join sSetup.tBatchMaster BM ON SA.BatchId=BM.Id AND BM.IsActive=1 
			INNER JOIN [sSetup].[tDivisionMaster] AS DM ON DM.Id = SA.DivisionId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id			
			WHERE SA.DivisionId=DM.Id AND SM.StatusId = 1 

	END

	ELSE

		BEGIN
		INSERT INTO #tUploadBulkPhotoData
			SELECT 
			EM.Id AS SourceId,
			EM.Code,
			(FirstName +' '+ MiddleName +' '+ LastName) AS Name, 
			'' AS RollNo,
			EI.EmployeePhoto AS Photo  
			FROM sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId=EM.Id 
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EM.Id 
			INNER JOIN [sSetup].[tDivisionMaster] AS DM ON DM.Id = EJ.OrganizationDepartmentId
			WHERE EJ.OrganizationDepartmentId=DM.Id AND  ISNULL(EM.IsOtherUser,0) = 0 AND EM.StatusId = 7
		END
		Declare @lCount int = (Select Count(Id) from #tUploadBulkPhotoData)

		select SourceId,Code,RollNo,Name,Photo,@lCount As TotalRecords
		from #tUploadBulkPhotoData 
		where Id between ((@lPageSize * (@rPageindex-1)) + 1) and (@lPageSize * @rPageindex)
		
		drop table #tUploadBulkPhotoData
	END
GO
PRINT N'Altering Procedure [sWf].[pWfApprovalGet]...';


GO


ALTER  PROCEDURE [sWorkflow].[pApprovalRequestGet]
			@rWorkflowFunctionalityId bigint=0,
			 @rFromDate date=null,
			 @rToDate date=null,
			 @rStatusId int=0,
			 @rCode nvarchar(200) =''
			 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
		SELECT
			WFM.Title AS WorkFlowName,
			WFM.Id AS WorkFlowId,
			AR.Id AS ApprovalRequestId,
			AR.CreatedDateTime AS CreatedDateTime,
			AR.ParticipantSourceTypeId AS ParticipantSourceTypeId,
			--CASE WHEN ParticipantSourceTypeId= 1019 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 2015 THEN EM.Id END AS SourceId,
			--CASE WHEN ParticipantSourceTypeId= 1019 THEN SA.Code WHEN ParticipantSourceTypeId= 2015 THEN EM.Code END AS Code ,
			--CASE WHEN ParticipantSourceTypeId= 1019 THEN SA.Name WHEN ParticipantSourceTypeId= 2015 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.AcademicId WHEN ParticipantSourceTypeId= 95 THEN EM.Id END AS SourceId,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.Remark AS Remark,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(case isnull(asm.title,'') when '' then 'Pending' else asm.title end) as status,
			AR.ParticipantSourceId
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id 
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId
		WHERE ((WFM.Id = @rWorkflowFunctionalityId) OR (@rWorkflowFunctionalityId =0)) 
			AND (( Convert(Date,AR.CreatedDateTime) >= Convert(Date,@rFromDate)) OR (ISNULL(Convert(Date,@rFromDate),'') = '')) -- Converted datatype to date for mantis : 30038
			AND (( Convert(Date,AR.CreatedDateTime) <=  Convert(Date,@rToDate)) OR (ISNULL(Convert(Date,@rToDate),'') = '')) -- Converted datatype to date for mantis : 30038
			AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
			AND (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode ='')))
			AND ISNULL(EM.IsOtherUser,0) = 0 
END
GO
PRINT N'Altering Procedure [sHrm].[pImportEmployee]...';


GO

ALTER PROCEDURE [sHrm].[pImportEmployee]
	
	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rUserId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
--BEGIN TRY

DECLARE @lCount INT, @lECount BigInt
DECLARE @lInterrorCode INT,
    
			@intDoc INT,
			@lCode nvarchar(20),
			@lShortName nvarchar(50),
			@lFirstName Nvarchar(100),
			@lMiddleName Nvarchar(100),
			@lLastName Nvarchar(100),
			@lGenderId int = 0,
			@lGender nvarchar(10),
			@lEmployeeTypeId int = 0,
			@lEmployeeType nvarchar(100),
			@lEmployeeGroupId int,
			@lEmployeeGroup nvarchar(100),
			@lEmployeeGradeId int,
			@lEmployeeGrade nvarchar(100),
			@lDepartmentId int,
			@lDepartment nvarchar(100),
			@lDesignationId int,
			@lDesignation nvarchar(100),
			@lQualification nvarchar(150),
			@lDOB DATETIME,
			@lDOJ DATETIME,
			@lReligionId int,
			@lReligion nvarchar(100),
			
			@lCastCategoryId int,
			@lCastCategory nvarchar(50),
				
			@lCompanyPhoneNo Nvarchar(50),
			@lExtentionNo Nvarchar(10),
			@lCompanyEmailId Nvarchar(100),
			@lPersonalEmailId Nvarchar(100),
			@lMobileNo Nvarchar(20),
			@lPresentStreetOne nvarchar(50),
			@lPresentStreetTwo nvarchar(50),
			@lPresentStreetThree nvarchar(50),
			@lPresentCity nvarchar(50),
			@lPresentZipCode nvarchar(20),
			@lPresentState nvarchar(50),
			@lPresentCountry nvarchar(50),
			@lPresentContactNo nvarchar(20),
			@lFamilyCast nvarchar(150),
			@lAccountNumber nvarchar(150),
			@lBankName nvarchar(150),
			@lBranch nvarchar(150),
			@lEPFNumber nvarchar(150),
			@lPanNumber nvarchar(150),
			@OutDesignationId int,
			@lAdhaarNumber nvarchar(20),
			@lNumber bigint = '',
			@lProbationUptoDate DATE,
			@lAhdocUptoDate DATE,
			@lPermanentDate DATE,
			@lDateOfResignation DATE,
			@lWhatsAppContactNo nvarchar(20),
			@lTribeId int = 0,
			@lTribe nvarchar(100),
			@lBloodGroupId TINYINT,
			@lBloodGroup nvarchar(100),
			@lMaritalStatusId TINYINT,
			@lMaritalStatus nvarchar(100)

DECLARE @OutEmployeeId bigint		
			
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

 
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		Code nvarchar(20),
		ShortName nvarchar(50),
		FirstName Nvarchar(100),
		MiddleName Nvarchar(100) null,
		LastName Nvarchar(100),
		GenderId int null,
		Gender nvarchar(10),
		EmployeeTypeId int null,
		EmployeeType nvarchar(100),
		EmployeeGroupId int null,
		EmployeeGroup nvarchar(100),
		EmployeeGradeId int null,
		EmployeeGrade nvarchar(100),
		DepartmentId int null,
		Department nvarchar(100),
		DesignationId int null,
		Designation nvarchar(100),
		Qualification nvarchar(150),	 
		DOB date,
		DOJ date,
		ReligionId int,
		Religion nvarchar(100),
		CastCategoryId int,
		CastCategory nvarchar(50),
		CompanyPhoneNo nvarchar(50) null,
		ExtentionNo nvarchar(10) null,
		CompanyEmailId nvarchar(100) null,
		PersonalEmailId nvarchar(100) null,
		MobileNo nvarchar(20) null,
		PresentStreetOne nvarchar(50),
		PresentStreetTwo nvarchar(50),
		PresentStreetThree nvarchar(50),
		PresentCity nvarchar(50),
		PresentZipCode nvarchar(20),
		PresentState nvarchar(50),
		PresentCountry nvarchar(50),
		PresentContactNo nvarchar(20),
		FamilyCast nvarchar(150),
		AccountNumber nvarchar(150),
		BankName nvarchar(150),
		Branch nvarchar(150),
		EPFNumber nvarchar(150),
		PanNumber nvarchar(150),
		CreatedUserId bigint null,
		AdhaarNumber nvarchar(20),
		Number bigint null,
		ProbationUptoDate date,
		AhdocUptoDate date,
		PermanentDate date,
		DateOfResignation date,
		WhatsAppContactNo nvarchar(20),
		TribeId int null,
		Tribe nvarchar(100),
		BloodGroupId TINYINT,
		BloodGroup nvarchar(100),
		MaritalStatusId TINYINT,
		MaritalStatus nvarchar(100)
	)
		
	INSERT INTO #tTable
	(
		Code,
		ShortName,
		FirstName,
		MiddleName,
		LastName,
		GenderId,
		Gender,
		EmployeeTypeId,
		EmployeeType,
		EmployeeGroupId,
		EmployeeGroup,
		EmployeeGradeId,
		EmployeeGrade,
		DepartmentId,
		Department,
		DesignationId,
		Designation,
		Qualification,	 
		DOB,
		DOJ,
		ReligionId,
		Religion,
		CastCategoryId,
		CastCategory,
		CompanyPhoneNo,
		ExtentionNo,
		CompanyEmailId,
		PersonalEmailId,
		MobileNo,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		FamilyCast,
		AccountNumber,
		BankName,
		Branch,
		EPFNumber,
		PanNumber,		
		CreatedUserId,
		AdhaarNumber,
		Number,
		ProbationUptoDate,
		AhdocUptoDate,
		PermanentDate,
		DateOfResignation,
		WhatsAppContactNo,
		TribeId,
		Tribe,
		BloodGroupId,
		BloodGroup,
		MaritalStatusId,
		MaritalStatus
	)
	SELECT
		Code,
		ShortName,
		FirstName,
		MiddleName,
		LastName,
		0,
		Gender,
		0,
		EmployeeType,
		0,
		EmployeeGroup,
		0,
		EmployeeGrade,
		0,
		Department,
		0,
		Designation,
		Qualification,	 
		DOB,
		DOJ,
		0,
		Religion,
		0,
		CastCategory,
		CompanyPhoneNo,
		ExtentionNo,
		CompanyEmailId,
		PersonalEmailId,
		MobileNo,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		FamilyCast,
		AccountNumber,
		BankName,
		Branch,
		EPFNumber,
		PanNumber,	
		CreatedUserId,
		AdhaarNumber,
		Number,
		ProbationUptoDate,
		AhdocUptoDate,
		PermanentDate,
		DateOfResignation,
		WhatsAppContactNo,
		0,
		Tribe,
		0,
		BloodGroup,
		0,
		MaritalStatus

	FROM OPENXML (@intDoc, '/Table/ImportEmployee', 1)
	WITH
	( 
		Code nvarchar(20) '@Code',
		ShortName nvarchar(50) '@ShortName',
		FirstName Nvarchar(100) '@FirstName',
		MiddleName Nvarchar(100) '@MiddleName',
		LastName Nvarchar(100) '@LastName',  			
		Gender nvarchar(10) '@Gender', 			
		EmployeeType nvarchar(100) '@EmployeeType',		
		EmployeeGroup nvarchar(100) '@EmployeeGroup',
		EmployeeGrade nvarchar(100) '@EmployeeGrade',	
		Department nvarchar(100) '@Department', 			
		Designation nvarchar(100) '@Designation',	 		
		Qualification nvarchar(150) '@Qualification',	 			
		DOB nvarchar(15) '@DOB', 			
		DOJ nvarchar(15) '@DOJ',	 			
		Religion nvarchar(100) '@Religion',
		CastCategory nvarchar(50) '@CastCategory',
		CompanyPhoneNo nvarchar(50) '@CompanyPhoneNo',
		ExtentionNo nvarchar(10) '@ExtentionNo', 	
		CompanyEmailId nvarchar(100) '@CompanyEmailId',
		PersonalEmailId nvarchar(100) '@PersonalEmailId',
		MobileNo nvarchar(20) '@MobileNo',
		PresentStreetOne nvarchar(50) '@PresentStreetOne',
		PresentStreetTwo nvarchar(50) '@PresentStreetTwo',
		PresentStreetThree nvarchar(50) '@PresentStreetThree',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		PresentState nvarchar(50) '@PresentState',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentContactNo nvarchar(20) '@PresentContactNo',		
		CreatedUserId bigint '@CreatedUserId',
		FamilyCast nvarchar(150) '@FamilyCast',
		AccountNumber nvarchar(150) '@AccountNumber',
		BankName nvarchar(150) '@BankName',
		Branch nvarchar(150) '@Branch',
		EPFNumber nvarchar(150) '@EPFNumber',
		PanNumber nvarchar(150) '@PanNumber',
		AdhaarNumber nvarchar(20) '@AdhaarNumber',
		Number bigint '@Number',
		ProbationUptoDate nvarchar(15) '@ProbationUptoDate',
		AhdocUptoDate nvarchar(15) '@AhdocUptoDate',
		PermanentDate nvarchar(15) '@PermanentDate',
		DateOfResignation nvarchar(15) '@DateOfResignation',
		WhatsAppContactNo nvarchar(20) '@WhatsAppContactNo',
		Tribe nvarchar(100) '@Tribe',
		BloodGroup nvarchar(100) '@BloodGroup',
		MaritalStatus nvarchar(100) '@MaritalStatus'
	)
	

EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable
SELECT Top 1 @lECount = Id FROM #tTable order by Id -- MantisId : 0029269
WHILE @lCount >= @lECount

BEGIN
		SET	@lCode = ''	
		SET @lShortName = ''
		SET @lFirstName = ''
		SET @lMiddleName = ''
		SET @lLastName = ''	
		SET	@lGenderId = 0
		SET	@lGender = ''
		SET	@lEmployeeTypeId = 0
		SET	@lEmployeeType = ''
		SET	@lEmployeeGroupId = null
		SET	@lEmployeeGroup = ''
		SET	@lEmployeeGradeId = null
		SET	@lEmployeeGrade = ''
		SET	@lDepartmentId = null
		SET	@lDesignationId = null
		SET	@lDepartment = ''
		SET	@lDesignation = ''
		SET @lQualification = ''	
		SET	@lDOB = null
		SET	@lDOJ = null
		SET @lReligionId = null
		SET @lReligion = ''
		SET @lCastCategoryId = NULL
		SET @lCastCategory =''
		SET	@lCompanyPhoneNo = null
		SET	@lExtentionNo = null
		SET	@lCompanyEmailId = null
		SET	@lPersonalEmailId = null
		SET	@lMobileNo = null
		SET @OutEmployeeId = null
		SET @lPresentStreetOne = ''
		SET @lPresentStreetTwo = ''
		SET @lPresentStreetThree = ''
		SET @lPresentCity = ''
		SET @lPresentZipCode = ''
		SET @lPresentState = ''
		SET @lPresentCountry = ''
		SET @lPresentContactNo = ''
		SET	@lFamilyCast = ''
		SET	@lAccountNumber = ''
		SET	@lBankName = ''
		SET	@lBranch = ''
		SET	@lEPFNumber = ''
		SET	@lPanNumber = ''
		SET @lAdhaarNumber=''
		SET @lNumber = null
		SET @lProbationUptoDate = null
		SET @lAhdocUptoDate = null
		SET @lPermanentDate = null
		SET @lDateOfResignation = null
		SET @lWhatsAppContactNo = ''
		SET	@lTribeId = 0
		SET	@lTribe = ''
		SET @lBloodGroupId = 0
		SET	@lBloodGroup = ''
		SET	@lMaritalStatusId = 0
		SET	@lMaritalStatus = ''
SELECT		
		@lCode = Code,
		@lShortName = ShortName,
		@lFirstName = FirstName,
		@lMiddleName = MiddleName,
		@lLastName = LastName,	
		@lGender = Gender,
		@lEmployeeType = EmployeeType,	
	    @lEmployeeGroup = EmployeeGroup,
	    @lEmployeeGrade = EmployeeGrade,
		@lDepartment = Department,
		@lDesignation= Designation,	
		@lQualification = Qualification,	
		@lDOB = CASE			
		WHEN DOB = '' THEN  '01/01/1900'
		ELSE DOB  
		--CONVERT(datetime, DOB, 103)
		END,		
		@lDOJ = CASE	
		WHEN DOJ = '' THEN  sCommon.fGetDate()
		ELSE DOJ 
		END,			
		--@lDOB = convert(datetime, DOB, 103),
		--@lDOJ = convert(datetime, DOJ, 103),
		@lReligion = Religion,
		@lCastCategory = CastCategory,
	    @lCompanyPhoneNo = CompanyPhoneNo,
	    @lExtentionNo = ExtentionNo,
	    @lCompanyEmailId = CompanyEmailId,
		@lPersonalEmailId = PersonalEmailId,
		@lMobileNo = MobileNo,
		@lPresentStreetOne = PresentStreetOne,
		@lPresentStreetTwo = PresentStreetTwo,
		@lPresentStreetThree = PresentStreetThree,
		@lPresentCountry = PresentCountry,
		@lPresentState = PresentState,
		@lPresentCity = PresentCity,
		@lPresentZipCode = PresentZipCode,
		@lPresentContactNo = PresentContactNo,
		@lFamilyCast = FamilyCast,
		@lAccountNumber = AccountNumber,
		@lBankName = BankName,
		@lBranch = Branch,
		@lEPFNumber = EPFNumber,
		@lPanNumber = PanNumber,
		@lAdhaarNumber =AdhaarNumber,
		--@lNumber = CASE WHEN Number = 0 THEN  null ELSE Number  END
		@lNumber = Number,
		@lProbationUptoDate = CASE 
		WHEN ProbationUptoDate = '01-01-1900' THEN null
		ELSE ProbationUptoDate END,
		@lAhdocUptoDate = CASE
		WHEN AhdocUptoDate = '01-01-1900' THEN null
		ELSE AhdocUptoDate END,
		@lPermanentDate = CASE
		WHEN PermanentDate = '01-01-1900' THEN null
		ELSE PermanentDate END,
		@lDateOfResignation = CASE
		WHEN DateOfResignation = '01-01-1900' THEN null
		ELSE DateOfResignation END,
		@lWhatsAppContactNo = WhatsAppContactNo,
		@lTribe = Tribe,
		@lBloodGroup = BloodGroup,
		@lMaritalStatus = MaritalStatus
											 	 
FROM #tTable WHERE Id = @lECount  


select * from #tTable

	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lEmployeeTypeId = ID FROM sHrm.tEmployeeTypeMaster WHERE Title = @lEmployeeType AND OrgId = @rOrgId
	SELECT	@lEmployeeGroupId  = ID FROM sHrm.tEmployeeGroupMaster WHERE Title = @lEmployeeGroup
	SELECT	@lEmployeeGradeId  = ID FROM sHrm.tEmployeeGradeMaster WHERE Title = @lEmployeeGrade AND OrgId = @rOrgId
	SELECT	@lDepartmentId  = ID FROM sSetup.tDepartmentMaster WHERE Title = @lDepartment AND OrgId = @rOrgId
	SELECT	@lDesignationId  = ID FROM sHrm.tEmployeeDesignationMaster WHERE Title = @lDesignation AND OrgId = @rOrgId
	SELECT	@lReligionId  = ID FROM sCommon.tReligionMaster WHERE Title = @lReligion AND OrgGroupId = @rOrgGroupId
	SELECT	@lCastCategoryId  = ID FROM sCommon.tCastCategoryMaster WHERE Title = @lCastCategory AND OrgGroupId = @rOrgGroupId
	SELECT	@lTribeId = ID FROM sCommon.tTribeMaster WHERE Title = @lTribe
	SELECT	@lBloodGroupId = ID FROM sCommon.tBloodGroupMaster WHERE Title = @lBloodGroup
	SELECT	@lMaritalStatusId = ID FROM sCommon.tMaritalStatusMaster WHERE Title = @lMaritalStatus

	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
	IF(@lEmployeeGroupId IS NULL)
		SET @lEmployeeGroupId = 0
	IF(@lEmployeeGradeId IS NULL)
		SET @lEmployeeGradeId = 0
	IF(@lTribeId IS NULL)
		SET @lTribeId = 0
	IF(@lBloodGroupId IS NULL)
		SET @lBloodGroupId = 0
	IF(@lMaritalStatusId IS NULL)
		SET @lMaritalStatusId = 0
 --BEGIN TRANSACTION
    --Default Group Id = 1
--IF 	@lDepartmentId IS NULL  AND @lDepartment != ''
--BEGIN
--DECLARE @1DepartmentGroupId  int 
-- SET @1DepartmentGroupId = sCommon.fGetIntIdForOrg(1,@rOrgId) 
-- EXEC [sCommon].[pOrganizationDepartmentMasterAdd] @rOrgId,@lDepartment,@lDepartment,0,@rUserId,@OutDepartmentId OUTPUT
--END
--ELSE
--SET @OutDepartmentId = @lDepartmentId

--IF 	@lEmployeeGradeId IS NULL  AND @lEmployeeGrade != ''
--BEGIN
--DECLARE @1EmployeeGradeGroupId  int 
-- EXEC [sHrm].[pEmployeeGradeMasterAdd] @rOrgId,@lEmployeeGrade,@lEmployeeGrade,0,@rUserId,@OutEmployeeGradeId OUTPUT
--END
--ELSE
--SET @OutEmployeeGradeId = @lEmployeeGradeId

IF 	@lDesignationId IS NULL  AND @lDesignation != ''
BEGIN
 EXEC [sHrm].[pEmployeeDesignationMasterAdd] @rOrgId,@lDesignation,@lDesignation,0,@rUserId,@OutDesignationId = @OutDesignationId OUTPUT
END
ELSE
SET @OutDesignationId = @lDesignationId

--UPDATE #tTable SET
--		GenderId = @lGenderId ,
--		EmpTypeId = @lEmpTypeId,
--		DepartmentId = @OutDepartmentId,
--		DesignationId = @lDesignationId,
--		ContractorId = @OutContractorId,
--		BloodGroupId = @lBloodGroupId WHERE Id = @lCount
  
EXEC [sHrm].[pEmployeeMasterAdd] @rOrgId,@lCode,@lFirstName,@lMiddleName,@lLastName,@lEmployeeTypeId,
@lDepartmentId,@lDOB,@lDOJ,@lGenderId,@lReligionId,7,0,@rUserId,@OutEmployeeId OUTPUT,
@lDesignationId,@lBloodGroupId,@lQualification,@lEmployeeGradeId,@lEmployeeGroupId,@lShortName,0,@lFamilyCast,@lCastCategoryId,@lNumber
,@lProbationUptoDate,@lAhdocUptoDate,@lPermanentDate,0,@lDateOfResignation,NULL,@lTribeId,@lAdhaarNumber,@lMaritalStatusId
 
EXEC [sHrm].[pEmployeeCommunicationsAdd] @OutEmployeeId,@lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetThree,
@lPresentCountry,@lPresentState,@lPresentCity,@lPresentZipCode,@lPresentContactNo,NULL,Null,Null,NULL,NULL,NULL,NULL,Null,
Null,NULL,NULL,NULL,NULL,NULL,NULL,NULL,@lCompanyPhoneNo,@lExtentionNo,@lCompanyEmailId,@lPersonalEmailId,@lMobileNo,@rUserId,@lWhatsAppContactNo
		
EXEC [sHrm].[pEmployeeStatutoryDetailAdd] @OutEmployeeId,@lAccountNumber,@lBankName,@lBranch,@lEPFNumber,@lPanNumber,
 0,NULL,NULL,0,0,NULL,NULL,NULL,@rUserId,NULL,0,NULL,NULL,NULL,NULL,NULL,NULL					

		SET @lECount = @lECount + 1	
		--COMMIT TRANSACTION	
END
		SELECT 1 Result		
	--END TRY
	--BEGIN CATCH
	
	--SELECT ERROR_MESSAGE(), ERROR_LINE()
	--END CATCH
	
END
GO
PRINT N'Altering Procedure [sAppraisal].[pConductAdd]...';


GO

ALTER PROCEDURE [sAppraisal].[pConductAdd]
	    @rId BIGINT,
		@rConductDate DATETIME,
		@rEmployeeId BIGINT,
		@rConductTypeId INT,
		@rBatchId int,
		@rTitle nvarchar(100),
		@rRemark nvarchar(400),
		@rOrgId SmallINT,
		@rOrgGroupId SmallINT,
		@rCreatedUserId BIGINT		       
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		--IF(@rId = 0)	
		--	BEGIN
		--		IF Exists(SELECT Id FROM [sAppraisal].[tConductTypeMaster]  WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId )
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END 
		--	END
		
		--ELSE
		--	BEGIN
		--		IF  Exists(SELECT Id FROM [sAppraisal].[tConductTypeMaster]  WHERE Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id<>@rId )
		--			BEGIN
		--				SELECT -102 as Result
		--				RETURN
		--			END
		--	END
	
		BEGIN TRANSACTION	
		DECLARE @lNextNumber BIGINT 
	
		IF(@rId = 0)	
			BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAppraisal.tConduct', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO [sAppraisal].[tConduct]
				(
					Id,
					ConductDate,
					EmployeeId,
					ConductTypeId,
					Title,
					Remark,
					BatchId,
					CreatedUserId,
					CreatedDateTime
					
				)
				VALUES
				(
					@lNextNumber,
					@rConductDate,
					@rEmployeeId,
					@rConductTypeId,
					@rTitle,
					@rRemark,
					@rBatchId,
					@rCreatedUserId,
					sCommon.fGetDate()
					
				)
				SELECT 1 AS Result
			END	 
		ELSE
			BEGIN
			SET @lNextNumber = @rId
				UPDATE  [sAppraisal].[tConduct]
				SET
					Title=@rTitle,
					Remark=@rRemark,
					ConductDate=@rConductDate, 
					ConductTypeId = @rConductTypeId -- Added field ConductTypeId for mantis 30032 
					
				WHERE Id = @rId
				SELECT 11 AS Result
			END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptStudentGradeAnalysisSubjectWise]...';


GO
ALTER PROCEDURE [sAssessment].[pRptStudentGradeAnalysisSubjectWise]
	 
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rClassStatusId int=0,
	 @rGroupId int=0

	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
   SELECT 
		COUNT(RD.id),
		@rBuilder1 AS Builder1,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		CS.IsOptional ,
		DM.Id AS DivisionId,
		Dm.DisplayTitle as DivisionName,
		Cm.Id AS ClassId,
		CM.DisplayTitle AS ClassName,
		ISNULL(GD.MarkRange,'') AS MarkRange,
		SM.OrderIndex AS SubjectOrderIndex,
		GM.Title AS Gender,
		GM.Id AS GenderId,
		GD.GradeSetId,
		GD.Minimumscore,

		CASE WHEN @rGroupId=1 THEN DM.Id
				WHEN @rGroupId=2 THEN CM.Id END AS GroupId,
				
		CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle END AS GroupName,
				
		CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex END AS OrderIndex,
				
		CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class' END AS GroupTitle,
		@rBatchId AS BatchId,
		SUM(CASE WHEN RD.IsPresent = 1 THEN 0 ELSE 1 END) AS AbsentCount    --Mantis 30006
				
  FROM 
		sAssessment.tResultDetail  RD
		Inner join sAssessment.tResult R ON R.Id=Rd.ResultId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId 	
		INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId 	
		INNER JOIN sCommon.tGenderMaster GM ON GM.Id=SO.GenderId
		LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode		
   WHERE 
	    EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		AND (ISNULL(Cm.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
	    and((STM.StatusId=@rStatusId) or (@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
   GROUP BY 
		RD.SubjectGrade,GD.MarkRange,SM.Title,CS.IsOptional ,DM.Id,DM.DisplayTitle,CM.Id,CM.DisplayTitle,SM.OrderIndex,GM.Title,GM.Id,GD.GradeSetId,GD.Minimumscore
		,Dm.OrderIndex,Cm.OrderIndex
END
GO
PRINT N'Altering Procedure [sAssessment].[pStudentExamNameGet]...';


GO
ALTER PROCEDURE [sAssessment].[pStudentExamNameGet]
 
	@rAcademicId bigint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lClassId int = 0
	DECLARE @lBatchId int = 0
	SELECT @lClassId = ClassId, @lBatchId = BatchId FROM sStudent.tAcademic WHERE Id=@rAcademicId
BEGIN 
	SELECT
	E.Id AS ExamId,
	ESGM.Title AS ExamName
	FROM 
	sAssessment.tExamMaster E
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
	WHERE 
	E.ClassId = @lClassId AND E.BatchId = @lBatchId AND ISNULL(E.IsPublishExamSchedule,0) = 1
	ORDER BY 
	--ESGM.OrderIndex comment for MantisID: 0029788
	E.UpdatedDateTime desc
END
GO
PRINT N'Altering Procedure [sAttendance].[pRptStudentMonthlyRegisterGet]...';


GO
ALTER PROCEDURE [sAttendance].[pRptStudentMonthlyRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint=0,
	 @rSubjectId int=0,
	 @rForYear smallint,
	 @rForMonth tinyint,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int,
	 @rFromAverage decimal=0,
	 @rToAverage decimal=0,
	 @rIsDetail bit=0,
	 @rReportId int = 0,
	 @rStatus smallint = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	IF((@rReportId <> 10132) AND (@rReportId <> 10131))     --Mantis 30087
	BEGIN
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			MR.ForMonth,
			MR.ForYear,
			M.Code +' - '+Convert(nvarchar(4),MR.ForYear) AS ForMonthYear,
			MR.TotalCount,
			ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
			MR.PresentCount,
			MR.AbsentCount,
			MR.AveragePresence,
			MR.AbsentDays,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SM.Title AS SubjectName,
			SA.DivisionOrder
			
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
		INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SA.AcademicId
		LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=MR.SubjectId
		INNER JOIN sCommon.tMonthMaster M ON MR.ForMonth = M.Id
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((MR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
		AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
		AND (SA.StatusId != 3)
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((MR.AveragePresence >= @rFromAverage) OR (@rFromAverage=0))
		AND ((MR.AveragePresence <= @rToAverage) OR (@rToAverage=0))
	END
	ELSE 
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			MR.ForMonth,
			MR.ForYear,
			M.Code +' - '+Convert(nvarchar(4),MR.ForYear) AS ForMonthYear,
			MR.TotalCount,
			ISNULL(MR.AttendanceCount,0) AS AttendanceCount,
			MR.PresentCount,
			MR.AbsentCount,
			MR.AveragePresence,
			MR.AbsentDays,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SM.Title AS SubjectName,
			SA.DivisionOrder
			
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
		INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SA.AcademicId
		LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id=MR.SubjectId
		INNER JOIN sCommon.tMonthMaster M ON MR.ForMonth = M.Id
		INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((MR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((MR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((MR.ForYear=@rForYear) OR (@rForYear=0))
		AND ((MR.ForMonth=@rForMonth) OR (@rForMonth=0))
		AND ((SA.StatusId = @rStatus) OR (@rStatus = 0))
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND ((MR.AveragePresence >= @rFromAverage) OR (@rFromAverage=0))
		AND ((MR.AveragePresence <= @rToAverage) OR (@rToAverage=0))
	END
END
GO
PRINT N'Altering Procedure [sCertificate].[pRptLeavingCertificateGet]...';


GO
ALTER PROCEDURE [sCertificate].[pRptLeavingCertificateGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId int,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rLCNumber nvarchar(20)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromDate date='',
     @rToDate date='',
     @rCode nvarchar(20)='',
     @rName nvarchar(20)='',
	 @rUserName nvarchar(100)=''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lIsOnPrePrinted bit = 0,@lIsDisplayReligion bit=0,@lConfigValue nvarchar(50),@lIsDisplayImageHeader bit = 0,@lOrgId smallint

DECLARE @lSchoolRemark1  nvarchar(500)
DECLARE @lSchoolRemark2  nvarchar(500)
DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0

Select @lOrgGroupId = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId


SELECT @lOrgId=RG.OrgId,
@lSchoolRemark1 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark1,'')  ELSE RG.SchoolRemark1 END,
@lSchoolRemark2= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark2,'')  ELSE RG.SchoolRemark2 END,
@lSchoolRemark3 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark3,'')  ELSE RG.SchoolRemark3 END,
@lSchoolRequiredSignature= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRequiredSignature,'')  ELSE RG.SchoolRequiredSignature END 
 
FROM sCommon.tReportRemarkGroupMaster RGM LEFT JOIN sCommon.tReportRemarkGroupOrg RG ON RGM.Id = RG.ReportRemarkGroupId AND RG.OrgId = @rOrgId AND RG.ReportRemarkGroupId=3 WHERE RGM.Id=3
 
--WHERE  RG.OrgId=@rOrgId AND RG.ReportRemarkGroupId=3

--IF(@lOrgId IS NULL)
--BEGIN
--SELECT @lSchoolRemark1=DefaultRemark1,@lSchoolRemark2=DefaultRemark2,@lSchoolRemark3=DefaultRemark3,@lSchoolRequiredSignature=DefaultRequiredSignature FROM sCommon.tReportRemarkGroupMaster WHERE Id=3
--END


SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 178 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 157 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsDisplayReligion = 0
	ELSE
	SET @lIsDisplayReligion = 1
	
	
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	

	--add for 27638 mantis start
	DECLARE @lIsShowPhoto bit = 0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 124 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsShowPhoto = 0
	ELSE
	SET @lIsShowPhoto = 1
	--add for 27638 mantis end
	
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--MR.PresentCount AS PresentDays ,
			--MR.TotalCount AS TotalDays ,
			L.Id,
			--(SELECT SUM(MR.PresentCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS PresentDaysSum ,
			--(SELECT SUM(MR.TotalCount) FROM sAttendance.tMonthlyRegister MR WHERE MR.AcademicId=A.Id) AS TotalDaysSum ,
			SM.Code,
			L.AcademicId,
			SM.FirstName,SM.MiddleName,SM.LastName,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			ISNULL(SF.FatherName,'') As FatherName,
			ISNULL(SF.MotherName,'') As MotherName,
			ISNULL(CTM.Nationality,'') AS Nationality,
			--0 As CastCategoryId,
			--ISNULL(SO.CastCategoryId,0) As CastCategoryId,
			ISNULL(RM.Title,'') AS Religion,
			ISNULL(so.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SO.BirthDistrict,'') AS BirthDistrict,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS BirthDateInWord,
			SA.PreviousSchool,
			SA.AdmissionDate,
			L.LCNumber,
			L.LeftDate,
			L.LCReason,
			L.LCProgress,
			L.LCConduct,
			L.LCRemark,
			L.LCDate,
			L.LCBookNumber,
			SO.GenderId,
			
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(SC.PresentState,'') AS CityState,
			CM.DisplayTitle AS AdmissionStandard,
			CMS.DisplayTitle AS CurrentStandard,
			CMS.Title AS CurrentStandardTitle,
			--'' AS CurrentStandardInWords,
			SM.StatusId,
			L.LastExamName AS Result,
			L.LastExamResult AS FailOrPass,
			L.SubjectStudied AS SubjectNAme,
			L.RepeatDetail as PromotedorNot,
			--ISNULL(SubM.Title,'') AS SubjectNAme,
			--'' AS PromotedorNot,
			ISNULL(L.PromoteToClass,'')  AS PromotedToClass,
			L.FeeDetail AS LastFeesPaid,
			L.FeeConcessionDetail AS AnyConcession,
			L.NCCScoutDetail  AS NCCScoutDetail,
			L.ExtraCurricularActivities AS GamesPlayed,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			vSA.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayReligion AS IsDisplayReligion,
			AD.PresentDaysAnnual AS PresentDaysSum,
			AD.TotalDaysAnnual AS TotalDaysSum,
			vSA.ClassName AS ClassName,
			vSA.DivisionName AS DivisionName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			isnull(MainCastCategoryId,0) AS CastCategoryId,
			ISNULL(L.ToCollege,'') AS ToCollege ,
			ISNULL(L.ToCollegeAddress,'')AS ToCollegeAddress,
			ISNULL(OM.University,'')AS University,
			@lSchoolRemark1 AS SchoolRemark1 ,
			@lSchoolRemark2 AS SchoolRemark2 ,
			@lSchoolRemark3 AS SchoolRemark3 ,
			@lSchoolRequiredSignature AS SchoolRequiredSignature,
			ISNULL(CMS.ClassNameInWord,'')AS CurrentStandardInWords,
			SO.MotherTongue,
			SO.AdhaarNumber,
			vSA.SUId,
			CASE WHEN isnull(BM.FromDate,'')>Isnull(SA.AdmissionDate,'') THEN BM.FromDate ELSE SA.AdmissionDate END AS BatchDate,
			SO.BirthState,
			SO.BirthCountry,
			SD.BankAccountNumber,
			SO.UIDNumber,
			SD.BankName,
			SD.BankIFSCCode,
			SA.PreviousStandard 
			,L.TermsInInstitute,
			@lIDConfigValue AS ItemValue 
			,L.LCCopy
			,DM.InchargeEmployeeId AS ClassTeacher
			,vSA.BatchName AS BatchName,
			CSM.Title As CasteCategory,
			ISNULL(SA.AdmissionNumber,'') AS AdmissionNumber,
			SI.StudentPhoto,
			SA.AdmissionFormNumber,
			BM.FromDate as BatchStartDate,
			BM.ToDate as BatchEndDate,
			SO.UIDNumber,
			SC.PresentStreetOne AS Address1,
			SC.PresentStreetTwo AS Address2,
			SC.PresentStreetThree AS Address3,
			SC.PresentCity AS PresentCity,
			SC.PresentZipCode AS PresentZipCode,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			OM.ReportOrgTitle,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			L.TotalDays,
			L.PresentDays,
			ISNULL(CMS.ClassNameInWord,'') AS ClassNameInWord,
			vSA.ClassId AS ClassId,
		--sFinanceCommon.fNumberToWords(ISNULL(CM.ClassGroupId,0),'',OM.OrgGroupId) AS CurrentStandardInWords
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.PresentCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.PresentCount,0))
		--END AS Presentdays,
		--CASE WHEN @rIsTransferCerti=1
		--THEN ISNULL(MR.TotalCount,0)
		--WHEN @rIsTransferCerti=0
		--THEN SUM(ISNULL(MR.TotalCount,0))
		--END AS TotalCount
		@rUserName AS UserName,
		EI.EmployeeSign,
		EI1.EmployeeSign AS DivisionInchargeEmployeeSign,
		ISNULL(L.ProofOfDOB,'')AS ProofOfDOB,
		U.LoginTitle AS CreatedUserName,
		OM.PrincipalSignature,
		CM.ClassNameInWord AS AdmissionStandardInWord,
		LM.Title AS LanguageTitle,
		@lIsShowPhoto AS IsShowPhoto,		--add for 27638 mantis start
		CAST((CASE WHEN SI.QRCode IS NULL THEN 0 ELSE 1 END) AS bit) AS IsDisplayQRCode,
		ISNULL(SI.QRCode,'') AS QRCode		--add for 27638 mantis end 
		,ISNULL(L.LCCopyRemark,'') AS LCCopyRemark    --add for 28079 mantis end 
		,SH.IdentificationMark1 AS IdentificationMark1
		                                    
	FROM 
			sCertificate.tLeaving L
			INNER JOIN sStudent.vStudentAcademic vSA ON vSA.AcademicId=L.AcademicId
			--INNER JOIN sStudent.tAcademic A ON L.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=vSA.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=vSA.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId 
			INNER JOIN sSecurity.tUser U ON U.Id = L.CreatedUserId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=vSA.StudentId 
			LEFT JOIN sCommon.tReligionMaster RM ON SO.ReligionId=RM.Id
			--LEFT JOIN  sAttendance.tMonthlyRegister MR ON MR.AcademicId=A.Id 
			LEFT JOIN sSetup.tClassMaster CM ON CM.Id=SA.AdmissionStandardId
			INNER JOIN sSetup.tDivisionMaster DM ON vSA.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CMS ON CMS.Id= DM.ClassId 
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=vSA.StudentId
			LEFT JOIN sCommon.tCountryMaster CTM ON CTM.Id=SO.NationalityId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=vSA.AcademicId
			--LEFT JOIN sSetup.tClassSubject CS ON CS.ClassId=A.ClassId
			--LEFT JOIN sSetup.tSubjectMaster SubM ON SM.Id=CS.SubjectId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sCommon.tCastCategoryMaster CSM ON CSM.Id=SO.CastCategoryId
			--LEFT JOIN sSetup.tClassGroupMaster CSG ON CSG.Id=CMS.ClassGroupId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=vSA.BatchId 
			--AND BM.OrgGroupBatchId=vSA.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentAdditional SD ON SD.StudentId=vSA.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sSetup.tDivisionInchargeEmployee DIE ON vSA.DivisionId = DIE.DivisionId AND DIE.BatchId = vSA.BatchId
			AND DIE.Number = (SELECT MIN(Number) FROM sSetup.tDivisionInchargeEmployee WHERE  DIE.DivisionId = vSA.DivisionId AND DIE.BatchId = vSA.BatchId)
			LEFT JOIN sHrm.tEmployeeImages EI1 ON EI1.EmployeeId = DIE.EmployeeId
			INNER JOIN sSetup.tLanguageMaster LM ON LM.Id = OM.LanguageId
			LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId=vSA.StudentId 
	WHERE 
				L.OrgId=@rOrgId
				AND	vSA.BatchId = @rBatchId 
				AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
				AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
				--AND ((L.LCNumber=@rNumber) OR (@rNumber=''))
				AND ((L.LCDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((L.LCDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				--AND ((L.LCDate=@rLCDate) OR (ISNULL(@rLCDate,'')=''))
				--AND ((L.LeftDate=@rLeftDate) OR (ISNULL(@rLeftDate,'')=''))
				--AND ((L.LCCopy=@rLCCopy) OR (@rLCCopy=0))
				--AND ((L.LCBookNumber=@rLCBookNumber) OR (@rLCBookNumber=''))
				AND ((vSA.ClassId=@rClassId) OR(@rClassId=0))
				AND ((vSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((L.LCNumber=@rLCNumber) OR (@rLCNumber=''))
				AND ((L.LCNumber >= @rFromNo) OR (@rFromNo=''))
				AND ((L.LCNumber <= @rToNo) OR (@rToNo=''))
				AND ((DM.ClassId=@rClassId) OR(@rClassId=0))
				--group by MR.PresentCount,MR.TotalCount, SubM.Title, SM.Code,L.AcademicId,SM.FirstName,SM.LastName,SM.MiddleName,SF.FatherName,SF.MotherName,NM.Title,
				--SO.CastCategoryId,RM.Title,so.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,SO.DateOfBirth,SO.BirthDateInWord,SA.PreviousSchool,
				--	SA.AdmissionDate,L.LeftDate,L.LCReason,L.LCProgress,L.LCConduct,L.LCRemark,L.LCDate,SO.GenderId,
				--	OM.CityName,OM.StateName,CM.DisplayTitle,CMS.DisplayTitle,SM.StatusId,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
END
GO
PRINT N'Altering Procedure [sCommunication].[pAllGalleryCategory_Get]...';


GO

ALTER PROCEDURE [sCommunication].[pAllGalleryCategory_Get]
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 @rBatchId int,
	 @rIsDivisionWise bit=true,
	 @rBatchYear int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
    DECLARE @lOrgGroupId smallint,@lOrgGroupBatchId int,@lOrgId smallint
    
	SELECT @lOrgGroupId=OM.OrgGRoupId,@lOrgGroupBatchId=OrgGroupBatchId,@lOrgId=OM.Id FROM sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	WHERE Bm.Id=@rBatchId
	
	SELECT  
			PCM.[Id]
			,PCM.[Title]
			,PCM.[IsObsolete]
			,ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(PCM.Remark,'') AS Remark,
			PCM.CreatedDateTime,
			--comment above line due to mantisid - 0029607 - for different time zone
			--[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(PCM.CreatedDateTime,'')) AS CreatedDateTime,
			--CASE WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 2003 THEN 'Student'
			--WHEN ISNULL(MPCS.ScopeSourceTypeId,0) = 95 THEN 'Employee'
			--END  AS ScopeSourceType,
			AM.Title AS ScopeSourceType,
			U.DisplayTitle AS UserName,
			ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
		FROM    
			[sCommunication].[tMultiPhotoCategoryMaster]  PCM 
			INNER JOIN sCommon.tAssigneeMaster AM ON PCM.ScopeSourceTypeId = AM.Id
			--INNER JOIN [sCommunication].[tMultiPhotoCategoryScope] MPCS ON MPCS.MultiPhotoCategoryId = PCM.Id
			INNER JOIN sSecurity.tUser U ON PCM.CreatedUserId = U.Id
		WHERE   
			((PCM.Id = @rId) OR (@rId = 0))
			AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			--AND PCM.IsObsolete =0
			AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
			AND (PCM.OrgGroupBatchId = @lOrgGroupBatchId OR ISNULL(PCM.OrgGroupBatchId,0)=0)
		ORDER BY 
			PCM.CreatedDateTime DESC
	
END
GO
PRINT N'Altering Procedure [sCommunication].[pAllPhotoCategory_Get]...';


GO
  

ALTER PROCEDURE [sCommunication].[pAllPhotoCategory_Get]
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 @rBatchId int,
	 @rIsDivisionWise bit=true,
	 @rBatchYear int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
    DECLARE @lOrgGroupId smallint,@lOrgGroupBatchId int,@lOrgId smallint
    
	SELECT @lOrgGroupId=OM.OrgGRoupId,@lOrgGroupBatchId=OrgGroupBatchId,@lOrgId=OM.Id FROM sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	WHERE Bm.Id=@rBatchId
	
    IF(@rIsDivisionWise=0)
    BEGIN
		SELECT   
			PCM.[Id]
			,PCM.[Title]
			,PCM.[IsObsolete]
			,ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(PCM.Remark,'') AS Remark,
			PCM.CreatedDateTime,
			--comment above line due to mantisid - 0029607 - for different time zone
			--[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(PCM.CreatedDateTime,'')) AS CreatedDateTime,
			CASE WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			END +' - '+ [sCommunication].[fPhotoCategoryScopeGet](PCM.Id,PCM.ScopeSourceTypeId) AS ScopeSourceType,
			U.DisplayTitle AS UserName,
			ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
		FROM    
			[sCommunication].[tPhotoCategoryMaster]  PCM 
			INNER JOIN sSecurity.tUser U ON PCM.CreatedUserId = U.Id
		WHERE   
			((PCM.Id = @rId) OR (@rId = 0))
			AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			AND PCM.IsObsolete =0
			AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
			AND (PCM.OrgGroupBatchId = @lOrgGroupBatchId OR ISNULL(PCM.OrgGroupBatchId,0)=0)
		ORDER BY 
			PCM.CreatedDateTime DESC
	END		
	ELSE
	
	 BEGIN
		SELECT   
			PCM.[Id]
			,PCM.[Title]
			,PCM.[IsObsolete]
			,ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(PCM.Remark,'') AS Remark,
			PCM.CreatedDateTime,
			--comment above line due to mantisid - 0029607 - for different time zone
			--[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(PCM.CreatedDateTime,'')) AS CreatedDateTime,
			CASE WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			END +' - '+ [sCommunication].[fPhotoCategoryScopeGet](PCM.Id,PCM.ScopeSourceTypeId) AS ScopeSourceType,
			U.DisplayTitle AS UserName,
			ISNULL(PCM.OrgGroupBatchId,0) AS OrgGroupBatchId
		FROM    
			[sCommunication].[tPhotoCategoryMaster]  PCM 
			INNER JOIN sSecurity.tUser U ON PCM.CreatedUserId = U.Id
		WHERE   
			((PCM.Id = @rId) OR (@rId = 0))
			AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			AND ScopeSourceTypeId=2005
			AND PCM.IsObsolete =0
			AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
			AND (PCM.OrgGroupBatchId = @lOrgGroupBatchId OR ISNULL(PCM.OrgGroupBatchId,0)=0)
		ORDER BY 
			PCM.CreatedDateTime DESC
	END		
END
GO
PRINT N'Altering Procedure [sCommunication].[pCircularGet]...';


GO

 
ALTER PROCEDURE [sCommunication].[pCircularGet]
	 @rId bigint = 0,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rOrgGroupBatchId int,
	 @rIsSearch bit = 1,
	 @rAssigneeId tinyint,
	 @rCircularTypeId int,
	 @rCreatedUserId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	--DECLARE @lTimeZoneConfigValue nvarchar(max)
	--SELECT @lTimeZoneConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 234
	--SELECT @lTimeZoneConfigValue
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			U.DisplayTitle as CreatedUserName,
			C.AssigneeId,
			AM.Title AS Assignee,
			CTM.Title AS CircularTypeTitle,
			CTM.HighlightColor,
			C.CircularTypeId,
			C.CreatedUserId,
			C.CreatedDateTime,
			ISNULL(C.StatusId,549) AS StatusId,
			ISNULL(C.PublishDateTime,'') as PublishDateTime,
			--comment above line due to mantisid - 0029607 - for different time zone
			--[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(C.PublishDateTime,'')) AS PublishDateTime,
			--CASE WHEN ISNULL(C.StatusId,549) =549 then 'Pending' WHEN C.StatusId=550 then 'Approve' ELSE 'Reject' END AS Status
			ISNULL(C.IsPublishInFuture,0) as PublishInFuture,
			ISNULL(C.IsConsent,0) AS IsConsent
  FROM 
            sCommunication.tCircular C
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=C.AssigneeId
            INNER JOIN sCommunication.tCircularTypeMaster CTM ON CTM.Id = C.CircularTypeId
  WHERE 
  
		((C.Id = @rId) OR (@rId = 0))
	AND ((C.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((C.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((C.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((C.AssigneeId IN (1,2,3) AND @rAssigneeId=1)  OR
		 (C.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2,3)) OR
		  @rIsSearch = 0)
     AND (C.CircularTypeId=@rCircularTypeId OR @rIsSearch = 0)
    AND (C.CreatedUserId = @rCreatedUserId OR @rCreatedUserId = 0)
	ORDER BY C.StartDate DESC
END
GO
PRINT N'Altering Procedure [sCommunication].[pPlayListMasterDataGet]...';


GO

ALTER PROCEDURE [sCommunication].[pPlayListMasterDataGet]
          
           @rTitle nvarchar(100),
		   @rOrgGroupId int
        
          
AS
SET NOCOUNT ON
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		
BEGIN
SELECT 
	   PLM.Id as PlayListId
	  ,PLM.Title
	  ,PLM.OrderIndex 
	  ,PLM.Remark
	  ,PLM.IsObsolete 
	  ,U.DisplayTitle as CreatedUserName
	  ,PLM.CreatedDateTime
	  --comment above line due to mantisid - 0029607 - for different time zone
	  --,[sCommon].[fConvertDateTimeToDifferentTimeZone](ISNULL(PLM.CreatedDateTime,'')) AS CreatedDateTime
  FROM sCommunication.tPlaylistMaster PLM
       INNER JOIN sSecurity.tUser U ON U.Id=PLM.CreatedUserId
  WHERE 
	PLM.OrgGroupId=@rOrgGroupId
	AND 
	((PLM.Title Like @rTitle) OR (ISNULL(@rTitle,'') = ''))
    order by PLM.OrderIndex
END
GO
PRINT N'Altering Procedure [sEMeeting].[pCancelMeeting]...';


GO

ALTER PROCEDURE [sFee].[pFeeSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rBatchId int=0,
	@rDepartmentId int =0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 

	--DECLARE @lAdmissionCategoryId int =  0
	--SET @lAdmissionCategoryId = [sCommon].[fGetIntIdForOrg](1,@rOrgId)
	
		if object_id('tempdb..#tTable') is not null
		BEGIN
			DROP TABLE #tTable
		END

		Create table #tTable(
			AcademicId bigint not null
		)

		Insert into #tTable
			select SA.AcademicId 
			FROM sFee.tFeeSetup FS
			INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
			where ((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			-- AND SA.AdmissionCategoryId=@lAdmissionCategoryId
			group by FS.ClassId,SA.AcademicId 

		--Create Table #ttemptable1
		--	(
		--		AcademicId bigint,
		--		PaidAmount int,
		--		PendingAmount int
		--	)
		--	Insert into #ttemptable1
		--	(
		--		AcademicId,
		--		PaidAmount,
		--		PendingAmount
		--	)
		--	Select SA.AcademicId , SUM(SF.PaidAmount) AS PaidAmount , SUM(SF.PendingAmount) AS PendingAmount
		--	From sStudent.vStudentAcademic SA 
		--	Inner Join sFee.tStudentFee SF ON SA.AcademicId=SF.AcademicId
		--	where SA.OrgId=9911 AND SA.BatchId=991100104
		--	Group by SA.AcademicId

		

	IF(@rType = 'FeeList')
	BEGIN

		if object_id('tempdb..#tempAcademicDetail') is not null
		BEGIN
			DROP TABLE #tempAcademicDetail
		END
		
		Create table #tempAcademicDetail(
			AcademicId bigint not null
		)

		SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
		INTO #tempReceiptDetail
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					Group By R.SourceId,FS.Id

		SELECT Distinct SourceId INTO #tempReceipt FROM sFee.tReceipt


		INSERT INTO #tempAcademicDetail
		SELECT 
			SA1.AcademicId 
		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
		LEFT JOIN #tempReceiptDetail R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
		INNER JOIN #tempReceipt RE ON RE.SourceId = SA1.AcademicId
		WHERE 
			((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND SA1.StatusId =1
			AND FS1.IsOptional = 0
			AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
			
		UNION 	
		--Add Union because data wrong due to insert in #tempAcademicDetail -- mantisId - 0030182		
		--INSERT INTO #tempAcademicDetail
		SELECT 
			SA1.AcademicId 
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
		LEFT JOIN #tempReceiptDetail R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
		INNER JOIN #tempReceipt RE ON RE.SourceId = SA1.AcademicId
		WHERE 
			((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND SA1.StatusId =1
			AND FS1.IsOptional = 1
			AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
		
		--SELECT * FROM #tempAcademicDetail

		CREATE TABLE #tmp
		(
			AcademicId bigint,
			Amount decimal(12,2),
			VariableAmount decimal(12,2),
			AdditionalAmount decimal(12,2),
			DiscountAmount decimal(12,2),
			NotApplicableAmount decimal(12,2)
		)
		INSERT INTO #tmp
			Select SA.AcademicId  AS AcademicId 
			, SUM(FS1.Amount) AS Amount , Sum(FA1.VariableAmount) AS VariableAmount, SUM(FA1.AdditionalAmount)AS AdditionalAmount,SUM(FA1.DiscountAmount)AS DiscountAmount,
			SUM(FA1.NotApplicableAmount)AS NotApplicableAmount
			From sStudent.vStudentAcademic SA

			--Changes for pending fee minus count for mantis Id :0027388
			--LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId
			--LEFT JOIN sFee.tFeeSetup FS1 ON FA1.FeeSetupId = FS1.Id AND FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId  AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId AND FS1.Id = FA1.FeeSetupId
			INNER JOIN #tTable tmp1 ON tmp1.AcademicId = SA.AcademicId
		
			Where
			((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			group by FS1.ClassId,SA.AcademicId 

			
			SELECT COUNT(SA.AcademicId)AS TotalCount,COUNT(T.PaidCount) AS PaidCount,(COUNT(tmp.AcademicId)-COUNT(T.PaidCount))AS UnPaidCount
			, COUNT(PS.AcademicId) AS PartialCount
			FROM sStudent.vStudentAcademic SA 
			LEFT JOIN #tmp tmp ON SA.AcademicId = tmp.AcademicId 
			AND ISNULL(((ISNULL(Amount,0) + ISNULL(VariableAmount,0)+ ISNULL(0,AdditionalAmount)) - (DiscountAmount + NotApplicableAmount)),1) <> 0 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			Inner Join #tTable FS  on  FS.AcademicId=SA.AcademicId
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId
			)T ON T.AcademicId = SA.AcademicId 

			LEFT JOIN #tempAcademicDetail PS ON PS.AcademicId=SA.AcademicId
			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
			--AND ACM.Code Like '%General%' 
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0	
			DROP TABLE  #tmp
		END
	ELSE IF(@rType = 'FeeGraph')
		BEGIN
		
		CREATE TABLE #tmpData
		(
			AcademicId bigint,
			Amount decimal(12,2),
			VariableAmount decimal(12,2),
			AdditionalAmount decimal(12,2),
			DiscountAmount decimal(12,2),
			NotApplicableAmount decimal(12,2)
		)
		INSERT INTO #tmpData
			Select SA.AcademicId  AS AcademicId 
			, SUM(FS1.Amount) AS Amount , Sum(FA1.VariableAmount) AS VariableAmount, SUM(FA1.AdditionalAmount)AS AdditionalAmount,SUM(FA1.DiscountAmount)AS DiscountAmount,
			SUM(FA1.NotApplicableAmount)AS NotApplicableAmount
			From sStudent.vStudentAcademic SA

			--Changes for pending fee minus count for mantis Id :0027388
			--LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId
			--LEFT JOIN sFee.tFeeSetup FS1 ON FA1.FeeSetupId = FS1.Id AND FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId  AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId
			LEFT JOIN sFee.tFeeAllocation FA1 ON FA1.SourceId = SA.AcademicId AND FS1.Id = FA1.FeeSetupId
			INNER JOIN #tTable tmp1 ON tmp1.AcademicId = SA.AcademicId
		
			Where
			((SA.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))AND SA.StatusId =1
			group by FS1.ClassId,SA.AcademicId 


		SELECT CM.Id,CM.Title,ISNULL(T.TotalCount,0)AS TotalCount,COUNT(T1.PaidCount) AS PaidCount,(COUNT(tmpData.AcademicId)-COUNT(T1.PaidCount))AS UnPaidCount,CM.OrderIndex
			FROM sStudent.vStudentAcademic SA
			LEFT JOIN #tmpData tmpData ON SA.AcademicId = tmpData.AcademicId 
			AND ISNULL(((ISNULL(Amount,0) + ISNULL(VariableAmount,0)+ ISNULL(0,AdditionalAmount)) - (DiscountAmount + NotApplicableAmount)),1) <> 0 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			LEFT JOIN sSetup.tClassMaster CM ON  CM.Id = SA.ClassId
			LEFT JOIN 
			(SELECT COUNT(SA1.AcademicId) AS TotalCount,SA1.ClassId AS ClassId FROM sStudent.vStudentAcademic SA1
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM1 ON SA1.AdmissionCategoryId = ACM1.Id
			Inner Join #tTable temp on SA1.AcademicId=temp.AcademicId
			WHERE ((SA1.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))AND SA1.StatusId =1
			--AND ACM1.Code Like '%General%' AND ACM1.IsObsolete = 0	
			--AND ACM1.ID = @lAdmissionCategoryId 
			AND ACM1.IsObsolete = 0
			GROUP BY ClassId
			)T ON T.ClassId = CM.Id	
			LEFT JOIN(
			SELECT COUNT(SA.AcademicId)as PaidCount,SA.AcademicId AS AcademicId,SA.ClassId AS ClassId FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			INNER JOIN sStudent.tAdmissionCategoryMaster ACM ON SA.AdmissionCategoryId = ACM.Id
			LEFT JOIN sSetup.tClassMaster CM ON  CM.Id = SA.ClassId
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))AND SA.StatusId =1
			--AND ACM.Code Like '%General%' AND ACM.IsObsolete = 0
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0		
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId,SA.ClassId
			)T1 ON T1.AcademicId = SA.AcademicId  AND CM.Id = SA.ClassId
			WHERE ((CM.OrgId =@rOrgId)OR(@rOrgId=0))
			AND SA.StatusId =1
			--AND ACM.ID = @lAdmissionCategoryId 
			AND ACM.IsObsolete = 0
			--AND ACM.Code Like '%General%' AND ACM.IsObsolete = 0	
			GROUP BY CM.Title, CM.Id,T.TotalCount,CM.OrderIndex
			ORDER BY CM.OrderIndex

			DROP TABLE #tmpData
		
		END
	ELSE IF (@rType = 'FeeListDetails')
		BEGIN

		if object_id('tempdb..#tempAcademicDetail') is not null
		BEGIN
			DROP TABLE #tempAcademicDetail1
		END
		
		Create table #tempAcademicDetail1(
			AcademicId bigint not null
		)

		SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
		INTO #tempReceiptDetail1
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					Group By R.SourceId,FS.Id

		SELECT Distinct SourceId INTO #tempReceipt1 FROM sFee.tReceipt

		INSERT INTO #tempAcademicDetail1
		SELECT 
			SA1.AcademicId 
		FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
		LEFT JOIN #tempReceiptDetail1 R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
		INNER JOIN #tempReceipt1 RE ON RE.SourceId = SA1.AcademicId
		WHERE 
			((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND SA1.StatusId =1
			AND FS1.IsOptional = 0
			AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
					
		UNION
		--Add Union because data wrong due to insert in #tempAcademicDetail -- mantisId - 0030182
		--INSERT INTO #tempAcademicDetail1
		SELECT 
			SA1.AcademicId 
		FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
		LEFT JOIN #tempReceiptDetail1 R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
		INNER JOIN #tempReceipt1 RE ON RE.SourceId = SA1.AcademicId
		WHERE 
			((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
			AND SA1.StatusId =1
			AND FS1.IsOptional = 1
			AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
		
		--SELECT * FROM #tempAcademicDetail1
		
		SELECT F.RollNo,F.Name,F.Code,F.Pending,F.[Partial],F.[Status],F.ClassDivision
		FROM
		(

		SELECT SA.RollNo,SA.Name,SA.Code, ISNULL(T.AcademicId,0) AS Pending, ISNULL(PS.AcademicId,0) AS [Partial],'' AS [Status]
			,SA.ClassName+'/'+SA.DivisionName AS ClassDivision,
			(
				Select (SUM(FS1.Amount)+Sum(FA1.VariableAmount)+ SUM(FA1.AdditionalAmount)) - (SUM(FA1.DiscountAmount)+ SUM(FA1.NotApplicableAmount)) 
				From sFee.tFeeAllocation FA1
				INNER JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId AND FA1.FeeSetupId = FS1.Id
				Where FA1.SourceId = SA.AcademicId 
			) AS IsFeePayAmount
			--,ISNULL(FS1.PaidAmount,0) AS PaidAmount ,ISNULL(FS1.PendingAmount,0)AS PendingAmount
			FROM sStudent.vStudentAcademic SA 
			Inner Join #tTable FS  on  FS.AcademicId=SA.AcademicId
			--LEFT Join #ttemptable1 FS1 ON FS1.AcademicId=SA.AcademicId
			LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,SA.AcademicId AS AcademicId, SA.Code,SA.Name FROM sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
			GROUP BY SA.AcademicId, SA.Code,SA.Name
			)T ON T.AcademicId = SA.AcademicId
			LEFT JOIN #tempAcademicDetail1 PS ON PS.AcademicId=SA.AcademicId

			WHERE ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND SA.StatusId =1
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	 			
			) AS F 
			WHERE ISNULL(F.IsFeePayAmount,1) >= 0
		END

	ELSE IF(@rType='FeeCollection')
		BEGIN
			SELECT Isnull(Sum(R.ReceiptAmount),0.00) as TodayCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate=CAST(GETDATE() as DATE))

			SELECT ISNULL(Sum(R.ReceiptAmount),0.00) as MonthlyCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate>=CAST(DATEADD(DD,-(DAY(GETDATE() -1)), GETDATE()) as DATE) AND R.ReceiptDate<=CAST(DATEADD(DD,-(DAY(GETDATE())), DATEADD(MM, 1, GETDATE())) as DATE))

			SELECT Isnull(Sum(R.ReceiptAmount),0.00) as UptodateCollection 
			FROM sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0)) AND (R.IsObsolete = 0) 
				AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				AND SA.StatusId =1
				AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (R.ReceiptDate<=CAST(GETDATE() as DATE))
		END
		--Drop Table #ttemptable1
		Drop Table #tTable
END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeInvoiceGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeInvoiceGet]
		
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rReportId int,
		@rIsFilter bit,
	    @rIsDisplayOrgGroup bit,
	    @rIsFeeInvoiceHeadwise bit,
		@rOrgGroupBatchId int,
		@rCommonBatch nvarchar(100),
		@rReceiptBookId int,
		@rOrgId int,
		@rBatchId int,
		@rDepartmentId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rStatusId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = '',
	    @rFeeId nvarchar(max) = '',
	    @rFilterId int=0,
	    @rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0    
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
   if(@rReportId =20886)
   begin
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		FS.AcademicId,
		FS.Name,
		FS.ClassId,
		FS.ClassName,
		FS.DivisionId,
		FS.DivisionName,
		FS.DivisionOrder,
		FS.RollNo,
		FS.Code,
		FS.DepartmentId,
		FS.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) AS FeeAmount,
		ISNULL(R.PaidAmount,0.00) AS PaidAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		FS.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		RBM.GroupTitle AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
		ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
			        
	         CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader
	  ,SC.PermanentStreetOne as PermanentStreetOne         -- #Start Mentis 29588
	  ,SC.PermanentStreetTwo as PermanentStreetTwo
	  ,SC.PermanentStreetThree as PermanentStreetThree 
	  ,SC.PermanentCountry as PermanentCountry
	  ,SC.PermanentState as PermanentState
	  ,SC.PermanentCity as PermanentCity
	  ,SC.PermanentZipCode as PermanentZipCode
	  ,SC.PermanentContactNo as PermanentContactNo 
	  ,SF.FatherName as FatherName
	  ,SF.MotherName as MotherName     
	  ,ISNULL(SAD.AdmissionNumber,'') AS AdmissionNumber 
	  ,SO.DateOfBirth as DateOfBirth                     
	  ,sFee.fFeeAmountSumGet (FS.AcademicId)  as TotalAmount	 -- #End Mentis 29588  
	  ,SI.StudentPhoto as StudentPhoto            -- Mentis 29588
	  ,SC.PresentStreetOne    --#Start mentis - 0030332
	  ,SC.PresentStreetTwo
	  ,SC.PresentCity        
	  ,OI.CertificateHeaderA4Portrait AS CertificateHeaderA4  --#End mentis - 0030332
	  
  FROM 
		sFee.tFeeMaster FM 
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId				
			    FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId				
				WHERE FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = SA.BatchId AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId				
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId			
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=SA.AcademicId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = SA.BatchId AND FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=1 
			AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OGM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId 
		AND FS.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=FS.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = FS.StudentId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=FS.AcademicId) AND(FA.SourceTypeId=2001)
		
         LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=FS.StudentId AND AR.SourceTypeId=2003 AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = FS.StudentId AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
    
    LEFT  JOIN
	(
	    SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,
				RD.FeeSetupId,
				R.SourceId
	    FROM
				sFee.tReceipt R 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			
			--AND (R.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId=0)
			--AND (R.CollectionGroupId=@rCollectionGroupId OR @rCollectionGroupId=0)
		WHERE		
			(R.SourceTypeId = 2001)
			AND (R.IsObsolete = 0) 
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				GROUP BY FeeSetupId,R.SourceId--,R.ReceiptNumber,R.ReceiptDate,PTM.Title,R.ChequeNo,R.BankName,R.ChequeDate
	) R ON R.FeeSetupId = FS.Id AND FS.AcademicId = R.SourceId

	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentID = FS.StudentID    -- Mentis 29588
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentID = FS.StudentID           -- Mentis 29588
	LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId = FS.StudentID 
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentID = FS.StudentID      -- Mentis 29588
    
WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) > 0  
		--AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0  
        --AND ISNULL(FS.Amount,0.00) > 0
		 AND (
			 (@rFilterId = 0) -- All
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			 ) 
       end

	   else
	     begin

		             SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		FS.AcademicId,
		FS.Name,
		FS.ClassId,
		FS.ClassName,
		FS.DivisionId,
		FS.DivisionName,
		FS.DivisionOrder,
		FS.RollNo,
		FS.Code,
		FS.DepartmentId,
		FS.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		--ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) AS FeeAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) AS FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		FS.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		RBM.GroupTitle AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		ISNULL(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
		ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
			        
	         CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader
	  ,'' as PermanentStreetOne         -- #Start Mentis 29588
	  ,'' as PermanentStreetTwo
	  ,'' as PermanentStreetThree 
	  ,'' as PermanentCountry
	  ,'' as PermanentState
	  ,'' as PermanentCity
	  ,'' as PermanentZipCode
	  ,'' as PermanentContactNo 
	  ,'' as FatherName
	  ,'' as MotherName     
	  ,0 as AdmissionNumber 
	  ,SO.DateOfBirth  
	  , Convert(Decimal,0) as TotalAmount      
	  ,convert(varbinary(max),'') as StudentPhoto -- #End Mentis 29588
	  ,'' as PresentStreetOne    --#Start mentis - 0030332
	  ,'' as PresentStreetTwo
	  ,'' as PresentCity        
	  ,convert(varbinary(max),'') as CertificateHeaderA4  --#End mentis - 0030332
  FROM 
		sFee.tFeeMaster FM 
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			    FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
				WHERE FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=0
				AND FS1.BatchId = SA.BatchId AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
				AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
				SA.AcademicId,
				SA.StudentId,
				SA.Name,
				SA.ClassId,
				SA.ClassName,
				SA.DivisionId,
				SA.DivisionName,
				SA.DivisionOrder,
				SA.RollNo,
				SA.Code,
				SA.DepartmentId,
				SA.DepartmentName,
				SA.BatchName,
				SA.OrgId,
				SA.OrgGroupBatchId,
				SA.AdmissionCategoryId,
				SA.StatusId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA.ClassId = FS1.ClassId
			INNER JOIN sFee.tFeeOptional FO
				ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=SA.AcademicId) AND(FO.SourceTypeId=2001)
			WHERE FS1.BatchId = SA.BatchId AND FS1.ClassId=SA.ClassId AND FS1.AdmissionCategoryId=SA.AdmissionCategoryId AND IsOptional=1 
			AND ((FS1.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		) FS ON FS.FeeId=FM.Id
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId 
		AND FS.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=FS.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = FS.StudentId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND (FA.SourceId=FS.AcademicId) AND(FA.SourceTypeId=2001)
		
         LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=FS.StudentId AND AR.SourceTypeId=2003 AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
         LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = FS.StudentId AND ((FS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
    
    LEFT  JOIN
	(
	    SELECT 
				ISNULL(SUM(RD.Amount),0) AS PaidAmount,
				RD.FeeSetupId,
				R.SourceId
	    FROM
				sFee.tReceipt R 
			INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
			INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = R.PayTypeId
			AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.ClassId=@rClassId OR @rClassId=0) 
			AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			
			--AND (R.ReceiptBookId=@rReceiptBookId OR @rReceiptBookId=0)
			--AND (R.CollectionGroupId=@rCollectionGroupId OR @rCollectionGroupId=0)
		WHERE		
			(R.SourceTypeId = 2001)
			AND (R.IsObsolete = 0) 
			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
			AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
			AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			AND ((SA1.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
				GROUP BY FeeSetupId,R.SourceId--,R.ReceiptNumber,R.ReceiptDate,PTM.Title,R.ChequeNo,R.BankName,R.ChequeDate
	) R ON R.FeeSetupId = FS.Id AND FS.AcademicId = R.SourceId
    
WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		--AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00) > 0  
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0  
         AND (
			 (@rFilterId = 0) -- All
			 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
			 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
			 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			 ) 

		 end


END
GO
PRINT N'Altering Procedure [sFee].[pRptFeeReceiptDetailListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailListGet]  
  @rReportId int,  
  @rReceiptBookId int,  
  @rAdmissionCategoryId int,  
  @rClassId int,  
  @rDivisionId int,  
  @rFromDate date,  
  @rToDate date,  
  @rFromReceiptNo int,  
  @rToReceiptNo int,  
  @rBatchId int,  
  @rUserId bigint,  
  @rBuilder1 nvarchar(max),  
  @rBuilder2 nvarchar(max),  
  @rIsCancel bit,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int,  
  @rCommonBatch nvarchar(100),  
  @rDepartmentId int,  
  @rFromRollNo int,  
     @rToRollNo int,  
     @rCode nvarchar(20),  
     @rIsDetail bit=0,  
  @rIsFilter bit,  
  @rIsHeader bit,  
  @rCreatedUserName nvarchar(100)='',  
  @rFeeHeadId nvarchar(max) = '',  
  @rIsDisplayOrgGroup bit=0,  
  @rPayTypeId int=0,  
  @rFeeId nvarchar(max) = '',  
  @rFilterId int=0,
  @rOrgIds nvarchar(max) = '',
  @rClassStatusId int=0,
  @rPayTypeIds nvarchar(max) = '' ,
  @rBankName nvarchar(200)='' ,
  @rUserAcessUserId bigint = 0  
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN  
SET @rBankName = sCommon.fSearchStringGet(@rBankName)  
IF(@rReportId=10145)
	BEGIN
	SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherName,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex,
  PTM.Id AS PayTypeId,
  ISNULL(SA.SUID,'') AS SUID,
  ISNULL(U.DisplayTitle,'') AS CreatedUser
  ,TBM.FromDate AS FromDate
  ,TBM.ToDate AS ToDate
	 ,'' as PermanentStreetOne         -- Start Mentis 29588
	  ,'' as PermanentStreetTwo
	  ,'' as PermanentStreetThree 
	  ,'' as PermanentCountry
	  ,'' as PermanentState
	  ,'' as PermanentCity
	  ,'' as PermanentZipCode
	  ,'' as PermanentContactNo    
	  ,'' as AdmissionNumber 
	  ,SO.DateOfBirth  
	  ,Convert(Decimal,0) as TotalAmount    
	  ,convert(varbinary(max),'') as StudentPhoto                -- #End Mentis 29588
	  ,'' as PresentStreetOne  --Mentis 0030332
	  ,'' as PresentStreetTwo
	  ,'' as PresentCity		--Mentis 0030332
	  ,convert(varbinary(max),'') as CertificateHeaderA4  --mantis - 0030332
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
    --for UserAccess Wise (in ReceiptListFeeHeadHeadwise report)
  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND O.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  
 
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
     LEFT JOIN  
 (SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
 INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id=R.BatchId AND ((TBM.OrgId=@rOrgId) OR (@rOrgId=0))
 INNER JOIN [sSecurity].[tUser] U ON U.Id=R.CreatedUserId 
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 --AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
 AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
 AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
 AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
   )  
  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
 ORDER BY R.ReceiptNumber  

	END


ELSE
	BEGIN
	SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,  
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherName,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex,
  PTM.Id AS PayTypeId,
  ISNULL(SA.SUID,'') AS SUID
  ,ISNULL(U.DisplayTitle,'NA') AS CreatedUser
  ,TBM.FromDate AS FromDate
  ,TBM.ToDate AS ToDate
   ,SC.PermanentStreetOne as PermanentStreetOne          -- Mentis 29588
	  ,SC.PermanentStreetTwo as PermanentStreetTwo
	  ,SC.PermanentStreetThree as PermanentStreetThree
	  ,SC.PermanentCountry as PermanentCountry
	  ,SC.PermanentState as PermanentState
	  ,SC.PermanentCity as PermanentCity
	  ,SC.PermanentZipCode as PermanentZipCode
	  ,SC.PermanentContactNo as PermanentContactNo    
	  ,SAD.AdmissionNumber as AdmissionNumber 
	  ,SO.DateOfBirth as DateOfBirth   
	  ,sFee.fFeeAmountSumGet (SA.AcademicId) AS TotalAmount 
	  ,SI.StudentPhoto as StudentPhoto              -- Mentis 29588 
	  ,SC.PresentStreetOne  --Mentis 0030332
	  ,SC.PresentStreetTwo
	  ,SC.PresentCity		--Mentis 0030332
	  ,OI.CertificateHeaderA4Portrait AS CertificateHeaderA4  --mantis - 0030332

	  
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
  LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = O.Id
  LEFT JOIN [sSecurity].[tUser] U ON U.Id=R.CreatedUserId -- Change innerjoin to left join for mantis id :0029242
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
     LEFT JOIN  
 (SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
 INNER JOIN sSetup.tBatchMaster TBM ON TBM.Id=R.BatchId AND ((TBM.OrgId=@rOrgId) OR (@rOrgId=0))

  LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentID = SA.StudentID   -- Mentis 29588
  LEFT JOIN sStudent.tStudentAdmission SAD ON SAD.StudentID = SA.StudentID      
  LEFT JOIN sStudent.tStudentImages SI ON SI.StudentID = SA.StudentID      -- Mentis 29588
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
 AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
 AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
 AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
   )  
  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
 ORDER BY R.ReceiptNumber  
	END
 --ORDER BY R.Id 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering Procedure [sMis].[pRptResultAnalysisExamWiseGet]...';


GO
ALTER PROCEDURE [sMis].[pRptResultAnalysisExamWiseGet]
	 
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		
		@rOrgGroupBatchId int,
		@rExamId int,
		@rStrOrgMainGroupId nvarchar(max),
		@rStrOrgSubGroupId nvarchar(max),
		@rStrOrgId nvarchar(max),
		@rStrDepartmentId nvarchar(max),
		@rStrClassId nvarchar(max)
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--Select 
--		0 AS OrgMainGroupId,
--	    '' AS OrgMainGroupName,
--		0 AS OrgSubGroupId,
--		'' AS SubGroupName,
--		'' AS OrgName,
--		0 AS DepartmentId,
--		0 AS OrgId,
--		'' AS Code,
--		'' AS Name,
--		0 AS RollNo,
--		0 AS AcademicId,			
--		'' AS Class,
--		0 As ClassId,
--		'' AS Division,
--		0 AS DivisionId,
--		'' AS Exam,
--		0 AS SubjectId,	
--		'' AS SubjectCode,
--		'' AS SubjectName,
--		--RD.SubjectGrade,
--		--R.ResultGrade,
--		--BM.OrgGroupBatchId,
--		--RD.Obtain,
--		'' AS SubjectGrade,
--		--R.Percentage,
--		'' AS ResultGrade,
--		@rExamId AS ExamId


			
 
 
 
		Select 
		OMGM.Id AS OrgMainGroupId,
		OMGM.Code AS OrgMainGroupName,
		OSGM.Id AS OrgSubGroupId,
		OSGM.Code AS SubGroupName,
		OM.Title AS OrgName,
		DM.Id AS DepartmentId,
		--CM.Id,
		stum.OrgId,
		Stum.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		A.Id AS AcademicId,			
		CM.DisplayTitle AS Class,
		CM.Id As ClassId,
		DM.DisplayTitle AS Division,
		DM.Id AS DivisionId,
		ETM.Code AS Exam,
		CS.Id AS SubjectId,	
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		--RD.SubjectGrade,
		--R.ResultGrade,
		--BM.OrgGroupBatchId,
		--RD.Obtain,
		[sAssessment].[fGetConfigGrade](stum.OrgId,RD.Obtain) AS SubjectGrade,
		--R.Percentage,
		[sAssessment].[fGetResuultGradeCount](stum.OrgId,RD.Obtain,@rExamId,@rStrOrgMainGroupId,@rStrOrgSubGroupId,@rStrOrgId,@rStrDepartmentId,@rStrClassId,@rOrgGroupBatchId,CM.Id,DM.Id)AS ResultGrade,
		@rExamId AS ExamId,
		--R.ResultGrade,
		 --OMGM.Id
		 CAST(ISNULL(RD.IsPresent, 0) AS INT) AS IsPresent      --Mantis 30006

		 from sStudent.tStudentMaster Stum 
		INNER JOIN  sStudent.tAcademic A ON Stum.Id=A.StudentId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sSetup.tOrganizationMaster OM ON Stum.OrgId = OM.Id
		INNER JOIN sAssessment.tResult R ON A.Id=R.AcademicId
		INNER JOIN sAssessment.tResultDetail RD ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		INNER JOIN sAssessment.tExamTypeMaster ETM ON ETM.Id=ESGM.ExamTypeId
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
		INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
		INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId	
		INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId

		WHERE		
			ETM.Id=@rExamId
			AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
			AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
			AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit (@rStrOrgId,','))OR @rStrOrgId='')
			AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrDepartmentId,','))OR @rStrDepartmentId='')
			AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit  (@rStrClassId,','))OR @rStrClassId='')
			AND BM.OrgGroupBatchId = @rOrgGroupBatchId


END
GO
PRINT N'Altering Procedure [sPurchase].[pGoodsReceivedNoteApprovedGet]...';


GO

ALTER PROCEDURE [sSecurity].[pAppPermissionGet]
	@rOrgGroupId [int],
	@rUserId [bigint]
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@rOrgGroupId)

	BEGIN
	
		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]
		FROM
		(
			SELECT 	
				P.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]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard 
			20097, -- View Query
			30249, -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786, --Online Learning 
			30787, --Online learning Student View
			30815, --Consolidate - Fee Status
			30813, --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,   -- Consolidate - Admission Inquiry Summary,
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App 
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,   -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,   -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,  -- Is Activity Entry View
			20556,  -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			,30600 -- MIS Consolidate DashBoard
			,31193 -- Consolidate - Admission Inquiry And Admission Form
			,31194 -- Consolidate - Staff Count
			,31195 -- Consolidate - Charge Receipt
			,31244 -- Lesson Plan Complete
			,20776 -- Front office --Student Gate Pass
			,31305 --Consolidate - Staff Biometric Attendance
			,31314 -- Event Attendance Student Wise
			,31323 -- Poll Result
			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		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]
		FROM
		(
			SELECT 	
				P.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]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769, -- Exam Schedule Dashboard
			20097, -- View Query
			30249,  -- Classwork/Homework
			30788, -- Online Learning - Teacher
			30792, -- Online Learning Admin View
			30786 , --Online Learning 
			30787,  --Online learning Student View
			30815,  --Consolidate - Fee Status
			30813,  --My Chat - OnlineLearning
			30862,  --Manage Mobile Account
			30900,  -- Close Query
			30927,  -- Classwork Homework Queue Search All
			30930,  -- Consolidate - Admission Inquiry Summary
			30933,   -- Biometric Punch
			20284,   --Visitor Gate Pass
			30646,   -- Mark Entry From App
			30944,   -- Circular - Data Search
			30945,   -- Assignment Data Search
			30946,   -- Lesson Data Search
			30947,   -- CW/HW Data Search
			30951,    -- Visitor Log Listing
			30861,   -- Consolidate - Student Subject Attendance
			30505,    -- Consolidate - Student Attendance			
			30983,    -- Consolidate - Fee Details Status
			20080,   -- AdmissionInquiry
			30994,   -- AttendanceFollowup
			20556,    -- HostelStudentGatePass
			20934,   -- CS Exam Mark Entry Bulk
			20710,   -- CS Exam Grade Entry Bulk
			20478,   -- CS Exam Indicator Entry Bulk
			20749,   -- Activity Mark Entry Bulk
			20745,   -- Activity Grade Score Bulk
			20746,   -- Activity Indicator Score Bulk
			31007,   -- Is Mark Entry View
			31008,  -- Is CS Entry View
			31009,   -- Is Activity Entry View
			20556,   -- Hostel Student Gate Pass
			31005,	-- My Digital Form
			20183, -- View Photo
			30580, -- Employee Attendance Summary
			20056, -- Event Schedule
			31033, --My Proxy
			20687, --  Employee Attendance
			31043 --  Pending Fee
			,30943 -- My Approval Request
			,30739 -- Behaviour Entry User Wise
			,31048 -- Add Gallery
			,31175 -- View Gallery
			,31179 -- Leave Hierarchy Listing
			,30331 -- My Exam Schedule
			,31182 -- My Admit Card
			,30600 -- MIS Consolidate DashBoard
			,31193 -- Consolidate - Admission Inquiry And Admission Form
			,31194 -- Consolidate - Staff Count
			,31195 -- Consolidate - Charge Receipt
			,31244 -- Lesson Plan Complete
			,20776 -- Front office --Student Gate Pass
			,31305 --Consolidate - Staff Biometric Attendance
			,31314 -- Event Attendance Student Wise
			,31323 -- Poll Result
			) 
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering Procedure [sSecurity].[pScreenGroupDataListGet]...';


GO
ALTER PROCEDURE [sSecurity].[pScreenGroupDataListGet]

	@rUserId [bigint]

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lOrgGroupId bigint , @lConfigValue nvarchar(10) = ''

IF EXISTS (SELECT OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId)
BEGIN
	SELECT @lOrgGroupId = OM.OrgGroupId FROM sSecurity.tUser U INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U.OrgId WHERE U.Id = @rUserId
		
	SELECT @lConfigValue = ISNULL(CS.ItemValue,'False') FROM sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id=CS.Configurationid AND CS.SourceId= @lOrgGroupId AND CS.SourceTypeId=2010 WHERE CM.Id = 327

		IF(@lConfigValue = 'True')
		BEGIN
		     IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962,20080,31002,31005,31015,30580,31023,31033,31038,31043,31048,31175,31188,20776)
				END
			ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
					AND T.Id IN (20085,20086,30401,30222,20762,20091,20184,20183,20054,20621,20056,20199,
					30228,20693,20692,20241,20563,20561,30249,20622,143,9072,144,20249,20223,20270,20246,20001,20002,20003,20004,20007,20285,20323,20616,20055,
					139,20175,20176,141,142,20158, 30499,20309,20021,20312,20269,30299,10187,20716,20268,20968,20216,20215,20962,20080,31002,31005,31015,30580,310235,31033,31038,31043,31048,31175,31179,30331,31182,31188,20776,31314,31295)
				END
		END
		ELSE
		BEGIN
			  IF EXISTS (SELECT 1 FROM sSecurity.tPermissionUser WHERE UserId=@rUserId AND OrgGroupId=@lOrgGroupId)
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermissionUser P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T.ModuleId AND MP.OrgGroupId=@lOrgGroupId
					WHERE (P.Permission & 2) =2 AND P.OrgGroupId = @lOrgGroupId AND T.IsObsolete = 0 AND P.UserId=@rUserId
				END
			  ELSE
				BEGIN
					SELECT S.Id AS Id,LEFT(S.Title,32) AS Title 
					From sSecurity.tScreen S 
					INNER JOIN sSecurity.tPermission P ON P.TaskId=S.TaskId 
					INNER JOIN sSecurity.tUserRole U ON U.RoleId=P.RoleId 
					INNER JOIN sSecurity.tTask T ON T.ID = p.TaskId 
					INNER JOIN sSecurity.tOrganizationTask OT ON T.Id = OT.TaskId AND OT.OrgGroupId = P.OrgGroupId 
					WHERE (P.Permission & 2) =2 AND U.IsObsolete=0 AND T.IsObsolete = 0 AND U.UserId=@rUserId
				END
		END
END

END
GO
PRINT N'Altering Procedure [sStudent].[pDigitalFormFieldApprove]...';


GO


ALTER PROCEDURE [sStudent].[pDigitalFormFieldApprove]
			@rId Bigint = 0,
			@rUpdateFieldId int=0,
			@rOldValue NVarchar(500)='',
			@rNewValue NVarchar(500)='',
			@rActionRemark nvarchar(500) = '',
			@rActionUserId BigInt,
			@rActionDateTime DateTime,
			@rStatusId int,
			@rRequestId int =0,
			@rOldValueImage varbinary(MAX) = 0x00000000,
			@rNewValueImage varbinary(MAX) = 0x00000000
			 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

		IF EXISTS(SELECT 1 FROM sStudent.vStudentAcademic WHERE AcademicId = @rId)
		BEGIN
		    
			DECLARE @lResult int
			DECLARE @lDataTypeId nvarchar(1)
			SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Id=@rUpdateFieldId

			IF(@lDataTypeId = 4)
			BEGIN
				SET @rNewValue = CONVERT(datetime,@rNewValue,104)
				SET @rOldValue = CONVERT(datetime,@rOldValue,104)
			END

			DECLARE @lUpdateField NVARCHAR(100)
			DECLARE @lUpdateFieldImage varbinary(MAX)
			DECLARE @lSubFunctionality NVARCHAR(100)
			DECLARE @lStudentId BigInt

			SET @lUpdateField = (SELECT Field FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)

			SET @lSubFunctionality = (SELECT SubFunctionalityName FROM sCommon.tUpdateFieldMaster WHERE Id = @rUpdateFieldId)
			SET @lStudentId = (SELECT StudentId FROM sStudent.vStudentAcademic WHERE AcademicId = @rId)

			IF(@lUpdateField = 'Gender' OR @lUpdateField = 'Religion' OR @lUpdateField = 'BloodGroup' 
			 OR @lUpdateField = 'TransportMode' OR @lUpdateField = 'House' OR @lUpdateField = 'Quota' 
			OR @lUpdateField = 'Nationality'  OR @lUpdateField = 'AdmissionStandard' OR  @lUpdateField = 'AdmissionCategory' OR @lUpdateField = 'AdmissionQuota' OR @lUpdateField = 'Tribe')
			BEGIN
			SET @lUpdateField =@lUpdateField + 'Id'
			END

			IF(@lUpdateField = 'CasteCategory' )
			BEGIN
			SET @lUpdateField = Replace(@lUpdateField,'Caste','Cast') + 'Id'
			END
			
			IF(	@lUpdateField = 'FamilyCaste' )
			BEGIN
				SET @lUpdateField = Replace(@lUpdateField,'Caste','Cast')  
			END
	
			IF(	@lUpdateField = 'StudentGroup' )
			BEGIN
				SET @lUpdateField = Replace(@lUpdateField,'StudentGroup','StudentGroupId')  
			END
			IF(	@lUpdateField = 'StudentOtherGroup' )
			BEGIN
				SET @lUpdateField = Replace(@lUpdateField,'StudentOtherGroup','StudentOtherGroupId')  
			END
	
			IF(@lUpdateField = 'FeeCategory' )
			BEGIN
				SET @lUpdateField = Replace(@lUpdateField,'FeeCategory','AdmissionCategory') + 'Id'
			END

			IF(@lUpdateField = 'FatherAnnualIncome' )											-- #Start Mantis Id : 0029214
			BEGIN
				SET @lUpdateField = Replace(@lUpdateField,'FatherAnnualIncome','FatherIncome')
			END
			IF(@lUpdateField = 'MotherAnnualIncome' )
			BEGIN
				SET @lUpdateField = Replace(@lUpdateField,'MotherAnnualIncome','MotherIncome')
			END																					
			IF(@lUpdateField = 'RelativeAnnualIncome' )
			BEGIN
				SET @lUpdateField = Replace(@lUpdateField,'RelativeAnnualIncome','RelativeIncome')
			END																					-- #End Mantis Id : 0029214

			Declare @Sql nvarchar(max)

			IF OBJECT_ID('ListofData') IS NOT NULL	
			BEGIN 
				DROP TABLE ListofData
			END	
			
			IF(@rStatusId = 550)
				BEGIN

				IF(@lSubFunctionality = 'StudentImages')
				BEGIN
					
					IF(@lUpdateField = 'StudentImage')
					BEGIN
						SET @lUpdateField = 'StudentPhoto'
					END
					 
					 IF(@lUpdateField = 'FatherImage')
					BEGIN
						SET @lUpdateField = 'FatherPhoto'
					END

					IF(@lUpdateField = 'MotherImage')
					BEGIN
						SET @lUpdateField = 'MotherPhoto'
					END

					IF(@lUpdateField = 'RelativeImage')
					BEGIN
						SET @lUpdateField = 'RelativePhoto'
					END
				CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory varbinary(MAX),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rNewValueImage,@rActionUserId,0)

			
			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentImages)
			
			
			set @sql='INSERT INTO sStudent.tStudentImages 
							(StudentId,'+@lUpdateField+',Original'+@lUpdateField+',UpdatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,Ld.SubCategory,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sStudent.tStudentImages  set '+@lUpdateField+' = LD.SubCategory,
							Original'+@lUpdateField+' = LD.SubCategory,
							UpdatedDateTime=sCommon.fGetDate()  
							from sStudent.tStudentImages  SI 
							INNER JOIN ListofData LD ON SI.StudentId=LD.StudentId AND IsExist=0'
		
				Exec sp_executesql @sql

				DROP TABLE ListofData
				SET @lResult = 1;
				--SELECT 1 AS StatusCode
			END
			ELSE
			BEGIN
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rNewValue,@rActionUserId,0)

			

			
			IF(@lSubFunctionality = 'Communication')  ----Communication
				BEGIN
			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication)
				set @sql='INSERT INTO sStudent.tStudentCommunication 
							(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sStudent.tStudentCommunication set '+@lUpdateField+' = LD.SubCategory,
							UpdatedUserId=LD.UpdatedUserId,
							UpdatedDateTime=sCommon.fGetDate()  
							from sStudent.tStudentCommunication SC 
							INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
				Exec sp_executesql @sql
	
		
				Drop Table ListofData
					 SET @lResult = 1;
				END

			
			Else IF(@lSubFunctionality = 'Other')         -------Other
				BEGIN
				UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentOther) 
					IF(@lUpdateField = 'DateOfBirth')
					BEGIN			
						set @sql='INSERT INTO sStudent.tStudentOther 
								(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sStudent.tStudentOther set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentOther SO 
									INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sStudent.tStudentOther SET '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE
					BEGIN
						set @sql='INSERT INTO sStudent.tStudentOther 
									(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sStudent.tStudentOther set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentOther SO 
									INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'
			
						Exec sp_executesql @sql
					END
					Drop Table ListofData
						 SET @lResult = 1;
				 END	

				Else IF(@lSubFunctionality = 'Admission')		--------Admission
					BEGIN
					set @sql='UPDATE sStudent.tStudentAdmission set '+@lUpdateField+' = LD.SubCategory,
								UpdatedUserId=LD.UpdatedUserId,
								UpdatedDateTime=sCommon.fGetDate()  
								from sStudent.tStudentAdmission SA 
								INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId'
		
					Exec sp_executesql @sql
					IF(@lUpdateField = 'AdmissionDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tStudentAdmission SET '+@lUpdateField+' = null WHERE AdmissionDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
		
					IF(@lUpdateField = 'PreviousLCDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tStudentAdmission SET '+@lUpdateField+' = null WHERE PreviousLCDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					
					Drop Table ListofData
							SET @lResult = 1;
					END	

				Else IF(@lSubFunctionality = 'Family')			---------Family
					BEGIN
						
						UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
						set @sql='INSERT INTO sStudent.tStudentFamily 
									(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofData LD WHERE LD.IsExist=1'				
						Exec sp_executesql @sql
						set @sql='UPDATE sStudent.tStudentFamily set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentFamily SA 
									INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
						Exec sp_executesql @sql
						
						IF(@lUpdateField = 'FatherDateOfBirth' )
						BEGIN
						SET @sql='UPDATE sStudent.tStudentFamily SET '+@lUpdateField+' = null WHERE FatherDateOfBirth=''1900-01-01'''
							Exec sp_executesql @sql
						END
		
						IF(@lUpdateField = 'MotherDateOfBirth' )
						BEGIN
						SET @sql='UPDATE sStudent.tStudentFamily SET '+@lUpdateField+' = null WHERE MotherDateOfBirth=''1900-01-01'''
							Exec sp_executesql @sql
						END

						IF(@lUpdateField = 'RelativeDateOfBirth' )
						BEGIN
						SET @sql='UPDATE sStudent.tStudentFamily SET '+@lUpdateField+' = null WHERE RelativeDateOfBirth=''1900-01-01'''
							Exec sp_executesql @sql
						END		
						Drop Table ListofData
							 SET @lResult = 1;
						END
			 Else IF(@lSubFunctionality = 'Health')	   ----------General
					 BEGIN

					 UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentHealth) 
					 set @sql='INSERT INTO sStudent.tStudentHealth 
								(StudentId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofData LD WHERE LD.IsExist=1'				
					Exec sp_executesql @sql
					 
					 set @sql='UPDATE sStudent.tStudentHealth set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentHealth SA 
									INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'

						Exec sp_executesql @sql
					  
						 Drop Table ListofData
							 SET @lResult = 1;
					END
			   Else IF(@lSubFunctionality = 'AcademicDetail')	   ----------General
					 BEGIN
					 UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
						set @sql='INSERT INTO sStudent.tAcademicDetail 
								(AcademicId,'+@lUpdateField+')
								SELECT
									LD.Id,Ld.SubCategory
								FROM
									ListofData LD WHERE LD.IsExist=1'				
					Exec sp_executesql @sql
		
					set @sql='UPDATE sStudent.tAcademicDetail set '+@lUpdateField+' = LD.SubCategory
								from sStudent.tAcademicDetail AD 
								INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
					Exec sp_executesql @sql
		
					IF(@lUpdateField = 'BatchAdmissionDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tAcademicDetail SET '+@lUpdateField+' = NULL WHERE BatchAdmissionDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					Drop Table ListofData
						 SET @lResult = 1;
					END	
			  Else IF(@lSubFunctionality = 'General')	   ----------General
					 BEGIN
						IF(@lUpdateField != 'AdmissionCategoryId')
						BEGIN
							
							UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
			
							set @sql='UPDATE sStudent.tStudentMaster set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sStudent.tStudentMaster SA 
										INNER JOIN ListofData LD ON SA.Id=LD.StudentId AND IsExist=0'
			
							Exec sp_executesql @sql
							Drop Table ListofData
						END
						IF(@lUpdateField = 'AdmissionCategoryId')
						BEGIN
							set @sql='UPDATE sStudent.tAcademic set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sStudent.tAcademic A 
										INNER JOIN ListofData LD ON A.Id=LD.Id AND IsExist=0'
			
							Exec sp_executesql @sql
							Drop Table ListofData
		
						END
						 SET @lResult = 1;
					END			 
			Else IF(@lSubFunctionality= 'AdditionalInformation')
				 BEGIN
	      
				UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
				set @sql='INSERT INTO sStudent.tStudentAdditional
							(StudentId,'+@lUpdateField+')
							SELECT
								LD.StudentId,Ld.SubCategory
							FROM
								ListofData LD WHERE LD.IsExist=1'				
				Exec sp_executesql @sql
		
				set @sql='UPDATE sStudent.tStudentAdditional set '+@lUpdateField+' = LD.SubCategory 
					 
							from sStudent.tStudentAdditional SA 
							INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
					
				Exec sp_executesql @sql
					
				IF(@lUpdateField = 'PassportIssueDate' )
				BEGIN
				SET @sql='UPDATE sStudent.tStudentAdditional SET '+@lUpdateField+' = null WHERE PassportIssueDate=''1900-01-01'''
					Exec sp_executesql @sql
				END
		
				IF(@lUpdateField = 'PassportExpiryDate' )
				BEGIN
				SET @sql='UPDATE sStudent.tStudentAdditional SET '+@lUpdateField+' = null WHERE PassportExpiryDate=''1900-01-01'''
					Exec sp_executesql @sql
				END						
		
				Drop Table ListofData
				--SELECT 1 AS StatusCode
				SET @lResult = 1;
				END					
			 Else IF(@lSubFunctionality= 'StudentSibling')
				BEGIN
				 
				UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
				set @sql='INSERT INTO sStudent.tStudentSibling
							(StudentId,'+@lUpdateField+')
							SELECT
								LD.StudentId,Ld.SubCategory
							FROM
								ListofData LD WHERE LD.IsExist=1'				
				Exec sp_executesql @sql
		
				set @sql='UPDATE sStudent.tStudentSibling set '+@lUpdateField+' = LD.SubCategory 
					 
							from sStudent.tStudentSibling SS 
							INNER JOIN ListofData LD ON SS.StudentId=LD.StudentId AND IsExist=0'
					
				Exec sp_executesql @sql
				
				Drop Table ListofData
				--SELECT 1 AS StatusCode
				SET @lResult = 1;
				END
				
			END	
			IF(@lResult = 1)
			BEGIN
				UPDATE sStudent.tDigitalFormStudent
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			
			SELECT 1 AS Result
			END
ELSE IF(@rStatusId = 551)
			BEGIN

			IF(@lSubFunctionality = 'StudentImages')
			BEGIN
			
			IF(@lUpdateField = 'StudentImage')
			BEGIN
				SET @lUpdateField = 'StudentPhoto'
			END
			 IF(@lUpdateField = 'FatherImage')
			BEGIN
				SET @lUpdateField = 'FatherPhoto'
			END

			IF(@lUpdateField = 'MotherImage')
			BEGIN
				SET @lUpdateField = 'MotherPhoto'
			END

			IF(@lUpdateField = 'RelativeImage')
			BEGIN
				SET @lUpdateField = 'RelativePhoto'
			END

				CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory varbinary(MAX),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rOldValueImage,@rActionUserId,0)

			
			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentImages)
			
			
			set @sql='INSERT INTO sStudent.tStudentImages 
							(StudentId,'+@lUpdateField+',Original'+@lUpdateField+',UpdatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,LD.SubCategory,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				--set @sql='UPDATE sStudent.tStudentImages  set '+@lUpdateField+' = LD.SubCategory,
				--			Original'+@lUpdateField+' = LD.SubCategory,
				--			UpdatedDateTime=sCommon.fGetDate()  
				--			from sStudent.tStudentImages  SI 
				--			INNER JOIN ListofData LD ON SI.StudentId=LD.StudentId AND IsExist=0'
		
				Exec sp_executesql @sql

				DROP TABLE ListofData
				SET @lResult = 1;
				
			END
			ELSE
			BEGIN
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rOldValue,@rActionUserId,0)

			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication)

			
			IF(@lSubFunctionality = 'Communication')  ----Communication
				BEGIN
			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication)
				set @sql='INSERT INTO sStudent.tStudentCommunication 
							(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sStudent.tStudentCommunication set '+@lUpdateField+' = LD.SubCategory,
							UpdatedUserId=LD.UpdatedUserId,
							UpdatedDateTime=sCommon.fGetDate()  
							from sStudent.tStudentCommunication SC 
							INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
				Exec sp_executesql @sql
	
		
				Drop Table ListofData
					 SET @lResult = 1;
				END

			Else IF(@lSubFunctionality = 'Other')         -------Other
				BEGIN
				UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentOther) 
					IF(@lUpdateField = 'DateOfBirth')
					BEGIN			
						set @sql='INSERT INTO sStudent.tStudentOther 
								(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
								SELECT
									LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sStudent.tStudentOther set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentOther SO 
									INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'			
						Exec sp_executesql @sql
						set @sql='UPDATE sStudent.tStudentOther SET '+@lUpdateField+' = null WHERE DateOfBirth=''1900-01-01'''
						Exec sp_executesql @sql
					END
					ELSE
					BEGIN
						set @sql='INSERT INTO sStudent.tStudentOther 
									(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofData LD WHERE LD.IsExist=1'
						Exec sp_executesql @sql				
			 				
						set @sql='UPDATE sStudent.tStudentOther set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentOther SO 
									INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'
			
						Exec sp_executesql @sql
					END
					Drop Table ListofData
						 SET @lResult = 1;
				 END	

				Else IF(@lSubFunctionality = 'Admission')		--------Admission
					BEGIN
					set @sql='UPDATE sStudent.tStudentAdmission set '+@lUpdateField+' = LD.SubCategory,
								UpdatedUserId=LD.UpdatedUserId,
								UpdatedDateTime=sCommon.fGetDate()  
								from sStudent.tStudentAdmission SA 
								INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId'
		
					Exec sp_executesql @sql
					IF(@lUpdateField = 'AdmissionDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tStudentAdmission SET '+@lUpdateField+' = null WHERE AdmissionDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
		
					IF(@lUpdateField = 'PreviousLCDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tStudentAdmission SET '+@lUpdateField+' = null WHERE PreviousLCDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					
					Drop Table ListofData
							SET @lResult = 1;
					END	

				Else IF(@lSubFunctionality = 'Family')			---------Family
					BEGIN
						
						UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
						set @sql='INSERT INTO sStudent.tStudentFamily 
									(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
									SELECT
										LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
									FROM
										ListofData LD WHERE LD.IsExist=1'				
						Exec sp_executesql @sql
						set @sql='UPDATE sStudent.tStudentFamily set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentFamily SA 
									INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
						Exec sp_executesql @sql
						
						IF(@lUpdateField = 'FatherDateOfBirth' )
						BEGIN
						SET @sql='UPDATE sStudent.tStudentFamily SET '+@lUpdateField+' = null WHERE FatherDateOfBirth=''1900-01-01'''
							Exec sp_executesql @sql
						END
		
						IF(@lUpdateField = 'MotherDateOfBirth' )
						BEGIN
						SET @sql='UPDATE sStudent.tStudentFamily SET '+@lUpdateField+' = null WHERE MotherDateOfBirth=''1900-01-01'''
							Exec sp_executesql @sql
						END

						IF(@lUpdateField = 'RelativeDateOfBirth' )
						BEGIN
						SET @sql='UPDATE sStudent.tStudentFamily SET '+@lUpdateField+' = null WHERE RelativeDateOfBirth=''1900-01-01'''
							Exec sp_executesql @sql
						END		
						Drop Table ListofData
							 SET @lResult = 1;
						END
			 Else IF(@lSubFunctionality = 'Health')	   ----------General
					 BEGIN

					 UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentHealth) 
					 set @sql='INSERT INTO sStudent.tStudentHealth 
								(StudentId,'+@lUpdateField+',UpdatedUserId,UpdatedDateTime)
								SELECT
									LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
								FROM
									ListofData LD WHERE LD.IsExist=1'				
					Exec sp_executesql @sql
					 
					 set @sql='UPDATE sStudent.tStudentHealth set '+@lUpdateField+' = LD.SubCategory,
									UpdatedUserId=LD.UpdatedUserId,
									UpdatedDateTime=sCommon.fGetDate()  
									from sStudent.tStudentHealth SA 
									INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'

						Exec sp_executesql @sql
					  
						 Drop Table ListofData
							 SET @lResult = 1;
					END
			   Else IF(@lSubFunctionality = 'AcademicDetail')	   ----------General
					 BEGIN
					 UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
						set @sql='INSERT INTO sStudent.tAcademicDetail 
								(AcademicId,'+@lUpdateField+')
								SELECT
									LD.Id,Ld.SubCategory
								FROM
									ListofData LD WHERE LD.IsExist=1'				
					Exec sp_executesql @sql
		
					set @sql='UPDATE sStudent.tAcademicDetail set '+@lUpdateField+' = LD.SubCategory
								from sStudent.tAcademicDetail AD 
								INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
					Exec sp_executesql @sql
		
					IF(@lUpdateField = 'BatchAdmissionDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tAcademicDetail SET '+@lUpdateField+' = NULL WHERE BatchAdmissionDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					Drop Table ListofData
						 SET @lResult = 1;
					END	
			  Else IF(@lSubFunctionality = 'General')	   ----------General
					 BEGIN
						IF(@lUpdateField != 'AdmissionCategoryId')
						BEGIN
							
							UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
			
							set @sql='UPDATE sStudent.tStudentMaster set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sStudent.tStudentMaster SA 
										INNER JOIN ListofData LD ON SA.Id=LD.StudentId AND IsExist=0'
			
							Exec sp_executesql @sql
							Drop Table ListofData
						END
						IF(@lUpdateField = 'AdmissionCategoryId')
						BEGIN
							set @sql='UPDATE sStudent.tAcademic set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sStudent.tAcademic A 
										INNER JOIN ListofData LD ON A.Id=LD.Id AND IsExist=0'
			
							Exec sp_executesql @sql
							Drop Table ListofData
		
						END
						 SET @lResult = 1;
					END			 
			Else IF(@lSubFunctionality= 'AdditionalInformation')
				 BEGIN
	      
				UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
				set @sql='INSERT INTO sStudent.tStudentAdditional
							(StudentId,'+@lUpdateField+')
							SELECT
								LD.StudentId,Ld.SubCategory
							FROM
								ListofData LD WHERE LD.IsExist=1'				
				Exec sp_executesql @sql
		
				set @sql='UPDATE sStudent.tStudentAdditional set '+@lUpdateField+' = LD.SubCategory 
					 
							from sStudent.tStudentAdditional SA 
							INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
					
				Exec sp_executesql @sql
					
				IF(@lUpdateField = 'PassportIssueDate' )
				BEGIN
				SET @sql='UPDATE sStudent.tStudentAdditional SET '+@lUpdateField+' = null WHERE PassportIssueDate=''1900-01-01'''
					Exec sp_executesql @sql
				END
		
				IF(@lUpdateField = 'PassportExpiryDate' )
				BEGIN
				SET @sql='UPDATE sStudent.tStudentAdditional SET '+@lUpdateField+' = null WHERE PassportExpiryDate=''1900-01-01'''
					Exec sp_executesql @sql
				END						
		
				Drop Table ListofData
					 SET @lResult = 1;
				END	
			 Else IF(@lSubFunctionality= 'StudentSibling')
				BEGIN
				 
				UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
				set @sql='INSERT INTO sStudent.tStudentSibling
							(StudentId,'+@lUpdateField+')
							SELECT
								LD.StudentId,Ld.SubCategory
							FROM
								ListofData LD WHERE LD.IsExist=1'				
				Exec sp_executesql @sql
		
				set @sql='UPDATE sStudent.tStudentSibling set '+@lUpdateField+' = LD.SubCategory 
					 
							from sStudent.tStudentSibling SS 
							INNER JOIN ListofData LD ON SS.StudentId=LD.StudentId AND IsExist=0'
					
				Exec sp_executesql @sql
		
		
		
				Drop Table ListofData
					 SET @lResult = 1;
				END			 
			END
			IF(@lResult = 1)
			BEGIN
				UPDATE sStudent.tDigitalFormStudent
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 2 AS Result
			END
		END
		ELSE
		BEGIN
		   SELECT -101 As Result
		END
		
		COMMIT TRANSACTION

		END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
		
END
GO
PRINT N'Altering Procedure [sStudent].[pDigitalFormFieldDetailGet]...';


GO

 
ALTER PROCEDURE [sStudent].[pDigitalFormFieldDetailGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(500),
	 @rAcademicId bigint,
	 @rIsBlank bit = 0

AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		 
		IF(@rSubCategory = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup' 
			OR @rSubCategory = 'TransportMode' OR @rSubCategory = 'House'
			OR @rSubCategory = 'Quota' OR @rSubCategory = 'Nationality' OR @rSubCategory = 'AdmissionStandard' OR  @rSubCategory = 'AdmissionCategory'
			OR @rSubCategory = 'AdmissionQuota' OR @rSubCategory = 'Tribe')
		BEGIN
			 
			SET @rSubCategory =@rSubCategory + 'Id'
			 -- print @rSubCategory
		END
		IF(@rSubCategory = 'CasteCategory' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') + 'Id'
		END
		
			IF(@rSubCategory = 'FamilyCaste' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') 
		END
		IF(@rSubCategory = 'StudentGroup' OR @rSubCategory='StudentOtherGroup')
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory ,'StudentGroup','StudentGroupId')
			SET @rSubCategory = Replace(@rSubCategory ,'StudentOtherGroup','StudentOtherGroupId')
		END
		
		IF(@rSubCategory = 'FeeCategory' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'FeeCategory','AdmissionCategory') + 'Id'
		END
		
		IF(@rSubCategory = 'FatherAnnualIncome' )											-- #Start Mantis Id : 0029214
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'FatherAnnualIncome','FatherIncome')
		END
		IF(@rSubCategory = 'MotherAnnualIncome' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'MotherAnnualIncome','MotherIncome')
		END																					
		IF(@rSubCategory = 'RelativeAnnualIncome' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'RelativeAnnualIncome','RelativeIncome')
		END	
																							-- #End Mantis Id : 0029214
		 Declare @Sql nvarchar(max)
		 Declare @Sql1 nvarchar(max)
		 
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- Communication
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SC.'+@rSubCategory+','''') 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SC.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SC.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SC.'+@rSubCategory+',''0001/01/01'') 
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SC.'+@rSubCategory+',''0'') 
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
							Where SA.AcademicId='+CAST(@rAcademicId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							 '
							
					 WHEN 2 THEN -- Other
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SO.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SO.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SO.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						SO.'+@rSubCategory+'
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SO.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
							Where SA.AcademicId='+CAST(@rAcademicId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SO.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SO.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SO.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SO.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
							
					WHEN 3 THEN -- Admission
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAD.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAD.'+@rSubCategory+',''0'')
						END AS SubCategory 
							FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
							Where SA.AcademicId='+CAST(@rAcademicId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					 
					WHEN 4 THEN --Family
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAF.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAF.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAF.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAF.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAF.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentFamily SAF ON SAF.StudentId=SA.StudentId
							Where SA.AcademicId='+CAST(@rAcademicId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAF.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAF.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAF.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAF.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
				   
					WHEN 5 THEN --Health
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAH.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAH.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentHealth SAH ON SAH.StudentId=SA.StudentId
							Where SA.AcademicId='+CAST(@rAcademicId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					WHEN 6 THEN --Academic Detail
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(AD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(AD.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(AD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(AD.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(AD.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(AD.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=SA.AcademicId
							Where SA.AcademicId='+CAST(@rAcademicId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(AD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(AD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(AD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(AD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					--WHEN 7 THEN --General
						
					--   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
					--	CASE WHEN '+@lDataTypeId+'=1 THEN
					--	ISNULL(SAH.'+@rSubCategory+','''')
					--	WHEN '+@lDataTypeId+'=2 THEN
					--	ISNULL(SAH.'+@rSubCategory+',''0'')
					--	WHEN '+@lDataTypeId+'=3 THEN
					--	ISNULL(SAH.'+@rSubCategory+',''False'')
					--	WHEN '+@lDataTypeId+'=4 THEN
					--	ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
					--	WHEN '+@lDataTypeId+'=5 THEN
					--	ISNULL(SAH.'+@rSubCategory+',''0'')
					--	END AS SubCategory
					--		FROM 
					--		sStudent.vStudentAcademic SA
					--		LEFT JOIN sStudent.tStudentMaster SAH ON SAH.Id=SA.StudentId
					--		Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
					--		+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
					--		AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
					--		AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
					--		AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
					--		AND 
					--		('+CAST(@rIsBlank AS nvarchar(1))+'=0 
					--			OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
					--			OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
					--			OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
					--			OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
					--		)'
					WHEN 8 THEN --Additonal Information
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAH.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAH.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentAdditional SAH ON SAH.StudentId=SA.StudentId
							Where SA.AcademicId='+CAST(@rAcademicId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'	
					
					WHEN 9 THEN --Student Sibling
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SS.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SS.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SS.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SS.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SS.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentSibling SS ON SS.StudentId=SA.StudentId
							Where SA.AcademicId='+CAST(@rAcademicId AS nvarchar(15))+'
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SS.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SS.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SS.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SS.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'	
					END				
					
			SET @Sql1 =  CASE
			WHEN @rCategoryId = 7 --AND @rSubCategory='AdmissionCategoryId'
			THEN 
			'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
			CASE WHEN '+@lDataTypeId+'=1 THEN
			ISNULL(SA.'+@rSubCategory+','''')
			WHEN '+@lDataTypeId+'=2 THEN
			ISNULL(SA.'+@rSubCategory+',''0'')
			WHEN '+@lDataTypeId+'=3 THEN
			ISNULL(SA.'+@rSubCategory+',''False'')
			WHEN '+@lDataTypeId+'=4 THEN
			ISNULL(SA.'+@rSubCategory+',''0001/01/01'')
			WHEN '+@lDataTypeId+'=5 THEN
			ISNULL(SA.'+@rSubCategory+',''0'')
			END AS SubCategory
			FROM 
			sStudent.vStudentAcademic SA
			LEFT JOIN sStudent.tStudentMaster SAH ON SAH.Id=SA.StudentId
			Where SA.AcademicId='+CAST(@rAcademicId AS nvarchar(15))+'
			AND 
			('+CAST(@rIsBlank AS nvarchar(1))+'=0 
			OR ('+@lDataTypeId+'=1 AND ISNULL(SA.'+@rSubCategory+','''')='''')
			OR ('+@lDataTypeId+'=2 AND ISNULL(SA.'+@rSubCategory+',''0'')=''0'')
			OR ('+@lDataTypeId+'=3 AND ISNULL(SA.'+@rSubCategory+',''False'')=''False'')
			OR ('+@lDataTypeId+'=4 AND ISNULL(SA.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
			)'
			END
	   if(@Sql1 IS NOT NULL)		
			EXECUTE  sp_executesql @Sql1
	   else
			EXECUTE  sp_executesql @Sql
	   
END
GO
PRINT N'Altering Procedure [sStudent].[ppImportStudent_Update_Dynamicly]...';


GO

ALTER proc [sStudent].[ppImportStudent_Update_Dynamicly]
@rOrgId int,
@rCreatedUserId bigint,
@rCode nvarchar(20) = '', 
@rFirstName nvarchar(100) = '',
@rMiddleName nvarchar(100) = '',
@rLastName nvarchar(100) = '',
@rGender nvarchar(20) = '',
@rAdmissionStandard nvarchar(100) = '',
@rAdmissionCategory nvarchar(100) = '',
@rAdmissionYear nvarchar(10) = '',
@rAdmissionDate datetime = '',
@rLeftStandard nvarchar(100) = '',
@rLeftDate datetime = '',
@rLeftYear nvarchar(10) = '',
@rLeftReason nvarchar(200) = '',
@rPreviousSchool nvarchar(200) = '',
@rDateOfBirth datetime = '',
@rBirthPlace nvarchar(150) = '',
@rBloodGroup nvarchar(20) = '',
@rBirthTaluka nvarchar(150) = '',
@rBirthDistrict nvarchar(150) = '',
@rFamilySubCast nvarchar(100) = '',
@rFamilyCast nvarchar(100) = '',
@rCastCatagory nvarchar(50) = '',
@rMotherTongue nvarchar(100) = '',
@rNationality nvarchar(50) = '',
@rReligion nvarchar(50) = '',
@rHobby nvarchar(50) = '',
@rFatherName nvarchar(100)='',
@rFatherContactNo nvarchar(50)='',
@rFatherDateOfBirth datetime = '',
@rFatherOccupation nvarchar(50)='',
@rFatherQualification nvarchar(50)='',
@rFatherMail nvarchar(50)='',
@rFatherOfficeAddress nvarchar(500)='',
@rFatherIncome int=0,
@rMotherDateOfBirth datetime = '',
@rMothername nvarchar(100)='',
@rMotherContactNo nvarchar(50)='',
@rMotherOccupation nvarchar(50)='',
@rMotherQualification nvarchar(50)='',
@rMotherMail nvarchar(50)='',
@rMotherOfficeAddress nvarchar(100)='',
@rMotherIncome int=0,
@rRelationshipName nvarchar(100)='',
@rRelativeName nvarchar(100)='',
@rRelativeDateOfBirth datetime='',
@rRelativeOccupation nvarchar(50)='',
@rRelativeQualification	nvarchar(50)='',
@rRelativeContactNo	nvarchar(50)='',
@rRelativeMail nvarchar(50)='',
@rRelativeOfficeAddress nvarchar(500)='',
@rRelativeIncome int=0,
@rPresentStreetOne nvarchar(150)='',
@rPresentStreetTwo nvarchar(150)='',
@rPresentStreetThree nvarchar(150)='',
@rPresentCity nvarchar(50)='',
@rPresentZipCode nvarchar(20)='',
@rPresentState nvarchar(50)='',
@rPresentCountry nvarchar(50)='',
@rPresentContactNo nvarchar(20)='', 
@rParentEmail nvarchar(50)='',
@rStudentContactNo  nvarchar(50)='',
@rStudentEmail nvarchar(50)='', 
@rAccountNumber nvarchar(20)='',
@rBankName nvarchar(100)=0,
@rBranch nvarchar(100)='', 
@rBankIFSCCode  nvarchar(20)='',
@rAdhaarNumber nvarchar(20)='',
@rValidate varchar(250)='' ,
@rOrgGroupId int,
@rBirthState  nvarchar(150)='',
@rUIDNumber nvarchar(50)='', 
@rBirthCountry nvarchar(150)='',
@rFatherOfficeContactNo nvarchar(50)='',
@rMotherOfficeContactNo varchar(50)='',
@rWhatsAppContactNo nvarchar(20)='',
@rPreviousLeftDate datetime = '',
@rMarriageAnniversaryDate datetime = '' -- Added parameter of @rMarriageAnniversaryDate for mantis 29443
as
begin	
	IF(@rAdmissionDate='') 
	SET @rAdmissionDate = NULL
	IF(@rDateOfBirth='') 
	SET @rDateOfBirth = NULL
	IF(@rFatherDateOfBirth='') 
	SET @rFatherDateOfBirth = NULL
	IF(@rMotherDateOfBirth='') 
	SET @rMotherDateOfBirth = NULL
	IF(@rRelativeDateOfBirth='') 
	SET @rRelativeDateOfBirth = NULL
	IF(@rPreviousLeftDate='') 
	SET @rPreviousLeftDate = NULL
	/**Changes done for mantis 29443**/
	IF(@rMarriageAnniversaryDate='') 
	SET @rMarriageAnniversaryDate = NULL
	
	declare @StudentId bigint = 0
	select @StudentId = Id from sStudent.tStudentMaster where Code = @rCode and OrgID = @rOrgId
	select @StudentId = isnull(@StudentId,0)
	
	declare @genderid int,@AdmissionStandardid int,@LeftStandardid int,@nationalityid int,@religionid int, 
	 @castcategoryid int,@admissioncategoryid int,@bloodgroupid int 
	
	select @rGender = case when upper(@rGender) = 'M' then 'Male'
	when  upper(@rGender) = 'MALE' then 'Male'
	when upper(@rGender) ='FEMALE' then 'Female'
	when upper(@rGender) = 'F' then 'Female' when upper(@rGender) = 'N' then 'Not Known' else 'Not Known' end
	 
	select @genderid = isnull(Id,0) from sCommon.tGenderMaster where Title = @rGender
	
	select @AdmissionStandardid = isnull(Id,0) from sSetup.tClassMaster where Title = @rAdmissionStandard and OrgId = @rOrgId
 
	select @LeftStandardid = isnull(Id,0) from sSetup.tClassMaster where Title = @rLeftStandard and OrgId = @rOrgId
	
	select @nationalityid = isnull(Id,0) from sCommon.tCountryMaster where Nationality = @rNationality and OrgGroupId = @rOrgGroupId
	 
	 select @religionid = isnull(Id,0) from sCommon.tReligionMaster where Title = @rReligion  and OrgGroupId = @rOrgGroupId
	 
	  select @castcategoryid = isnull(Id,0) from sCommon.tCastCategoryMaster where Title = @rcastcatagory and OrgGroupId = @rOrgGroupId
	  
	  select @admissioncategoryid = isnull(Id,0) from sStudent.tAdmissionCategoryMaster where Title = @radmissioncategory and OrgGroupId = @rOrgGroupId
	 
	 select @bloodgroupid = isnull(Id,0) from sCommon.tBloodGroupMaster  where Title = @rBloodGroup  
	  
	select @genderid = isnull(@genderid,0),@AdmissionStandardid = isnull(@AdmissionStandardid,0),@LeftStandardid = isnull(@LeftStandardid,0),
	@nationalityid = isnull(@nationalityid,0),@religionid = isnull(@religionid,0),@castcategoryid = isnull(@castcategoryid,0),
	@admissioncategoryid = isnull(@admissioncategoryid,0),@bloodgroupid = isnull(@bloodgroupid,0) 
	
	declare @lNextNumber bigint,@Title varchar(100)=''
	
	 
	 
	if @rFirstName <> ''
	select @rFirstName = [sSetup].[fPortalXMLTagsReplaceReverse](@rFirstName)
	if @rMiddleName <> ''
	select @rMiddleName = [sSetup].[fPortalXMLTagsReplaceReverse](@rMiddleName)
	if @rLastName <> ''
	select @rLastName = [sSetup].[fPortalXMLTagsReplaceReverse](@rLastName)
	 if @rAdmissionDate <> ''
	select @rAdmissionDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdmissionDate)
	 if @rAdmissionYear <> ''
	select @rAdmissionYear = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdmissionYear)
	 if @rLeftDate <> ''
	select @rLeftDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rLeftDate)
	if @rLeftYear <> ''
	select @rLeftYear= [sSetup].[fPortalXMLTagsReplaceReverse](@rLeftYear)
	if @rLeftReason <> ''
	select @rLeftReason= [sSetup].[fPortalXMLTagsReplaceReverse](@rLeftReason)
	if @rPreviousSchool <> ''
	select @rPreviousSchool= [sSetup].[fPortalXMLTagsReplaceReverse](@rPreviousSchool)
	if @rDateOfBirth <> ''
	select @rDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rDateOfBirth)
	if @rBirthPlace <> ''
	select @rBirthPlace= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthPlace)
	if @rBirthTaluka<> ''
	select @rBirthTaluka= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthTaluka)
	if @rBirthDistrict <> ''
	select @rBirthDistrict= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthDistrict)
	if @rFamilyCast <> ''
	select @rFamilyCast= [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilyCast)
	if @rFamilySubCast <> ''
	select @rFamilySubCast= [sSetup].[fPortalXMLTagsReplaceReverse](@rFamilySubCast)
	if @rMotherTongue <> ''
	select @rMotherTongue= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherTongue)
	if @rHobby <> ''
	select @rHobby= [sSetup].[fPortalXMLTagsReplaceReverse](@rHobby)
	if @rFatherName<> ''
	select @rFatherName= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherName)
	if @rFatherContactNo<> ''
	select @rFatherContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherContactNo)
	if @rFatherDateOfBirth<> ''
	select @rFatherDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherDateOfBirth)
	if @rFatherOccupation<> ''
	select @rFatherOccupation= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherOccupation)
	if @rFatherQualification<> ''
	select @rFatherQualification= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherQualification)
	if @rFatherMail<> ''
	select @rFatherMail= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherMail)
	if @rFatherOfficeAddress<> ''
	select @rFatherOfficeAddress= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherOfficeAddress)
	if @rFatherIncome<> ''
	select @rFatherIncome= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherIncome)
	if @rMothername<> ''
	select @rMothername= [sSetup].[fPortalXMLTagsReplaceReverse](@rMothername)
	if @rMotherContactNo<> ''
	select @rMotherContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherContactNo)
	if @rMotherDateOfBirth<> ''
	select @rMotherDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherDateOfBirth)
	if @rMotherOccupation<> ''
	select @rMotherOccupation= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherOccupation)
	if @rMotherQualification <> ''
	select @rMotherQualification= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherQualification)
	if @rMotherMail<> ''
	select @rMotherMail= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherMail)
	if @rMotherOfficeAddress<> ''
	select @rMotherOfficeAddress= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherOfficeAddress)
	if @rMotherIncome<> ''
	select @rMotherIncome= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherIncome)
	if @rRelationshipName <> ''
	select @rRelationshipName= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelationshipName)
	if @rRelativeName <> ''
	select @rRelativeName= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeName)
	if @rRelativeDateOfBirth <> ''
	select @rRelativeDateOfBirth= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeDateOfBirth)
	if @rRelativeOccupation <> ''
	select @rRelativeOccupation= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeOccupation)
	if @rRelativeQualification <> ''
	select @rRelativeQualification= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeQualification)
	if @rRelativeContactNo<> ''
	select @rRelativeContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeContactNo)
	if @rRelativeMail<> ''
	select @rRelativeMail= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeMail)
	if @rRelativeOfficeAddress <> ''
	select @rRelativeOfficeAddress= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeOfficeAddress)
	if @rRelativeIncome <> ''
	select @rRelativeIncome= [sSetup].[fPortalXMLTagsReplaceReverse](@rRelativeIncome)
	 
	if @rPresentStreetOne <> ''
	select @rPresentStreetOne = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetOne)
	if @rPresentStreetTwo <> ''
	select @rPresentStreetTwo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetTwo)
	if @rPresentStreetThree <> ''
	select @rPresentStreetThree = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentStreetThree)
	 
	if @rPresentZipCode <> ''
	select @rPresentZipCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentZipCode)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rPresentCountry <> ''
	select @rPresentCountry = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCountry)
	if @rPresentCity <> ''
	select @rPresentCity = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentCity)
	if @rPresentContactNo <> ''
	select @rPresentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentContactNo)
	if @rPresentState <> ''
	select @rPresentState = [sSetup].[fPortalXMLTagsReplaceReverse](@rPresentState)
	if @rAccountNumber <> ''
	select @rAccountNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAccountNumber)
	if @rBankName <> ''
	select @rBankName = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankName)
	if @rBranch <> ''
	select @rBranch = [sSetup].[fPortalXMLTagsReplaceReverse](@rBranch)
	if @rParentEmail<> ''
	select @rParentEmail = [sSetup].[fPortalXMLTagsReplaceReverse](@rParentEmail)
	if @rUIDNumber <> ''
	select @rUIDNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rUIDNumber)
	if @rAdhaarNumber <> ''
	select @rAdhaarNumber = [sSetup].[fPortalXMLTagsReplaceReverse](@rAdhaarNumber)
	  if @rStudentContactNo <> ''
	select @rStudentContactNo = [sSetup].[fPortalXMLTagsReplaceReverse](@rStudentContactNo)
	if @rStudentEmail <> ''
	select @rStudentEmail= [sSetup].[fPortalXMLTagsReplaceReverse](@rStudentEmail)
	if @rBankIFSCCode <> ''
	select @rBankIFSCCode = [sSetup].[fPortalXMLTagsReplaceReverse](@rBankIFSCCode)
	if @rBirthState<> ''
	select @rBirthState= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthState)
	if @rBirthCountry<> ''
	select @rBirthCountry= [sSetup].[fPortalXMLTagsReplaceReverse](@rBirthCountry)
	if @rFatherOfficeContactNo<> ''
	select @rFatherOfficeContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rFatherOfficeContactNo)
	if @rMotherOfficeContactNo<> ''
	select @rMotherOfficeContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rMotherOfficeContactNo)
	if @rWhatsAppContactNo<> ''
	select @rWhatsAppContactNo= [sSetup].[fPortalXMLTagsReplaceReverse](@rWhatsAppContactNo)

	 if @rPreviousLeftDate <> ''
	select @rPreviousLeftDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rPreviousLeftDate)

	/***Changes done for mantis 29443***/
	if @rMarriageAnniversaryDate <> ''
	select @rMarriageAnniversaryDate = [sSetup].[fPortalXMLTagsReplaceReverse](@rMarriageAnniversaryDate)
	
	begin

		UPDATE sStudent.tStudentMaster
		SET 
		FirstName = case when isnull(@rFirstName,'') <> '' then @rFirstName else FirstName end
		,MiddleName   = case when isnull(@rMiddleName,'') <> '' then @rMiddleName else MiddleName end
		,LastName     = case when isnull(@rLastName,'') <> '' then @rLastName else LastName end
		--,StatusId     = case when isnull(@statusid,0) <> 0 then @statusid else StatusId end
		 ,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		WHERE Id = @StudentId and OrgId = @rOrgId
		
		IF NOT EXISTS(Select * from sStudent.tStudentAdmission where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentAdmission(StudentId,CreatedUserId,CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

		SELECT @rLeftDate,@LeftStandardid			
		UPDATE sStudent.tStudentAdmission
		SET 
			AdmissionStandardId = case when isnull(@AdmissionStandardid,0) <> 0 then @AdmissionStandardid else AdmissionStandardId end,	 
			AdmissionYear = case when isnull(@rAdmissionYear,0) <> 0 then @rAdmissionYear else AdmissionYear end,			
			AdmissionDate = case when isnull(@rAdmissionDate,'') <> '' then @rAdmissionDate else AdmissionDate end,
			LeftStandardId =	case when isnull(@LeftStandardid,'') <> '' then @LeftStandardid else LeftStandardId end,
			LeftDate = case when isnull(@rLeftDate,'') <> '' then @rLeftDate else LeftDate end,	 
			LeftYear = case when isnull(@rLeftYear,0) <> 0 then @rLeftYear else LeftYear end,
			LeftReason = case when isnull(@rLeftReason,'') <> '' then @rLeftReason else LeftReason end,
			PreviousSchool = case when isnull(@rPreviousSchool,'') <> '' then @rPreviousSchool else PreviousSchool end,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			PreviousLeftDate = case when isnull(@rPreviousLeftDate,'') <> '' then @rPreviousLeftDate else PreviousLeftDate end
		WHERE StudentId = @StudentId 
	 

		IF NOT EXISTS(Select * from sStudent.tStudentOther where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentOther (StudentId, CreatedUserId, CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

		Update sStudent.tStudentOther
		set  
		GenderId = case when isnull(@genderid,0) <> 0 then @genderid else GenderId  end,
		ReligionId =  case when isnull(@religionId,0) <> 0 then @religionId else ReligionId  end,
		 BloodGroupId =  case when isnull(@bloodgroupid,0) <> 0 then @bloodgroupid else BloodGroupId  end,
		DateOfBirth =  case when isnull(@rDateOfBirth,'') <> '' then @rDateOfBirth else DateOfBirth  end,
		BirthPlace = case when isnull(@rBirthPlace,'') <> '' then @rBirthPlace else BirthPlace  end,
		BirthTaluka = case when isnull(@rBirthTaluka,'') <> '' then @rBirthTaluka else BirthTaluka  end,
			BirthDistrict = case when isnull(@rBirthDistrict,'') <> '' then @rBirthDistrict else BirthDistrict  end,
		 UIDNumber =  case when isnull(@rUIDNumber,'') <> '' then @rUIDNumber else UIDNumber  end,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = sCommon.fGetDate(),
		FamilyCast =case when isnull(@rFamilyCast,'') <> '' then @rFamilyCast else FamilyCast  end,
		AdhaarNumber =case when isnull(@rAdhaarNumber,'') <> '' then @rAdhaarNumber else AdhaarNumber  end,
		FamilySubCast = case when isnull(@rFamilySubCast,'') <> '' then @rFamilySubCast else FamilySubCast  end,
		MotherTongue = case when isnull(@rMotherTongue,'') <>'' then @rMotherTongue else MotherTongue  end,
		NationalityId = case when isnull(@NationalityId,0) <> 0 then @NationalityId else NationalityId  end,
		 Hobby = case when isnull(@rHobby,'') <> '' then @rHobby else Hobby  end,
		CastCategoryId =case when isnull(@castcategoryid,0) <> 0 then @castcategoryid else CastCategoryId  end,
			BirthState = case when isnull(@rBirthState,'') <> '' then @rBirthState else BirthState  end,
				BirthCountry = case when isnull(@rBirthCountry,'') <> '' then @rBirthCountry else BirthCountry  end
		where StudentId = @StudentId 
		
	
		IF NOT EXISTS(Select * from sStudent.tStudentFamily where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentFamily (StudentId, CreatedUserId, CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

  		UPDATE sStudent.tStudentFamily
		SET 
	      
		   FatherName = case when isnull(@rFatherName,'') <> '' then @rFatherName else FatherName end 
		  ,FatherDateOfBirth =  case when isnull(@rFatherDateOfBirth,'') <> '' then @rFatherDateOfBirth else FatherDateOfBirth end 
		  ,FatherOccupation = case when isnull(@rFatherOccupation,'') <> '' then @rFatherOccupation else FatherOccupation end 
		  ,FatherQualification = case when isnull(@rFatherQualification,'') <> '' then @rFatherQualification else FatherQualification end 
		  ,FatherContactNo =  case when isnull(@rFatherContactNo,'') <> '' then @rFatherContactNo else FatherContactNo end 
		  ,FatherMail =  case when isnull(@rFatherMail,'') <> '' then @rFatherMail else FatherMail end 
		  ,FatherOfficeAddress = case when isnull(@rFatherOfficeAddress,'') <> '' then @rFatherOfficeAddress else FatherOfficeAddress end 
		  ,FatherIncome = case when isnull(@rFatherIncome,'') <> '' then @rFatherIncome else FatherIncome end 
		  ,MotherName = case when isnull(@rMotherName,'') <> '' then @rMotherName else MotherName end  
		  ,MotherDateOfBirth =  case when isnull(@rMotherDateOfBirth,'') <> '' then @rMotherDateOfBirth else MotherDateOfBirth  end   
		  ,MotherOccupation =  case when isnull(@rMotherOccupation,'') <> '' then @rMotherOccupation else MotherOccupation  end   
		  ,MotherQualification =  case when isnull(@rMotherQualification,'') <> '' then @rMotherQualification else MotherQualification  end      
		   ,MotherContactNo = case when isnull(@rMotherContactNo,'') <> '' then @rMotherContactNo else MotherContactNo end
		   ,MotherMail = case when isnull(@rMotherMail,'') <> '' then @rMotherMail else MotherMail end
		   ,MotherOfficeAddress = case when isnull(@rMotherOfficeAddress,'') <> '' then @rMotherOfficeAddress else MotherOfficeAddress end
		   ,MotherIncome = case when isnull(@rMotherIncome,'') <> '' then @rMotherIncome else MotherIncome end
		   ,RelationshipName = case when isnull(@rRelationshipName,'') <> '' then @rRelationshipName else RelationshipName end
		   ,RelativeName = case when isnull(@rRelativeName,'') <> '' then @rRelativeName else RelativeName end
			,RelativeDateOfBirth = case when isnull(@rRelativeDateOfBirth,'') <> '' then @rRelativeDateOfBirth else RelativeDateOfBirth end 
			,RelativeOccupation = case when isnull(@rRelativeOccupation,'') <> '' then @rRelativeOccupation else RelativeOccupation end 
			,RelativeQualification = case when isnull(@rRelativeQualification,'') <> '' then @rRelativeQualification else RelativeQualification end 
			,RelativeContactNo = case when isnull(@rRelativeContactNo,'') <> '' then @rRelativeContactNo else RelativeContactNo end 
			,RelativeMail = case when isnull(@rRelativeMail,'') <> '' then @rRelativeMail else RelativeMail end 
			,RelativeOfficeAddress = case when isnull(@rRelativeOfficeAddress,'') <> '' then @rRelativeOfficeAddress else RelativeOfficeAddress end 
			,RelativeIncome = case when isnull(@rRelativeIncome,'') <> '' then @rRelativeIncome else RelativeIncome end 
			,FatherOfficeContactNo = case when isnull(@rFatherOfficeContactNo,'') <> '' then @rFatherOfficeContactNo else FatherOfficeContactNo end 
			,MotherOfficeContactNo = case when isnull(@rMotherOfficeContactNo,'') <> '' then @rMotherOfficeContactNo else MotherOfficeContactNo end 
			,MarriageAnniversaryDate = case when isnull(@rMarriageAnniversaryDate,'') <> '' then @rMarriageAnniversaryDate else MarriageAnniversaryDate end -- Added new field of MarriageAnniversaryDate for mantis : 29443
		  ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		WHERE StudentId = @StudentId
			

		IF NOT EXISTS(Select * from sStudent.tStudentCommunication where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentCommunication (StudentId, CreatedUserId, CreatedDateTime) Values (@StudentId, @rCreatedUserId, sCommon.fGetDate())
		END

  		UPDATE sStudent.tStudentCommunication
		SET 
	      
		   [PresentStreetOne] = case when isnull(@rPresentStreetOne,'') <> '' then @rPresentStreetOne else [PresentStreetOne] end 
		  ,[PresentStreetTwo] =  case when isnull(@rPresentStreetTwo,'') <> '' then @rPresentStreetTwo else [PresentStreetTwo] end 
		  ,[PresentStreetThree] = case when isnull(@rPresentStreetThree,'') <> '' then @rPresentStreetThree else [PresentStreetThree] end 
		  ,[PresentCountry] = case when isnull(@rPresentCountry,'') <> '' then @rPresentCountry else [PresentCountry] end 
		  ,[PresentState] =  case when isnull(@rPresentState,'') <> '' then @rPresentState else [PresentState] end 
		  ,[PresentCity] =  case when isnull(@rPresentCity,'') <> '' then @rPresentCity else [PresentCity] end 
		  ,PresentZipCode = case when isnull(@rPresentZipCode,'') <> '' then @rPresentZipCode else PresentZipCode end 
		  ,PresentContactNo = case when isnull(@rPresentContactNo,'') <> '' then @rPresentContactNo else PresentContactNo end 
		  ,ParentEmail = case when isnull(@rParentEmail,'') <> '' then @rParentEmail else ParentEmail end  
		  ,StudentContactNo =  case when isnull(@rStudentContactNo,'') <> '' then @rStudentContactNo else StudentContactNo  end   
		  ,StudentEmail =  case when isnull(@rStudentEmail,'') <> '' then @rStudentEmail else StudentEmail  end   
		   ,[UpdatedUserId] = @rCreatedUserId
		  ,[UpdatedDateTime] =  sCommon.fGetDate() 
		  ,WhatsAppContactNo =  case when isnull(@rWhatsAppContactNo,'') <> '' then @rWhatsAppContactNo else WhatsAppContactNo  end   
		WHERE StudentId = @StudentId
		

		IF NOT EXISTS(Select * from sStudent.tStudentAdditional where StudentId= @StudentId) 
		BEGIN
			INSERT INTO sStudent.tStudentAdditional (StudentId) Values (@StudentId)
		END

		UPDATE sStudent.tStudentAdditional
		SET
			BankBranch = case when isnull(@rBranch,'') <> '' then @rBranch else BankBranch end 
		  ,BankAccountNumber = case when isnull(@rAccountNumber,'') <> '' then @rAccountNumber else BankAccountNumber end 
		  ,BankName = case when isnull(@rBankName,'') <> '' then @rBankName else BankName end 
		  ,BankIFSCCode = case when isnull(@rBankIFSCCode,'') <> '' then @rBankIFSCCode else BankIFSCCode end 
		  
		where StudentId=@StudentId
		
	end	
end
GO
PRINT N'Altering Procedure [sStudent].[pStudentDataModify]...';


GO

ALTER PROCEDURE [sStudent].[pStudentDataModify]	 
	@rCategoryId int,
	@rXML nvarchar(max),
	@rSubCategoryField nvarchar(100),
	@rOrgId int = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
DECLARE @lInterrorCode INT
Declare @Sql nvarchar(max) 
DECLARE @loDoc INT

--BEGIN TRY
--BEGIN TRANSACTION

        --CategoryId
        --Communication = 1,
        --Other = 2,
        --Admission = 3,
        --Family = 4,
        --Health = 5,
        --AcademicDetail = 6,
        --General = 7
        --CustomDetail = 8
        --Sibling = 9

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup' 
			 OR @rSubCategoryField = 'TransportMode' OR @rSubCategoryField = 'House'
			OR @rSubCategoryField = 'Quota' 
			OR @rSubCategoryField = 'Nationality' OR @rSubCategoryField = 'AdmissionStandard' OR  @rSubCategoryField = 'AdmissionCategory' OR @rSubCategoryField = 'AdmissionQuota'
			OR @rSubCategoryField = 'Tribe')
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	
	IF(	@rSubCategoryField = 'CasteCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast') + 'Id'
	END
	
	IF(	@rSubCategoryField = 'FamilyCaste' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')  
	END
	
	IF(	@rSubCategoryField = 'StudentGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentGroup','StudentGroupId')  
	END
	IF(	@rSubCategoryField = 'StudentOtherGroup' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'StudentOtherGroup','StudentOtherGroupId')  
	END
	
	IF(@rSubCategoryField = 'FeeCategory' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'FeeCategory','AdmissionCategory') + 'Id'
	END

	IF(@rSubCategoryField = 'FatherAnnualIncome' )													-- #Start Mantis Id : 0029214
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'FatherAnnualIncome','FatherIncome')
	END
	IF(@rSubCategoryField = 'MotherAnnualIncome' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'MotherAnnualIncome','MotherIncome')
	END																								
	IF(@rSubCategoryField = 'RelativeAnnualIncome' )
	BEGIN
		SET @rSubCategoryField = Replace(@rSubCategoryField,'RelativeAnnualIncome','RelativeIncome')
	END																								-- #End Mantis Id : 0029214

	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)  
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication) 
		
		set @sql='INSERT INTO sStudent.tStudentCommunication 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCommunication set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCommunication SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentOther) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
			set @sql='INSERT INTO sStudent.tStudentOther 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sStudent.tStudentOther SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='INSERT INTO sStudent.tStudentOther 
						(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
						SELECT
							LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
						FROM
							ListofData LD WHERE LD.IsExist=1'
			Exec sp_executesql @sql				
			 				
			set @sql='UPDATE sStudent.tStudentOther set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentOther SO 
						INNER JOIN ListofData LD ON SO.StudentId=LD.StudentId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	    
	Else IF(@rCategoryId= 3)
		BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		set @sql='UPDATE sStudent.tStudentAdmission set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentAdmission SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'AdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE AdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'PreviousLCDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE PreviousLCDate=''1900-01-01'''
			Exec sp_executesql @sql
		END

		IF(@rSubCategoryField = 'InActiveDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdmission SET '+@rSubCategoryField+' = null WHERE InActiveDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
 
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentFamily) 
		
		set @sql='INSERT INTO sStudent.tStudentFamily 
					(StudentId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentFamily set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentFamily SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'FatherDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE FatherDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'MotherDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE MotherDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END

		IF(@rSubCategoryField = 'RelativeDateOfBirth' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE RelativeDateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END		

		/****Change for mantis 29443*****/
		IF(@rSubCategoryField = 'MarriageAnniversaryDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentFamily SET '+@rSubCategoryField+' = null WHERE MarriageAnniversaryDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		/****Change for mantis 29443*****/		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
    Else IF(@rCategoryId= 5)
	     BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentHealth) 
		
		set @sql='INSERT INTO sStudent.tStudentHealth 
					(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentHealth set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentHealth SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
		
		Exec sp_executesql @sql
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END		 
	 
	 Else IF(@rCategoryId= 6)
	    BEGIN
		insert into ListofData
		select E.Id,0,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
		
		set @sql='INSERT INTO sStudent.tAcademicDetail 
					(AcademicId,'+@rSubCategoryField+')
					SELECT
						LD.Id,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tAcademicDetail set '+@rSubCategoryField+' = LD.SubCategory
					from sStudent.tAcademicDetail AD 
					INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		IF(@rSubCategoryField = 'BatchAdmissionDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tAcademicDetail SET '+@rSubCategoryField+' = NULL WHERE BatchAdmissionDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	Else IF(@rCategoryId= 7)
	     BEGIN
	    IF(@rSubCategoryField NOT IN ('AdmissionCategoryId','FeesRemark'))
		BEGIN
			insert into ListofData
			select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
			from
			(
					SELECT StudentId,SubCategory,UpdatedUserId FROM
					OPENXML (@loDoc, '/Students/Students', 2)
					WITH (
							StudentId BIGINT, 
							SubCategory nvarchar(100),
							UpdatedUserId bigint)	
							)E 	
			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT Id FROM sStudent.tStudentMaster) 
			
			--set @sql='INSERT INTO sStudent.tStudentMaster 
			--			(StudentId,'+@rSubCategoryField+',UpdatedUserId,UpdatedDateTime)
			--			SELECT
			--				LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
			--			FROM
			--				ListofData LD WHERE LD.IsExist=1'				
			--Exec sp_executesql @sql
			
			set @sql='UPDATE sStudent.tStudentMaster set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tStudentMaster SA 
						INNER JOIN ListofData LD ON SA.Id=LD.StudentId AND IsExist=0'
			
			Exec sp_executesql @sql
			Drop Table ListofData
		END
		IF(@rSubCategoryField IN ('AdmissionCategoryId','FeesRemark'))
		BEGIN
			insert into ListofData
			select E.Id,0,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
			from
			(
					SELECT Id,SubCategory,UpdatedUserId FROM
					OPENXML (@loDoc, '/Students/Students', 2)
					WITH (
							Id BIGINT, 
							SubCategory nvarchar(100),
							UpdatedUserId bigint)	
							)E 
							
			set @sql='UPDATE sStudent.tAcademic set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sStudent.tAcademic A 
						INNER JOIN ListofData LD ON A.Id=LD.Id AND IsExist=0'
			
			Exec sp_executesql @sql
			Drop Table ListofData
		
		END
		
			 SELECT 1 AS StatusCode
	    END			 
	 
	 
	 Else IF(@rCategoryId= 8)
	     BEGIN
	     
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(100)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 

		set @sql='INSERT INTO sStudent.tStudentAdditional
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentAdditional set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentAdditional SA 
					INNER JOIN ListofData LD ON SA.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
					
		IF(@rSubCategoryField = 'PassportIssueDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportIssueDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'PassportExpiryDate' )
		BEGIN
		SET @sql='UPDATE sStudent.tStudentAdditional SET '+@rSubCategoryField+' = null WHERE PassportExpiryDate=''1900-01-01'''
			Exec sp_executesql @sql
		END						
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
	    
	    
	     
	 Else IF(@rCategoryId= 9)
	    BEGIN
		insert into ListofData
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),0,0
		from
		(
				SELECT StudentId,SubCategory FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (
						StudentId BIGINT, 
						SubCategory nvarchar(200)
						 )	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentadditional) 
		
		set @sql='INSERT INTO sStudent.tStudentSibling
					(StudentId,'+@rSubCategoryField+')
					SELECT
						LD.StudentId,Ld.SubCategory
					FROM
						ListofData LD WHERE LD.IsExist=1'				
		Exec sp_executesql @sql
		
		set @sql='UPDATE sStudent.tStudentSibling set '+@rSubCategoryField+' = LD.SubCategory 
					 
					from sStudent.tStudentSibling SS 
					INNER JOIN ListofData LD ON SS.StudentId=LD.StudentId AND IsExist=0'
					
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END	
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering Procedure [sStudent].[pStudentDataUpdateGet]...';


GO


ALTER PROCEDURE [sStudent].[pStudentDataUpdateGet]
	 
	 @rCategoryId int,
	 @rSubCategory nvarchar(500),
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int,
	 @rIsBlank bit,
	 @rStatusId int,
	 @rOrderBy int
	 
AS
SET NOCOUNT ON

BEGIN
		DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory
		 
		IF(@rSubCategory = 'Gender' OR @rSubCategory = 'Religion' OR @rSubCategory = 'BloodGroup' 
			OR @rSubCategory = 'TransportMode' OR @rSubCategory = 'House'
			OR @rSubCategory = 'Quota' OR @rSubCategory = 'Nationality' OR @rSubCategory = 'AdmissionStandard' OR  @rSubCategory = 'AdmissionCategory'
			OR @rSubCategory = 'AdmissionQuota' OR @rSubCategory = 'Tribe')
		BEGIN
			 
			SET @rSubCategory =@rSubCategory + 'Id'
			 -- print @rSubCategory
		END
		IF(@rSubCategory = 'CasteCategory' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') + 'Id'
		END
		
			IF(@rSubCategory = 'FamilyCaste' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'Caste','Cast') 
		END
		IF(@rSubCategory = 'StudentGroup' OR @rSubCategory='StudentOtherGroup')
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory ,'StudentGroup','StudentGroupId')
			SET @rSubCategory = Replace(@rSubCategory ,'StudentOtherGroup','StudentOtherGroupId')
		END
		
		IF(@rSubCategory = 'FeeCategory' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'FeeCategory','AdmissionCategory') + 'Id'
		END

		IF(@rSubCategory = 'FatherAnnualIncome' )											-- #Start Mantis Id : 0029214
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'FatherAnnualIncome','FatherIncome')
		END
		IF(@rSubCategory = 'MotherAnnualIncome' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'MotherAnnualIncome','MotherIncome')
		END																					
		IF(@rSubCategory = 'RelativeAnnualIncome' )
		BEGIN
			SET @rSubCategory = Replace(@rSubCategory,'RelativeAnnualIncome','RelativeIncome')
		END																					-- #End Mantis Id : 0029214

		 Declare @Sql nvarchar(max)
		 Declare @Sql1 nvarchar(max)
		 
		 SET @Sql =  CASE @rCategoryId					  
					 WHEN 1 THEN -- Communication
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SC.'+@rSubCategory+','''') 
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SC.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SC.'+@rSubCategory+',''False'') 
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SC.'+@rSubCategory+',''0001/01/01'') 
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SC.'+@rSubCategory+',''0'') 
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SC.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SC.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SC.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SC.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)
							 '
							
					 WHEN 2 THEN -- Other
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SO.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SO.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SO.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						SO.'+@rSubCategory+'
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SO.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SO.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SO.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SO.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SO.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
							
					WHEN 3 THEN -- Admission
						'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAD.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAD.'+@rSubCategory+',''0'')
						END AS SubCategory 
							FROM 
							sStudent.vStudentAcademic SA
							INNER JOIN sStudent.tStudentAdmission SAD ON SAD.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					 
					WHEN 4 THEN --Family
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAF.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAF.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAF.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAF.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAF.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentFamily SAF ON SAF.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAF.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAF.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAF.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAF.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
				   
					WHEN 5 THEN --Health
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAH.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAH.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentHealth SAH ON SAH.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					WHEN 6 THEN --Academic Detail
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(AD.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(AD.'+@rSubCategory+',''0'')						
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(AD.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(AD.'+@rSubCategory+',''0001/01/01'')	
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''=''RepeatCount'' THEN
						ISNULL(AD.'+@rSubCategory+',''1'')
						WHEN '+@lDataTypeId+'=5 AND ''' + @rSubCategory + '''<>''RepeatCount'' THEN
						ISNULL(AD.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=SA.AcademicId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(AD.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(AD.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(AD.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(AD.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'
					--WHEN 7 THEN --General
						
					--   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
					--	CASE WHEN '+@lDataTypeId+'=1 THEN
					--	ISNULL(SAH.'+@rSubCategory+','''')
					--	WHEN '+@lDataTypeId+'=2 THEN
					--	ISNULL(SAH.'+@rSubCategory+',''0'')
					--	WHEN '+@lDataTypeId+'=3 THEN
					--	ISNULL(SAH.'+@rSubCategory+',''False'')
					--	WHEN '+@lDataTypeId+'=4 THEN
					--	ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
					--	WHEN '+@lDataTypeId+'=5 THEN
					--	ISNULL(SAH.'+@rSubCategory+',''0'')
					--	END AS SubCategory
					--		FROM 
					--		sStudent.vStudentAcademic SA
					--		LEFT JOIN sStudent.tStudentMaster SAH ON SAH.Id=SA.StudentId
					--		Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
					--		+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
					--		AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
					--		AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
					--		AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
					--		AND 
					--		('+CAST(@rIsBlank AS nvarchar(1))+'=0 
					--			OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
					--			OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
					--			OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
					--			OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
					--		)'
					WHEN 8 THEN --Additonal Information
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SAH.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SAH.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SAH.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentAdditional SAH ON SAH.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SAH.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SAH.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SAH.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SAH.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'	
					
					WHEN 9 THEN --Student Sibling
					   'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
						CASE WHEN '+@lDataTypeId+'=1 THEN
						ISNULL(SS.'+@rSubCategory+','''')
						WHEN '+@lDataTypeId+'=2 THEN
						ISNULL(SS.'+@rSubCategory+',''0'')
						WHEN '+@lDataTypeId+'=3 THEN
						ISNULL(SS.'+@rSubCategory+',''False'')
						WHEN '+@lDataTypeId+'=4 THEN
						ISNULL(SS.'+@rSubCategory+',''0001/01/01'')
						WHEN '+@lDataTypeId+'=5 THEN
						ISNULL(SS.'+@rSubCategory+',''0'')
						END AS SubCategory
							FROM 
							sStudent.vStudentAcademic SA
							LEFT JOIN sStudent.tStudentSibling SS ON SS.StudentId=SA.StudentId
							Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
							+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
							AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
							AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
							AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
							AND 
							('+CAST(@rIsBlank AS nvarchar(1))+'=0 
								OR ('+@lDataTypeId+'=1 AND ISNULL(SS.'+@rSubCategory+','''')='''')
								OR ('+@lDataTypeId+'=2 AND ISNULL(SS.'+@rSubCategory+',''0'')=''0'')
								OR ('+@lDataTypeId+'=3 AND ISNULL(SS.'+@rSubCategory+',''False'')=''False'')
								OR ('+@lDataTypeId+'=4 AND ISNULL(SS.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
							)'	
					END				
					
			SET @Sql1 =  CASE
			WHEN @rCategoryId = 7 --AND @rSubCategory='AdmissionCategoryId'
			THEN 
			'Select SA.StudentId,SA.AcademicId,SA.Code,SA.Name,SA.ClassName+'' - ''+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Number,
			CASE WHEN '+@lDataTypeId+'=1 THEN
			ISNULL(SA.'+@rSubCategory+','''')
			WHEN '+@lDataTypeId+'=2 THEN
			ISNULL(SA.'+@rSubCategory+',''0'')
			WHEN '+@lDataTypeId+'=3 THEN
			ISNULL(SA.'+@rSubCategory+',''False'')
			WHEN '+@lDataTypeId+'=4 THEN
			ISNULL(SA.'+@rSubCategory+',''0001/01/01'')
			WHEN '+@lDataTypeId+'=5 THEN
			ISNULL(SA.'+@rSubCategory+',''0'')
			END AS SubCategory
			FROM 
			sStudent.vStudentAcademic SA
			LEFT JOIN sStudent.tStudentMaster SAH ON SAH.Id=SA.StudentId
			Where SA.OrgId='+CAST(@rOrgId AS nvarchar(15))
			+'AND (SA.ClassId='+CAST(@rClassId AS nvarchar(15))+ 'OR '+CAST(@rClassId AS nvarchar(15))+'=0)
			AND (SA.DivisionId='+CAST(@rDivisionId AS nvarchar(15))+ 'OR '+CAST(@rDivisionId AS nvarchar(15))+'=0)
			AND (SA.StatusId='+ CAST(@rStatusId AS nvarchar(15)) +' OR '+CAST(@rStatusId AS nvarchar(15))+'=0)
			AND (SA.BatchId='+CAST(@rBatchId AS nvarchar(15))+')
			AND 
			('+CAST(@rIsBlank AS nvarchar(1))+'=0 
			OR ('+@lDataTypeId+'=1 AND ISNULL(SA.'+@rSubCategory+','''')='''')
			OR ('+@lDataTypeId+'=2 AND ISNULL(SA.'+@rSubCategory+',''0'')=''0'')
			OR ('+@lDataTypeId+'=3 AND ISNULL(SA.'+@rSubCategory+',''False'')=''False'')
			OR ('+@lDataTypeId+'=4 AND ISNULL(SA.'+@rSubCategory+',''0001/01/01'')=''0001/01/01'') 
			)'
			END
			Print @Sql
	   if(@Sql1 IS NOT NULL)		
			EXECUTE  sp_executesql @Sql1
	   else
			EXECUTE  sp_executesql @Sql
	   
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentGenerateReport]...';


GO


ALTER PROCEDURE [sStudent].[pStudentGenerateReport]
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'RollNo',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	@rDivisionId nvarchar(max) = '',
	@rStatusId nvarchar(max) = '',
	@rTransportModeId nvarchar(max) = '',
	@rBusRouteDestinationId nvarchar(max) = '',
	@rBloodGroupId nvarchar(max) = '',
	@rGenderId nvarchar(max) = '',
	@rReligionId nvarchar(max) = '',
	@rCastCategoryId nvarchar(max) = '',
	@rHouseId nvarchar(max) = '',
	@rMotherTongueId nvarchar(max) = '',
	@rNationalityId nvarchar(max) = '',
	@rHobby nvarchar(50) = '',
	@rFatherQualification nvarchar(max) = '',
	@rMotherQualification nvarchar(max) = '',
	@rFatherOccupation nvarchar(max) = '',
	@rMotherOccupation nvarchar(max) = '',
	@rPreviousSchool nvarchar(max) = '',
	@rAdmissionCategoryId nvarchar(max) = '',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9999-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9999-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@rIsCommon bit,
	@rIsCommonForOrg bit,
	@rCreatedUserId bigint,
	@BatchId int,
	@rIsBlackList bit,
	@rFromCode nvarchar(20), 
	@rToCode nvarchar(20),
	@rSpecificCode nvarchar(max),
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rCustomTagId nvarchar(max) = '',
	@rCustomGroupId nvarchar(max) = '',
	@rClubId nvarchar(max) = '',
	@rRepeatCount smallint=0,
	@rStudentStatusId smallint=0,
	@rHostelId nvarchar(max) = '',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption nvarchar(max)='',
	@rRecordTagId nvarchar(max) = '',
	@rContactNo nvarchar(50) = '',
	@rBirthDay int =0,
	@rDateOfMonth int =0,
	@rStopApplicationAccess int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		IF(@rHostelId IS NULL)
			SET @rHostelId = ''
		IF(@rStudentGroupId IS NULL)
			SET @rStudentGroupId = ''
		IF(@rStudentOtherGroupId IS NULL)
			SET @rStudentOtherGroupId = ''	
		IF(@rOrgGroupBatchId IS NULL)
			SET @rOrgGroupBatchId = 0
		IF(@rGenderId IS NULL)
			SET @rGenderId = ''
		IF(@rBusRouteId IS NULL)
			SET @rBusRouteId = ''	
		IF(@rDOBFromDate IS NULL)
			SET @rDOBFromDate='0001-01-01'
		IF(@rDOBToDate IS NULL)
			SET @rDOBToDate='9999-12-31'
		IF(@rDOAFromDate IS NULL)
			SET @rDOAFromDate='0001-01-01'
		IF(@rDOAToDate IS NULL)
			SET @rDOAToDate='9999-12-31'
		IF(@rDOLFromDate IS NULL)
			SET @rDOLFromDate='0001-01-01'
		IF(@rDOLToDate IS NULL)
			SET @rDOLToDate='9999-12-31'
		
		IF(@rTitle != '' AND @rId = 0)
		BEGIN
			DECLARE @lNextNumber BIGINT
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sStudent.tStudentCustomSearch
			(
				Id,Title,ColumnName,OrderBy,OrgId,Code,FirstName,LastName,Country,State,City,Area,DivisionId,
				StatusId,TransportModeId,BusRouteDestinationId,BloodGroupId,GenderId,ReligionId,CastCategoryId,
				HouseId,MotherTongueId,NationalityId,Hobby,FatherQualification,MotherQualification,FatherOccupation,
				MotherOccupation,PreviousSchool,AdmissionCategoryId,DOBFromDate,DOBToDate,DOAFromDate,DOAToDate,
				DOLFromDate,DOLToDate,IsPysicalDeformity,IsMajorIllness,IsCommon,IsCommonForOrg, CreatedUserId,CreatedDateTime,
				IsBlackList,FromCode,ToCode,CustomTag,CustomGroup,Club,RepeatCount,StudentStatusId,Hostel,StudentGroup,
				StudentOtherGroup,FeeExemption,RecordTag,ContactNo,BirthDay,DateOfMonth,IsStopApplicationAccess
			)
			VALUES
			(
				@lNextNumber,@rTitle,@rColumnName,@rOrderBy,@rOrgId,@rSpecificCode,@rFirstName,@rLastName,@rCountry,@rState,
				@rCity,@rArea,@rDivisionId,@rStatusId,@rTransportModeId,@rBusRouteDestinationId,@rBloodGroupId,@rGenderId,
				@rReligionId,@rCastCategoryId,@rHouseId,@rMotherTongueId,@rNationalityId,@rHobby,@rFatherQualification,
				@rMotherQualification,@rFatherOccupation,@rMotherOccupation,@rPreviousSchool,@rAdmissionCategoryId,
				@rDOBFromDate,@rDOBToDate,@rDOAFromDate,@rDOAToDate,@rDOLFromDate,@rDOLToDate,@rIsPysicalDeformity,
				@rIsMajorIllness,@rIsCommon,@rIsCommonForOrg,@rCreatedUserId,sCommon.fGetDate(),@rIsBlackList,@rFromCode,@rToCode,
				@rCustomTagId,@rCustomGroupId,@rClubId,@rRepeatCount,@rStudentStatusId,@rHostelId,@rStudentGroupId,
				@rStudentOtherGroupId,@rFeeExemption,@rRecordTagId,@rContactNo,@rBirthDay,@rDateOfMonth,@rStopApplicationAccess
			)
		END
		
		
		IF(@rId > 0)
		BEGIN
			Select @rColumnName=ColumnName,@rOrderBy=OrderBy,@rOrgId=OrgId,@rSpecificCode=Code,@rFirstName=FirstName,
			@rLastName=LastName,@rCountry=Country,@rState=State,@rCity=City,@rArea=Area,@rDivisionId=DivisionId,
			@rStatusId=StatusId,@rTransportModeId=TransportModeId,@rBusRouteDestinationId=BusRouteDestinationId,
			@rBloodGroupId=BloodGroupId,@rGenderId=GenderId,@rReligionId=ReligionId,@rCastCategoryId=CastCategoryId,
			@rHouseId=HouseId,@rMotherTongueId=MotherTongueId,@rNationalityId=NationalityId,@rHobby=Hobby,
			@rFatherQualification=FatherQualification,@rMotherQualification=MotherQualification,
			@rFatherOccupation=FatherOccupation,@rMotherOccupation=MotherOccupation,
			@rPreviousSchool=PreviousSchool,@rAdmissionCategoryId=AdmissionCategoryId,
			@rDOBFromDate=DOBFromDate,@rDOBToDate=DOBToDate,@rDOAFromDate=DOAFromDate,
			@rDOAToDate=DOAToDate,@rDOLFromDate=DOLFromDate,@rDOLToDate=DOLToDate,
			@rIsPysicalDeformity=IsPysicalDeformity,@rIsMajorIllness=IsMajorIllness,
			@rIsBlackList=IsBlackList,@rFromCode=FromCode,@rToCode=ToCode,
			@rCustomTagId=CustomTag,@rCustomGroupId = CustomGroup,@rClubId = Club,
			@rRepeatCount = RepeatCount,@rStudentStatusId =StudentStatusId,
			@rHostelId = Hostel,@rStudentGroupId = StudentGroup,
			@rStudentOtherGroupId = StudentOtherGroup,@rFeeExemption =FeeExemption,
			@rRecordTagId=RecordTag,@rContactNo=ContactNo,@rStopApplicationAccess=IsStopApplicationAccess
			FROM sStudent.tStudentCustomSearch WHERE Id=@rId
		END
		
		DECLARE @ListofCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
			INSERT INTO @ListofCodes
	     
		SELECT q2.value from
			(SELECT cast('<x>'+replace(@rSpecificCode,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
			(SELECT x.value('.','nvarchar(max)') as value FROM thexml.nodes('x') as f(x))q2
		
		SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
		SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		SET @rColumnName=Replace(@rColumnName,'PhysicalDeformityRemark','PysicalDeformityRemark')
		SET @rColumnName=Replace(@rColumnName,'IsPhysicalDeformity','IsPysicalDeformity')
		SET @rOrderBy=Replace(@rOrderBy,'PhysicalDeformityRemark','PysicalDeformityRemark')
		SET @rOrderBy=Replace(@rOrderBy,'IsPhysicalDeformity','IsPysicalDeformity')
		
		DECLARE @Sql nvarchar(MAX)= ''
		
		SET @rSpecificCode = sCommon.fSearchStringGet(@rSpecificCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		SET @rCountry = sCommon.fSearchStringGet(@rCountry)
		SET @rState = sCommon.fSearchStringGet(@rState)
		
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent1')
		 BEGIN
			DROP Table sStudent.tTempStudent1
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent2')
		 BEGIN		
			DROP Table sStudent.tTempStudent2
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent3')
		 BEGIN
			DROP Table sStudent.tTempStudent3
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent4')
		 BEGIN
			DROP Table sStudent.tTempStudent4
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent5')
		 BEGIN
			DROP Table sStudent.tTempStudent5  
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent6')
		 BEGIN
			DROP Table sStudent.tTempStudent6
		 END
		 
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent7')
		 BEGIN
			DROP Table sStudent.tTempStudent7
		 END
		 
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent8')
		 BEGIN
			DROP Table sStudent.tTempStudent8
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent9')
		 BEGIN
			DROP Table sStudent.tTempStudent9
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent10')
		 BEGIN
			DROP Table sStudent.tTempStudent10
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent11')
		 BEGIN
			DROP Table sStudent.tTempStudent11
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent12')
		 BEGIN
			DROP Table sStudent.tTempStudent12
		 END
		 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent13')
		 BEGIN
			DROP Table sStudent.tTempStudent13
		 END
		  IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempStudent14')
		 BEGIN
			DROP Table sStudent.tTempStudent14
		 END
		
		SELECT  DISTINCT SM.Id AS StudentId6,
		CASE WHEN SF.IsFatherExStudent = 0 THEN 'No' WHEN SF.IsFatherExStudent = 1 THEN 'Yes' ELSE '' END AS IsFatherExStudent,
		CASE WHEN SF.IsMotherExStudent = 0 THEN 'No' WHEN SF.IsMotherExStudent = 1 THEN 'Yes' ELSE '' END AS IsMotherExStudent,
		SF.FatherOrganization, SF.FatherDesignation, SF.MotherOrganization, SF.MotherDesignation, SF.RelativeOrganization, SF.RelativeDesignation
		INTO sStudent.tTempStudent11
		FROM sStudent.tStudentMaster SM
			 INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND ((SM.OrgId = @rOrgId) OR (@rOrgId=0)) AND ((A.BatchId=@BatchId) OR (@BatchId = 0))
			 INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
	
		-- For Left Detail
		SELECT DISTINCT  SA.StudentId AS StudentId12,InactiveDate,InActiveReason,LCBook,--LeftStandardId,
		CM.Title AS LeftStandard,
		CONVERT(VARCHAR(10),LCDate,111) AS LCDate,LCCopy,LeftReason,LCProgress,
		LCConduct,LCRemark 
		INTO sStudent.tTempStudent12
		FROM sStudent.tStudentAdmission SA
		     INNER JOIN sStudent.tAcademic A ON A.StudentId = SA.StudentId AND ((A.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((A.BatchId=@BatchId) OR (@BatchId=0))
		     LEFT JOIN sSetup.tClassMaster CM ON CM.Id = SA.LeftStandardId
		
		-- For Custom Tag
		IF (@rCustomTagId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId1
			INTO sStudent.tTempStudent5
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tStudentCustomTag SCT ON SCT.StudentId=SM.Id
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(SCT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId1
			INTO sStudent.tTempStudent5
		END
		
		-- For Custom Group
		IF (@rCustomGroupId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId2
			INTO sStudent.tTempStudent6
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = A.Id AND CGM.SourceTypeId=2001
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(CGM.CustomGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomGroupId,','))OR @rCustomGroupId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId2
			INTO sStudent.tTempStudent6
		END
		
		-- For Club Group
		IF (@rClubId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId3
			INTO sStudent.tTempStudent7
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId = A.Id
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(AC.ClubId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClubId,','))OR @rClubId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId3
			INTO sStudent.tTempStudent7
		END
		
		-- For Hostel
		IF (@rHostelId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId4
			INTO sStudent.tTempStudent9
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId = A.StudentId
			AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId
			WHERE((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  
			AND (ISNULL(RM.HostelId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHostelId,','))OR @rHostelId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId4
			INTO sStudent.tTempStudent9
		END
		
		--Transport
		IF (@rBusRouteId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId5
			INTO sStudent.tTempStudent10
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			INNER JOIN sTransport.tAssignRoute AT ON AT.SourceId = A.StudentId
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId
			AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) 
			AND (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		END
		ELSE
		BEGIN
			SELECT DISTINCT NULL AS StudentId5
			INTO sStudent.tTempStudent10
			
			
		END
		-- For Record Tag
		IF (@rRecordTagId <> '')
		BEGIN
			SELECT DISTINCT SM.Id AS StudentId14		
			INTO sStudent.tTempStudent14
			FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
			WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))  AND ((A.BatchId = @BatchId) OR (@BatchId = 0))
			AND (ISNULL(SM.RecordStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rRecordTagId,','))OR @rRecordTagId='')
		END
		ELSE
		BEGIN
		
			SELECT DISTINCT NULL AS StudentId14
			INTO sStudent.tTempStudent14
		END
		
		SET @rColumnName=Replace(@rColumnName,'GR No','Code')
		SET @rColumnName=Replace(@rColumnName,'ID No','Code')
		--if @rColumnName <> ''
		--begin
		--	select @rColumnName = left(@rColumnName,len(@rColumnName)-1)
		--end
		--print 'asdasda'
		    DECLARE @lAvailableStudentColumns nvarchar(max)=''
			DECLARE @lAvailableStudentCustomRes nvarchar(max)=''
			Declare @Title as nvarchar(max)
			DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
		
          --BEGIN  
		   
		   --drop table sStudent.tTempStudent13

             
			--print @BatchId
			--print @rOrgId
            DECLARE @rOrgGroupId smallint
             SET @rOrgGroupId = (Select orggroupid from sSetup.tOrganizationMaster where Id=@rOrgId)           
             
			SET @lAvailableStudentColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
								from sStudent.tStudentCustomFieldMaster PP  WHERE PP.OrgGroupId = @rOrgGroupId  
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					Print @lAvailableStudentColumns
	        IF(@lAvailableStudentColumns IS NOT NULL)
	        BEGIN
				set @query = 'SELECT  StudentId AS StudentId13 ,' + @lAvailableStudentColumns + ' into sStudent.tTempStudent13 from 
					 (
						select PPE.FieldTitle,PP.StudentId,FieldData 
						FROM
						sStudent.tStudentCustomFieldData PP 
							INNER JOIN sStudent.tStudentCustomFieldMaster PPE ON PPE.Id = PP.StudentCustomFieldId AND PPE.IsObsolete=0
							INNER JOIN sStudent.tStudentMaster SM ON SM.Id = PP.StudentId						
							INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND A.BatchId='+convert(varchar(20),@BatchId)+' 
							WHERE SM.OrgId='''+convert(varchar(20),@rOrgId)+''' 
					) x 
					pivot 
					(
						Max(FieldData)
						for FieldTitle in (' +@lAvailableStudentColumns  + ')
					) p'
					
				 print @query
                execute(@query)
		   
		   
		
		Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		LEFT JOIN  sStudent.tTempStudent13 T13 ON SCS.StudentId= T13.StudentId13 
		INNER JOIN sStudent.tTempStudent14 T14 ON SCS.StudentId = T14.StudentId14 OR @rRecordTagId = ''
		WHERE ((SCS.OrgId = @rOrgId) OR (@rOrgId = 0)) 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0))
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) >= (REPLICATE(0, 50 - LEN(@rFromCode)) + @rFromCode) OR (@rFromCode='') OR (@rFromCode=0))	-- Add @rFromCode=0 for MantisId : 0029214
		AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) <= (REPLICATE(0, 50 - LEN(@rToCode)) + @rToCode) OR (@rToCode='') OR (@rToCode=0))			-- Add @rToCode=0 for MantisId : 0029214
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		AND ((SCS.PresentContactNo=@rContactNo) OR (SCS.PermanentContactNo=@rContactNo) OR (SCS.EmergencyContactNo=@rContactNo) OR (SCS.ParentContactno=@rContactNo) OR (SCS.StudentContactNo=@rContactNo) OR (SCS.FatherContactNo=@rContactNo) OR (SCS.MotherContactNo=@rContactNo) OR (@rContactNo=''))
		AND (( DAY(CONVERT(date,SCS.DateOfBirth)) = @rBirthDay) OR (@rBirthDay = 0))
	    AND (( MONTH(CONVERT(date,SCS.DateOfBirth)) = @rDateOfMonth) OR (@rDateOfMonth = 0))
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		AND ((SCS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		AND ((SCS.IsStopApplicationAccess = @rStopApplicationAccess) OR (@rStopApplicationAccess = -1))
				
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		DROP Table sStudent.tTempStudent13
		DROP Table sStudent.tTempStudent14
 
	END 
	 
	ELSE
	BEGIN
	    Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		INNER JOIN sStudent.tTempStudent14 T14 ON SCS.StudentId = T14.StudentId14 OR @rRecordTagId = ''
		
		WHERE ((SCS.OrgId = @rOrgId) OR (@rOrgId = 0)) 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0)) 
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) >= (REPLICATE(0, 50 - LEN(@rFromCode)) + @rFromCode) OR (@rFromCode='') OR (@rFromCode=0))	-- Add @rFromCode=0 for MantisId : 0029214
		AND ((REPLICATE(0, 50 - LEN(SCS.Code)) + SCS.Code) <= (REPLICATE(0, 50 - LEN(@rToCode)) + @rToCode) OR (@rToCode='') OR (@rToCode=0))			-- Add @rToCode=0 for MantisId : 0029214
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		AND ((SCS.PresentContactNo=@rContactNo) OR (SCS.PermanentContactNo=@rContactNo) OR (SCS.EmergencyContactNo=@rContactNo) OR (SCS.ParentContactno=@rContactNo) OR (SCS.StudentContactNo=@rContactNo) OR (SCS.FatherContactNo=@rContactNo) OR (SCS.MotherContactNo=@rContactNo) OR (@rContactNo=''))
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		AND ((SCS.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		AND (( DAY(CONVERT(date,SCS.DateOfBirth)) = @rBirthDay) OR (@rBirthDay = 0))
	    AND (( MONTH(CONVERT(date,SCS.DateOfBirth)) = @rDateOfMonth) OR (@rDateOfMonth = 0))
		AND ((SCS.IsStopApplicationAccess = @rStopApplicationAccess) OR (@rStopApplicationAccess = -1))		
				--Select * From sStudent.tTempStudent
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		
	    
	    
	END 
	 
	 
END
GO
PRINT N'Altering Procedure [sWf].[pWfApprovalAdd]...';


GO


CREATE PROCEDURE [sActivity].[pEventAttendanceViewGet]	
	@rOrgId int=0,
	@rBatchId int =0,
	@rEventTypeId int = 0,
	@rAcademicId bigint=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 
	DECLARE @lEventAttendanceGrid NVARCHAR(MAX)=''
	SELECT  @lEventAttendanceGrid = @lEventAttendanceGrid + '<tr>
	<td align="left" scope="col">' + CONVERT(VARCHAR,ISNULL(ES.FromDate,''),103) + '</td>
	<td align="left" scope="col">' + CONVERT(VARCHAR,ISNULL(ES.ToDate,''),103) + '</td>
	<td align="left" scope="col">' + ISNULL(ES.Title,'')  + '</td>
	<td align="left" scope="col">' + CASE WHEN EA.IsSelfPresent = 1 then 'Yes' ELSE 'No' END + '</td>	
	<td align="left" scope="col">' + CASE WHEN EA.IsFatherPresent = 1 then 'Yes' ELSE 'No' END + '</td>	
	<td align="left" scope="col">' + CASE WHEN EA.IsMotherPresent = 1 then 'Yes' ELSE 'No' END + '</td>	
	<td align="left" scope="col">' + ISNULL(EA.ParentFeedBack,'')+ '</td>	
	<td align="left" scope="col">' + ISNULL(EA.SchoolFeedback,'')+ '</td>	
	</tr>'
  FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sActivity.tEventAttendance EA ON  SA.AcademicId = EA.SourceId AND EA.SourceTypeId = 2001
			INNER JOIN sActivity.tEventSchedule ES ON EA.EventScheduleId=ES.Id 
			INNER JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
  WHERE 
			(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND ((ES.EventTypeId = @rEventTypeId) OR (@rEventTypeId = 0))
			AND((SA.AcademicId=@rAcademicId)OR(@rAcademicId=0)) 
			ORDER BY SA.ClassId,SA.DivisionId

	SELECT ISNULL(@lEventAttendanceGrid,'') as EventAttendanceGrid

END
GO
PRINT N'Creating Procedure [sEMeeting].[pEventTemplateGetForAttendance]...';


GO

CREATE PROCEDURE [sFee].[pRptFeeSummaryPaytypewiseReportGet]  
	@rReportId int=0,  
	@rIsFilter bit=0,  
	@rIsDisplayOrgGroup bit=0,
	@rOrgGroupBatchId int,  
	@rCommonBatch nvarchar(100)='',
	@rReceiptBookId int=0,  
	@rOrgId int,  
	@rBatchId int,
	@rDepartmentId int=0,  
	@rAdmissionCategoryId int=0,  
	@rClassId int=0,  
	@rDivisionId int=0, 
	@rFromDate date='',  
	@rToDate date='',  
	@rPaytypeId int=0, 
	@rCode nvarchar(20),
	@rFilterId int=0,  
	@rClassStatusId int=0 ,
	@rPayTypeIds nvarchar(max) = '',
	@rBuilder1 nvarchar(max)=0,  
    @rBuilder2 nvarchar(max)=0
	

 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
   
  --BEGIN      
  --SET @rBankName = sCommon.fSearchStringGet(@rBankName)      
  --  END   
  
 SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  
  --(CASE WHEN @rReportId IN (20456,30804) THEN  R.IsObsolete ELSE @rIsCancel END) AS IsCancel,  
  --@rIsCancel AS IsCancel,  
  @rIsFilter As IsFilter,  
   
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,
   RBM.Id AS ReceiptBookId,
   RBM.Title AS ReceiptBookTitle,
   RBM.FullTitle AS ReceiptBookFullTitle,
  --R.Id AS ReceiptId,  
  --R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.Code,  
  SA.Name,  
  ISNULL(PTM.Title,'') AS PayType,  
  RD.Amount AS ReceiptDetailAmount,  
  R.ReceiptAmount  
  --R.ReceiptDate,  
  --CASE  WHEN @rReportId = 30611 AND R.ChequeClearDate IS NOT NULL THEN R.ChequeClearDate ELSE R.ReceiptDate END AS ReceiptDate,  
  --R.CreatedUserId,  
  --ISNULL(U.LoginTitle,'') AS UserName,  
  --ISNULL(RBM.BankName,'') AS ReceiptBookBank,  
  --ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,  
  --ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,   
  -- R.Remark,  
  -- R.DiscountAmount,  
  -- ISNULL(RBM.OrderIndex,0) AS ReceiptBookOrderIndex,  
  -- SA.OrgId,  
  -- SA.OrganizationName,  
   --ISNULL(R.AmountAfterDiscount,0) AS AmountAfterDiscount,  
   --ISNULL(R.CGSTPercentage,0) AS CGSTPercentage,  
   --ISNULL(R.SGSTPercentage,0) AS SGSTPercentage,  
   --ISNULL(R.CGSTAmount,0) AS CGSTAmount,  
   --ISNULL(R.SGSTAmount,0) AS SGSTAmount,  
   --@rCustomGroupId AS CustomGroupId,  
   --SA.OrgGroupBatchId AS BatchId,  
   --SA.BatchName,  
   --R.ChequeDate,  
   --R.ChequeClearDate,
   --@rFeeGroupId As FeeGroup ,
   --FM.Title AS FeeName,
   --FHM.Title AS FeeHeadName
  FROM   
   sFee.tReceipt R  
	INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
  --INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id  
  --INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
  --INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId	
    
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId
   --LEFT JOIN sSecurity.tUser U  
   --ON U.Id=R.CreatedUserId  
 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId))   
    LEFT JOIN  
 (SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId   
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
   ON RT.SourceId = SA.StudentId   
 --   AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))    
 --   AND (SA.OrgGroupBatchId = RT.OrgGroupBatchId) 
 --  INNER JOIN sSetup.tDepartmentMaster DM  
 --  ON SA.DepartmentId=DM.Id  
 -- INNER JOIN sSetup.tOrganizationMaster O  
 --  ON O.Id=sa.OrgId 
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 --AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 --AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 --AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 --AND ((R.IsObsolete =@rIsCancel  AND (@rReportId != 20456 OR @rReportId != 30804))  OR   
 -- ((@rReportId = 20456 OR @rReportId = 30804) AND ((@rFeeStatusId = 0) -- All  
 -- OR (@rFeeStatusId = 1 AND R.IsObsolete = 0) -- Valid  
 -- OR (@rFeeStatusId = 2 AND R.IsObsolete = 1) -- Cancel  
 -- )))  
 --AND (SA.StatusId=@rStatusId OR @rStatusId=0)  
 AND (SA.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)  
 AND (R.PayTypeId = @rPaytypeId OR @rPaytypeId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 --AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 --AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 --AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 --AND ((@rIsDiscount =1 AND R.DiscountAmount!=0) OR (@rIsDiscount=0))  
 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
  AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
    )  
    --AND ((RBM.OrgGroupId=@rOrgGroupId) OR (@rOrgGroupId=0))  
 --AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))  
 --AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')    
 --AND (ISNULL(R.BankName,'') IN( SELECT cast(item as nvarchar(100)) FROM  sCommon.fnsplit(@rBankNames,',')) OR @rBankNames='')   
 --AND ((R.ChequeClearDate>=@rFromChequeClearDate)OR(ISNULL(@rFromChequeClearDate,'')=''))      
 --AND ((R.ChequeClearDate<=@rToChequeClearDate)OR(ISNULL(@rToChequeClearDate,'')=''))
 AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')     
  
 ORDER BY R.ReceiptNumber  
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Creating Procedure [sHrm].[pEmployeeWiseAttendanceGet]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeWiseAttendanceGet]
	 
	@rForYear  bigint,
	@rForMonth tinyint,
	@rBatchId int,
	@rOrgId int,
	@rDepartmentId int=0,
	@rEmployeeId bigint = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	DECLARE @lFirstDate Date
	DECLARE @lLasteDate Date
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))
	SET @lLasteDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@lFirstDate)+1,0))

	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	
BEGIN 
	SELECT  
		EM.Code AS EmployeeCode,
		EM.EmployeeName,
		EM.EmployeeId,
		ISNULL(EM.EmployeeGrade,'') AS EmployeeGrade,
		--ISNULL(WD.TotalDays,0) AS TotalDays,
		CASE 
			WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
			THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
			WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
			THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
			ELSE ISNULL(EWD.TotalDays,@lMonthDay)

		END AS TotalDays,

		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate) + 1 
		--	ELSE ISNULL(WD.TotalDays,0) 
		--END AS TotalDays,
		--ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
		
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
		--	WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
		--	THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
		--	ELSE ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) 
		--END AS WorkingDays,
		(CASE 
			WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
			THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate)  + 1 
			WHEN YEAR(EJD.DateOfleaving) = @rForYear AND MONTH(EJD.DateOfleaving) = @rForMonth 
			THEN  DATEDIFF(day, @lFirstDate , EJD.DateOfleaving) + 1
			ELSE ISNULL(AT.TotalWorkingDays,ISNULL(EWD.WorkingDays,@lMonthDay))		--add AT.TotalWorkingDays for 29619 Mantis Id

		END ) AS WorkingDays,
		
		(ISNULL(AT.TotalWorkingDays,0) - ((ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)))) AS PresentDays,
		
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)) + (1) 
		--	ELSE (ISNULL(AT.TotalWorkingDays,0) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0))) 
		--END AS PresentDays,
		
		(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS PayrollDays,
		
		--CASE 
		--	WHEN YEAR(EJD.DateOfJoining) = @rForYear AND MONTH(EJD.DateOfJoining) = @rForMonth  
		--	THEN DATEDIFF(day, EJD.DateOfJoining , @lLasteDate) - ISNULL(AT.LWP,0) + (1)
		--	ELSE (ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) 
		--END AS PayrollDays,
		
		(ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)) AS LWP,   -- Absent Days
		ISNULL(AT.PaidLeave,0) AS PaidLeave,
		ISNULL(AT.LWP,0) AS UnPaidLeave,
		ISNULL(AT.LateCount,0) AS LateCount,
		ISNULL(AT.LateDeductionDays,0) AS LateDeductionDays,
		ISNULL(AT.SandwichDeductionDays,0) AS SandwichDeductionDays,
		ISNULL(CONVERT(VARCHAR(50),EM.DateOfJoining,103),'') AS DateOfJoining,
		ISNULL(CONVERT(VARCHAR(50),EM.DateOfLeaving,103),'') AS DateOfLeaving
		
	FROM 
		sHrm.vEmployeeCommonDetail EM 
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
		--INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
		--AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId
		INNER JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id =  EJD.EmployeeGradeId
		INNER JOIN sHrm.tEmployeeWorkingDays EWD ON EWD.EmployeeId=EM.EmployeeId	--make a inner join insted of left join for 29619 Mantis Id
		AND EWD.BatchId=@rBatchId 
		AND EWD.ForYear=@rForYear
		AND EWD.ForMonth =@rForMonth 
		LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId		 
		AND AT.ForMonth=@rForMonth AND AT.ForYear=@rForYear AND AT.BatchId = @rBatchId
	WHERE 
		EM.OrgID = @rOrgId 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
		AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (EM.IsOtherUser = 0)
		AND ((EM.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
	ORDER BY 
		EM.Number
END
GO
PRINT N'Creating Procedure [sPurchase].[pPurchaseStoreLocationMasterGet]...';


GO

CREATE PROCEDURE [sStudent].[pRptClassDivisionCapacityGet]
	
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rOrgMainGroupId int,
		@rOrgSubGroupId int,
		@rOrgId int,
		@rDepartmentId int,
		@rClassId int,
		@rDivisionId int,
		@rOrgGroupId int
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			--@rIsTestMainGroup AS IsTestMainGroup,
			--@rIsTestSubGroup AS IsTestSubGroup,
			--@rIsTestOrg AS IsTestOrg,
			--@rIsTestClass AS IsTestClass,
			--@rIsTestDepartment AS IsTestDepartment,
			--@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			CM.Id AS ClassId,
			CM.DisplayTitle AS ClassName,
			CM.OrderIndex,
			CM.DepartmentId,
			DeptM.DisplayTitle AS DepartmentName,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			ISNULL(CM.Capacity,0) AS ClassCapacity,
			ISNULL(DM.Capacity,0) AS DivisionCapacity,
			(SELECT ISNULL(count(1),0)  FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id = BM.BatchGroupId 
			--INNER JOIN sStudent.tStudentAdmission  SA on SA.StudentId = SM.Id 
			WHERE A.ClassId = CM.Id 
			--AND SA.AdmissionDate <= @rUptoDate
			--AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			--AND ((BGM.Id = @rBatchGroupId) OR (@rBatchGroupId = 0)) 
			--AND ((SM.StatusId = @rStudentStatusId) OR (@rStudentStatusId=0))
			) 
			AS ClassCurrentStrength,

			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.ID=BM.BatchgroupId
			WHERE A.DivisionId = DM.Id 
			--AND SM.StatusId = 1 			
			) AS DivisionCurrentStrength,

			(SELECT ISNULL(count(1),0)  FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id = BM.BatchGroupId 
			--INNER JOIN sStudent.tStudentAdmission  SA on SA.StudentId = SM.Id 
			WHERE A.ClassId = CM.Id 
			AND SM.StatusId = 3
			--AND SA.AdmissionDate <= @rUptoDate
			--AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			--AND ((BGM.Id = @rBatchGroupId) OR (@rBatchGroupId = 0)) 
			--AND ((SM.StatusId = @rStudentStatusId) OR (@rStudentStatusId=0))
			) 
			AS LeftStudentClassWise,

			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.ID=BM.BatchgroupId
			WHERE A.DivisionId = DM.Id 
			AND SM.StatusId = 3 			
			) AS LeftStudentDivisionWise,

			(SELECT ISNULL(count(1),0)  FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.Id = BM.BatchGroupId 
			--INNER JOIN sStudent.tStudentAdmission  SA on SA.StudentId = SM.Id 
			WHERE A.ClassId = CM.Id 
			AND SM.StatusId = 2
			--AND SA.AdmissionDate <= @rUptoDate
			--AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			--AND ((BGM.Id = @rBatchGroupId) OR (@rBatchGroupId = 0)) 
			--AND ((SM.StatusId = @rStudentStatusId) OR (@rStudentStatusId=0))
			) 
			AS InActiveStudentClassWise,

			(SELECT ISNULL(count(1),0) FROM sStudent.tAcademic A 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id 
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
			INNER JOIN sSetup.tBatchGroupMaster BGM ON BGM.ID=BM.BatchgroupId
			WHERE A.DivisionId = DM.Id 
			AND SM.StatusId = 2			
			) AS InActiveStudentDivisionWise,
			DM.Title AS  DivisionName
					
	FROM 
			sSetup.tDivisionMaster DM
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId
			--INNER JOIN sSetup.tBatchClass BC ON CM.Id=BC.ClassId
			INNER JOIN sSetup.tDepartmentMaster DeptM ON DeptM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = DM.OrgId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			--LEFT JOIN 
  WHERE 
			--BC.BatchId = @rBatchId
			((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((DM.Id=@rDivisionId) OR (@rDivisionId=0)) 
			AND ((CM.Id=@rClassId) OR (@rClassId=0))
			AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
			AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
			AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
			AND ((OM.OrgGroupId = @rOrgGroupId))
			
			ORDER BY CM.OrderIndex ASC
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentDetailFormGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentDetailFormGet]
	@rBatchId int = 0,
	@rStudentId bigint = 0,
	@rOrgGroupBatchId int = 0,
	@rOrgId int = 0,
	@Tab nvarchar(20) = '',
	@rAttendanceTypeId smallint = 0,
	@rDepositHeadId int = 0,
	@rAlertModeId smallint = 0,
	@rIsMobileApp bit = 0,
	@rExamId int = 0

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @lSUIdBarcode nvarchar(50)
	DECLARE @lAcademicId bigint = 0, @lClassId int  = 0, @lAdmissionCategoryId int = 0,@lCode nvarchar(20) = '',@lEmail nvarchar(50) = '',@lContactNo nvarchar(50) ='',@lDate datetime = (SELECT sCommon.fGetDate()),@lOrgGroupId int = 0,
	@lDepartmentId int = 0, @lDivisionId int = 0
	SELECT @lAcademicId = Id,@lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId,@lDivisionId = DivisionId from sStudent.tAcademic
	Where StudentId = @rStudentId AND BatchId = @rBatchId
	SELECT @lCode = Code FROM sStudent.tStudentMaster WHERE Id = @rStudentId
	SELECT @lEmail = ParentEmail, @lContactNo = ParentContactNo FROM sStudent.tStudentCommunication WHERE StudentId = @rStudentId
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId	
	SELECT @lDepartmentId = DepartmentId FROM sSetup.tClassMaster WHERE Id = @lClassId
	SELECT @lSUIdBarcode = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 168 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId



	IF(LOWER(@Tab) = 'overview')
	BEGIN
		SELECT
			SA.StudentId AS Id,			
			SA.Name AS StudentName,
			SA.FirstName as FirstName,
			SA.MiddleName as MiddleName,
			SA.LastName as LastName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			ISNULL(SA.DateOfBirth,'0001/01/01') AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			SA.GenderId,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,			
			ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			ISNULL(SA.LeftDate,'0001/01/01') AS LeftDate,						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,			
			ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,			
			ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			--Communication
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.FatherIncome,'') AS FatherIncome,

			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.MotherIncome,'') AS MotherIncome,

			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SF.RelativeIncome,'') AS RelativeIncome,
			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,

			-- Photos		
	   	    ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentPhoto,
	   	    ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
	   	    ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
	   	    ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			
		   -- Transport Details
		    A.VehicleName AS VehicleName,
		    A.VehicleRegistrationNumber AS VehicleRegistrationNumber,
		    A.TypeOfVehicle AS TypeOfVehicle,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    A.DriverName,
		    A.DriverMobileNo,
		    A.ConductorName,
		    A.ConductorMobileNo,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,		    
		    A.DropVehicleName AS DropVehicleName,
		    A.DropVehicleRegistrationNumber AS DropVehicleRegistrationNumber,
		    A.DropTypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    A.DropRouteDriverName AS DropRouteDriverName,
		    A.DropRouteDriverMobileNo AS DropRouteDriverMobileNo,
		    A.DropRouteConductorName AS DropRouteConductorName,
		    A.DropRouteConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
			ISNULL(FED.PaidAmount,0) AS FeePaidAmount,
			ISNULL(FED.PendingAmount,0) AS FeePendingAmount,
			ISNULL(FED.PaidAmount,0) + ISNULL(FED.PendingAmount,0) AS FeeTotalAmount,
			(SELECT COUNT(AcademicId) FROM sAttendance.tStudentRegister WHERE AcademicId = @lAcademicId AND IsPresent = 0) AS AbsentCount,
			(SELECT COUNT(AcademicId) FROM sAttendance.tStudentRegister WHERE AcademicId = @lAcademicId AND IsPresent = 1) AS PresentCount,

			--TecherSubjectDivision
			--EM.FirstName + ' ' + EM.LastName AS DivisionTeacherName,
			--SM.Title AS DivisionSubjectName,

			-- Today's Lectures

			ISNULL(STUFF((
			SELECT ',' + OnlineLearningTitle FROM 
			(SELECT OL.Title AS OnlineLearningTitle FROM sAcademic.tOnlineLearning OL INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
				WHERE (
				( 
				(OLS.SourceTypeId = 2021 AND OLS.SourceId =SA.OrgId) 
				OR
				(OLS.SourceTypeId = 2017 AND OLS.SourceId =SA.DepartmentId) OR
				(OLS.SourceTypeId = 2016 AND OLS.SourceId =SA.ClassId) OR
				(OLS.SourceTypeId = 2005 AND OLS.SourceId =SA.DivisionId) OR
				(OLS.SourceTypeId = 2003 AND OLS.SourceId =SA.StudentId) OR
				(OLS.SourceTypeId = 2001 AND OLS.SourceId =SA.AcademicId)
				 ))
				) D
				ON D.OnlineLearningId= OL.Id WHERE OL.StartDate >= CAST(sCommon.fGetDate() AS DATE) AND OL.EndDate <= CAST(sCommon.fGetDate() AS DATE)) OL FOR XML PATH('')),1,1,''),'') AS OnlineLearningLectures,

			ISNULL(STUFF((
				SELECT ',' + ExamName + ' (' + CAST([Percentage] AS NVARCHAR(20)) + ')' FROM (
				SELECT AD.Id AS AcademicId,E.[Name] AS ExamName, R.[Percentage] FROM
				sStudent.tAcademic AD 
				INNER JOIN  sAssessment.vExamMaster E ON E.BatchId = AD.BatchId AND E.ClassId = AD.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON E.BatchId = BM.Id 
				INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=AD.DivisionId
				INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = E.Id
 
				 WHERE ((AD.Id=@lAcademicId) OR (@lAcademicId=0))	
					AND IsProcessResult=1 ) E
				FOR XML PATH('')),1,1,''),'') AS ExamPercentage,
				
			(SELECT SUM(Amount) FROM sFee.tDepositAdd WHERE AcademicId = @lAcademicId) AS DepositCreditAmount,
			(SELECT SUM(Amount) FROM sFee.tDepositAdjustment WHERE AcademicId = @lAcademicId) + (SELECT SUM(RefundAmount) FROM sFee.tDepositRefund WHERE AcademicId = @lAcademicId) AS DepositDebitAmount,
			ISNULL(SI.QRCode,0x) AS QRCode,
			CASE WHEN @lSUIdBarcode = 'True' THEN SA.SUId  ELSE SA.Code END AS BarcodeNumber

			FROM 
			sStudent.vStudentAllDetail SA          
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId           
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId  
		   LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
		   --LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = SA.DivisionId
		   --LEFT JOIN sSetup.tSubjectMaster SBM ON SBM.Id = TSD.SubjectId
		   --LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD.EmployeeId
            LEFT JOIN --HostelDetails
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1           
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN -- Transport Details
           ( SElect AR1.SourceId,
           VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		      FROM
             sTransport.tAssignRoute AR1   
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId) A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.StudentId AND CGM.SourceTypeId = 2003
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
		   LEFT JOIN sStudent.tStudentAdmission SAM ON SAM.StudentId = SA.StudentId
		   LEFT JOIN -- Fee Details
		   (
				SELECT 
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount,
			FS.BatchId
			  FROM 
						sFee.tFeeMaster FM
					INNER JOIN 
					(
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
				 
						FROM sFee.tFeeSetup FS1
			   
							WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
							AND FS1.BatchId = @rBatchId
							UNION ALL
				
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId 
				 
						FROM sFee.tFeeSetup FS1
			 
					INNER JOIN sFee.tFeeOptional FO
						ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
						WHERE
						 FS1.BatchId = @rBatchId
						AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
					) FS ON FS.FeeId=FM.Id
					LEFT JOIN sFee.tFeeAllocation FA
						ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
					LEFT JOIN
					(
						SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
						FROM
						sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
						WHERE						
						 R.SourceId= @lAcademicId
						AND ((R.SourceTypeId = 2001))
						AND R.IsObsolete = 0 
						AND R.BatchId = @rBatchId
						 GROUP BY FeeSetupId
					) R ON R.FeeSetupId = FS.Id	
			WHERE 
				FS.BatchId=@rBatchId
				GROUP BY FS.BatchId
		   ) FED ON FED.BatchId = SA.BatchId			  		  

  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))			
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))			
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))			
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId = 0))
	END
	ELSE IF(LOWER(@Tab) = 'studentdetails')
	BEGIN
		exec sStudent.pStudentFullProfileGet @rBatchId=@rBatchId,@rStudentId=@rStudentId,@rOrgGroupBatchId=@rOrgGroupBatchId,@rOrgId=@rOrgId
	END	
	ELSE IF(LOWER(@Tab) = 'feedetails')
	BEGIN
		IF(@rIsMobileApp = 0)
		BEGIN
			exec [sFee].[pFeeAllocationViewGet] @rSourceId=@lAcademicId,@rSourceTypeId=2001,@rBatchId=@rBatchId
		
			DECLARE @Receiptgrid NVARCHAR(max)=''
			SELECT  @Receiptgrid = @Receiptgrid + '<tr>		
			<td align="left" scope="col">' + ISNULL(RBM.Title,'') + '</td>
			<td style="color:Black;overflow-wrap:anywhere;"><a style="color: #03afc5 !important;" onclick="FeeReceiptEdit(' + convert(nvarchar,R.ReceiptBookId) + ',' + convert(nvarchar,R.PayTypeId) + ',' + convert(nvarchar,R.ReceiptNumber) + ')">' + convert(varchar,isnull(R.ReceiptNumber,'')) + '</a></td>		
			<td align="left" scope="col">' +  convert(varchar,isnull(R.ReceiptDate,'01/01/0001'),103) + '</td>
			<td align="left" scope="col">' +  ISNULL(PTM.Title,'') + '</td>
			<td align="left" scope="col">' +  isnull(R.ChequeNo,'') + '</td>
			<td align="left" scope="col">' + isnull(R.BankName,'') + '</td>
			<td align="left" scope="col">' +  ISNULL([sFee].[fReceiptFeeDetailGet](R.Id),'') + '</td>
			<td align="left" scope="col">' +  convert(varchar,isnull(R.ReceiptAmount,0)) + '</td>
			<td><input type="button" id="' + convert(varchar,R.Id) + '" value="&#xf02f; Print Fee Receipt" onclick="PrintFeeReceipt(this, ' + convert(varchar,R.Id) + ', ' + convert(varchar,RBM.Id) + ');" class="fas btn btn-report " /></td>
			</tr>'	
			
		  FROM 
					sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic SA
					ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
				INNER JOIN sFinanceCommon.tPayTypeMaster PTM
					ON PTM.Id=R.PayTypeId
				LEFT JOIN sSecurity.tUser U
					ON U.Id=R.CreatedUserId
				INNER JOIN sFee.tReceiptBookMaster RBM 
					ON RBM.Id=R.ReceiptBookId
			
		WHERE 
			R.SourceTypeId = 2001
			AND SA.AcademicId=@lAcademicId		
			ORDER BY R.ReceiptNumber
			
			
		select isnull(@Receiptgrid,'') as Receiptgrid

			--exec [sFee].[pFeeReceiptListViewGet] @rAcademicId=@lAcademicId,@rOrgId=@rOrgId
			exec [sFee].[pFeecancelReceiptListviewGet] @rBatchId=@rBatchId,@rOrgId=@rOrgId,@rAcademicId=@lAcademicId		
			exec [sFee].[pRptFeePendingAllBatchGet] @rOrgGroupBatchId=0,@rOrgId=@rOrgId,@rBatchId=0,@rCode=@lCode,@rUserId=0

			--exec [sFee].[pFeeAllocationViewGet] @rSourceId=@lAcademicId,@rSourceTypeId=2001,@rBatchId=@rBatchId
		END
		ELSE
		BEGIN
			exec [sFee].[pFeeAllocationViewGet] @rSourceId=@lAcademicId,@rSourceTypeId=2001,@rBatchId=@rBatchId

			SELECT  
			ISNULL(RBM.Title,'') AS ReceiptBook,
			convert(varchar,isnull(R.ReceiptNumber,'')) AS ReceiptNumber,
			convert(varchar,isnull(R.ReceiptDate,'01/01/0001'),103) AS ReceiptDate,
			ISNULL(PTM.Title,'') AS PayType,
			isnull(R.ChequeNo,'') AS ChequeNo,
			isnull(R.BankName,'') AS BankName,
			ISNULL([sFee].[fReceiptFeeDetailGet](R.Id),'') AS FeeDetail,
			convert(varchar,isnull(R.ReceiptAmount,0)) AS ReceiptAmount						
			  FROM 
						sFee.tReceipt R
					INNER JOIN sStudent.vStudentAcademic SA
						ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
					INNER JOIN sFinanceCommon.tPayTypeMaster PTM
						ON PTM.Id=R.PayTypeId
					LEFT JOIN sSecurity.tUser U
						ON U.Id=R.CreatedUserId
					INNER JOIN sFee.tReceiptBookMaster RBM 
						ON RBM.Id=R.ReceiptBookId			
			WHERE 
				R.SourceTypeId = 2001
				AND SA.AcademicId=@lAcademicId		
				ORDER BY R.ReceiptNumber


			SELECT convert(varchar,Isnull(R.ReceiptNumber,0)) AS ReceiptNumber,
			convert(varchar,ISNULL(R.ReceiptDate,'01/01/0001'),103) AS ReceiptDate,
			Convert(varchar,ISNULL(R.ReceiptAmount,0)) AS ReceiptAmount,
			ISNULL(PTM.Title,'') AS PayType,
			ISNULL(R.ChequeNo,'') AS ChequeNo,
			ISNULL(R.BankName,'') AS BankName,
			ISNULL(RBM.Title,'') AS ReceiptBook,
			convert(varchar,ISNULL(FI.InvoiceNumber,0)) AS InvoiceNumber,
			 convert(varchar,ISNULL(R.Remark,'')) AS Remark			
		  FROM 
				sFee.tReceipt R
				INNER JOIN sStudent.vStudentAcademic A
					ON A.AcademicId=R.SourceId
				INNER JOIN sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=R.PayTypeId
				INNER JOIN sFee.tReceiptBookMaster RBM
					ON RBM.Id=R.ReceiptBookId
				LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId
		WHERE 
				R.SourceTypeId=2001 AND R.IsObsolete=1
				AND A.OrgId=@rOrgId AND R.BatchId=@rBatchId
				AND A.AcademicId=@lAcademicId
			   ORDER BY R.ReceiptNumber DESC


            /**** Changes done for mantis : 28925 ****/
		
		SELECT 
			ISNULL(OM.DisplayTitle,'') AS OrganizationName,
			SA.FirstName+' '+SA.LastName as StudentName,
			convert(varchar,Isnull(CR.ReceiptNumber,0)) AS ReceiptNumber,
			convert(varchar,ISNULL(CR.ReceiptDate,'01/01/0001'),103) AS ReceiptDate,
			ISNULL(RBM.Title,'') AS ReceiptBook,
			ISNULL(CCM.Title,'') AS ChargeCategory,
			convert(varchar,ISNULL(SUM(CRD.Amount),0)) AS Amount
			
		    FROM 
            sFee.tChargeReceipt CR
		    INNER JOIN sFee.tChargeReceiptDetail CRD ON CRD.ChargeReceiptId=CR.Id	
		    INNER JOIN sFee.tChargeMaster CM ON CM.Id=CRD.ChargeId
		    INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId AND CR.SourceTypeId=2001
		    INNER JOIN sFee.tChargeCategoryMaster CCM ON CCM.Id=CM.ChargeCategoryId
		    INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		    INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CR.OrgId
		    WHERE 
			CR.SourceTypeId=2001 AND CR.IsObsolete=0
			AND SA.OrgId=@rOrgId AND CR.BatchId=@rBatchId
			AND SA.AcademicId=@lAcademicId
			GROUP BY
            OM.DisplayTitle,
            SA.FirstName,
            SA.LastName,
            CR.ReceiptNumber,
            CR.ReceiptDate,
            RBM.Title,
            CCM.Title
            ORDER BY CR.ReceiptNumber DESC

		SELECT 
		    ISNULL(DHM.Title,'') AS DepositHeadName,
		    ISNULL(vSA.Name,'') AS StudentName, 
		    ISNULL(vSA.Code,'') AS GrNo,
		    vSA.ClassName AS Class,
		    ISNULL(EM.Title,'') As ExpenseType,
		    Convert(varchar,ISNULL(DA.Amount,0)) AS Amount,
		    convert(varchar,ISNULL(DA.AdjustmentDate,'01/01/0001'),103) AS AdjustmentDate
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdjustment DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId
		LEFT JOIN  sFee.tFeeDepositExpenseTypeMaster EM ON EM.Id=DA.FeeDepositExpenseTypeId
  WHERE 				
		vSA.OrgId=@rOrgId AND vSA.BatchId=@rBatchId
		AND vSA.AcademicId=@lAcademicId
		ORDER BY vSA.Name DESC

		SELECT 
		ISNULL(DHM.Title,'') AS DepositHeadName,
		ISNULL(vSA.Name,'') AS StudentName,
		ISNULL(vSA.Code,'') AS GrNo, 
		ISNULL(vSA.ClassName,'') AS Class,
		convert(varchar,(CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
        (SELECT ISNULL(SUM(D.Amount),0) FROM sFee.tDepositAdd D 
        INNER JOIN sFee.tDepositRefund DR1 ON DR1.DepositHeadId=D.DepositHeadId AND DR1.AcademicId=D.AcademicId AND D.AcademicId = DR.AcademicId
        WHERE D.DepositHeadId = DR1.DepositHeadId AND D.AcademicId=DR1.AcademicId )         
		 - (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sFee.tDepositAdjustment DA 
		 INNER JOIN sFee.tDepositRefund DR2 ON DR2.DepositHeadId=DA.DepositHeadId AND DR2.AcademicId=DA.AcademicId AND DA.AcademicId= DR.AcademicId
		 WHERE DA.DepositHeadId = DR2.DepositHeadId AND DA.AcademicId=DR2.AcademicId ) END)) AS RefundAmount,
		 convert(varchar,ISNULL(DR.RefundDate,'01/01/0001'),103) AS RefundDate
		
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DR.DepositHeadId

  WHERE 				
		vSA.OrgId=@rOrgId AND vSA.BatchId=@rBatchId
		AND vSA.AcademicId=@lAcademicId
		--AND DR.DepositHeadId=@rDepositHeadId
		ORDER BY vSA.Name DESC

		/**** Changes done for mantis : 28925 ****/

		END
	END	
	ELSE IF(LOWER(@Tab) = 'attendance')
	BEGIN
		IF(@rIsMobileApp = 0)
		BEGIN
			IF(@rAttendanceTypeId = 5)
			BEGIN
			exec [sAttendance].[pSubjectRegisterStudentViewGet] @rAcademicId = @lAcademicId,@rBatchId = @rBatchId, @rAttendanceTypeId = @rAttendanceTypeId		
			END
			ELSE 
			BEGIN
			exec [sAttendance].[pMonthlyRegisterStudentviewGet] @rAttendanceTypeId = @rAttendanceTypeId, @rAcademicId = @lAcademicId,@rBatchId = @rBatchId
			END
		END
		ELSE
		BEGIN	
			IF(@rAttendanceTypeId <> 5)
			BEGIN
			SELECT 
				Isnull(MY.MonthTitle,'') AS ForMonth,
				CAST(isnull(MY.YearNumber,0) AS NVARCHAR(20)) AS ForYear,
				CAST(isnull(MR.AttendanceCount,0) AS NVARCHAR(20)) AS AttendanceCount,
				CAST(isnull(MR.PresentCount,0) AS NVARCHAR(20)) AS PresentDays,
				CAST(isnull(MR.AbsentCount,0) AS NVARCHAR(20)) AS AbsentDays,
				CAST(isnull(MR.AveragePresence,0) AS NVARCHAR(20)) AS AveragePresence,
				CAST(isnull(MR.AbsentDays,0) AS NVARCHAR(20)) AS AbsentDate					
			FROM sStudent.vStudentName SN 
			INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@lAcademicId 
			INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
				AND MR.AttendanceTypeId=@rAttendanceTypeId
				AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
			WHERE
				SN.AcademicId=@lAcademicId	
			ORDER BY MY.YearNumber,MY.MonthNumber
			END
			ELSE
			BEGIN
			Select 
				isnull(SM.Title,'') AS [Subject],
				(SELECT convert(varchar,ISNULL(count(1),0) )FROM sAttendance.tStudentRegister SR  WHERE  SR.AttendanceTypeId = 5 AND SR.IsPresent = 1 AND SR.AcademicId = SN.AcademicId  AND SR.SubjectId = CS.SubjectId) AS PresentCount,
				(SELECT convert(varchar,ISNULL(count(1),0)) FROM sAttendance.tStudentRegister SR WHERE SR.AttendanceTypeId = 5 AND SR.IsPresent = 0 AND SR.AcademicId = SN.AcademicId AND SR.SubjectId = CS.SubjectId) AS AbsentCount	
				From sStudent.vStudentName SN
				INNER JOIN sSetup.tClassSubject CS
				ON SN.ClassId = CS.ClassId
				INNER JOIN sSetup.tSubjectMaster SM
				ON CS.SubjectId = SM.Id 
				WHERE
					(SN.AcademicId=@lAcademicId)
					AND SN.BatchId = @rBatchId
			END
		END
	END
	ELSE IF(LOWER(@Tab) = 'assessment')
	BEGIN
		IF (@rIsMobileApp = 0) 
		BEGIN
			exec [sAssessment].[pExamListGet] @rAcademicId = @lAcademicId, @rBatchId = @rBatchId
		END
		ELSE
		BEGIN
			SELECT  ISNULL(Cm.DisplayTitle,'')+' - '+isnull(Dm.DisplayTitle,'')+' : '+isnull(E.Name,'') AS ExamName,
			isnull(BM.Title,'') AS [Year],
			convert(varchar,isnull(R.TotalMarks,0)) AS TotalMarks,
			convert(varchar,isnull(R.TotalObtain,'')) AS TotalObtain,
			isnull(R.ResultStatus,'') AS Result,
			isnull(R.ResultGrade,'') AS Grade,
			convert(varchar,isnull(R.RankNumber,0)) AS [Rank],
			convert(varchar,isnull(R.Percentage,0)) AS [Percentage],
			convert(varchar,isnull(R.Percentile,0)) AS Percentile,
			@lAcademicId AS AcademicId,
			convert(varchar,E.Id) AS ExamId
			 From
			 sStudent.tAcademic AD 
			 INNER JOIN  sAssessment.vExamMaster E ON E.BatchId = AD.BatchId AND E.ClassId = AD.ClassId
			 INNER JOIN sSetup.tBatchMaster BM ON E.BatchId = BM.Id 
			 INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=AD.DivisionId
			 INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = E.Id
 
			 WHERE ((AD.Id=@lAcademicId) OR (@lAcademicId=0))	
			 AND IsProcessResult=1
			 ORDER BY DM.OrderIndex DESC


			 SELECT isnull(ESGM.Title,'') AS ExamName,
			 isnull(SBM.Title,'') AS [Subject],
			convert(varchar,isnull(ED.Maximum,0)) AS Maximum,
			convert(varchar,isnull(ED.Minimum,0)) AS Minimum,
			convert(varchar,isnull(RD.Obtain,0)) As Obtain,
			convert(varchar,isnull(RD.GraceMark,0)) AS GraceMark,
			isnull(RD.Remark,'') AS Remark			
    	
		   FROM sStudent.tAcademic AD
			INNER JOIN sAssessment.tExamMaster EM ON EM.BatchId = AD.BatchId AND EM.ClassId = AD.ClassId
			INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
			INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = EM.Id
			INNER JOIN sAssessment.tResultDetail RD ON RD.ExamDetailId = ED.Id AND R.Id = RD.ResultId
			INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SBM ON SBM.Id = CS.SubjectId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId
			Where
			((AD.Id=@lAcademicId) OR (@lAcademicId=0))
			AND ((AD.BatchId =  @rBatchId) OR (@rBatchId=0))
		   AND ((EM.Id=@rExamId) OR (@rExamId=0))
		END
	END
	ELSE IF(LOWER(@Tab) = 'certificate')
	BEGIN
		SELECT 'Bonafied' AS CertificateName,CreatedDateTime,Number AS CertificateNumber,Id FROM [sCertificate].[tBonafide] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId
		UNION ALL
		SELECT 'Character' AS CertificateName,CreatedDateTime,Number AS CertificateNumber,Id FROM [sCertificate].[tCharacter] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId		
		UNION ALL
		SELECT 'Leaving' AS CertificateName,CreatedDateTime,LCNumber AS CertificateNumber,Id FROM [sCertificate].[tLeaving] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId
		UNION ALL
		SELECT 'FirstTrial' AS CertificateName,CreatedDateTime,Number AS CertificateNumber,Id FROM [sCertificate].[tFirstTrial] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId		
		UNION ALL
		SELECT 'Transfer' AS CertificateName,CreatedDateTime,Number AS CertificateNumber,Id FROM [sCertificate].[tTransfer] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId
	END
	ELSE IF(LOWER(@Tab) = 'deposit')
	BEGIN
		exec sFee.pStudentLedgerGet @rAcademicId=@rStudentId,@rDepositHeadId=@rDepositHeadId,@rCode=@lCode,@rSUId=N'',@rOrgId=@rOrgId
	END
	ELSE IF(LOWER(@Tab) = 'alert')
	BEGIN				
		IF(@rIsMobileApp = 1)
		BEGIN
			SELECT 
				'Notification' AS SourceEvent,EM.Title AS EventName,AL.MessageTitle AS AlertSubject,[sCommon].[fXMLTagsReplace](AL.NotificationMessage) as AlertMessage,CONVERT(VARCHAR(10),AL.CreatedDateTime,103) AS CreatedDate,'3' AS AlertModeId			
			FROM
				sAlert.tNotificationLog AL
				INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			WHERE  
				AL.SourceId = @lAcademicId AND AL.SourceTypeId = 2001				

				UNION ALL

			SELECT 
				AL.SourceEvent,EM.Title AS EventName,AL.AlertSubject,[sCommon].[fXMLTagsReplace](AL.AlertMessage) as AlertMessage,CONVERT(VARCHAR(10),AL.CreatedDateTime,103) AS CreatedDate,CAST(AL.AlertModeId AS NVARCHAR(10)) AS AlertModeId
			FROM
				sAlert.tAlertLog AL
				INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			WHERE  
				((AL.ContactId = @lContactNo) OR (AL.ContactId = @lEmail))
				And AL.OrgId=@rOrgId				
		END
		ELSE 
		BEGIN
			IF(@rAlertModeId = 3)
			BEGIN
				exec sAlert.pNotificationViewGet @rSourceId = @lAcademicId, @rSourceTypeId = 2001, @rIsFlag = 1
			END
			ELSE
			BEGIN
				exec [sAlert].[pSMSViewGet] @rMobileNumber = @lContactNo,@rEmail = @lEmail, @rOrgId = @rOrgId, @rIsFlag = 1, @rAlertModeId = @rAlertModeId		
			END
		END
	END
	ELSE IF(LOWER(@Tab) = 'library')
	BEGIN
		IF(@rIsMobileApp = 1)
		BEGIN
			SELECT
				Isnull(LM.Title,'') AS [Library],
				ISNULL(BM.Code,'') AS BookCode,
				isnull(BM.Title,'') AS BookTitle,
				convert(varchar,isnull(BL.LogDate,''),103) AS LogDate,
				convert(varchar,isnull(BL.DueDate,''),103) AS DueDate,
				CASE WHEN SM.Title = 'Available' THEN  'Returned' ELSE ISNULL(SM.Title,'') END AS [Status]		
			FROM 
				sLibrary.tBookLog BL
				INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
				INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId
				INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId=2005 AND BL.LibraryId = IS1.LibraryId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId AND SM.IsObsolete = 0 AND SM.StatusTypeId=106
				INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
			WHERE 
				(BL.ReaderSourceTypeId=2003)
				AND BL.IsCurrentStatus=1
				AND ((BL.StatusId=521) OR (BL.StatusId=523))
				AND (BL.OrgId=@rOrgId)
				AND (BL.BatchId=@rBatchId)
				AND SA.AcademicId=@lAcademicId
		END
		ELSE BEGIN
		exec [sLibrary].[pBookLogListViewGet] @rAcademicId = @lAcademicId, @rOrgId = @rOrgId,@rBatchId = @rBatchId
		END
	END
	ELSE IF(LOWER(@Tab) = 'paymentdetails')
	BEGIN
		exec sOp.pPaymentTransactionGet @rId=@lAcademicId,@rFromDate=NULL,@rToDate=@lDate,@rTransactionStatusId=0,@rFunctionalityId=0,
		@rFirstName=NULL,@rOrgGroupId=@lOrgGroupId,@rOrgId=@rOrgId,
		@rBatchId=@rBatchId,@rReceiptBookId=0,@rOSTypeId=0,@rFormNo=0,@rReferenceNo=0,@rPaymentGatewayId=0
	END
	ELSE IF(LOWER(@Tab) = 'onlinelearning')
	BEGIN
	SELECT OL.Title AS OLTitle,  OL.StartTime, OL.EndTime, SM.Title AS [Subject], EM.FirstName + ' ' + Em.LastName AS EmployeeName, DM.Title AS LearningType FROM sAcademic.tOnlineLearningScope OLS
	INNER JOIN sAcademic.tOnlineLearning OL ON OL.Id = OLS.OnlineLearningId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TeacherEmployeeId
	INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
	WHERE (
	( 
	(OLS.SourceTypeId = 2021 AND OLS.SourceId = @rOrgId) 
	OR
	(OLS.SourceTypeId = 2017 AND OLS.SourceId = @lDepartmentId) OR
	(OLS.SourceTypeId = 2016 AND OLS.SourceId = @lClassId) OR
	(OLS.SourceTypeId = 2005 AND OLS.SourceId = @lDivisionId) OR
	(OLS.SourceTypeId = 2003 AND OLS.SourceId = @rStudentId) OR
	(OLS.SourceTypeId = 2001 AND OLS.SourceId = @lAcademicId)
		))

	AND OL.StartDate = CAST(sCommon.fGetDate() AS DATE)

	SELECT
		ISNULL((SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 1 And AcademicId = @lAcademicId),0) AS PresentCount,
		ISNULL((SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 0 And AcademicId = @lAcademicId),0) AS AbsentCount,
		CAST(ISNULL((((SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 1 And AcademicId = @lAcademicId) / 
		(SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 0 And AcademicId = @lAcademicId)) * 100 ),0) AS DECIMAL(10,2)) AS PresentPercentage
	
	END
	ELSE IF(LOWER(@Tab) = 'charge')
	BEGIN
		exec sFee.pChargeReceiptListGet @rSourceTypeId=0,@rGuestName=N'*',@rSourceCode=@lCode,@rFromDate=NULL,@rToDate=NULL,@rReceiptBookId=0,@rChargeCategoryId=0,@rOrgId=@rOrgId,@rBatchId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromNo=0,@rToNo=0,@rOrgGroupId=@lOrgGroupId
	END
	ELSE IF(LOWER(@Tab) = 'siblingdetails')
	BEGIN
		exec sStudent.pSiblingLinkListGet @rStudentId=@rStudentId
	END
	ELSE IF (LOWER(@Tab) = 'teachersubject')
	BEGIN
		SELECT DISTINCT SM.Title AS SubjectName,
		(SELECT Stuff (( select ',' + Convert(nvarchar(MAX),EM.FirstName + ' ' + EM.LastName)
			FROM 
			sAcademic.tTeacherSubjectDivision TSD1
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD1.EmployeeId AND EM.StatusId = 7
			WHERE 
			TSD1.SubjectId = TSD.SubjectId AND TSD1.DivisionId = @lDivisionId
			  FOR XML PATH('')  
			 ),1,1,'')) TeacherName

		FROM 
		sAcademic.tTeacherSubjectDivision TSD
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TSD.SubjectId
		WHERE TSD.DivisionId = @lDivisionId
	END
	ELSE IF (LOWER(@Tab) = 'activitybehaviour')
	BEGIN		
		SELECT
			convert(varchar,isnull(A.FromDate,''),103) AS FromDate,
			convert(varchar,isnull(A.ToDate,''),103) AS ToDate,
			isnull (A.Title,'') AS Title,
			isnull( A.Remark,'') AS Remark				
		FROM 
			sActivity.tActivity A 
			INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=@rStudentId AND SA.BatchId = @rBatchId
			INNER JOIN sActivity.tActivityParticipant AP ON AP.ActivityId=A.Id AND AP.SourceTypeId=2003
		WHERE 
			AP.SourceTypeId = 2003 AND AP.SourceId = @rStudentId  AND A.BatchId=@rBatchId
					
		SELECT 
			convert(varchar,isnull(B.BehaviourDate,''),103) AS BehaviourDate,
			isnull (BTM.Title,'') AS BehaviourType,
			isnull( B.Title,'') AS BehaviourDetails,
			isnull(B.Remark,'') AS Remark
		FROM 
			sCommunication.tBehaviour B
			 INNER JOIN sCommunication.tBehaviourTypeMaster BTM
			 ON B.BehaviourTypeId=BTM.Id
			 INNER JOIN sStudent.vStudentAcademic SA
			 ON SA.AcademicId=B.AcademicId      
		WHERE 
			SA.OrgGroupBatchId=@rOrgGroupBatchId AND SA.AcademicId=@lAcademicId

		SELECT  CONVERT(VARCHAR,ISNULL(ES.FromDate,''),103) AS FromDate, CONVERT(VARCHAR,ISNULL(ES.ToDate,''),103) AS ToDate
			,ISNULL(ES.Title,'') AS EventName, (CASE WHEN EA.IsSelfPresent = 1 then 'Yes' ELSE 'No' END) AS StudentAttendance
			,(CASE WHEN EA.IsFatherPresent = 1 then 'Yes' ELSE 'No' END) AS FatherAttendance
			,(CASE WHEN EA.IsMotherPresent = 1 then 'Yes' ELSE 'No' END) AS MotherAttendance
			,ISNULL(EA.ParentFeedBack,'') AS ParentFeedBack, ISNULL(EA.SchoolFeedback,'') AS SchoolFeedback
		FROM 
			sStudent.vStudentAcademic SA 
			INNER JOIN sActivity.tEventAttendance EA ON  SA.AcademicId = EA.SourceId AND EA.SourceTypeId = 2001
			INNER JOIN sActivity.tEventSchedule ES ON EA.EventScheduleId=ES.Id 
			INNER JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
  WHERE 
			(SA.OrgId=@rOrgId)
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND((SA.AcademicId=@lAcademicId)OR(@lAcademicId=0)) 
			ORDER BY SA.ClassId,SA.DivisionId
	END
END
GO
PRINT N'Altering Procedure [sPurchase].[pGoodsReceivedNoteAdd]...';


GO


ALTER PROCEDURE [sTool].[pUpgradeVersion]
	 
	@rVersionId int,
	@rVersion nvarchar(20),
	@rOrgGroupId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if 	@rVersionId = 0
BEGIN
SELECT 'Enter Version Id'
return	
END


if 	@rVersion = ''
BEGIN
SELECT 'Enter Version Detail'
return	
END

if 	@rOrgGroupId = 0
BEGIN
SELECT 'Enter Org Group Id'
return	
END



--if 	@rOrgGroupId = 1
--BEGIN
--SELECT '1 OrgGroup Not Valid'
--return	
--END

IF NOT EXISTS (SELECT 1 FROM sSetup.tOrgGroupMaster WHERE Id = @rOrgGroupId)
BEGIN
SELECT 'Org Group Not Exists'
return	
END

-- For Upgrade Vesion Start
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES(@rVersion,@rVersionId,'BEGIN','Upgrade Vesion',sCommon.fGetDate(),sCommon.fGetDate(),@rOrgGroupId)

--exec [sTool].[pInsertStaticData]
		
-- add newly added task for admin role
exec [sSecurity].[pNewTaskAdd] @rOrgGroupId

-- update tablerowid master data from excel to table

--pass orgGroupId
-- add new table row ids added
exec [sTool].[pTableRowIdAdd] @rOrgGroupId

-- Pass OrgGroupId
-- Remove tablrowid for organization
--exec sTool.pTableRowChangeOrgToOrgGroupRemove @rOrgGroupId

update sstudent.tAcademic   set rollno = 0 where RollNo is null



delete from sSecurity.tPermission where TaskId in (select ID from sSecurity.tTask where IsObsolete = 1)
delete from sSecurity.tPermission where TaskId not in (select ID from sSecurity.tTask)




exec [sTool].[pTableRowIdCurrentNumberSet] @rOrgGroupId

IF NOT EXISTS(SELECT 1 FROM sCommunication.teContentTypeMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
 BEGIN
				INSERT INTO sCommunication.teContentTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,'Subject'
						,'Subject'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						
 END


IF NOT EXISTS(SELECT 1 FROM sCommunication.tCircularTypeMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
 BEGIN
				INSERT INTO sCommunication.tCircularTypeMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,HighlightColor)
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,'Circular'
						,'Circular'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						,NULL
 END

IF NOT EXISTS(SELECT 1 FROM sCommon.tPublishDocumentMaster WHERE Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sCommon.tPublishDocumentMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId])
				 VALUES
						(sCommon.fGetIntIdForOrg(1,@rOrgGroupId),'Fee Receipt','Fee Receipt',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(2,@rOrgGroupId),'Bonafide','Bonafide',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(3,@rOrgGroupId),'Trial','Trial',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(4,@rOrgGroupId),'Charactor','Charactor',0,1,Getdate(),1,Getdate(),@rOrgGroupId),
						(sCommon.fGetIntIdForOrg(5,@rOrgGroupId),'Id Card','Id Card',0,1,Getdate(),1,Getdate(),@rOrgGroupId)
						
END


IF NOT EXISTS(SELECT 1 FROM sAdmission.tInquiryStatusMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sAdmission.tInquiryStatusMaster
					   ([Id]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   ,StatusId
					   --,HighlightColor
					   --,InquiryMainStatusId
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Title
						,Title
						,0
						,1
						,getdate()
						,NULL
						,NULL
						,@rOrgGroupId
						,Id	
						--,ISM.HighlightColor
						--,ISM.InquiryMainStatusId					
						FROM sCommon.tStatusMaster
						--INNER JOIN sAdmission.tInquiryStatusMaster ISM ON SM.Id = ISM.StatusId AND ISM.OrgGroupId = 1
						where statustypeId = 104


						UPDATE ISM  
							SET ISM.HighlightColor = ISM1.HighlightColor ,
								ISM.InquiryMainStatusId = ISM1.InquiryMainStatusId
							FROM sAdmission.tInquiryStatusMaster ISM  
							INNER JOIN sAdmission.tInquiryStatusMaster ISM1 ON ISM.StatusId = ISM1.StatusId AND ISM1.OrgGroupId = 1
							INNER JOIN sCommon.tStatusMaster SM ON SM.Id = ISM1.StatusId 
							where SM.statustypeId = 104 AND ISM.OrgGroupId = @rOrgGroupId

						
	DECLARE @lMaxId int
	SET @lMaxId = sCommon.fGetIntIdForOrg(213,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sAdmission.tInquiryStatusMaster', @rCurrentNumber = @lMaxId
						
END

--static entry in tVisitorTypeMaster

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE Id = 1)
BEGIN	
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
           (1,
		   'Visitor',
		   'Visitor',
		   0,
		   1,
		   GetDate(),
		   NULL,
		   NULL,
		   1)
END

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE Id = 2)
BEGIN	
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
           ([Id]
           ,[Code]
           ,[Title]
           ,[IsObsolete]
           ,[CreatedUserId]
           ,[CreatedDateTime]
           ,[UpdatedUserId]
           ,[UpdatedDateTime]
           ,[OrgGroupId])
     VALUES
           (2,
		   'Parents',
		   'Parents',
		   0,
		   1,
		   GetDate(),
		   NULL,
		   NULL,
		   1)
END

--OrgGoup wise VisitorTypeMaster entry
IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE OrgGroupId = @rOrgGroupId AND Id = sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId])
		 VALUES
			   (
			   sCommon.fGetIntIdForOrg(1,@rOrgGroupId),
			   'Visitor',
			   'Visitor',
			   0,
			   --1,
			   [sCommon].[fGetBigIntIdForOrg](3,@rOrgGroupId),
			   GetDate(),
			   NULL,
			   NULL,
			   @rOrgGroupId)
END

IF NOT EXISTS(SELECT 1 FROM sFrontOffice.tVisitorTypeMaster WHERE OrgGroupId = @rOrgGroupId AND Id = sCommon.fGetIntIdForOrg(2,@rOrgGroupId))
BEGIN
	INSERT INTO [sFrontOffice].[tVisitorTypeMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[IsObsolete]
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[UpdatedUserId]
			   ,[UpdatedDateTime]
			   ,[OrgGroupId])
		 VALUES
			   (
			   sCommon.fGetIntIdForOrg(2,@rOrgGroupId),
			   'Parents',
			   'Parents',
			   0,
			   --1,
			   [sCommon].[fGetBigIntIdForOrg](3,@rOrgGroupId),
			   GetDate(),
			   NULL,
			   NULL,
			   @rOrgGroupId)
END

--PeriodNoMaster Entry

IF NOT EXISTS(SELECT 1 FROM [sAttendance].[tPeriodNoMaster])
BEGIN	

INSERT INTO [sAttendance].[tPeriodNoMaster]
           ([Id]
           ,[Title]
           ,[IsObsolete])
     VALUES
          (1, '1', 0),
		  (2, '2', 0),
		  (3, '3', 0),
		  (4, '4', 0),
		  (5, '5', 0),
		  (6, '6', 0),
		  (7, '7', 0),
		  (8, '8', 0),
		  (9, '9', 0),
		  (10,'10', 0),
		  (11,'11', 0),
		  (12,'12', 0)

END

IF NOT EXISTS(SELECT 1 FROM sCommon.tCastCategoryMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sCommon.tCastCategoryMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]
					   , MainCastCategoryId 
					   ,OrderIndex)
				 SELECT
						 sCommon.fGetIntIdForOrg(Id,@rOrgGroupId)
						,Id	
						,Code
						,Title
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						,Id
						,Id						
						FROM sCommon.tMainCastCategoryMaster
						 
						
	DECLARE @lMaxCatId int
	SET @lMaxCatId = sCommon.fGetIntIdForOrg(100,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sCommon.tCastCategoryMaster', @rCurrentNumber = @lMaxCatId

UPDATE
    o
SET
    o.CastCategoryId	=  sCommon.fGetIntIdForOrg(o.CastCategoryId,@rOrgGroupId)
FROM
    sStudent.tStudentOther o
    INNER JOIN
    sStudent.tStudentMaster S ON S.Id = o.StudentId
WHERE
o.CastCategoryId < 100 
AND CastCategoryId IS NOT NULL
AND S.OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)		
			
UPDATE sAdmission.tAdmissionForm SET CastCategoryId	= sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100 
AND OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)

UPDATE sCommon.tFamiliyCastMaster SET 	CastCategoryId	=  sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100   AND OrgGroupId = @rOrgGroupId

UPDATE sCommon.tSurnameMaster SET 	CastCategoryId	=  sCommon.fGetIntIdForOrg(CastCategoryId,@rOrgGroupId)	
WHERE CastCategoryId IS NOT NULL AND CastCategoryId < 100 AND OrgGroupId = @rOrgGroupId
			
			
END


IF NOT EXISTS(SELECT 1 FROM sTransport.tTransportMaster WHERE OrgGroupId = @rOrgGroupId)
BEGIN				
				INSERT INTO sTransport.tTransportMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[IsObsolete]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   ,[OrgGroupId]					    
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,1
						,'Common'
						,'Common'
						,0
						,1
						,getdate()
						,1
						,getdate()
						,@rOrgGroupId
						 
		DECLARE @lMaxTranId int
	SET @lMaxTranId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)					
	EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sTransport.tTransportMaster', @rCurrentNumber = @lMaxTranId
						 
					 				
	INSERT INTO sTransport.tAssignTransportOrg
					   (TransportId
					   ,OrgId					    				    
					   )
	SELECT 		
	@lMaxTranId
	,Id
	FROM
	sSetup.tOrganizationMaster
	WHERE OrgGroupId = 		@rOrgGroupId	 
						 
						

UPDATE sTransport.tBusRouteMaster
SET TransportId = @lMaxTranId WHERE OrgGroupId = @rOrgGroupId

UPDATE sTransport.tVehicleMaster
SET TransportId = @lMaxTranId WHERE OrgGroupId = @rOrgGroupId


			
			
END


IF NOT EXISTS(SELECT 1 FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId AND Id =  sCommon.fGetIntIdForOrg(1,@rOrgGroupId))
BEGIN				
				INSERT INTO sSetup.tBatchGroupMaster
					   ([Id]
					   ,[Number]
					   ,[Code]
					   ,[Title]
					   ,[OrgGroupId]					    
					   ,[OrderIndex]
					   ,[CreatedUserId]
					   ,[CreatedDateTime]
					   ,[UpdatedUserId]
					   ,[UpdatedDateTime]
					   )
				 SELECT
						 sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
						,1
						,'Common'
						,'Common'
						,@rOrgGroupId
						,1
						
						,1
						,getdate()
						,1
						,getdate()
						
						 
	--DECLARE @lBatchGroupId int
	--SET @lMaxTranId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)					
	--EXECUTE sCommon.pTableRowIdModify @rOrgGroupId, @rTableTitle = 'sSetup.tBatchGroupMaster', @rCurrentNumber = @lBatchGroupId
	
	UPDATE B    
	SET BatchGroupId = sCommon.fGetIntIdForOrg(1,@rOrgGroupId)
	FROM sSetup.tBatchMaster B INNER JOIN sSetup.tOrganizationMaster O ON B.OrgId = O.ID
	WHERE O.OrgGroupId = @rOrgGroupId AND B.BatchGroupId IS NULL

END


UPDATE sSetup.tClassMaster SET DepartmentId = sCommon.fGetIntIdForOrg(OrgId,1) where DepartmentId is null

if (@rOrgGroupId <> 1154)
BEGIN
UPDATE sCommon.tReport SET IsObsolete = 1
 Where Id in (20642,20643,20644,20645,20646,20647,20648,20649,20650,20665,20718,20779,20692,20693,20694)

END

UPDATE sSystem.tDatabaseInfo SET ApplicationId = 1

UPDATE sSystem.tDatabaseInfo SET 
VersionNumber = @rVersion,
VersionId = @rVersionId,
LastVersionUpdateDateTime = getdate() ,
IsNewVersion = 1
WHERE ApplicationId = 1 
 
-- for student - remove permission for employee center
DECLARE @lRoleId int = 0
DECLARE @lDefaultRoleId int = 10
SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
 
--DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
--WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId AND T.ModuleId =  234

---- for employee - remove permisiion for student center
--SET @lDefaultRoleId = 22
--SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
--DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
--WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId AND T.ModuleId =  233

-- for SysSuperAdmin
SET @lDefaultRoleId = 1
SET @lRoleId = (@rOrgGroupId * 100000) + @lDefaultRoleId
DELETE P FROM sSecurity.tPermission P INNER JOIN sSecurity.tTask T ON P.TaskId = T.Id 
WHERE P.RoleId = @lRoleId AND P.OrgGroupId=@rOrgGroupId
AND T.Id IN (30258,30262,30266,30257,30160,30243,30244)

IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,20596,2
END

--default permission for Lesson Plan Complete Task for Admin only (for execute permission)
IF NOT EXISTS (SELECT 1 FROM sSecurity.tOrganizationTask  T   WHERE TaskId = 31244  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tOrganizationTask 
	(OrgGroupId, TaskId, AvailablePermission)
	SELECT  @rOrgGroupId,31244,64
END

IF NOT EXISTS (SELECT * FROM sSecurity.tPermission   WHERE RoleId =sCommon.fGetIntIdForOrg(2,@rOrgGroupId) AND TaskId = 20596  AND OrgGroupId = @rOrgGroupId)
BEGIN
	INSERT INTO sSecurity.tPermission(TaskId, RoleId, Permission, IsObsolete, CreatedUserId, CreatedDateTime, UpdatedUserId, UpdatedDateTime,OrgGroupId)
	SELECT  20596,sCommon.fGetIntIdForOrg(2,@rOrgGroupId),2,0,1,sCommon.fGetDate(),1,sCommon.fGetDate(),@rOrgGroupId
	FROM sSecurity.tOrganizationTask WHERE OrgGroupId = @rOrgGroupId
END

---- for SysSuperAdmin update password
--UPDATE sSecurity.tUser SET LoginPassword='XAqFcL/nd0bnDNhkyF/PxobplNJ+ggbN9370AHxj7oU=' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
--UPDATE sSecurity.tUser SET LoginPassword='XAqFcL/nd0bnDNhkyF/PxobplNJ+ggbN9370AHxj7oU=' WHERE Id = 1

-- for SysSuperAdmin update password
--UPDATE sSecurity.tUser SET LoginPassword='FxYuAuSiWcl4MZWDctl++A==' WHERE Id = sCommon.fGetBigIntIdForOrg(1,@rOrgGroupId)
--UPDATE sSecurity.tUser SET LoginPassword='FxYuAuSiWcl4MZWDctl++A==' WHERE Id = 1

 -- For Upgrade Vesion END
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES(@rVersion,@rVersionId,'END','Upgrade Vesion',sCommon.fGetDate(),sCommon.fGetDate(),@rOrgGroupId)

END

GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('24.01.16',240116,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO

