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

 
GO
PRINT N'Altering [sFee].[tFeeAllocationHistory]...';


GO
ALTER TABLE [sFee].[tFeeAllocationHistory]
    ADD [HistoryTypeId] TINYINT NULL,
        [IsOptional]    BIT     NULL;


GO
PRINT N'Creating [sHrm].[tEmployeeCustomFieldData]...';


GO
CREATE TABLE [sHrm].[tEmployeeCustomFieldData] (
    [AutoId]                INT            IDENTITY (1, 1) NOT NULL,
    [EmployeeId]            BIGINT         NOT NULL,
    [EmployeeCustomFieldId] INT            NOT NULL,
    [FieldData]             NVARCHAR (500) NOT NULL,
    [CreatedUserId]         BIGINT         NULL,
    [CreatedDateTime]       DATETIME       NULL,
    [UpdatedUserId]         BIGINT         NULL,
    [UpdatedDateTime]       DATETIME       NULL
);


GO
PRINT N'Creating PK_tEmployeeCustomFieldData...';


GO
ALTER TABLE [sHrm].[tEmployeeCustomFieldData]
    ADD CONSTRAINT [PK_tEmployeeCustomFieldData] PRIMARY KEY CLUSTERED ([AutoId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO
PRINT N'Creating [sHrm].[tEmployeeCustomFieldMaster]...';


GO
CREATE TABLE [sHrm].[tEmployeeCustomFieldMaster] (
    [Id]               INT            NOT NULL,
    [FieldTitle]       NVARCHAR (500) NOT NULL,
    [FieldTypeId]      TINYINT        NOT NULL,
    [FieldList]        NVARCHAR (500) NULL,
    [IsFieldMandatory] BIT            NOT NULL,
    [FieldGroup]       NVARCHAR (200) NULL,
    [FieldOrder]       SMALLINT       NULL,
    [IsObsolete]       BIT            NULL,
    [CreatedUserId]    BIGINT         NULL,
    [CreatedDateTime]  DATETIME       NULL,
    [UpdatedUserId]    BIGINT         NULL,
    [UpdatedDateTime]  DATETIME       NULL,
    [OrgGroupId]       SMALLINT       NULL,
    [DataId]           INT            NULL
);


GO
PRINT N'Creating PK_tEmployeeCustomFieldMaster...';


GO
ALTER TABLE [sHrm].[tEmployeeCustomFieldMaster]
    ADD CONSTRAINT [PK_tEmployeeCustomFieldMaster] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


GO
PRINT N'Creating [sHrm].[tTempEmployee13]...';


GO
CREATE TABLE [sHrm].[tTempEmployee13] (
    [EmployeeId13]                  BIGINT         NOT NULL,
    [Currently Having any disease?] NVARCHAR (500) NULL,
    [Currently Taking Medicines?]   NVARCHAR (500) NULL
);


GO


 
GO
PRINT N'Altering [sCertificate].[vPrintTemplateStudentBasicDetails]...';


GO
 
 
 
ALTER VIEW [sCertificate].[vPrintTemplateStudentBasicDetails]
AS
	SELECT 
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS StudentName,
	  SM.Code,	
	  DM.Code AS ClassDivision,
	  A.RollNo,
	  BM.Title AS BatchName,
	  SO.DateOfBirth AS DateOfBirth,  	 
	  '[BatchName],[ClassDivision],[Code],[DateOfBirth],[RollNo],[FirstName],[MiddleName],
	  [LastName],[PreviousSchool],[Gender],[Caste],[SubCaste],[BirthPlace],[DOBInWords],[PreviousSchoolYear],
	  [OldGRNo],[PreviousLCDate],[PreviousLCResult],[PreviousLCNumber],[PreviousStandard],
	  [BirthTaluka],[BirthState],[BirthCountry],[BirthDistrict],[Address],[ContactNo],[Email],[Religion],[FamilyCaste],[CasteCategory],[Nationality],[MotherTongue],[BloodGroup],[AadhaarNumber],[PhysicalCategory],
	  [FatherName],[FatherQualification],[FatherOccupation],[FatherContactNo],[FatherOfficeAddress],[FatherEmail],[FatherExStudent],[FatherPassingYear],[FatherIncome],
	  [MotherName],[MotherQualification],[MotherOccupation],[MotherContactNo],[MotherOfficeAddress],[MotherEmail],[MotherExStudent],[MotherPassingYear],[MotherIncome],
	  [AdmissionDate],[AdmissionStandard],[ClassName]' As ColumnList
  FROM 
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id
	INNER JOIN sStudent.tStudentAdmission SA
		ON SA.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId
	INNER JOIN sSetup.tDepartmentMaster DeptM
		ON DeptM.Id=CM.DepartmentId
	INNER JOIN sSetup.tOrganizationMaster OM 
	    ON A.OrgId = OM.Id
	INNER JOIN [sStudent].[tStudentOther] SO
	    ON SO.StudentId=SM.Id
GO
PRINT N'Altering [sCertificate].[vPrintTemplateStudentDetail]...';


GO
 
 
 

ALTER VIEW [sCertificate].[vPrintTemplateStudentDetail]
 
AS  
  
SELECT 
			A.Id AS AcademicId,
		    DivM.Id AS DivisionId,
		    DivM.DisplayTitle AS DivisionName,
		    CM.Id AS ClassId,
		    CM.DisplayTitle AS ClassName,
		    CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivision,
		    DM.Id AS DepartmentId,
		    DM.DisplayTitle AS DepartmentName,
		    SM.FirstName AS FirstName,
		    SM.MiddleName AS MiddleName,
		    SM.LastName AS LastName,
		    SM.Code,
		    A.RollNo,
		    A.BatchId,
		    BM.Title AS BatchName,
		    CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
		    SA.PreviousSchool,
			ISNULL(GM.Title,'') AS Gender,
			SO.FamilyCast AS Caste,  
			SO.FamilySubCast AS SubCaste,
			SO.BirthPlace,
			SO.BirthDateInWord AS DOBInWords,
			SA.PreviousLCDate AS PreviousLCDate,
			SA.PreviousLCResult AS PreviousLCResult,
			SA.PreviousLCNumber AS PreviousLCNumber,
			SA.AdmissionNumber AS OldGRNo,
			SA.PassingYear AS PreviousSchoolYear,			
			SA.PreviousStandard AS PreviousStandard,
			SO.BirthTaluka AS BirthTaluka,
			SO.BirthState AS BirthState,
			SO.BirthCountry AS BirthCountry,
			SO.BirthDistrict AS BirthDistrict,
			ISNULL(SC.PermanentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS Address,
			SC.ParentContactNo AS ContactNo,		
			SC.ParentEmail AS Email,
			ISNULL(RM.Title,'') AS Religion,
			SO.FamilyCast AS FamilyCaste,
			ISNULL(CCM.Title,'') AS CasteCategory,
			ISNULL(NM.Title,'') AS Nationality,
			ISNULL(SO.MotherTongue,'') AS MotherTongue,
			ISNULL(BGM.Title,'') As BloodGroup,
			ISNULL(SO.AdhaarNumber,'') AS AadhaarNumber,
			ISNULL(PDCM.Title,'') AS PhysicalCategory,
			SF.FatherName AS FatherName,
			SF.FatherQualification AS FatherQualification,
			SF.FatherOccupation AS FatherOccupation,
			SF.FatherContactNo AS FatherContactNo,
			SF.FatherOfficeAddress AS FatherOfficeAddress,
			SF.FatherMail AS FatherEmail,
			SF.IsFatherExStudent AS FatherExStudent,
			SF.FatherPassOutYear AS FatherPassingYear,
			SF.FatherIncome AS FatherIncome,
			SF.MotherName AS MotherName,
			SF.MotherQualification AS MotherQualification,
			SF.MotherOccupation AS MotherOccupation,
			SF.MotherContactNo AS MotherContactNo,
			SF.MotherOfficeAddress AS MotherOfficeAddress,
			SF.MotherMail AS MotherEmail,
			SF.IsMotherExStudent AS MotherExStudent,
			SF.MotherPassOutYear AS MotherPassingYear,
			SF.MotherIncome AS MotherIncome,
			SA.AdmissionDate AS AdmissionDate,
			CM1.Title AS AdmissionStandard
	FROM 
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = A.StudentId
			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 sCommon.tMotherTongueMaster MT ON MT.Id = SO.MotherTongueId
			LEFT JOIN sCommon.tCountryMaster NM ON NM.Id = SO.NationalityId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId
			LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId = A.StudentId
			LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id=SA.AdmissionStandardId
GO
PRINT N'Altering [sStudent].[vStudentColumnName]...';


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,
	  --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,
      
	  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,
	  --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,
	  SF.MotherName,
	  SF.MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
	  SF.MotherOfficeContactNo,
      SF.MotherOfficeAddress,
      SF.MotherIncome,      
	  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,
	  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,
      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 ,
		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
           
           
	  
  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
GO
PRINT N'Altering [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.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,
	  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,
	  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,      
	  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,
	  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,
	  '' SiblingName1,
	  '' SiblingInstitue1,
	  '' SiblingClass1,
	  '' SiblingAge1,
	  '' SiblingRelation1,
	  '' SiblingName2,
	  '' SiblingInstitue2,
	  '' SiblingClass2,
	  '' SiblingAge2,
	  '' SiblingRelation2,
	  '' SiblingName3,
	  '' SiblingInstitue3,
	  '' SiblingClass3,
	  '' SiblingAge3,
	  '' 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,
      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

	  	  	   
  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.PickupDestinationId AS BusRouteDestinationId,BDM.Title AS BusRouteDestination, 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
    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
GO

 
GO
PRINT N'Altering [sAcademic].[pTopicMasterGet]...';


GO
 
ALTER PROCEDURE [sAcademic].[pTopicMasterGet]

	 @rId int,
	 @rOrgId smallint,
	 @rClassId int,
	 @rSubjectId int,
	 @rEmployeeId bigint,
	 @rSourceTypeId smallint = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF(@rSourceTypeId = 0)
	BEGIN
		SELECT 
				DISTINCT TM.Id,
				TM.Number,
				TM.Title,
				TM.OrgId,
				TM.ClassId,
				TM.SubjectId,
				TM.CreatedUserId,
				TM.CreatedDateTime,
				CM.DisplayTitle AS ClassName,
				SM.Title AS SubjectName,
				CM.OrderIndex,
				SM.OrderIndex
		FROM 
				sAcademic.tTopicMaster TM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
				LEFT JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = TM.ClassId 			
				--AND vTSD.SubjectId = TM.SubjectId 
				AND vTSD.EmployeeId = @rEmployeeId
		WHERE 
			(TM.OrgId=@rOrgId)
			AND ((TM.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
			--AND ((vTSD.EmployeeId = @rEmployeeId) OR (vTSD.EmployeeId = 0))
			--ORDER BY CM.OrderIndex
		ORDER BY CM.OrderIndex,SM.OrderIndex,TM.Number ASC
	END
	ELSE IF (@rSourceTypeId = 95)
	BEGIN
		SELECT 
				DISTINCT TM.Id,
				TM.Number,
				TM.Title,
				TM.OrgId,
				TM.ClassId,
				TM.SubjectId,
				TM.CreatedUserId,
				TM.CreatedDateTime,
				CM.DisplayTitle AS ClassName,
				SM.Title AS SubjectName,
				CM.OrderIndex,
				SM.OrderIndex
		FROM 
				sAcademic.tTopicMaster TM
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = TM.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
				INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = TM.ClassId AND vTSD.SubjectId = TM.SubjectId 
				AND vTSD.EmployeeId = @rEmployeeId
		WHERE 
			(TM.OrgId=@rOrgId)
			AND ((TM.Id = @rId) OR (@rId = 0))
			AND ((TM.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		ORDER BY CM.OrderIndex,SM.OrderIndex,TM.Number ASC
	END
END
GO
PRINT N'Altering [sAlert].[pAppRegisteredUserDelete]...';


GO
 
ALTER PROCEDURE [sAlert].[pAppRegisteredUserDelete]
	 @rOrgId int,
	 @rOSTypeId tinyint=0,
	 @rUserSourceTypeId smallint,
	 @rUserSourceId bigint,
	 @rUserId bigint,
	 @rDeviceToken nvarchar(200) = '',
	 @rDate DateTime
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION	

		
			DELETE FROM 
			sCommunication.tRegisteredUsers 
			WHERE 
			OrgId = @rOrgId 
			AND UserId = @rUserId 
			AND UserSourceId = @rUserSourceId 
			AND UserSourceTypeId = @rUserSourceTypeId 
			AND OSTypeId = @rOSTypeId
			AND ISNULL(DeviceToken,'') = ISNULL(@rDeviceToken,'')
			AND CreatedDateTime = @rDate
			SELECT 1 AS Result
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		SELECT -1 AS Result
		ROLLBACK TRANSACTION
	END CATCH	
END
GO
PRINT N'Altering [sAlert].[pFeeReceiptCancelGet]...';


GO

ALTER PROCEDURE [sAlert].[pFeeReceiptCancelGet]
	 	 
	 	 @rReceiptId bigint,
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rSubject nvarchar(100),
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 @rAdmissionCategoryId int=0,
	 	 @rIdNos nvarchar(500)='',
		 @rCollectionGroupId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		SELECT 
				SC.AcademicId,
				SC.Code,
				SC.Name,
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
				ISNULL(SC.StudentEmail,'') AS StudentEmail,
				ISNULL(SC.FatherContactNo,'') AS FatherContactNo,
				ISNULL(SC.FatherMail,'') AS FatherMail,
				ISNULL(SC.MotherContactNo,'') AS MotherContactNo,
				ISNULL(SC.MotherMail,'') AS MotherMail,
				@rSubject AS Subject,
				replace (
				replace (
				replace (
				replace (
				replace (
				replace (
				replace(@rTemplate,'[Name]',SC.Name),
				'[Class]',SC.ClassName),
				'[Division]',SC.DivisionName),
				'[ReceiptNumber]',R.ReceiptNumber),
				'[ReceiptDate]',convert(varchar,R.ReceiptDate,103)),
				'[PaidAmount]',convert(int,R.ReceiptAmount)),
				'[ChequeNo]',ISNULL(R.Chequeno,''))
				 AS MsgText,				 
				 SC.OrgId,
				 SC.OrgGroupId,
				 SC.AcademicId AS SourceId,
				 2001 AS SourceTypeId,
				 2001 AS ReceiverSourceTypeId,
				 SC.AcademicId AS ReceiverSourceId
				 
		FROM 
			sStudent.vStudentCommunication SC
		INNER JOIN sFee.tReceipt R ON R.SourceId=SC.AcademicId AND R.SourceTypeId=2001 AND R.IsObsolete=1
				AND ((R.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((R.Id=@rReceiptId) OR (@rReceiptId=0))
				AND ((R.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			
		WHERE
				((SC.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SC.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((SC.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (SC.StatusId=1)
			AND (SC.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
			AND (SC.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
			AND SC.IsBlockAllAlert=0
			ORDER BY R.ReceiptNumber	
END
GO
PRINT N'Altering [sAssessment].[pGeneralExamCustomSearchGet]...';


GO
 
ALTER PROCEDURE [sAssessment].[pGeneralExamCustomSearchGet]
(
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rPageIndex int = null,
	@rDivisionId nvarchar(max) = '',
	@rExamId nvarchar(max) = '',
	@rFromMarks decimal(5,2),
	@rToMarks decimal(5,2),
	@rFromGradePoint decimal(6,2),
	@rToGradePoint decimal(6,2),
	@rFromRankNumber int,
	@rToRankNumber int,
	@rFromPercentage decimal(5,2),
	@rToPercentage decimal(5,2),
	@rFromPercentile decimal(5,2),
	@rToPercentile decimal(5,2),
	@rResultGrade nvarchar(10),
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownExamSubGroupId int,
	@rDepartmentId int=0,
	@rCastCategoryId nvarchar(max) = ''
 )
AS
SET NOCOUNT ON
BEGIN
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	DECLARE @Sql nvarchar(MAX)
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rResultGrade = sCommon.fSearchStringGet(@rResultGrade)
	
	
	SELECT * into #TempExam11
	FROM sAssessment.vGeneralExamCustomSearch ECS
	WHERE (ECS.OrgId = @rOrgId) AND (ECS.BatchId = @rBatchId)
	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ECS.TotalObtain >= @rFromMarks) OR (@rFromMarks=0))
	AND ((ECS.TotalObtain <= @rToMarks) OR (@rToMarks=0))
	AND ((ECS.ResultGradePoint >= @rFromGradePoint) OR (@rFromGradePoint=0))
	AND ((ECS.ResultGradePoint <= @rToGradePoint) OR (@rToGradePoint=0))
	AND ((ECS.RankNumber >= @rFromRankNumber) OR (@rFromRankNumber=0))
	AND ((ECS.RankNumber <= @rToRankNumber) OR (@rToRankNumber=0))
	AND ((ECS.Percentage >= @rFromPercentage) OR (@rFromPercentage=0))
	AND ((ECS.Percentage <= @rToPercentage) OR (@rToPercentage=0))
	AND ((ECS.Percentile >= @rFromPercentile) OR (@rFromPercentile=0))
	AND ((ECS.Percentile <= @rToPercentile) OR (@rToPercentile=0))
	AND ((ECS.ResultGrade Like @rResultGrade + '%')OR(@rResultGrade = ''))
	AND (ECS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (ECS.ExamId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rExamId,','))OR @rExamId='')
	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((ECS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((ECS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((ECS.ExamSubGroupId = @rDropDownExamSubGroupId) OR (@rDropDownExamSubGroupId=0))
	AND ((ECS.DepartmentId =@rDepartmentId) OR (@rDepartmentId =0))
	AND (ISNULL(ECS.CastCategoryId,'') IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
	SET @sql='SELECT Code AS Code,Name,ClassName,RollNo,TotalMarks,TotalObtain,
	ResultStatus,ResultGrade,ResultGradePoint,RankNumber,Percentage,Percentile,
	ResultReMark,OtherRemark1,ExamName FROM #TempExam11 ORDER BY ' + @rOrderBy
	
	exec(@Sql)
	
	create table #TEMPExam
	(
		tid int identity(1,1),t_AcedemicId bigint,t_ResultId bigint
	)
	SET @sql='insert into #TEMPExam SELECT AcademicId,ResultId FROM #TempExam11 ORDER BY ' + @rOrderBy

	exec (@sql)

	declare @lTotalRecords int,@lPageSize int = 10,@lPaging varchar(max)='',@lResult varchar(max)=''
	
	select @lTotalRecords = count(*) from #TEMPExam
	select @lPaging = @lPaging + dbo.fnc_searchpagingformat(@rPageIndex,@lTotalRecords,@lPageSize)
	 
	select @lResult = @lResult + '<tr><td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td>
	<td>' + isnull(convert(varchar,RollNo),'') + '</td><td>' + isnull(ExamName,'') + '</td>
	<td>' + isnull(convert(varchar,TotalMarks),'') + '</td><td>' + isnull(convert(varchar,TotalObtain),'') + '</td>
	<td>' + isnull(ResultStatus,'') + '</td><td>' + isnull(ResultGrade,'') + '</td>

	<td>' + isnull(convert(varchar,RankNumber),'') + '</td>
	<td>' + isnull(convert(varchar,Percentage),'') + '</td><td>' + isnull(convert(varchar,Percentile),'') + '</td>
	<td>' + isnull(ResultReMark,'') + '</td><td>' + isnull(OtherRemark1,'') + '</td></tr>' 
	from #TempExam11,#TEMPExam
	where AcademicId = t_AcedemicId and  ResultId = t_ResultId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	Order By tid
	
	select @lResult as StudentList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP table #TEMPExam
	DROP Table #TempExam11
	
		--<td>' + isnull(convert(varchar,ResultGradePoint),'') + '</td>
END
GO
PRINT N'Altering [sAssessment].[pRptResultListGet]...';


GO
 
ALTER PROCEDURE [sAssessment].[pRptResultListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
	 @rExamSubGroupId int=0,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rAcademicId bigint=0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rDepartmentid int=0,
	 @rStatus int =1,
	 @rGenderId int,
	 @rClassStatusId int=0,
	 @rResultStatus nvarchar(20)='',
	 @rMultiCode nvarchar(max)=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			Convert(nvarchar(20),A.Id) AS   AcademicIdText,	
	CONVERT (nvarchar(20),@rExamId) AS ExamIdText,
	CONVERT (nvarchar(20),EM.GradeSetId) AS GradeSetIdText,
	CONVERT (nvarchar(20),@rBatchId) AS BatchIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0))AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			SM.Code,
			  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			 DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			EM.IsMarksInDecimal,
			SI.StudentPhoto,
			EM.DisplayTitle,
			OM.SmallAddress1,
			R.ResultRemark,
			R.OtherRemark1,
			EM.Remark1,
			EM.Remark2,
			EM.Remark3,
			SR.ResultRemark2,
			Em.GradeSetId,
			R.ResultStatus,
			SR.ResultRemark1,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			EI.EmployeeSign,
			EM.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsOnPrePrinted,
			Em.IsDisplayPhoto,
			SR.PresentDays ,			
			SR.TotalDays,
			EM.DecimalFormat
			
			 
		 
			
      
	FROM 
			sAssessment.tExamMaster EM
			INNER JOIN sAssessment.tResult R ON EM.Id=R.ExamId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			 
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId=A.Id AND SR.ExamId = EM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			
			 
	WHERE 
			
		      EM.BatchId = @rBatchId 
		AND (EM.ClassId=@rClassId OR @rClassId=0) 
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=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 ((ESGM.Id=@rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))
		AND ((SM.Code=@rCode) OR (@rCode=''))
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		
		AND ((R.Percentage >=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage <=@rToPercentage) OR (@rToPercentage=0))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		ANd SM.StatusId= @rStatus
		AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND (ISNULL(SM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetFloating]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultSheetFloating]
	 
	 @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,
	 @rClassStatusId int=0 ,
	 @rMultiCode nvarchar(max)=''

	
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 --Select * from dbo.Float
DECLARE @GradeString nvarchar(1000),
@GradeSetId int 
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  

CREATE TABLE #TempExam
(
	ExamId int, 
	ExamOrderIndex int 
)
INSERT INTO #TempExam
(
	ExamId,	 
	ExamOrderIndex
)
Select 
	--EC.ExamId,
	EC.SubExamId,
	EC.ExamOrder 	 
	from sAssessment.tExamMaster EM 
	INNER JOIN sAssessment.tExamCombine EC ON EC.ExamId = EM.Id 
	WHERE EM.Id=@rExamId 
	
INSERT INTO #TempExam
(
	ExamId,
	--SubExamId,
	ExamOrderIndex
)
Select 
	--EC.ExamId,
	@rExamId,
	999
	
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			StuM.Code,
	[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,
			RD.SubjectGrade,
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			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.IsMarksInDecimal,
			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,
			SR.StudentHeight,
			SR.StudentWeight,		
			SR.PresentDays,			
			SR.TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			EM.TermScopeId,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
			ELSE NULL END) AS StudentPhoto,
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(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,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			SF.FatherName,
			SF.MotherName,
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
			(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
				EI.EmployeeSign
			ELSE NULL END)AS EmployeeSign,
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
				OI.CertificateHeaderA4 
			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,
			 
			EC.ExamId,
			EC.ExamOrderIndex,
			EM.DecimalFormat,
			SM.Code
			
			--[sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId) AS HighestDivisionMark,
			--[sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId) AS HighestDivisionGrade
			
			
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R 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 #TempExam EC ON EC.ExamId = EM.Id 	
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			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
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			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
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=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 (R.ExamId = @rExamId)
	 
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=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 A.RollNo,CS.OrderIndex 
		 drop table #TempExam
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetOnlyCoScholasticCombineGet]...';


GO


ALTER PROCEDURE [sAssessment].[pRptResultSheetOnlyCoScholasticCombineGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20),
	 @rStatusId int,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
 
 --select * from  dbo.tTempCoScholasticCombine
 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int, 
@Exam1 int,
@Exam2 int

SELECT @Exam1 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 1
SELECT @Exam2 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 2
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  	
 
 	CREATE TABLE #TempExam 
	(
		AcademicId bigint,
		ExamId int,
		CCECSId int,
		CCECSGroupId int,
		CoSubject nvarchar(150),
		CoSubjectGroup nvarchar(150),
		CoSubjectOrderIndex int,
		CoSubjectGroupOrderIndex int,
		Grade1 nvarchar(10) NULL,
		GradeIndicator1 nvarchar(50) NULL,
		DescriptiveIndicator1 nvarchar(200) NULL,
		Grade2 nvarchar(10) NULL,
		GradeIndicator2 nvarchar(50) NULL,
		DescriptiveIndicator2 nvarchar(200) NULL
	 )
	 
 

 INSERT INTO  #TempExam 
	(
	AcademicId,
	ExamId,
	CCECSId,
	CCECSGroupId,
	CoSubject,
	CoSubjectGroup,
	CoSubjectOrderIndex,
	CoSubjectGroupOrderIndex
	
	)
 SELECT A.Id,@rExamId,CS.Id,CS.CCECAGroupId,CS.Title,csg.Title,CS.OrderIndex,CSG.OrderIndex 
 FROM sStudent.tAcademic A INNER JOIN
 sAssessment.tCCECSClass C ON A.ClassId = C.ClassId  
 INNER JOIN sAssessment.tCCECSMaster CS ON C.CCECSGroupId = cs.CCECAGroupId
 INNER JOIN sAssessment.tCCECSGroupMaster CSG ON CS.CCECAGroupId = CSG.Id 
 WHERE DivisionId = @rDivisionId
 AND A.BatchId = @rBatchId
 
UPDATE
    TE
SET
    TE.Grade1 = ES.Grade,
    TE.GradeIndicator1 = ES.GradeIndicator,
    TE.DescriptiveIndicator1 = ES.DescriptiveIndicator
FROM
    #TempExam TE
    INNER JOIN sAssessment.tCCECSExamScore ES
    ON TE.AcademicId = ES.AcademicId AND   
    TE.CCECSId = ES.CCECSId
    AND ES.ExamId = @Exam1
    
  UPDATE
    TE
SET
    TE.Grade2 = ES.Grade,
    TE.GradeIndicator2 = ES.GradeIndicator,
    TE.DescriptiveIndicator2 = ES.DescriptiveIndicator
FROM
    #TempExam TE
    INNER JOIN sAssessment.tCCECSExamScore ES
    ON TE.AcademicId = ES.AcademicId AND   
    TE.CCECSId = ES.CCECSId
    AND ES.ExamId = @Exam2

	SELECT 
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			TE.AcademicId,			 
			ISNULL(R.ResultStatus,'') AS ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(R.TotalMarks,0) AS TotalMarks ,
			ISNULL(R.TotalObtain,0) AS TotalObtain,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.RankNumber,0) AS RankNumber,
			ISNULL(R.ResultGrade,'') AS ResultGrade,
			ISNULL(R.Percentile,0) AS Percentile,		 
			ISNULL(R.Id ,0) AS ResultId, 
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,	 
			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,
			SI.StudentPhoto,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			TE.CoSubject,
			TE.CoSubjectGroup,
			TE.CoSubjectGroupOrderIndex,
			TE.CoSubjectOrderIndex,
			TE.Grade1,
			TE.GradeIndicator1,
			TE.DescriptiveIndicator1,
			TE.Grade2,
			TE.GradeIndicator2,
			TE.DescriptiveIndicator2,
			SF.FatherName,
			SF.MotherName,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			EI.EmployeeSign ,
			SR.StudentHeight,
			SR.TotalDays,
			SR.PresentDays,
			SR.StudentWeight,
			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,
			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,
			SR.ResultRemark3,
			SR.ResultRemark1,
			Sr.ResultRemark2,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader
	FROM 
			#TempExam TE INNER JOIN 	 
			sAssessment.tExamMaster EM ON EM.Id=TE.ExamId 		 
			INNER JOIN sStudent.tAcademic A ON A.Id=TE.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID			 
			LEFT JOIN sAssessment.tResult R	ON TE.AcademicId = R.AcademicId AND TE.ExamId = R.ExamId
			LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	WHERE 
			EM.BatchId = @rBatchId 
			AND (A.ClassId=@rClassId OR @rClassId=0) 
			--AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
			AND (A.DivisionId=@rDivisionId OR @rDivisionId=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 (TE.ExamId = @rExamId)
			AND ((StuM.Code=@rCode) OR (@rCode=''))		
			AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=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 A.RollNo,TE.CoSubjectGroupOrderIndex,TE.CoSubjectOrderIndex 
			--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetOnlyCoScholasticTermwiseGet]...';


GO
 


ALTER PROCEDURE [sAssessment].[pRptResultSheetOnlyCoScholasticTermwiseGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20),
	 @rStatusId int,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @GradeString nvarchar(1000),
@GradeSetId int
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  
	SELECT 
			ESGM.Title AS Exam,
			StuM.Code,
			StuM.FirstName+' '+StuM.MiddleName+' '+StuM.LastName AS Name,
			A.RollNo,
			CCEEM.AcademicId,
			--RD.Obtain,
			ISNULL(R.ResultStatus,'') AS ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			ISNULL(R.TotalMarks,0) AS TotalMarks,
			ISNULL(R.TotalObtain,0) AS TotalObtain,
			ISNULL(R.Percentage,0) AS Percentage,
			ISNULL(R.RankNumber,0) AS RankNumber,
			ISNULL(R.ResultGrade,0) AS ResultGrade,
			ISNULL(R.Percentile,0) AS Percentile,
			--SM.Title AS ClassSubject,
			--RD.Id AS ResultDetailId,
			ISNULL(R.Id,0) AS ResultId,
			--CS.Id AS SubjectId,
			--ED.Maximum,
			--RD.SubjectGrade,
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			--SM.Code AS SubjectCode,
			--SM.OrderIndex AS SubjectOrderIndex,
			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.IsMarksInDecimal,
			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,
			SI.StudentPhoto,
			@GradeString AS GradeString,
			CCEEM.Grade,
			CCEEM.GradeIndicator,
			CCEEM.DescriptiveIndicator,
			CCEM.Title AS CoSubject,
			CCEM.OrderIndex AS CoOrderIndex,
			CCEGM.Title AS CoSubjectGroup,
			CCEGM.OrderIndex AS CoOrderIndexGroup,
			EM.IsDisplayPrincipalSign,
			Em.IsDisplayTeacherSign,
			EI.EmployeeSign ,
			SR.StudentHeight,
			SR.TotalDays,
			SR.PresentDays,
			SR.StudentWeight,
			EM.IsCoScholasticGrade,
			EM.IsCoScholasticGradeIndicator,
			EM.IsCoScholasticGradeDesIndicator,
				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,
		SR.ResultRemark3,
		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,
		SR.ResultRemark1,
		SR.ResultRemark2,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,

		sAssessment.fGetGradepoint(CCEEM.Grade) AS GradePoint,
		SF.FatherName,
		SF.MotherName,
		EM.IsDisplayParentName
	FROM 
			 
			 
			sAssessment.tCCECSExamScore CCEEM INNER JOIN   
			--INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			  sAssessment.tExamMaster EM ON EM.Id=CCEEM.ExamId AND CCEEM.ExamId=@rExamId
			--INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId		
			INNER JOIN sStudent.tAcademic A ON A.Id=CCEEM.AcademicId
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sAssessment.tCCECSMaster CCEM ON CCEM.Id=CCEEM.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster CCEGM ON CCEGM.Id= CCEM.CCECAGroupId	
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			
			LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			LEFT JOIN sAssessment.tResult R ON R.AcademicId = CCEEM.AcademicId AND R.ExamId = CCEEM.ExamId
			LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
	WHERE 
			
		EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		--AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=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 (CCEEM.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))		
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=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 A.RollNo--,CS.OrderIndex 
		--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardGet]...';


GO

 
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardGet]
	 
	 @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,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
 
	SELECT 
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		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.IsMarksInDecimal,
		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,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(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,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		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,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		SR.PresentDays,			
		SR.TotalDays,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.Resultremark3,
		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.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		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(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		BM.Title AS BatchName,
		Em.DecimalFormat,
		RD.GraceMark,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RD.Remark AS OtherDetailRemark,
		ISNULL(SO.AdhaarNumber,'') AS AdharNumber,
		ISNULL(SO.UIDNumber,'') AS UIDNumber,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		(CASE  When EM.IsDisplayAbsentCount=1 then ([sAssessment].[fGetAbsentCount](@rExamId,R.AcademicId, CS.Id)) ELSE 0 END) AS AbsentCount
	

	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R 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 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
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		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 sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
		LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.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 sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=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 (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		AND  ISNULL(EMP.IsOtherUser,0) = 0
		AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		order by A.RollNo,ED.DisplayOrder
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardGet_AllCombine]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardGet_AllCombine]
	 
	 @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,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
 
	SELECT 
	@rBuilder1 AS Builder1,
	@rBuilder1 AS Builder2,
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.Id AS ClassId,
		CM.DisplayTitle AS Class,
		DM.Id AS DivisionId,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		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.IsMarksInDecimal,
		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,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(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,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		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,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		SR.PresentDays,			
		SR.TotalDays,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.Resultremark3,
		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.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		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(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		BM.Title AS BatchName,
		Em.DecimalFormat,
		RD.GraceMark,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		--RAD.SubjectHighestDivisionGrade,
		--RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RD.Remark AS OtherDetailRemark,
		ED2.ExamDate AS ExamDate2,
		SM.Title AS SubjectName2,
		RD2.Obtain AS SubjectObtain2,
		ED2.Minimum AS SubjectMinimum2,
		ED2.Maximum AS SubjectMaximum2,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD2.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark2,
		ED.Id AS ExamDetailId2,
		EM2.DisplayTitle As Exam2,
		EM2.Id As ExamId
		
	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R 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 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
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		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 sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
		LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.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
		INNER JOIN sAssessment.tExamCombine EC2 ON EC2.ExamId = EM.Id
		INNER JOIN sAssessment.tExamMaster EM2 ON EM2.Id = EC2.SubExamId
		INNER JOIN sAssessment.tExamDetail ED2 ON EM2.Id = ED2.ExamId AND ED2.ClassSubjectId = ED.ClassSubjectId
		INNER JOIN sAssessment.tResult R2 ON R2.ExamId = EM2.Id AND R2.AcademicId = A.Id
		INNER JOIN sAssessment.tResultDetail RD2 ON ED2.Id = RD2.ExamDetailId AND RD2.ResultId = R2.Id

	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=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 (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0)
		AND  ISNULL(EMP.IsOtherUser,0) = 0
		AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		order by A.RollNo,ExamDate2
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExam_Get]...';


GO
 
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExam_Get]
	 
	 @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,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rMultiCode nvarchar(max)=''
	 --,@rcolumn_visible bit
	 
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 
 --Select * from sAssessment.tTempAll_Exam 
   --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam

 
--#TempAllExam
	 
	SELECT 
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) As CoScholasticScopeIdText ,
		A.Id AS AcademicId,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS StudentName,
		A.RollNo,
 
		R.Id AS ResultId,

	 
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
	     
		SF.FatherName,
		SF.MotherName,
		 
		EM.IsDisplayPrincipalSign,
		Em.IsDisplayTeacherSign,
		(CASE Em.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
			ELSE NULL END ) AS EmployeeSign,
		    
		ISNULL(EM.TeacherSignCaption,'') AS TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') AS PrincipalSignCaption,
		ISNULL(Em.ParentSignCaption,'') As ParentSignCaption  
	
		 
		 	
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R 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 sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	 
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	 
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
	LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
	 
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID 
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	LEFT JOIN sAssessment.tStudentRemark SR ON A.Id = SR.AcademicId AND EM.Id = SR.ExamId
	 
	 
 
	--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
	
	 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.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		 
	 
	Order By ED.DisplayOrder
	
	 
	
	END
GO
PRINT N'Altering [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
-- --drop table 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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		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) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 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(1000),
		Remark3 nvarchar(1000),
		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), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 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),
		
		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),
		
		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),
		
		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),
		
		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),
		
		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),
		
		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),
		
		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),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays smallint,
		PresentDays smallint,
		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),
		
		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(50),
		LastName nvarchar(50),
		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(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,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(100),
		TotalDays1 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		TotalDays7 smallint,
		PresentDays7 smallint, 
		TotalDays8 smallint,
		PresentDays8 smallint,
		TotalDays9 smallint,
		PresentDays9 smallint,
		TotalDays10 smallint,
		PresentDays10 smallint,
		TotalDays11 smallint,
		PresentDays11 smallint,
		TotalDays12 smallint,
		PresentDays12 smallint,
		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(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 smallint,
		SR_PresentDaysTerm2 smallint,
		SR_TotalDaysTerm1 smallint,
		SR_TotalDaysTerm2 smallint,
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100)
	
	)	
	 --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
	
	)
	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,
		SR.TotalDays,
		SR.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,
		SR.PresentDays AS SR_PresentDaysTerm1,
	    SR.PresentDays AS SR_PresentDaysTerm2,
	    SR.TotalDays AS SR_TotalDaysTerm1,
	    SR.TotalDays 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
	
		
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R 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 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.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
	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 sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 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  ISNULL(EMP.IsOtherUser,0) = 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,	
					 				
					 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
						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)
		
		
	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
						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
					
					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
						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			
					 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
						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			
					 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,
 --          0 As TotalDaysSubjectWise,
 --          0 As PresentDaysubjectWise
-- 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 [sAssessment].[pRptResultSheetStandardMultiExamGetwithResultDetailOther]...';


GO

 
 ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiExamGetwithResultDetailOther]
	@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,
	 @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
-- --drop table sAssessment.tTempAllExam
 
  
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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		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) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 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(500),
		Remark3 nvarchar(500),
		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), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 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),
		
		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),
		
		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),
		
		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),
		
		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),
		
		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),
		
		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),
		
		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),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays smallint,
		PresentDays smallint,
		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),
		
		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(max),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(200),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(20),
		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(100),
		TotalDays1 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		TotalDays7 smallint,
		PresentDays7 smallint, 
		TotalDays8 smallint,
		PresentDays8 smallint,
		TotalDays9 smallint,
		PresentDays9 smallint,
		TotalDays10 smallint,
		PresentDays10 smallint,
		TotalDays11 smallint,
		PresentDays11 smallint,
		TotalDays12 smallint,
		PresentDays12 smallint,
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(200),
		AchievementsTerm2 nvarchar(200),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 smallint,
		SR_PresentDaysTerm2 smallint,
		SR_TotalDaysTerm1 smallint,
		SR_TotalDaysTerm2 smallint,
		TotalCount smallint,
		PresentCount smallint,
		Remark4 nvarchar(1000)
	
		
	)	
	 --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,
	TotalCount,
	PresentCount,
	Remark4
	
	)
	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,
		SR.TotalDays,
		SR.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,
		[sAssessment].[fSubjectEmployeeGet](DM.Id,SM.Id) 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,
		SR.PresentDays AS SR_PresentDaysTerm1,
	    SR.PresentDays AS SR_PresentDaysTerm2,
	    SR.TotalDays AS SR_TotalDaysTerm1,
	    SR.TotalDays AS SR_TotalDaysTerm2,
	    ISNULL(RDO.TotalCount,0) As TotalCount,
	    ISNULL(RDO.PresentCount,0) As PresentCount,
	    Isnull(RDO.Remark,'') As Remark4
	    ---[sAssessment].[fSubjectEmployeeGet](DM.Id,SM.Id) As ClassTeacherName
	   		
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R 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 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.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
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.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 sAssessment.tResultDetailOther RDO ON  RDO.ExamId = EM.Id AND R.Academicid =RDO.AcademicId AND ED.ClassSubjectId = RDO.ClassSubjectId
	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 sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId=SM.Id AND TSD.DivisionId = A.DivisionId
	--LEFT JOIN sHrm.tEmployeeMaster EMP ON TSD.EmployeeId = EMP.Id
	
	 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.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
	--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,	
					 				
					 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
						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 
				    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)
		
		
	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
						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
					
					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
						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			
					 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
						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			
					 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
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

--SELECT @rBuilder1,@rBuilder2, T.* FROM sAssessment.tTempAllExam T
--end
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiMaxExamGet]...';


GO
 
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardMultiMaxExamGet]
	 
	 @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,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	 --,@rcolumn_visible bit

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 
  
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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		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),
		ObtainedMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		ObtainedMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		ObtainedMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		ObtainedMaximum4 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,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2),
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2),
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2),
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2),
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		Percentile decimal(5,2),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(500),
		Remark2 nvarchar(500),
		Remark3 nvarchar(500),
		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), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		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),
		
		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),
		
		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),
		
		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),
		
		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),
		
		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),
		
		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),
		
		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),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays smallint,
		PresentDays smallint,
		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),
		
		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(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(200),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(20),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(200),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		TotalDays7 smallint,
		PresentDays7 smallint, 
		TotalDays8 smallint,
		PresentDays8 smallint,
		TotalDays9 smallint,
		PresentDays9 smallint,
		TotalDays10 smallint,
		PresentDays10 smallint,
		TotalDays11 smallint,
		PresentDays11 smallint,
		TotalDays12 smallint,
		PresentDays12 smallint,
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		HouseId int,
		HouseName nvarchar(100)
	)	
	 
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	Percentile,
	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,
	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,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
   IsShowWithDetail,
 IsPresent,
 GradeTitle,
	
	 SubjectHighestDivisionGrade,
	 SubjectHighestDivisionMark,
	 HouseName,
	HouseId
	)
	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,
		R.Percentile,
		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,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.TotalDays,
		SR.PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ED.IsShowSubjectMark,
		(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,
		@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),
		@rIsShowWithDetail AS IsShowWithDetail,
		IsPresent,
		GradeTitle ,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark ,
		HM.Title As HouseName,HM.Id as HouseId
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R 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 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.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
	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
			  
	
	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.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))
		 AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	 AND  ISNULL(EMP.IsOtherUser,0) = 0
	 AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
	Order By ED.DisplayOrder
 
	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
 	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
	
	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
		if(@lCount <= 4)
		BEGIN
			set @query ='update T SET
						 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
						 Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
						 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,
					
						 ObtainedMaximum' + convert(nvarchar(15),@lCount)+ '= CASE WHEN EM.IsDisplayHighestDivisionMark = 1
									THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
									ELSE 0  END,
						 				
						 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 sStudent.tAcademic A ON A.Id=R.AcademicId
							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)
			
		END
		
		ELSE
		
		BEGIN
			set @query ='update T SET
						 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
						 Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
						 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,	
						 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 sStudent.tAcademic A ON A.Id=R.AcademicId
							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)
			
		END
						
			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,
					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)
		
		
	set @lCount = @lCount -1
	end
	

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		
			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
						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					 
					 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 = 2
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= 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
						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
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 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
						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			
					 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
	
	-- For Getting Highest Mark in Class in 2nd and 3rd Exam in One Field
	
	CREATE TABLE #HighestMarkTerm2Term3
	(
		SubjectId int,
		Term2Term3ClassHighestMarkSum decimal(8,2)
	)
	INSERT INTO #HighestMarkTerm2Term3 
	(
		SubjectId,
		Term2Term3ClassHighestMarkSum
	)
	SELECT 
		CS.SubjectId,		 
		MAX(RD.Obtain) AS Term2Term3ClassHighestMarkSum
	FROM
	sAssessment.tResultDetail RD INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id
	 INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id
	INNER JOIN sAssessment.tExamMaster EM ON ED.ExamId = EM.Id
	INNER JOIN  sSetup.tClassSubject CS  ON ED.ClassSubjectId = CS.Id
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id
	WHERE
	A.BatchId = @rBatchId
	AND EM.BatchId =  @rBatchId
	AND	((A.ClassId = @rClassId) OR (@rClassId = 0)) 
		AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0)) 
		--AND ((CS.Id = @rSubjectId) OR (@rSubjectId = 0))
		AND ((EM.Id = @rExamId) OR (@rExamId = 0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		group by CS.SubjectId,A.DivisionId 
		
	
	
	
	
	SELECT 
		  @rBuilder1,@rBuilder2, T.*,H.Term2Term3ClassHighestMarkSum
	FROM 
	      #TempAllExam T
		  INNER JOIN #HighestMarkTerm2Term3 H ON H.SubjectId = T.SubjectId
	
	
	Drop table #tempcombineExam
	
	Drop table #TempAllExam
	
	Drop table #HighestMarkTerm2Term3
	
	END
	
	
	--SELECT @rBuilder1,@rBuilder2,T.* FROM sAssessment.tTempAllExam T
 -- end
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardWithAnalysisGet]...';


GO

ALTER  PROCEDURE [sAssessment].[pRptResultSheetStandardWithAnalysisGet]
	 
	 @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,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

DECLARE @GradeString nvarchar(1000),
@GradeSetId int 
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  
	SELECT 
			--Convert(nvarchar(20),A.Id) AS AcademicIdText,
			--Convert(nvarchar(20),@rExamId) AS ExamIdText,
			RAD.SubjectHighestClassMark,
			RAD.SubjectHighestDivisionMark,
			RAD.SubjectAverageClassMark,
			RAD.SubjectAverageDivisionMark,
			RAD.SubjectHighestClassGrade,
			RAD.SubjectHighestDivisionGrade,
			RAD.ClassSubjectId,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,
			RD.SubjectGrade,
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			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.IsMarksInDecimal,
			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,
			SR.StudentHeight,
			SR.StudentWeight,		
			SR.PresentDays,			
			SR.TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			EM.TermScopeId,
			SI.StudentPhoto,
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(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,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			SF.FatherName,
			SF.MotherName,
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			RAN.HighestClassMark,
			RAN.HighestDivisionMark AS DivisionHighestMark,
			RAn.HighestClassGrade,
			RAN.HighestDivisionGrade AS DivisionHighestGrade,
			RAN.AverageClassMark,
			RAn.AverageDivisionMark,
			RAN.DivisionPercentile,
			RAN.ClassPercentile 
			,RAN.TotalStudentClass,
			RAN.TotalStudentDivision,
		 
			RA.ClassRank,
			RA.DivisionRank,
			RD.Remark,
			RA.PassedSubject,
			RA.FailedSubject,
			EMP.Id AS EmployeeId,
			--TSD.EmployeeId,
			EMP.FirstName + ' ' +EMP.MiddleName +' ' +Emp.LastName AS EmployeeName,
			EI.EmployeeSign,
			EM.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.DecimalFormat,
			SR.ResultRemark3,
			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,
			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, 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			--(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
	FROM 
			 sAssessment.tResultDetail RD
			 INNER JOIN sAssessment.tResult R 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 sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			  INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			 LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM .InchargeEmployeeId
			 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId		
			 --Left Join sAcademic.tTeacherSubjectDivision TSD ON TSD.SubjectId = SM.Id AND Tsd.DivisionId=A.DivisionId
			 --AND TSD.EmployeeId = EI.EmployeeId
			 LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id=EI.EmployeeId 
			
			  
			  LEFT JOin sAssessment.tResultAnalysis RA ON RA.AcademicId = A.Id AND RA.ExamId = EM.Id
			  LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
			  LEFT JOIN sAssessment.tResultAnalysisDivision RAN ON RAN.DivisionId = A.DivisionId AND RAN.ExamId = EM.Id
			   
			  
		      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			  LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			  LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			  INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			  LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			  LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			  INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			
			  INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			  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 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
				 
	WHERE 
			
			((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
			AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
			--AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=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 (R.ExamId = @rExamId)
			AND ((StuM.Code=@rCode) OR (@rCode=''))
			AND ((R.Id = @rResultId) OR (@rResultId = 0))
			AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
			AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
			AND  ISNULL(EMP.IsOtherUser,0) = 0
			AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
			order by A.RollNo,CS.OrderIndex 
			--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardWithGradeGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardWithGradeGet]
	 
	 @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,
	 @rClassStatusId int=0,
	 @rMultiCode nvarchar(max)=''
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

DECLARE @GradeString nvarchar(1000),  @GradeStringRemark nvarchar(500),
@GradeSetId int,@lGradeStringText nvarchar(1000)
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
 SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
 Select @lGradeStringText = GradeStringText from sAssessment.tGradeSetMaster where Id=@Gradesetid
   
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId
 
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
				Convert(nvarchar(20),@rBatchId) AS BatchIdText,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,
			RD.SubjectGrade,
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			
			--CS.OrderIndex AS SubjectOrderIndex,
			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.IsMarksInDecimal,
			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,
			SR.StudentHeight,
			SR.StudentWeight,		
			SR.PresentDays,			
			SR.TotalDays,
			SR.ResultRemark1,
			SR.ResultRemark2,						 
			EM.TermScopeId,
			(CASE EM.IsDisplayPhoto WHEN 1 THEN
				SI.StudentPhoto
			ELSE NULL END) AS StudentPhoto,
			RD.IsPresent,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			EM.IsDisplayGradeString,
			(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,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			SF.FatherName,
			SF.MotherName,
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
			(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
				EI.EmployeeSign
			ELSE NULL END)AS EmployeeSign,
			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,
			ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
			BM.Title AS BatchName,
			Em.DecimalFormat,
			SR.Resultremark3,
			RD.GraceMark,
			ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		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,
		GS.GradeTitle,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		GSCSD.GradeRemark
			--[sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId) AS HighestDivisionMark,
			--[sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId) AS HighestDivisionGrade
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R 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 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
			LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			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 sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
			LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId  and RD.SubjectGrade = GS.GradeCode
			
			LEFT JOIN sAssessment.tGradeSetClassSubjectMaster GSCSM ON GSCSM.ClassId = CM.Id AND GSCSM.SubjectId = SM.Id AND GSCSM.GradeSetId = GS.GradeSetId
			LEFT JOIN sAssessment.tGradeSetClassSubjectDetail GSCSD ON GSCSD.GradeSetDetailId = GS.Id AND GSCSD.GradeSetClassSubjectId = GSCSM.Id
			
			LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=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 (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		AND  ISNULL(EMP.IsOtherUser,0) = 0
		AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		order by A.RollNo,ED.DisplayOrder
		--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptSubjectActivityExamDetailGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptSubjectActivityExamDetailGet]
	 
		@rOrgId int=0,
		@rExamId int=0,
		@rClass int=0,
		@rDivisionId int=0,
		@rBatchId int=0,
		@rBuilder1 nvarchar(max)='',
		@rAcademicId bigint=0,
		@rCode nvarchar(20)='',
		@rFromRollNo int=0,
		@rToRollNo int=0,
		@rMultiCode nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	 

Declare @GradeSetId int,@GradeString nvarchar(1000),@GradeStringRemark nvarchar(1000)
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)
Select @GradeStringRemark = GradeStringText from sAssessment.tGradeSetMaster Where Id =@GradeSetId

	SELECT 			 
			Convert(nvarchar(20),SA.Id) AS AcademicIdText,	
			CONVERT (nvarchar(20),@rExamId) AS ExamIdText, 
			@rBuilder1 AS Builder1,
			SA.Id AS AcademicId,
			SA.RollNo,
			StuM.Number,
			AIS.Grade,
			SAM.Title AS SubjectActivityTitle,
			SSA.Title AS SubjectSubActivityTitle,
			SAM.Id AS ActivityId,
			SSA.Id AS SubjectSubActivityId,
			SAM.OrderIndex AS ActivityOrderIndex,
			SSA.OrderIndex AS SubjectSubActivityOrderIndex ,
			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,
			EM.IsDisplayGradeString,
			EM.IsDisplayParentName,
			[sStudent].[fStudentNameGet](StuM.FirstName , ISNULL(StuM.MiddleName,'') , StuM.LastName,OM.StudentNameFormatId ) AS Name,
			SO.DateOfBirth,
			CMM.Title AS ClassName,
			StuM.code,
			SF.FatherName,
			SF.MotherName,
			SAM.ClassSubjectId ,
			SM.Title AS SubjectName,
			SM.OrderIndex AS SubjectOrderIndex,
			CMM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			CASE WHEN EM.IsDisplayPhoto = 1 THEN SI.StudentPhoto ELSE NULL END AS StudentPhoto, 
			ISNULL(AIS.DescriptiveIndicator,'') AS DescriptiveIndicator,
			CASE WHEN CS.OrderIndex % 2 = 0 THEN 2 
			ELSE 1 END AS ColumnSubjectCount,
			CS.OrderIndex,
			EM.SubjectGroupPerPage,
			AIS.GradeIndicator,
			EM.IsCoScholasticGradeIndicator,
			CASE WHEN EM.IsDisplayTeacherSign = 1 THEN EI.EmployeeSign ELSE NULL END AS EmployeeSign,
			Em.IsDisplayPrincipalSign,
			EM.IsDisplayTeacherSign,
			EM.IsCoScholasticGradeDesIndicator,
			EM.IsCoScholasticGrade,
			Em.IsDisplayParentName,
			(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS MarksheetHeaderA4,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			RD.Remark,
			
			HM.Title AS House,
			BM.Title AS BAtch ,
			[sAttendance].[fSubjectTeacherGet](SA.DivisionId,SM.ID) AS TEacherName,
			ED.IsShowSubjectGrade,
			CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
			--@GradeString AS GradeString,
			Convert(nvarchar(20),ISNULL(Em.IsDisplayMonthlyAttendance,0)) As IsDisplayMonthlyAttendanceText,
			TeacherSignCaption,
			EM.PrincipalSignCaption,
			ParentSignCaption,
			--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,
			SR.ResultRemark1,
			SR.ResultRemark2,	
			SR.ResultRemark3,
			SR.ClassTeacherRemark,
			SR.HouseRemark,
			SR.PresentDays,			
			SR.TotalDays,
			SR.StudentHeight,
			SR.StudentWeight,
			
			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,
			ISNULL(SR.ImprovementArea,'') As ImprovementArea,
			ISNULL(SR.ProgressArea,'') AS ProgressArea,
			ISNULL(SR.GeneralRemark,'') As GeneralRemark,
			ISNULL(SR.MyActivity,'') AS MyActivity,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SC.PresentStreetONe,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
			DivisionId,
			SM.ID
	 FROM 
			sAssessment.tCCESubjectSubActivityExamScore AIS 
			INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON AIS.SubjectSubActivityId = SSA.Id 
			INNER JOIN	sAssessment.tCCESubjectActivityMaster SAM  ON SAM.Id = SSA.SubjectActivityId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=SAM.ClassSubjectId		
			INNER JOIN sStudent.tAcademic SA ON SA.Id = AIS.AcademicId 
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId AND ED.ClassSubjectId = CS.Id 		 			 
			INNER JOIN sAssessment.tResult AR ON AR.ExamId = AIS.ExamId AND AIS.AcademicId = AR.AcademicId
			INNER JOIN sAssessment.tResultDetail ARD ON ARD.ResultId = AR.Id AND ARD.ExamDetailId = ED.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId	
			INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=DM.ClassId 
			
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sAssessment.tStudentRemark SR ON SA.Id = SR.AcademicId	AND EM.Id = SR.ExamId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.Id AND EM.ID=RD.ExamId AND CS.Id=RD.ClassSubjectID 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =StuM.ID
	    --LEFT JOIN @lAcademicId A ON A.AcademicId = SA.AcademicId AND A.ClassSubjectId = ED.ClassSubjectId
			----------------------------------------------------------------------------
			--sAssessment.tCCESubjectActivityMaster SAM 	
			--INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSA ON SAM.Id=SSA.SubjectActivityId 
			--INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
			--INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId = CS.ClassId 
			--INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=SA.StudentId			 
			--LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore AIS ON AIS.AcademicId =SA.AcademicId AND AIS.SubjectSubActivityId= SSA.Id 	
			--LEFT JOIN sAssessment.tExamMaster EM ON EM.Id=AIS.ExamId
			--LEFT JOIN sAssessment.tExamDetail ED ON EM.Id=ED.ExamId	AND ED.ClassSubjectId = CS.ClassSubjectId 		 
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			--LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId	
			--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
			--INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.divisionId
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM.Id AND TSD.SubjectId = SM.Id 
			--LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = TSD.EmployeeId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			--LEFT JOIN sAssessment.tStudentRemark SR ON SA.AcademicId = SR.AcademicId	AND EM.Id = SR.ExamId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = Stum.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id= SA.BatchID
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = Om.Id
			--LEFT JOIN sAssessment.tResultDetailOther RD ON RD.AcademicId = SA.AcademicId AND EM.ID=RD.ExamId AND CS.ClassSubjectId=RD.ClassSubjectID 
		WHERE
			((SA.Id=@rAcademicId) OR(@rAcademicId=0))
			AND ((CS.ClassId=@rClass) OR (@rClass=0))
			And ((SA.DivisionId =@rDivisionId) or(@rDivisionId=0))	
			And ((SA.BatchId =@rBatchId) OR (@rBatchId=0))
			and ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			And AIS.ExamId=@rExamId
			AND ((STum.Code = @rCode) OR(@rCode=''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND StuM.StatusId = 1
			AND (ISNULL(STum.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		ORDER BY 
			SA.RollNo ASC,
			SAM.OrderIndex ASC,
			SSA.OrderIndex ASC;
END
GO
PRINT N'Altering [sAssetManagement].[pAssetMaintenanceDetailGet]...';


GO
 
ALTER PROCEDURE [sAssetManagement].[pAssetMaintenanceDetailGet]
	@rOrgId int,
	@rNumber nvarchar(20) = '',
	@rAssetId int = 0,
	@rFromMaintenanceDate Date ='',
	@rToMaintenanceDate Date = '',
	@rId int = 0,
	@rStatusId int = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;

BEGIN
	
	SELECT	AMT.Id,
			AMT.Number,
			AMT.AssetId,
			AMT.CreatedUserId,
			AMT.MaintenenceBy,
			AMT.MaintenenceCost,
			--CONVERT(varchar,AMT.MaintenenceDate, 105) as MaintenenceDate, 
			AMT.MaintenenceDate,
			AMT.MaintenenceReason,
			--CONVERT(varchar,AMT.NextMaintenenceDate, 105) as NextMaintenenceDate,
			AMT.NextMaintenenceDate,
			LM.Title AS LocationName,
			LM.Id,
			AM.StatusId,
			AM.Title AS AssetName,
			AM.Code AS AssetCode,
			AM.CategoryId AS AssetCategoryId,
			LM.Id AS LocationId,
			AMT.DocumentNo,
			AMT.DocumentDate,
			AD.Title AS DepartmentName,
			SM.Title AS StatusName,
			CM.Title AS CategoryName,
			AM.ModelNumber AS ModelNumber
			
			
	FROM sAssetManagement.tMaintenence AMT
	INNER JOIN 
		sAssetManagement.tAssetMaster AM
	ON
		AMT.AssetId = AM.Id
	INNER JOIN
		sFixedAsset.vExtLocationMaster LM
	ON
		AM.LocationId = LM.Id
	INNER JOIN sSetup.tDepartmentMaster  AD
	ON	AD.Id=AM.DepartmentId
	INNER JOIN
	    sCommon.tStatusMaster SM
	ON	 SM.Id = AM.StatusId
	INNER JOIN sFixedAsset.tCategoryMaster CM
	ON CM.Id=AM.CategoryId 

	WHERE ((AMT.Number = @rNumber) OR (@rNumber = 0)) AND AM.UsageStatusId <> 124 
	AND AMT.OrgId = @rOrgId AND ((AMT.AssetId = @rAssetId) OR (@rAssetId = 0))
	AND ((AMT.MaintenenceDate >= @rFromMaintenanceDate) OR (ISNULL(@rFromMaintenanceDate,'')='')) 
	AND ((AMT.MaintenenceDate <= @rToMaintenanceDate) OR (ISNULL(@rToMaintenanceDate,'') = '')) 
	AND ((AMT.Id = @rId) OR (@rId = 0))
	AND ((AM.StatusId = @rStatusId) OR (@rStatusId = 0))
END
GO
PRINT N'Altering [sAssetManagement].[pAssetMasterListDataGet]...';


GO
ALTER PROCEDURE [sAssetManagement].[pAssetMasterListDataGet]
 	@rOrgGroupId smallint,

	@rId [int] = 0,
	@rCode [nvarchar](100) = '',
	@rTitle [nvarchar](100) = '',
	@rLocationId [int] = 0,
	@rIsWildCard [bit] = 0,
	@rStoreLocationId int,
	@rDepartmentId int

 	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

SET @rCode  = ISNULL(@rCode, '') 
SET @rTitle = ISNULL(@rTitle, '') 

IF @rIsWildCard = 1
BEGIN
SET @rCode  = sCommon.fSearchStringGet(@rCode)
SET @rTitle = sCommon.fSearchStringGet(@rTitle)
END

       SELECT AM.Id,
                  AM.Code,
                  AM.Title,
                  Specification,
                  Accessories,
                  AM.LocationId,
                  StatusId,
                  VendorId,
                  VM.Title AS VendorName,
                  GoodsReceiptNumber,
                  GoodsReceiptDate,
                  IsInstallationRequired,
                  InstallationDate,
                  CategoryId,
                  DepreciationUptoDate,
                  IsFullyDepreciated,
                  StandardPrice,
                  MinStockRequired,
                  MaintenancePeriod,
                  IsAmc,                  
                  MaintenanceAlertPeriod,
                  AmcVendorId,
                  VM1.Title AS AmcVendorName,
                  UsageStatusId,
                  LastServiceCost,
                  TotalServiceCost,
                  LastDownTime,
                  TotalDownTime,
                  LastMaintenanceDate,
                  NextMaintenanceDate,
                  ModelNumber,
                  IsCritical,
                  AM.IsObsolete,
                  AM.CreatedUserId,
                  AM.CreatedDateTime,
                  AM.UpdatedUserId,
                  AM.UpdatedDateTime,
                  AM.DepartmentID,
                  ServiceEntry,
                  ODM.Title AS DepartmentTitle,
                  VAD1.Title AS LocationTitle,
                  FCM.Title AS CategoryTitle,
                  CM.Title AS StatusTitle,
                  
                   AM.IsCheckRequired,
				  ISNULL (AM.CheckFrequencyId,0) AS CheckFrequencyId,	
				  AM.CheckList,	
                  --AM.CheckedLastDate,
                   ISNULL(AM.CheckedLastDate,'0001/01/01') AS CheckedLastDate,
                  AM.CheckedByUserId,
                  ISNULL(AM.CheckedStatusId,0) AS CheckedStatusId,
                  AM.CheckedRemark,
                  IsRenewRequired,
                  ISNULL(RenewLastDate,'0001/01/01') AS RenewLastDate,
                  ISNULL(RenewNextDate,'0001/01/01') AS RenewNextDate,
                --  AM.RenewLastDate,
                  --AM.RenewNextDate,
				  AM.RenewRemark,
				  AM.RenewCheckList,
				  AM.RenewAlertBeforeDays,
				  U.LoginTitle AS UserTitle
				,ISNULL (AM.IsMaintenanceRequired,0) AS IsMaintenanceRequired
         FROM sAssetManagement.tAssetMaster AM
         LEFT JOIN sProcurement.tVendorMaster VM
                  ON VM.Id = AM.VendorId 
         LEFT JOIN sProcurement.tVendorMaster VM1
                  ON VM1.Id = AM.AmcVendorId 
            --INNER JOIN (SELECT DISTINCT DepartmentId, DepartmentTitle FROM sAssetManagement.vExtAssetDepartment) VAD
            --ON VAD.DepartmentId = AM.DepartmentID
            INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = AM.DepartmentId
             --left JOIN sCommon.tOrganizationDepartmentMaster ODM ON ODM.Id = AM.DepartmentId
            INNER JOIN sFixedAsset.tLocationMaster VAD1
            ON VAD1.Id = AM.LocationId 
            INNER JOIN (SELECT DISTINCT Id, Title FROM sFixedAsset.tCategoryMaster ) FCM
            ON FCM.Id = AM.CategoryId
            INNER JOIN (SELECT DISTINCT Id, Title FROM sCommon.tStatusMaster) CM
            ON CM.Id = AM.UsageStatusId
             LEFT JOIN sSecurity.tUser U ON U.Id=AM.CheckedByUserId
        WHERE ((AM.Id = @rId) OR (@rId = 0)) AND ((AM.Code LIKE @rCode) OR (@rCode = '')) AND ((AM.Title LIKE @rTitle) OR (@rTitle = ''))
        AND AM.OrgGroupId = @rOrgGroupId
        AND AM.StoreLocationId=@rStoreLocationId
        AND ((AM.LocationId = @rLocationId) OR (@rLocationId = 0))
        AND ((AM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
        ORDER BY AM.Code DESC

END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


GO
 
ALTER PROCEDURE [sCommon].[pOrganizationSetupRemove]
	 
	 @rOrgId bigint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
  --  BEGIN TRY
	
	 --BEGIN TRANSACTION
	 
	 --EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    
DELETE FROM sAccounting.tExpense WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tExpenseGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursementDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAccounting.tReimbursementTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tActivity WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tActivityParticipant WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tAssignClub WHERE CAST(LEFT(ClubId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tEventAssign WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tEventEnrollment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tEventSchedule WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupAssign WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupDetail WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupParameter WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthCheckupStudent WHERE CAST(LEFT(HealthCheckupId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterList WHERE CAST(LEFT(HealthParameterId, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthParameterMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tHealthTrack WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tHouseMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tPlacement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sActivity.tPlacementInvite WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sActivity.tStudentImmunizationStatus WHERE CAST(LEFT(ImmunizationChartId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionForm WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormIssue WHERE OrgId = @rOrgId
DELETE FROM sAdmission.tAdmissionInquiry WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tAlertConfiguration WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tAlertLog WHERE OrgId = @rOrgId
DELETE FROM sAlert.tAlertQueue WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tAlertQueueDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAlert.tCustomTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tDepartmentRecipient WHERE CAST(LEFT(DepartmentId, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tEmailConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tEventTemplate WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tExternalRecipientMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAlert.tSMSConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sAlert.tTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSClass WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSIndicatorGrade WHERE CAST(LEFT(CCECSId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCECSScore WHERE CAST(LEFT(CCECSId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamMapping WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamSetting WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEFAGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCEFAScore WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCEFASubject WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEResult WHERE AcademicId = @rOrgId
DELETE FROM sAssessment.tCCEResultDetail WHERE AcademicId = @rOrgId
DELETE FROM sAssessment.tExamCombine WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamStatus WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tExamsubgroupmaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tGeneralExamCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tGradeSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tGradeSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tLevelSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tLevelSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tOptionalSubject WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tRankSetDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tRankSetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tResult WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAudit WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetAuditDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tAssetMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tDepartmentLocation WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMaintenence WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMovement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tMovementDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAssetManagement.tRecordManualEvent WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tApplicableAttendanceType WHERE OrgId = @rOrgId
DELETE FROM sAttendance.tMonthlyRegister WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tMonthlySetup WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tStudentRegister WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tStudentSetup WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAttendance.tSubjectBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tSubjectBatchStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAudit WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAuditLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sAudit.tAuditLogTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTable WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTableField WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tAuditTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAction WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tActionStatusMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tActionTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAudit WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tAuditLocation WHERE CAST(LEFT(AuditId, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tAuditReasonMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAuditStatusMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tAuditTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tDocument WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tDocumentTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tFinding WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tFindingTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tInspection WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tQuestionAnswerMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionAnswerTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionMainGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionnairesMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tQuestionResponse WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sBi.tQuestionSubGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBi.tSeverityMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sBiometric.tPunchMaster WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sCertificate.tBonafide WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCertificate.tCharacter WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tFirstTrial WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCertificate.tLeaving WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tAgeGroupMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tClinicMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId


DELETE FROM sCommon.tDurationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tExceptions WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sCommon.tFileUpload WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tFirstAidMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tFunctionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tLocationMaster WHERE OrgId = @rOrgId
DELETE FROM sCommon.tOrganizationDepartmentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPrefixSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPublicHolidayMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tPublicHolidayTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tReasonMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sCommon.tReportFormatGroupOrg WHERE OrgId = @rOrgId
 
DELETE FROM sCommunication.tAssignment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignmentScope WHERE CAST(LEFT(AssignmentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignmentView WHERE CAST(LEFT(AssignmentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tAssignTask WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tBehaviour WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussion WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionComment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionGroup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tDiscussionGroupMember WHERE CAST(LEFT(DiscussionGroupId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tPhotoCategoryOrg WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tQueryCategoryOrg WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tUploadBookLog WHERE CAST(LEFT(BookLogId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommunication.tUploadResult WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tColorLegendDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tConfigurationSetup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId AND SourceTypeId <> 2010
DELETE FROM sConfig.tCultureConfiguration WHERE OrgId = @rOrgId
DELETE FROM sConfig.tImport WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sConfig.tLocalDeviceSetting WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tMachineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tMachinePrinterMapping WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sConfig.tPrinterMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sEExam.tTestAssign WHERE CAST(LEFT(TestId, 4) AS int) = @rOrgId
DELETE FROM sEExam.tTestMaster WHERE OrgId = @rOrgId
DELETE FROM sEExam.tTestParticipant WHERE CAST(LEFT(TestId, 4) AS BIGINT) = @rOrgId
DELETE FROM sEExam.tTestParticipantAnswer WHERE CAST(LEFT(TestId, 4) AS INT) = @rOrgId
DELETE FROM sEExam.tTestQuestion WHERE CAST(LEFT(TestId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tChargeReceipt WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tChargeReceiptDetail WHERE CAST(LEFT(ChargeReceiptId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeAllocation WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeOptional WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tFeeSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tReceipt WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tReceiptDetail WHERE CAST(LEFT(ReceiptId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFixedAsset.tCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFixedAsset.tLocationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFrontOffice.tVisitorLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tActivityIndicatorScore WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tAnusuchiB WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tClassActivity WHERE CAST(LEFT(ActivityId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tExamSetting WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tGSEBExamMapping WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tHetuMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sGSEB.tAnusuchiB WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResult WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResultDetail WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tResultDetailOptional WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sGSEB.tSubjectIndicatorMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tAssignRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tHostelWarden WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeAttendance WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeCommunications WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeDesignationMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeFamilyDetails WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeGradeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeImages WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeJobDetail WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeePersonalDetail WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeePreviousEmployment WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeStatutoryAndOther WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tGuestMaster WHERE OrgId = @rOrgId
DELETE FROM sHrm.tLeave WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tLeaveTypeGradeSettings WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sHrm.tLeaveTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tWorkingDays WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sIp.tBinMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tItemStandardPriceLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tStockItemBin WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tStockItemPlanning WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tStockItemPurchaseUom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sIp.tWeightedAverageCostLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tAssignOrganization WHERE OrgId = @rOrgId
DELETE FROM sLibrary.tBookLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tBookLogPenalty WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sLibrary.tBooksForClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sLibrary.tIssueSetting WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sOmr.tAnswerKeySetup WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tExamSetup WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tScanHistory WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sOmr.tSetting WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sOmr.tSheetCallibration WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOmr.tTempAnsKeyAnalysis WHERE CAST(LEFT(ExamDetailId, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tIssueReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tIssueReturnDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sOrderEntry.tOrderEntry WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sOrderEntry.tOrderEntryBatch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sOrderEntry.tServiceItemTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tFirstAidEmoloyee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidEmployeeDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidInspection WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tFirstAidInspectionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNote WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturnBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tGoodsReceiptNoteReturnDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tPurchaseOrder WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tPurchaseOrderDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustmentBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAudit WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockAuditDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockFreezeAdjustment WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockFreezeAdjustmentDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInward WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardReturn WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockInwardReturnBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssue WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockIssueRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockItemFreeze WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockTransfer WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferBatch WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferRequest WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockTransferRequestDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sProcurement.tStockVerification WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sProcurement.tStockVerificationApproval WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tConfiguration WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSecurity.tDivisionPermission WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tLdapUser WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUser WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserAccess  WHERE CAST(LEFT(UserId, 4) AS int) = @rOrgId
DELETE FROM sSecurity.tUserFavoriteScreen WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserLocation WHERE CAST(LEFT(StoreLocationId, 4) AS INT) = @rOrgId
DELETE FROM sSecurity.tUserLog WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserOrganization WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSecurity.tUserPreference WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserProfile WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSecurity.tUserRole WHERE CAST(LEFT(UserId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId
DELETE FROM sSetup.tClassMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tClassSubject WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDepartmentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDivisionMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
 
DELETE FROM sSetup.tReportConfiguration WHERE OrgId = @rOrgId
DELETE FROM sSetup.tReportSetting WHERE CAST(LEFT(OrgId, 4) AS SMALLINT) = @rOrgId
DELETE FROM sSetup.tSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tTermMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tAcademic WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tAcademicDetail WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentAdmission WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentCommunication WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentCustomSearch WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentFamily WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentHealth WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentImages WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sStudent.tStudentOther WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tContactMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tContactTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tImageMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tImageTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSupport.tLinkMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tVideoMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sSupport.tVideoTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTax.tTaxRateSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tDivisionWorkLoad WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tProxySetting WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTeacherWorkLoad WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeSetup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeTable WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTimeTableSchema WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sTransport.tAssignRoute WHERE CAST(LEFT(SourceId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCECSExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEFAExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tExamCombineTerm WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tGradeSujbectExamScore WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tStudentRemark WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tSubjectIndicatorMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tTempAllExam
DELETE FROM sAssessment.tTempCoScholasticExam

DELETE FROM sFee.tAccountMapping WHERE CAST(LEFT(FeeSetupId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tDepositAdd WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tDepositAdjustment WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tDepositBalance WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tDepositRefund WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipEligibleStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipMaster WHERE CAST(LEFT(BatchId, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipReceive WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sScholarship.tScholarshipStudentPaid WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sSetup.tYearChangeDivisionMapping WHERE CAST(LEFT(OldDivisionId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tClasswork WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tLessonPlan WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tLessonPlanResource WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tTopicMaster WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tPrintTemplate WHERE OrgId = @rOrgId
DELETE FROM sCertificate.tPrintTemplateStudent WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sHostel.tStudentGatePass WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tFeeHeadOrgwise WHERE OrgId = @rOrgId
DELETE FROM sFee.tReceiptBookOrgwise WHERE OrgId = @rOrgId

DELETE FROM sAcademic.tTeacherSubject WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sAcademic.tTeacherSubjectDivision WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionCriteriaMaster WHERE OrgId = @rOrgId
--DELETE FROM sAdmission.tAdmissionCriteriaStudent WHERE CAST(LEFT(AdmissionSetupId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormSelected WHERE CAST(LEFT(AdmissionFormId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionSetup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tFilterCriteria WHERE OrgId = @rOrgId
DELETE FROM sAttendance.tFilterCriteriaDetail WHERE CAST(LEFT(FilterCriteriaId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tYearlyRegister WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tWinfeeDetail WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeAttendanceRegister WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tEmployeeICardOrg WHERE OrgId = @rOrgId
DELETE FROM sSecurity.tUserDashlet WHERE CAST(LEFT(UserId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tICardOrg WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionSetupStudent WHERE CAST(LEFT(AdmissionSetupId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCECSForClass WHERE CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sAudit.tActivityLog WHERE CAST(LEFT(OrgId, 4) AS INT)  = @rOrgId
DELETE FROM sAudit.tReceiptDelete WHERE BatchId = @rOrgId
DELETE FROM sAudit.tReceiptDetailDelete WHERE CAST(LEFT(ReceiptId, 4) AS INT) = @rOrgId

DELETE FROM sCommunication.tViewResult WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tViewResultDetail WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrgInfo WHERE OrgId = @rOrgId

DELETE FROM sStudent.tStudentCustomTag WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionCriteria WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormFamilyDetail WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormParentAcademic WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormReference WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormSibling WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormStudentAcademic WHERE CAST(LEFT(AdmissionFormId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCESubjectActivityMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tCCESubjectSubActivityExamScore WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tCCESubjectSubActivityMaster WHERE OrgId = @rOrgId
DELETE FROM sAssessment.tResultAnalysis WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDetail WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sCommon.tReportOrg WHERE ScopeSourceId = @rOrgId AND ScopeSourceTypeId = 2021
DELETE FROM sAssessment.tCCESubjectSubActivityIndicatorMaster WHERE  OrgId = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDivision WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tResultAnalysisDivisionDetail WHERE CAST(LEFT(ExamId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFrontOffice.tStudentGatePass WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgCalander WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgDrive WHERE OrgId = @rOrgId
DELETE FROM sGoogle.tOrgYouTube WHERE OrgId = @rOrgId
DELETE FROM sHrm.tLeaveBalance WHERE CAST(LEFT(BatchId, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceAdd WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sTimetable.tAssignTeacher WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId
DELETE FROM sTimetable.tDivision WHERE CAST(LEFT(OrgId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tSubject WHERE CAST(LEFT(OrgId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tSubjectTimeOff WHERE CAST(LEFT(SubjectId, 4) AS INT) = @rOrgId
DELETE FROM sTimetable.tTeacher WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sHrm.tEmployeeQualification WHERE OrgId = @rOrgId
DELETE FROM sSecurity.tUserDashboardNotification WHERE CAST(LEFT(UserId, 4) AS BIGINT) = @rOrgId
DELETE FROM sTransport.tAssignTransportOrg WHERE OrgId = @rOrgId

--DELETE FROM sFee.tOnlinePayment WHERE  CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
--DELETE FROM sFee.tOnlinePaymentDetail WHERE  CAST(LEFT(OnlinePaymentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tReceiptRefund WHERE  CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tReceiptRefundDetail WHERE  CAST(LEFT(ReceiptRefundId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformIssue WHERE  CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformIssue WHERE  CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformItemForClass WHERE  CAST(LEFT(ClassId, 4) AS INT) = @rOrgId
DELETE FROM sIp.tUniformOrder WHERE  CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sIp.tUniformOrderDetail WHERE  CAST(LEFT(UniformOrderId, 4) AS BIGINT) = @rOrgId
 
DELETE FROM sFee.tFeeInvoice WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tFeeInvoiceDetail WHERE CAST(LEFT(FeeInvoiceId, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFee WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeDetail WHERE CAST(LEFT(OnlineFeeId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tCertificateEmployment WHERE CAST(LEFT(EmployeeId, 4) AS INT) = @rOrgId
DELETE FROM sOp.tPaymentTransaction WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrgImages WHERE OrgId = @rOrgId
DELETE FROM sStudent.tStudentadditional WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tStudentBatchStatus WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId

DELETE FROM sCommon.tPrefixConfig WHERE OrgId = @rOrgId
DELETE FROM sConfig.tDisplayFieldOrg WHERE OrgId = @rOrgId
DELETE FROM sHrm.tCertificateExperience WHERE OrgId = @rOrgId
DELETE FROM sHrm.tCertificateRelieving WHERE OrgId = @rOrgId
DELETE FROM sRFID.tAttendance WHERE OrgId = @rOrgId
DELETE FROM sRFID.tRegistration WHERE CAST(LEFT(RegistrtionId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tBatchClassLecture WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tStudentSibling WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tTranscriptAssessment WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sTally.tStudentLedgerMapping WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

/* -- Date : 13/06/2016 -- */
DELETE FROM sActivity.tEventAttendance WHERE CAST(LEFT(SourceId, 4) AS INT) = @rOrgId
DELETE FROM sCanteen.tAssignOrganization WHERE OrgId = @rOrgId
DELETE FROM sCommunication.tRegisteredUsers WHERE OrgId = @rOrgId
DELETE FROM sStudent.tCollegeDetail WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

-- 15.7.2016
DELETE FROM sFrontOffice.tInwardRegister WHERE OrgId = @rOrgId
DELETE FROM sFrontOffice.tOutwardRegister WHERE OrgId = @rOrgId
DELETE FROM sSetup.tSubjectGroupMaster WHERE OrgId = @rOrgId

/* -- Date : 12/08/2016 -- */
DELETE FROM sAssessment.tExamCombineSubject WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tResultDetailOther WHERE CAST(LEFT(ExamId, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tDivisionInchargeEmployee WHERE CAST(LEFT(DivisionId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tEnrollmentStatusOrg WHERE OrgId = @rOrgId
DELETE FROM sStudent.tEnrollmentStatusStudent WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sStudent.tLinkSibling WHERE CAST(LEFT(StudentId, 4) AS INT) = @rOrgId

/* -- Date : 17/09/2016 -- */

DELETE FROM sAssessment.tTempAllExamSubjectActivity WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tTempAttendance WHERE CAST(LEFT(AcademicId, 4) AS INT) = @rOrgId

/* -- Date : 05/10/2016 -- */

DELETE FROM sAdmission.tAdmissionInquiryFollowup WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgId
--DELETE FROM sAssessment.tStaticCCECSGroupMaster WHERE OrgId = @rOrgId
--DELETE FROM sAssessment.tStaticCCECSMaster WHERE OrgId = @rOrgId

/* -- Date : 20/10/2016 -- */

DELETE FROM sAssessment.tOptionalCCECS WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId

/* -- Date : 24/11/2016 -- */
DELETE FROM sBiometric.tMonthTrans WHERE CAST(LEFT(EmployeeId, 4) AS BIGINT) = @rOrgId

/* -- Date : 23/12/2016 -- */
DELETE FROM sAdmission.tAdmissionFormReceipt WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tCCEExamStatus WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tAttendanceGroup WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAttendance.tAttendanceGroupStudent WHERE CAST(LEFT(AcademicId, 4) AS BIGINT) = @rOrgId
DELETE FROM sFee.tAccountPosting WHERE CAST(LEFT(AccountId, 4) AS INT) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceAddRequest WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

/* -- Date : 14/02/2017 -- */

DELETE FROM sCRM.tChannelPartnerMaster WHERE OrgId = @rOrgId
DELETE FROM sCRM.tInstituteGroupMaster WHERE OrgId = @rOrgId
DELETE FROM sCRM.tInstituteMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sSetup.tOrganizationOtherDetail WHERE OrgId = @rOrgId

DELETE FROM sAppraisal.tConduct WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId
DELETE FROM sAssessment.tAllBatchClassGroup WHERE OrgId= @rOrgId
DELETE FROM sAssessment.tAllBatchResult WHERE CAST(LEFT(StudentId, 4) AS BIGINT) = @rOrgId
DELETE FROM sAssessment.tAllBatchSubject WHERE OrgId= @rOrgId
DELETE FROM sHrm.tEmployeeTravel WHERE OrgId= @rOrgId


DELETE FROM sLoan.tLoanDetail WHERE OrgId= @rOrgId
DELETE FROM sLoan.tLoanEMI WHERE CAST(LEFT(LoanDetailId, 4) AS BIGINT) = @rOrgId
DELETE FROM sLoan.tLoanPayrollMapping WHERE OrgId= @rOrgId
DELETE FROM sLoan.tLoanTypeMaster WHERE OrgId= @rOrgId
DELETE FROM sPayroll.tPayrollCustomSearch WHERE OrgId= @rOrgId
DELETE FROM sErp.tChannelMaster WHERE OrgId = @rOrgId

DELETE FROM sAccounting.tExpenseDetail WHERE CAST(LEFT(ExpenseId, 4) AS int) = @rOrgId
DELETE FROM sAccounting.tExpenseSubGroupMaster WHERE OrgId= @rOrgId
DELETE FROM sAppraisal.tAppraisalTypeMaster WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tBusinessHeadsRatingStatus WHERE CAST(LEFT(AppraisalTypeId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployee WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeDetail WHERE CAST(LEFT(KPAEmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeRating WHERE CAST(LEFT(KPAEmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sAppraisal.tKPAEmployeeRatingDetail WHERE CAST(LEFT(KPAEmployeeRatingId, 4) AS bigint) = @rOrgId
DELETE FROM sPoliciesForms.tFolderFile WHERE OrgId = @rOrgId
DELETE FROM sPoliciesForms.tFolderFilePermission WHERE CAST(LEFT(FolderFileId, 4) AS int) = @rOrgId


DELETE FROM sFee.tFeeMainGroupOptionalFee WHERE OrgId = @rOrgId
DELETE FROM sFee.tFeeStructureDetail WHERE CAST(LEFT(FeeStructureId, 4) AS int) = @rOrgId
DELETE FROM sFee.tFeeStructureMaster WHERE OrgId = @rOrgId
DELETE FROM sFrontOffice.tEmployeeGatePass WHERE OrgId = @rOrgId
DELETE FROM sHostel.tHostelStudentGatePass WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveBalanceLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sTransport.tAttendanceRegister WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAssessment.tCCESubjectActivityExamScore WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tTempAll_Exam WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sCanteen.tAttendanceForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCanteen.tRegisterForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCertificate.tTransfer WHERE OrgId = @rOrgId
DELETE FROM sCanteen.tRegisterForBreak WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sErp.tLeadFollowup WHERE CAST(LEFT(LeadId, 4) AS int) = @rOrgId
DELETE FROM sErp.tLeadMaster WHERE OrgId = @rOrgId


DELETE FROM sAdmission.tAdmissionHSCDetail WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sBiometric.tEmployeeCheckIn WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId

DELETE FROM sBiometric.tEmployeeLateStatus WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tSubmitDocumentMaster WHERE OrgId = @rOrgId
DELETE FROM sStudent.tStudentDocument WHERE CAST(LEFT(SubmitDocumentMasterId, 4) AS int) = @rOrgId
DELETE FROM sTimetable.tAnnualSubjectWorkLoad WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sFee.tReceiptDeleted WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sFee.tReceiptDetailDeleted WHERE CAST(LEFT(ReceiptId, 4) AS bigint) = @rOrgId

DELETE FROM sAttendance.tStudentLeaveRequest WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sInfrastructure.tResourceMaster WHERE CAST(LEFT(Id, 4) AS int) = @rOrgId
DELETE FROM sInfrastructure.tResourceRequest WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM sAlumni.tRegistration WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tMonthlyStatusUpdate WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tDSR WHERE OrgId = @rOrgId
DELETE FROM sErp.tDSRWorkTypeMaster WHERE OrgId = @rOrgId
DELETE FROM sErp.tProjectMaster WHERE OrgId = @rOrgId
DELETE FROM sFee.tFeeFollowup WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
 
DELETE FROM sActivity.tWeekOffSetting WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tAllBatchResultCoScholestic WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tEmployeeDocument WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tChangeIdLog WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sAlert.tAssociateRecipient WHERE CAST(LEFT(ForUserId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tPreLessonPlan WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAssessment.tAllBatchResultGrade WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId

DELETE FROM sVts.tvtsClassMaster WHERE CAST(LEFT(ClassId, 4) AS int) = @rOrgId
DELETE FROM sVts.tvtsOrganizationMaster WHERE OrgId = @rOrgId
DELETE FROM sVts.tvtsStudent WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tLeadChannelPartnerMaster WHERE  OrgId = @rOrgId


DELETE FROM sAlumni.tStudentMapping WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tUserFeedback WHERE CAST(LEFT(UserId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeExpense WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaForm WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormField WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tGradeSetClassSubjectDetail WHERE CAST(LEFT(Id, 4) AS int) = @rOrgId
DELETE FROM sAssessment.tGradeSetClassSubjectMaster WHERE OrgId = @rOrgId
DELETE FROM sBiometric.BioDetailMapping WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tLog WHERE OrgId = @rOrgId

DELETE FROM sCertificate.tOtherCertificate WHERE OrgId = @rOrgId
DELETE FROM sWorkflow.tApprovalAction WHERE CAST(LEFT(ActionUserId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tApprovalRequest WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sWorkflow.tFunctionalityApprovingAuthority WHERE OrgId = @rOrgId
DELETE FROM sWorkflow.tFunctionalityApprovingDepartment WHERE OrgId = @rOrgId

DELETE FROM sBiometric.tProcess WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAssessment.tConfiguration WHERE OrgId = @rOrgId

DELETE FROM sAcademic.tHomeworkCheck WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId

DELETE FROM sAdmission.tAdmissionCriteriaFee WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionFormFee WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId


DELETE FROM sFee.tFeeOpening WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sTransport.tChangeRouteLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tClassworkConfig WHERE OrgId = @rOrgId
DELETE FROM sBiometric.tPunchData WHERE CAST(LEFT(StudentID, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tCallLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tMarketingActivityPlan WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
--DELETE FROM tMarketingActivityStatus WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sErp.tTripLog WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAudit.HistoryLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sAudit.tOperationLog WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId

--DELETE FROM sErp.tCustomerTicket WHERE OrgId= @rOrgId
DELETE FROM sPayroll.tPayProcessEmployeeRemark WHERE CAST(LEFT(EmployeeId, 4) AS int) = @rOrgId


/*==============================*/

DELETE FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgId


DELETE FROM sAlert.tAlertLogHistory WHERE OrgId= @rOrgId
DELETE FROM sAlert.tNotificationLogHistory WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeCommunications WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeFamilyDetails WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tBatchEmployeeJobDetail WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeeMaster WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeePersonalDetail WHERE OrgId= @rOrgId
DELETE FROM sHrm.tBatchEmployeeStatutoryAndOther WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sSecurity.tUserLogHistory WHERE OrgId= @rOrgId
DELETE FROM sStudent.tAcademicStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentAdditional WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentCommunication WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentFamily WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentHealth WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tAcademicStudentOther WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tStudentCustomFieldData WHERE CAST(LEFT(StudentId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tStudentMasterDelete WHERE OrgId= @rOrgId

DELETE FROM sAudit.ChangeLog WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tCertificateIncrement WHERE OrgId= @rOrgId
DELETE FROM sAudit.ChangeLog WHERE CAST(LEFT(ScreenId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tClassworkView WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sBiometric.tPunchCount WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sFrontOffice.tOTPLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveDeduction WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaDocument WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionStudentDocument WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sTimetable.tTimeTableTime WHERE CAST(LEFT(DivisionId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeWorkingDays WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sErp.tContactBookMaster WHERE OrgId= @rOrgId
DELETE FROM sErp.tEmployeeERPDetail WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sFrontOffice.tLostFoundRegisterScope WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeChangeHistory WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sCommon.tReportTemplate WHERE OrgId= @rOrgId
DELETE FROM sTransport.tBusRouteAssignedTo WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tStudentDataChange WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearning WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignment WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignmentSubmit WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendance WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendanceLog WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningReference WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningResource WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningScope WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tTempOnlineLearningScope WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tChat WHERE CAST(LEFT(FromSourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tTempChatGroupScope WHERE CAST(LEFT(MemberSourceId, 4) AS bigint) = @rOrgId


DELETE FROM sAcademic.tOnlineMeetingSettings WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tDigitalForm WHERE OrgId= @rOrgId
DELETE FROM sStudent.tDigitalFormScope WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormField WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormStudent WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningView WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId

DELETE FROM sOp.tPaymentTransactionHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROMsFee.tOnlineFeeHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeDetailHistory WHERE CAST(LEFT(OnlineFeeId, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tStudentDocumentUpload WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

DELETE FROM sFee.tFeeAllocationHistory WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tUploadDocument WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId

DELETE FROM sFee.tFeeAllocationStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeClassBatchStatus WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeBatch WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tEmployeeDocumentUpload WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tEmployeeCustomFieldData] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId


--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

	SELECT 1 AS Result
 
-- COMMIT TRANSACTION
		
--	END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
		
--	END CATCH
END
GO
PRINT N'Altering [sCommon].[pOrgGroupSetupRemove]...';


GO
 
ALTER PROCEDURE [sCommon].[pOrgGroupSetupRemove]
	 
	 @rOrgGroupId smallint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
    BEGIN TRY
	
	IF EXISTS(SELECT TOP 1 1 FROM sSetup.tOrganizationMaster WHERE OrgGroupId = @rOrgGroupId)
	BEGIN
	SELECT -101 AS Result
	RETURN
	END
	
	
	BEGIN TRANSACTION
	 
	EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
    




DELETE FROM sAccounting.tAccountingYearMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tAccountMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerGroupMaster  WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tLedgerMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransaction WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionDetail WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sActivity.tActivityTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tClubMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tImmunizationChart WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryReferenceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAttendance.tAbsentReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingConductMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingProgressMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCertificate.tLeavingRemarkMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAreaMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tBirthPlaceMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tCountryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tDistrictMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHobbyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tMotherTongueMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tNationalityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tOccupationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tPreviousSchoolMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tReligionMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tStateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tSurnameMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBehaviourTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tBlogComment WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogFavorite WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tBlogScope WHERE CAST(LEFT(BlogId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircular WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCircularScope WHERE CAST(LEFT(CircularId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularView WHERE CAST(LEFT(CircularId, 4) AS BIGINT) =@rOrgGroupId
DELETE FROM sCommunication.tNews WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tNewsComment WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tNewsScope WHERE CAST(LEFT(NewsId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPhotoCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPoll WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tPollAnswer WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollMember WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tPollResult WHERE CAST(LEFT(PollId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQuery WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryAssignedTo WHERE CAST(LEFT(QueryCategoryId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sCommunication.tQueryCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tQueryComment WHERE CAST(LEFT(QueryId, 4) AS BIGINT) =  @rOrgGroupId
DELETE FROM sEExam.tDataBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataSubjectMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tDataTopicTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sEExam.tQuestionMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionOption WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tQuestionParagraph WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sEExam.tTestTemplateQuestion WHERE CAST(LEFT(TestTemplateId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tBankMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFinanceCommon.tStockUomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sGSEB.tActivityGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityIndicatorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sGSEB.tActivityMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tRoomCategoryMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tRoomMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tQualificationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tItemMainGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tItemSubGroupMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemCategoryMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sIp.tStockItemMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tStoreLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAgeGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookAuthorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLanguageMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookLocationMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookMaster WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sLibrary.tBookPublisherMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSubjectMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookSupplierMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tBookTagMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tLibraryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tEsiProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tEsiSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayElement WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcess WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessElement WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPayProcessEmployee WHERE CAST(LEFT(Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPaySetupDependent WHERE CAST(LEFT(PaySetupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcess WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfProcessCharge WHERE CAST(LEFT(PayProcessElementId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sPayroll.tPfSetup WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sPayroll.tProfessionalTaxRange WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sProcurement.tVendorCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tModulePermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrganizationTask WHERE CAST(LEFT(OrgGroupId, 4) AS SMALLINT) = @rOrgGroupId
DELETE FROM sSecurity.tPermission WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRole WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

 
DELETE FROM sStudent.tAdmissionCategoryMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTax.tTaxGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteDestinationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tFamiliyCastMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sScholarship.tScholarshipTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgMainGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgSubGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tFeeMainGroupOrgGroupwise WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tVisitorGatePass WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tChargeReceiptBookMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sPayroll.tPayrollYearMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sActivity.tEventTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tRoleDashlet WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId


DELETE FROM sCommon.tFrequencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tRangeDetail WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tRangeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommunication.tCircularTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sFinanceCommon.tCurrencyMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierDispatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFrontOffice.tCourierReceive WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tBuildingMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tChangeRoom WHERE CAST(LEFT(RoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelAdmission WHERE CAST(LEFT(Hosteld, 4) AS INT) = @rOrgGroupId

DELETE FROM sLibrary.tLibraryAttendance WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sLibrary.tMagazineReceive WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tFuelLogs WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tFuelTypeMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleDocumentMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId

DELETE FROM sStudent.tCustomTagMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTransport.tVehicleDocuments WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenance WHERE CAST(LEFT(VehicleId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleMaintenanceDetail WHERE CAST(LEFT(VehicleMaintenanceId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTransport.tVehicleTypeMaster WHERE OrgGroupId = @rOrgGroupId

--DELETE FROM sTimetable.tAssignSchoolRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tDivisionTimeOff WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolBuildingMaster WHERE  OrgGroupId = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomMaster WHERE  CAST(LEFT(SchoolBuildingId, 4) AS INT) = @rOrgGroupId
--DELETE FROM sTimetable.tSchoolRoomTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tTeacherTimeOff WHERE  CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

DELETE FROM sCommunication.tEbook WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tEbookScope WHERE  CAST(LEFT(EbookId, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sActivity.tClubTypeMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tHouseGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sAdmission.tInquiryStatusMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroup WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tCustomGroupMember WHERE  CAST(LEFT(CustomGroupId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sTally.tFeeLedgerMapping WHERE CAST(LEFT(FeeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptBookCompanyMapping WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTally.tReceiptPosting WHERE CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoom WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tClassRoomTimeOff WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sTimetable.tSchoolBuilding WHERE  OrgGroupId = @rOrgGroupId
 DELETE FROM sCommon.tCastCategoryMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tTransportMaster WHERE  OrgGroupId = @rOrgGroupId

DELETE FROM sAlert.tOtherGroupDetail WHERE  CAST(LEFT(OtherGroupId, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tOtherGroupMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sCommon.tAdmissionQuotaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tCollectionGroupMaster WHERE  CAST(LEFT(OrgGroupBatchId, 4) AS INT) = @rOrgGroupId

DELETE FROM sHrm.tWorkAreaMaster WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItem WHERE  OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformItemSize WHERE  CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sIp.tUniformStock WHERE  CAST(LEFT(UniformSizeId, 4) AS INT) = @rOrgGroupId

DELETE FROM sSetup.tShiftMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTimetable.tAssignClassRoom WHERE CAST(LEFT(ClassRoomId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCommon.tReportOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayConfiguration WHERE OrgGroupId = @rOrgGroupId
DELETE FROM  sTimetable.tDivisionClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tSubjectClassRoom WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId
DELETE FROM  sTimetable.tTimeTableDetail WHERE CAST(LEFT(TimetableId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFee.tExemptionTypeDetail WHERE CAST(LEFT(ExemptionTypeId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSecurity.tRoleModulePermission WHERE CAST(LEFT(RoleId, 4) AS INT) = @rOrgGroupId

/* -- Date : 13/06/2016 -- */
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sAlert.tNotificationLog WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenIssueDetail WHERE CAST(LEFT(CanteenIssueId, 4) AS INT) = @rOrgGroupId
DELETE FROM sCanteen.tCanteenMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tFoodItemMaster WHERE CAST(LEFT(CanteenId, 4) AS INT) = @rOrgGroupId
DELETE FROM sFrontOffice.tLostFoundRegister WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tAssetTypeMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tAssignRoomAsset WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tRoomAssetMaster WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHrm.tLeaveReasonMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupSetting WHERE OrgGroupId = @rOrgGroupId
 
DELETE FROM sStudent.tSUIdConfig WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sTimetable.tAssignDivision WHERE CAST(LEFT(TimeTableSchemaId, 4) AS INT) = @rOrgGroupId

/* -- Date : 12/08/2016 -- */
DELETE FROM sHostel.tHostelDepositAdd WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositAdjustment WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositHeadMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelDepositRefund WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sSystem.tExceptionLog WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 17/09/2016 -- */
DELETE FROM sCommon.tReportClient WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tTempCircularScope WHERE CAST(LEFT(SourceID, 4) AS BIGINT) = @rOrgGroupId

DELETE FROM sErp.tCustomerMaster WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 05/10/2016 -- */
DELETE FROM sHostel.tAttendanceRegister WHERE CAST(LEFT(HostelId, 4) AS INT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateCommunications WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateImages WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidatePreviousEmployment WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateQualification WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tCandidateVacancyCriteriaScore WHERE CAST(LEFT(CandidateId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tInterviewCriteria WHERE CAST(LEFT(VacancyId, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM sRecruitment.tRecruitmentStatusLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sRecruitment.tVacancy WHERE OrgGroupId = @rOrgGroupId

/* -- Date : 24/11/2016 -- */

DELETE FROM siTax.tAssessmentYear WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16 WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tForm16Detail WHERE CAST(LEFT(Form16Id, 4) AS BIGINT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxChallan WHERE CAST(LEFT(AssesmentYearId, 4) AS INT) = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSlab WHERE OrgGroupId = @rOrgGroupId
DELETE FROM siTax.tIncomeTaxSubGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tBatchGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sActivity.tPlacementCompanyMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAppraisal.tConductTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sErp.tCustomerActivationLog WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tIpPolicyDetail WHERE  CAST(LEFT(IpPolicyId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tTimePolicy WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserPolicy WHERE  CAST(LEFT(TimePolicyId, 4) AS int) = @rOrgGroupId


DELETE FROM sAppraisal.tKPATemplateDetail WHERE CAST(LEFT(KPATemplateId, 4) AS int) = @rOrgGroupId
DELETE FROM sAppraisal.tKPATemplateMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sOp.tGatewayProduct WHERE CAST(LEFT(GatewayConfigurationId, 4) AS int) = @rOrgGroupId
DELETE FROM sOp.tGatewayProductReceiptBookMapping WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tSstockIssueTypeMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeDepositExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelAttendanceTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseSubTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sHostel.tHostelGatePassReasonMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sIp.tUniformOrderItem WHERE CAST(LEFT(StockItemId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturn WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockIssueReturnBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentOtherGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sStudent.tStudentUIdMaster WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sAssetManagement.tAssetCheck WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAssetManagement.tAssetInchargeUser WHERE CAST(LEFT(AssetId, 4) AS int) = @rOrgGroupId
DELETE FROM sCanteen.tBreakTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCanteen.tDailyMenu WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId

DELETE FROM sAlert.tAdVendorMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sFee.tChargeAccountMapping WHERE CAST(LEFT(ChargeId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tChargeAccountPosting WHERE CAST(LEFT(ReceiptBookId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountMapping WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId
DELETE FROM sFee.tDepositeAccountPosting WHERE CAST(LEFT(DepositeHeadId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tFeedback WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeDetail WHERE CAST(LEFT(FeedbackAnswerTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAnswerTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackAssign WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackFor WHERE CAST(LEFT(FeedbackId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackQuestionResponse WHERE CAST(LEFT(FeedbackResponseId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackResponse WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplate WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tFeedbackTemplateQuestion WHERE CAST(LEFT(FeedbackTemplateId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tStockReset WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sProcurement.tStockResetBatch WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tBackupLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSystem.tPortalSync WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sAccounting.tBudget WHERE CAST(LEFT(LedgerId, 4) AS int) = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApprove WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sAccounting.tTransactionApproveDetail WHERE CAST(LEFT(LedgerId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSetup.tScreenMandatoryFeild WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sCommunication.tPhotoCategoryScope WHERE CAST(LEFT(PhotoCategoryId, 4) AS int) = @rOrgGroupId
DELETE FROM sTool.tTestCase WHERE CAST(LEFT(Id, 4) AS int) = @rOrgGroupId

DELETE FROM sLibrary.tMagazineTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tOrgGroupMobileAppDetail WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sLibrary.tBookCategoryMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookSubCategoryMaster WHERE OrgGroupId = @rOrgGroupId


/*============================================*/

	-- special case will come orgwise and orggroupwise

DELETE FROM sCommon.tTableRowId WHERE OrgId = @rOrgGroupId 
DELETE FROM sConfig.tConfigurationSetup WHERE SourceTypeId = 2010 AND SourceId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupBatchMaster WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupMaster WHERE Id=@rOrgGroupId


DELETE FROM sCanteen.tGuestRequest WHERE CAST(LEFT(CanteenId, 4) AS int) = @rOrgGroupId
DELETE FROM sSecurity.tPermissionUser WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSystem.tLimitLog WHERE OrgGroupId = @rOrgGroupId


DELETE FROM sProcurement.tOtherStockBatch WHERE CAST(LEFT(StockBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssue WHERE CAST(LEFT(StoreLocationId, 4) AS int) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockIssueBatch WHERE CAST(LEFT(OtherStockBatchId, 4) AS bigint) = @rOrgGroupId
DELETE FROM sProcurement.tOtherStockLocationMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sVts.tvtsOrgGroupMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sLibrary.tBookGroup1Master WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sLibrary.tBookGroup2Master WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sHostel.tHostelEventAssign WHERE CAST(LEFT(HostelEventScheduleId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tHostelEventAttendance WHERE CAST(LEFT(HostelEventScheduleId, 4) AS int) = @rOrgGroupId

DELETE FROM sHostel.tHostelEventSchedule WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sHostel.tHostelEventTypeMaster WHERE CAST(LEFT(HostelId, 4) AS int) = @rOrgGroupId

DELETE FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @rOrgGroupId



DELETE FROM sCommon.tOrgGroupDepartmentMaster WHERE OrgGroupId = @rOrgGroupId

DELETE FROM sFee.tFeeExpenseTypeMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSecurity.tUserOrgGroup WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sSetup.tOrgGroupEIS WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sTransport.tBusRouteTripLog WHERE CAST(LEFT(BusRouteId, 4) AS int) = @rOrgGroupId
DELETE FROM sTransport.tBusRouteTripTemplate WHERE CAST(LEFT(BusRouteId, 4) AS int) = @rOrgGroupId


DELETE FROM sCommunication.tCircularTypeAssignedTo WHERE CAST(LEFT(CircularTypeId, 4) AS int) = @rOrgGroupId
DELETE FROM sErp.tSupportTicket WHERE OrgGroupId= @rOrgGroupId
DELETE FROM siTax.tTaxPlanning WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sStudent.tStudentCustomFieldMaster WHERE OrgGroupId= @rOrgGroupId

DELETE FROM sErp.tCustomerPlugInLog WHERE OrgGroupId= @rOrgGroupId

DELETE FROM sErp.tScreenFunctionalityTraining WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommon.tPhysicalDisabilityCategoryMaster WHERE OrgGroupId= @rOrgGroupId

DELETE FROM siTax.tForm16SubDetail WHERE CAST(LEFT(Form16Id, 4) AS bigint) = @rOrgGroupId
DELETE FROM sSecurity.tAssignSubRole WHERE CAST(LEFT(RoleId, 4) AS int) = @rOrgGroupId

DELETE FROM sCommunication.tChatGroupMaster WHERE OrgGroupId = @rOrgGroupId
DELETE FROM sCommunication.tChatGroupScope WHERE CAST(LEFT(ChatGroupId, 4) AS int) = @rOrgGroupId


DELETE FROM sAcademic.tOnlineMeetingAccount WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommunication.teContentTypeMaster WHERE OrgGroupId= @rOrgGroupId
DELETE FROM sCommunication.teContent WHERE CAST(LEFT(OrgGroupBatchId, 4) AS int) = @rOrgGroupId
DELETE FROM sPayroll.tPayElementHistory WHERE CAST(LEFT([PayrollId], 4) AS int) = @rOrgGroupId

DELETE FROM [sHrm].[tEmployeeCustomFieldMaster] WHERE OrgGroupId= @rOrgGroupId

	
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

	SELECT 1 AS Result
 
 COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		
	END CATCH
END
GO
PRINT N'Altering [sCommunication].[pOnlineLearningLectureListGet]...';


GO
 
--exec [sCommunication].[pOnlineLearningLectureListGet] '2020-06-04','2020-07-06',1101000000111,95,1101,0,0,0,0,0,'','',0
ALTER PROCEDURE [sCommunication].[pOnlineLearningLectureListGet]
	@rFromDate date,
	@rToDate date,
	@rSourceId bigint,
	@rSourceTypeId int,
	@rOrgId int,
	@rClassId int=0,
	@rTopicId int= 0,
	@rSubjectId int = 0,
	@rLearningtypeId tinyint = 0,
	@rTeacherEmployeeId bigint = 0,
	@rTitle nvarchar(200) = '',
	@rDescription nvarchar(1000) = '',
	@rIsAdmin bit = 0,
	@rBatchId int = 0
	
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	DECLARE @lOrgGroupId int,@lOrgGroupBatchId int = 0

	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId

	SELECT @lOrgGroupBatchId = ISNULL(OrgGroupBatchId,0) FROM sSetup.tBatchMaster WHERE Id = @rBatchId

	 

	DECLARE @lConfigValue nvarchar(50)=''

	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 375 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId

	 IF @lConfigValue = ''
		SET @lConfigValue = 'False'

	IF(@lConfigValue = 'False')
	BEGIN
	DECLARE @lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint, @lClassDivisionName nvarchar(50),@lUserId bigint
	 If (@rSourceTypeId = 2001) -- For Student LogIn
	 BEGIN
		
			SELECT @lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
			@lClassDivisionName = CM.Title +' ' +DM.Title
				FROM sStudent.tAcademic A 
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
				WHERE A.Id = @rSourceId 
	 
		SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			@lClassDivisionName AS ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName
		FROM 
			sAcademic.tOnlineLearning OL	
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
			--LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = OL.ClassId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
			WHERE (((OLS.SourceTypeId = 2021 AND OLS.SourceId =@lOrgId) 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 =@lStudentId) OR
			(OLS.SourceTypeId = 2001 AND OLS.SourceId =@rSourceId)))) D ON D.OnlineLearningId = OL.Id
      
		WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--AND ((SA.AcademicId = @rSourceId))
			--AND SA.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rTeacherEmployeeId)OR (ISNULL(@rTeacherEmployeeId,0)=0))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			AND ((OL.BatchId = @rBatchId ) OR (@rBatchId = 0))
			AND OL.IsCompleted <> 721

			ORDER BY OL.StartDate,OL.StartTime
	END
		
		IF (@rSourceTypeId = 95 AND @rIsAdmin = 0) --For Employee LogIn
		BEGIN
			SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as AssignedTo
			
			FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON (EM.Id = OL.TeacherEmployeeId OR EM.Id = ISNULL(OL.CoTeacherEmployeeId1,0) OR EM.Id = ISNULL(OL.CoTeacherEmployeeId2,0))
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = OL.BatchId
			WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--AND ((SA.AcademicId = @rSourceId))
			AND (EM.Id = @rSourceId)
			--AND SA.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rSourceId) OR (ISNULL(OL.CoTeacherEmployeeId1,0)= @rSourceId) OR (ISNULL(OL.CoTeacherEmployeeId2,0)= @rSourceId))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			AND ((BM.OrgGroupBatchId = @lOrgGroupBatchId ) OR (@lOrgGroupBatchId = 0))
			AND OL.IsCompleted <> 721

			ORDER BY OL.StartDate,OL.StartTime
	
		END
		
		
		IF (@rSourceTypeId = 95 AND @rIsAdmin = 1) --For Admin LogIn
		
		BEGIN
		SELECT @lUserId= Id FROM sSecurity.tUser Where SourceId = @rSourceId AND  SourceTypeId  =95 
			SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			TM.Title As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as AssignedTo
			
			FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = OL.BatchId
			INNER JOIN (SELECT EM.Id FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.vUserOrganization OM ON EM.OrgID = OM.Id 
			AND ((OM.UserId = @lUserId) OR (@lUserId = 0)) ) A ON OL.TeacherEmployeeId = A.Id
   --         INNER JOIN 
			--(SELECT  distinct CM.Id As ClassId, TSD.SubjectId FROM
			--sSetup.tClassMaster CM
			--INNER JOIN sSetup.tDivisionMaster DM1  ON CM.Id = DM1.ClassId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
			--INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM1.Id
   --         INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=DM1.Id AND UA.SourceTypeId=2005 AND ((UA.UserId=@lUserId) OR (@lUserId=0)) ) A ON A.ClassId = OL.ClassId  AND A.SubjectId = OL.SubjectId
            
			WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--AND ((SA.AcademicId = @rSourceId))
			--AND (EM.Id = @rSourceId)
			--AND CM.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rTeacherEmployeeId)OR (ISNULL(@rTeacherEmployeeId,0)=0))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			AND ((BM.OrgGroupBatchId = @lOrgGroupBatchId ) OR (@lOrgGroupBatchId = 0))
			AND OL.IsCompleted <> 721

			ORDER BY OL.StartDate,OL.StartTime
	
		END
				
	END
	ELSE IF(@lConfigValue = 'True')
	BEGIN
	
	 If (@rSourceTypeId = 2001) -- For Student LogIn
	 BEGIN
		
			SELECT @lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId,
			@lClassDivisionName = CM.Title +' ' +DM.Title
				FROM sStudent.tAcademic A 
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId
				WHERE A.Id = @rSourceId 
	 
		SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			@lClassDivisionName AS ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName
		FROM 
			sAcademic.tOnlineLearning OL	
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
			LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
			--LEFT JOIN sStudent.vStudentAcademic SA ON SA.ClassId = OL.ClassId 
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
			LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
			WHERE (((OLS.SourceTypeId = 2021 AND OLS.SourceId =@lOrgId) 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 =@lStudentId) OR
			(OLS.SourceTypeId = 2001 AND OLS.SourceId =@rSourceId)))) D ON D.OnlineLearningId = OL.Id
      
		WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OL.EndDate >= CASE WHEN OL.LearningTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '1900-01-01' END)) 
			AND ((OL.StartDate <= CASE WHEN OL.LearningTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '9999-01-01' END))
			AND ((OL.StartTime <= CASE WHEN OL.LearningTypeId = 1 AND OL.StartDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OL.StartTime END)) 
			AND ((OL.EndTime >= CASE WHEN OL.LearningTypeId = 1 AND OL.EndDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OL.EndTime END))
			--AND ((SA.AcademicId = @rSourceId))
			--AND SA.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rTeacherEmployeeId)OR (ISNULL(@rTeacherEmployeeId,0)=0))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			AND ((OL.BatchId = @rBatchId ) OR (@rBatchId = 0))
			AND OL.IsCompleted <> 721

			ORDER BY OL.StartDate,OL.StartTime
	END
		
		IF (@rSourceTypeId = 95 AND @rIsAdmin = 0) --For Employee LogIn
		BEGIN
			SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			ISNULL(TM.Title,'') As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as AssignedTo
			
			FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON (EM.Id = OL.TeacherEmployeeId OR EM.Id = ISNULL(OL.CoTeacherEmployeeId1,0) OR EM.Id = ISNULL(OL.CoTeacherEmployeeId2,0))
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = OL.BatchId
			WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((OL.EndDate >= CASE WHEN OL.LearningTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '1900-01-01' END)) 
			AND ((OL.StartDate <= CASE WHEN OL.LearningTypeId = 1 THEN CONVERT(varchar,GETDATE(),23) ELSE '9999-01-01' END))
			AND ((OL.StartTime <= CASE WHEN OL.LearningTypeId = 1 AND OL.StartDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OL.StartTime END)) 
			AND ((OL.EndTime >= CASE WHEN OL.LearningTypeId = 1 AND OL.EndDate = CONVERT(varchar,GETDATE(),23) THEN CONVERT(varchar,GETDATE(),14) ELSE OL.EndTime END))
			--AND ((SA.AcademicId = @rSourceId))
			AND (EM.Id = @rSourceId)
			--AND SA.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rSourceId) OR (ISNULL(OL.CoTeacherEmployeeId1,0)= @rSourceId) OR (ISNULL(OL.CoTeacherEmployeeId2,0)= @rSourceId))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			AND ((BM.OrgGroupBatchId = @lOrgGroupBatchId ) OR (@lOrgGroupBatchId = 0))
			AND OL.IsCompleted <> 721

			ORDER BY OL.StartDate,OL.StartTime
	
		END
		
		
		IF (@rSourceTypeId = 95 AND @rIsAdmin = 1) --For Admin LogIn
		
		BEGIN
		SELECT @lUserId= Id FROM sSecurity.tUser Where SourceId = @rSourceId AND  SourceTypeId  =95 
			SELECT 
			OL.Id As OnlineLearningId,
			OL.Title,
			CONVERT(NVARCHAR(32),OL.StartTime,8) as FromTime,
			CONVERT(NVARCHAR(32),OL.EndTime,8) as ToTime,
			ISNULL(OL.Description,'') As Description,
			SM.Title As SubjectName,
			ISNULL(EM.FirstName,'') +' ' + ISNULL(EM.MiddleName,'') +' ' + ISNULL(EM.LastName ,'') As TeacherName,
			--SA.ClassName+'-'+SA.DivisionName AS ClassDivision,
			CM.Title As ClassDivision,
			CASE WHEN ISNULL(OL.IsCompleted,0) =1 then 'Completed' WHEN ISNULL(OL.IsCompleted,0) =0 then 'Pending' END AS Status,
			TM.Title As Topic,
			OL.StartDate,
			OL.EndDate,
			OL.LearningTypeId,
			DM.Title As LearningTypeName,
			(SELECT
			  (
			  STUFF((SELECT ',' + a.Code
			  FROM
			  (
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
			  UNION ALL
			  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
			  ) a
			  FOR XML PATH ('')), 1, 1, '') ) ) as AssignedTo
			
			FROM 
            sAcademic.tOnlineLearning OL
            INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = OL.TeacherEmployeeId
            LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId 
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
            LEFT JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = OL.BatchId
			INNER JOIN (SELECT EM.Id FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.vUserOrganization OM ON EM.OrgID = OM.Id 
			AND ((OM.UserId = @lUserId) OR (@lUserId = 0)) ) A ON OL.TeacherEmployeeId = A.Id
   --         INNER JOIN 
			--(SELECT  distinct CM.Id As ClassId, TSD.SubjectId FROM
			--sSetup.tClassMaster CM
			--INNER JOIN sSetup.tDivisionMaster DM1  ON CM.Id = DM1.ClassId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
			--INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = DM1.Id
   --         INNER JOIN sSecurity.tUserAccess UA ON UA.SourceId=DM1.Id AND UA.SourceTypeId=2005 AND ((UA.UserId=@lUserId) OR (@lUserId=0)) ) A ON A.ClassId = OL.ClassId  AND A.SubjectId = OL.SubjectId
            
			WHERE
			 ((OL.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((OL.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			--AND ((SA.AcademicId = @rSourceId))
			--AND (EM.Id = @rSourceId)
			--AND CM.OrgId = @rOrgId
			AND ((OL.TeacherEmployeeId= @rTeacherEmployeeId)OR (ISNULL(@rTeacherEmployeeId,0)=0))
			AND ((OL.TopicId=@rTopicId)OR(ISNULL(@rTopicId,0)=0))
			AND ((OL.SubjectId=@rSubjectId)OR(ISNULL(@rSubjectId,0)=0))
			AND ((OL.ClassId = @rClassId ) OR (ISNULL(@rClassId ,0)=0))
			AND ((OL.LearningtypeId = @rLearningtypeId)OR (ISNULL(@rLearningtypeId,0)=0))
			AND((OL.Title like '%' +@rTitle+ '%') OR (ISNULL(@rTitle,'')=''))
			AND ((OL.Description like '%'+ @rDescription+'%') OR (ISNULL(@rDescription,'')=''))
			AND ((BM.OrgGroupBatchId = @lOrgGroupBatchId ) OR (@lOrgGroupBatchId = 0))
			AND OL.IsCompleted <> 721

			ORDER BY OL.StartDate,OL.StartTime
	
		END
	END	
END
GO
PRINT N'Altering [sConfig].[pConfigurationValueGet]...';


GO
 
ALTER PROCEDURE [sConfig].[pConfigurationValueGet] 
			
			@rOrgGroupId int,
			@rOrgId int,
			@rUserId bigint
			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

	DECLARE @lSourceTypeId smallint=0
	SELECT @lSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE Id = @rUserId

BEGIN
	SELECT 
		CM.ItemKey AS ItemKey,ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue
	FROM 
		sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=1016 AND SourceId = @rOrgId 
	WHERE 
		CM.ConfigurationLevelId = 1

	UNION ALL

	SELECT 
		CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue
	FROM 
		sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=95 AND SourceId = @rUserId  
	WHERE 
		CM.ConfigurationLevelId = 4

	UNION ALL

	SELECT 
		CM.ItemKey, (CASE WHEN CM.Id=247 AND @lSourceTypeId=2003 THEN  'True' ELSE  ISNULL(CS.ItemValue,CM.ItemValue)  END) AS ItemValue
	FROM 
		sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id AND CS.SourceTypeId=2010 AND SourceId = @rOrgGroupId  
	WHERE 
		CM.ConfigurationLevelId = 5
	
	UNION ALL

	SELECT 
		CM.ItemKey,ISNULL(CS.ItemValue,CM.ItemValue) AS ItemValue  
	FROM 
		sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = CM.Id 
	WHERE 
		CM.ConfigurationLevelId = 6
END
GO
PRINT N'Altering [sCRM].[pOrgGroupSetting]...';


GO

ALTER PROCEDURE [sCRM].[pOrgGroupSetting]

		@rPaymentDueDate Date =null,
		@rIsPaymentReminder bit=0,
		@rPaymentRemainderRemark nvarchar(300) = '',
		@rstudentExtraCap int=0,
		@rLastStudentCapReminderDate date = null,
		@rStudentCapReminderCount smallint=0,
		@rStudentCapReminderDate date =null,
		@rIsStopServiceReminder bit=0,
		@rServiceStopRemark nvarchar(300)='',
		@rServiceStopDate date=null,
		@rOrgGroupId int =0
		
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	UPDATE sSetup.tOrgGroupSetting
	SET PaymentDueDate=@rPaymentDueDate,
	IsPaymentReminder=@rIsPaymentReminder ,
	PaymentReminderRemark=@rPaymentRemainderRemark,
	StudentExtraCap=@rstudentExtraCap,
	LastStudentCapReminderDate=@rLastStudentCapReminderDate,
	StudentCapReminderCount=@rStudentCapReminderCount,
	StudentCapReminderDate=@rStudentCapReminderDate,
	IsStopServiceReminder=@rIsStopServiceReminder,
	ServiceStopRemark=@rServiceStopRemark,
	ServiceStopDate=@rServiceStopDate,
	UpdatedDate=sCommon.fGetDate()
	WHERE OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Altering [sEExam].[pDeleteAllTestParticipant]...';


GO

ALTER PROCEDURE [sEExam].[pDeleteAllTestParticipant]
	 
	 @rTestId bigint,
	 @rSourceId bigint,
	 @rSourceTypeId int,
	 @rBatchId int	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION			
		    IF(@rSourceTypeId = 2005)
			   BEGIN           
					IF EXISTS(SELECT 1  FROM sEExam.tTestParticipantAnswer WHERE TestId=@rTestId)
					BEGIN
			         DELETE TPA
					 FROM sEExam.tTestParticipantAnswer TPA
					 INNER JOIN sEExam.tTestParticipant TP  ON TP.Id = TPA.TestParticipantId
					 INNER JOIN sStudent.vStudentAcademic VSA 
					 ON TP.SourceId = VSA.StudentId 
					 Where DivisionId = @rSourceId  AND TP.TestId = @rTestId AND VSA.BatchId = @rBatchId

					 END
					SELECT 1 AS Result 
               END 
			ELSE 
			   BEGIN
				IF EXISTS(SELECT 1  FROM sEExam.tTestParticipantAnswer WHERE TestId=@rTestId)
					BEGIN
			         DELETE TPA
					 FROM sEExam.tTestParticipantAnswer TPA
					 INNER JOIN sEExam.tTestParticipant TP  ON TP.Id = TPA.TestParticipantId
					 INNER JOIN sStudent.vStudentAcademic VSA 
					 ON TP.SourceId = VSA.StudentId 
					 Where TP.SourceId = @rSourceId  AND TP.TestId = @rTestId AND VSA.BatchId = @rBatchId

					 END 
			   END			   
			   
		  
			SELECT 1 AS Result 
			
		COMMIT TRANSACTION	
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sEExam].[pTestAssignGet]...';


GO


ALTER PROCEDURE [sEExam].[pTestAssignGet]

			--@rClassId int,
			@rDivisionId int,
			@rTestId int,
			@rBatchId int,			 
			@rSourceTypeID int,
			@rOrgId int,
			@rClassId int
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON  
BEGIN    

    SELECT  
			--VSA.AcademicId,
			VSA.RollNo,
			VSA.StudentId AS SourceId,
			VSA.Name AS StudentName,			
			'Student' AS ParticipantType,
			2003 AS SourceTypeId,
			VSA.DivisionId, 
			VSA.Code,	   
			CASE WHEN ISNULL(A.TestId,0) != 0 THEN 1 ELSE 0 END AS IsSelected,
			ISNULL(A.TestStatusId,0) AS TestStatusId,
			VSA.DivisionName AS DivisionName
    
    FROM 
			 sStudent.vStudentAcademic VSA
			 LEFT JOIN sEExam.tTestAssign A ON A.SourceId = VSA.StudentId AND A.SourceTypeId = 2003 AND A.TestId = @rTestId
			 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = A.TestStatusID
	WHERE 
		--VSA.DivisionId=@rDivisionId
	 --   AND 
	    VSA.BatchId=@rBatchId  
		AND VSA.StatusId=1
		 
    --ORDER BY VSA.RollNo ASC 
	
UNION ALL
  
      SELECT 
          0 AS RollNo,
          EM.EmployeeId AS  SourceId,
          EM.EmployeeName AS StudentName,
	      'Employee' AS ParticipantType,
		  95 AS SourceTypeId,
		  0 AS DivisionId,
          EM.Code,
		  CASE WHEN ISNULL(A.TestId,0) != 0 THEN 1 ELSE 0 END AS IsSelected,
          ISNULL(A.TestStatusId,0) AS TestStatusId,
          EM.DepartmentName AS DivisionName
         
      FROM sHrm.vEmployeeCommonDetail EM LEFT JOIN sEExam.tTestAssign A ON A.SourceId = EM.EmployeeId AND A.SourceTypeId = 95 AND A.TestId = @rTestId
      LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = A.TestStatusID 
      
      WHERE OrgID = @rOrgId
  
 UNION ALL
     SELECT 
          0 AS RollNo,
          DM.Id AS  SourceId,
          DM.Title AS StudentName,
		  'Division' AS ParticipantType,
		  2005 AS SourceTypeId,
		  DM.Id AS DivisonId, 
          DM.Code,
		  CASE WHEN ISNULL(A.TestId,0) != 0 THEN 1 ELSE 0 END AS IsSelected,
          ISNULL(A.TestStatusId,0) AS TestStatusId,
          DM.Title AS DivisionName    
         
      FROM sSetup.tDivisionMaster DM  LEFT JOIN sEExam.tTestAssign A ON A.SourceId = DM.Id AND A.TestId = @rTestId
      LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = A.TestStatusID 
      
      WHERE 
          ClassId = @rClassId AND DM.IsObsolete = 0 

		  ORDER By Code
END
GO
PRINT N'Altering [sFee].[pFeeAllocationDivisionwiseHistoryAdd]...';


GO
 
ALTER PROCEDURE [sFee].[pFeeAllocationDivisionwiseHistoryAdd]
	
	@rXmlDoc nvarchar(MAX),
	@rClassId int,
	@rDivisionId int,
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rFeeSetupId int,
	@rCreatedUserId bigint,
	@rOrgId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lInterrorCode INT,
			@intDoc INT
	--BEGIN TRY
	
	 --BEGIN TRANSACTION	
	 EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

	Declare @lSourceId bigint

	
	CREATE TABLE #TEMP_TABLE
	(
	    [SourceTypeId] smallint,
		[SourceId] bigint,
		[FeeSetupId] int,
		[VariableAmount] decimal(12,2),
		[DiscountAmount] decimal(12,2),
		[AdditionalAmount] decimal (12,2),
		[NotApplicableAmount] decimal (12,2),
		[Remark] nvarchar(200) COLLATE SQL_Latin1_General_CP1_CI_AS,
		[DiscountRemark] nvarchar(200) COLLATE SQL_Latin1_General_CP1_CI_AS ,
		[AdditionalRemark] nvarchar(200) COLLATE SQL_Latin1_General_CP1_CI_AS,
		[NotApplicableRemark] nvarchar(200) COLLATE SQL_Latin1_General_CP1_CI_AS 
	)
	
	      INSERT INTO #TEMP_TABLE
		  SELECT
		    SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark	
		
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		Remark nvarchar(200) '@Remark',
		DiscountRemark nvarchar(200) '@DiscountRemark',
		AdditionalRemark nvarchar(200) '@AdditionalRemark',
		NotApplicableRemark nvarchar(200) '@NotApplicableRemark'
	) 
	
	--Select * from  #TEMP_TABLE

	Declare @ldata int

	CREATE TABLE #FeeSetup
	(
	SourceId bigint
	)
	
	DELETE FROM  #TEMP_TABLE WHERE ISNULL(VariableAmount,0) = 0 AND ISNULL(DiscountAmount,0) = 0 AND ISNULL(AdditionalAmount,0) = 0 AND ISNULL(NotApplicableAmount,0) = 0 

	--Select * from  #TEMP_TABLE
	INSERT INTO #FeeSetup(SourceId)
	SELECT tmp.SourceId 
	FROM #TEMP_TABLE tmp
	INNER JOIN  sFee.tFeeAllocation FA ON FA.SourceTypeId=tmp.SourceTypeId AND FA.SourceId =tmp.SourceId 
	AND FA.FeeSetupId=tmp.FeeSetupId 
	AND ISNULL(FA.VariableAmount,0)=ISNULL(tmp.VariableAmount,0) AND ISNULL(FA.DiscountAmount,0)=ISNULL(tmp.DiscountAmount,0)
	AND ISNULL(FA.AdditionalAmount,0)=ISNULL(tmp.AdditionalAmount,0) AND ISNULL(FA.NotApplicableAmount,0)=ISNULL(tmp.NotApplicableAmount,0) AND ISNULL(FA.Remark,'')=ISNULL(tmp.Remark,'')
	AND ISNULL(FA.DiscountRemark,'')=ISNULL(tmp.DiscountRemark,'') AND ISNULL(FA.AdditionalRemark,'')=ISNULL(tmp.AdditionalRemark,'') AND ISNULL(FA.NotApplicableRemark,'')=ISNULL(tmp.NotApplicableRemark,'')
	--WHERE ISNULL(tmp.VariableAmount,0) <> 0 AND ISNULL(tmp.DiscountAmount,0) <> 0 AND ISNULL(tmp.AdditionalAmount,0) <> 0 AND ISNULL(tmp.NotApplicableAmount,0) <> 0 


	--Select * from #FeeSetup
	
	INSERT INTO sFee.tFeeAllocationHistory
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			UserId,
			LogDateTime,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark
		)
	SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark	
			FROM #TEMP_TABLE tmp
			WHERE 
			tmp.SourceId NOT IN(SELECT SourceId FROM #FeeSetup)
		
	
	--Second Condition
	  INSERT INTO #TEMP_TABLE
		  SELECT
		    SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark	
		
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		Remark nvarchar(200) '@Remark',
		DiscountRemark nvarchar(200) '@DiscountRemark',
		AdditionalRemark nvarchar(200) '@AdditionalRemark',
		NotApplicableRemark nvarchar(200) '@NotApplicableRemark'
	) 

	CREATE TABLE #FeeSetup1
	(
	SourceId bigint
	)
	
	INSERT INTO #FeeSetup1(SourceId)
	SELECT tmp.FeeSetupId 
	FROM #TEMP_TABLE tmp
	INNER JOIN  sFee.tFeeAllocation FA ON FA.SourceTypeId=tmp.SourceTypeId AND FA.SourceId =tmp.SourceId 
	AND FA.FeeSetupId=tmp.FeeSetupId 
	AND tmp.VariableAmount=0 AND tmp.DiscountAmount=0
	AND tmp.AdditionalAmount=0 AND tmp.NotApplicableAmount=0
	
	INSERT INTO sFee.tFeeAllocationHistory
		(
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			UserId,
			LogDateTime,
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark
		)
	SELECT
			SourceTypeId,
			SourceId,
			FeeSetupId,
			VariableAmount,
			DiscountAmount,
			AdditionalAmount,
			NotApplicableAmount,
			Remark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			DiscountRemark,
			AdditionalRemark,
			NotApplicableRemark	
		
	FROM OPENXML (@intDoc, '/Table/FeeAllocation', 1)
	WITH
	(
		SourceTypeId smallint '@SourceTypeId',
		SourceId bigint '@SourceId',
		FeeSetupId int '@FeeSetupId',
		VariableAmount decimal(12,2) '@VariableAmount',
		DiscountAmount decimal(12,2) '@DiscountAmount',
		AdditionalAmount decimal(12,2) '@AdditionalAmount',
		NotApplicableAmount decimal(12,2) '@NotApplicableAmount',
		Remark nvarchar(200) '@Remark',
		DiscountRemark nvarchar(200) '@DiscountRemark',
		AdditionalRemark nvarchar(200) '@AdditionalRemark',
		NotApplicableRemark nvarchar(200) '@NotApplicableRemark'
	) H
	WHERE H.SourceId  IN(SELECT SourceId FROM #FeeSetup1)


   SELECT 1 AS Result 
	
 
		
	EXEC sp_xml_removedocument @intDoc
	--COMMIT TRANSACTION

		DROP TABLE #TEMP_TABLE
		DROP TABLE #FeeSetup
		--DROP TABLE #FeeSetup1
END
GO
PRINT N'Altering [sFee].[pFeeAllocationHistoryGet]...';


GO
 
ALTER PROCEDURE [sFee].[pFeeAllocationHistoryGet]

	@rOrgId int,
	@rBatchId bigint,
	@rSourceId bigint,
	@rUserId bigint=0,
	@rFromDate date=NULL,
	@rToDate date=NULL,
	@rHistoryTypeId tinyint=null

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT 
	   
	   (SM.FirstName +''+SM.MiddleName +''+SM.LastName)	AS StudentName
	   ,FAH.SourceId
	  ,FM.Code AS FeeName
      ,FAH.VariableAmount
      ,FAH.DiscountAmount
      ,FAH.AdditionalAmount
      ,FAH.NotApplicableAmount
      ,FAH.Remark
      ,FAH.ReferenceTypeId
      ,FAH.ReferenceSourceId
      ,FAH.UserId
	  ,U.DisplayTitle AS UserName
      ,FAH.LogDateTime
      ,FAH.DiscountRemark
      ,FAH.AdditionalRemark
      ,FAH.NotApplicableRemark
	FROM sFee.tFeeAllocationHistory FAH
	INNER JOIN sStudent.tAcademic A ON FAH.SourceId=A.Id
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
	LEFT JOIN sFee.tFeeSetup FS ON FS.Id=FAH.FeeSetupId
	INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
	INNER JOIN sSecurity.tUser U ON U.Id=FAH.UserId
  Where 
		((FAH.SourceId=@rSourceId )OR(@rSourceId=0))
		AND ((FAH.UserId=@rUserId) OR (@rUserId=0))
		AND SM.OrgId=@rOrgId
		AND A.BatchId=@rBatchId
		AND ((CAST(FAH.LogDateTime AS DATE) >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((CAST(FAH.LogDateTime AS DATE) <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		AND ISNULL(FAH.HistoryTypeId,1) = @rHistoryTypeId
END
GO
PRINT N'Altering [sFee].[pFeeReceiptListGet]...';


GO
 
 
  
ALTER PROCEDURE [sFee].[pFeeReceiptListGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(20)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(20) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='',
  @rCancelStatusId int = 0
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN       
 SELECT 
  A.StatusId,    
  R.Id AS ReceiptId,    
  R.SourceId AS SourceId,    
  R.SourceTypeId AS SourceTypeId,    
  CASE WHEN R.SourceTypeId=2001 THEN 'Student'    
  ELSE  'Employee' END AS SourceType,    
  --STM.Title     
  A.Code AS Code,    
  A.Name,    
  R.ReceiptNumber,    
  R.ReceiptDate,    
  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,    
  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
  ISNULL(R.DiscountAmount,0)AS DiscountAmount,    
  R.PayTypeId,    
  PTM.Title AS PayType,    
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
  --R.ChequeNo,    
  R.BankName,    
  R.ReceiptBookId,    
  RBM.Title AS ReceiptBook,    
  R.IsObsolete,    
  A.OrgId,    
  OM.DisplayTitle AS Organization,    
  R.BatchId,    
  BM.Title AS Batch,    
  R.Remark,    
  ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,    
  ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,    
  ISNULL(R.ChequeDate,'') AS ChequeDate,    
  ISNULL(R.CollectionGroupId,0) AS CollectionGroupId,    
  Cm.title,    
  CM.Id,    
  ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
  CM.Title +' - '+ DM.Title AS Class,    
  A.SUId,    
  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,    
  ISNULL(R.DepositedLedgerId,0) AS DepositedLedgerId,    
  R.CreatedDateTime AS ReceiptCreatedDateTime,
  ISNULL(R.ReceiptPrintGroupId,'') AS ReceiptPrintGroupId   ,
  R.CancelStatusRemark AS  CancelStatusRemark
  FROM     
   sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
 ORDER BY R.ReceiptNumber DESC    
END
GO
PRINT N'Altering [sFee].[pFeeReceiptRemove]...';


GO
 
ALTER PROCEDURE [sFee].[pFeeReceiptRemove]
	 @rReceiptId bigint,
	 @rIsDelete bit,
	 @rCancelRemark nvarchar(300)='',
	 @rUserId bigint=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON



BEGIN 
BEGIN TRY
	
	 BEGIN TRANSACTION	


IF EXISTS (SELECT 1 FROM sFee.tReceipt WHERE Id = @rReceiptId AND IsObsolete = 0)
BEGIN
		DECLARE  @lFeeSetupId int,@rCharge decimal(12,2)=0,
		@lSourceId bigint,@lSourceTypeId int 
		
		SELECT  @lFeeSetupId = FS.ID,@rCharge = RD.Amount,
		@lSourceId = R.SourceId ,@lSourceTypeId =SourceTypeId 
		FROM sFee.tReceiptDetail RD 
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id 
		INNER JOIN sFee.tFeeHeadMaster FH ON FH.Id = FM.FeeHeadId
		WHERE RD.ReceiptId = @rReceiptId AND FH.Number = 100 AND FS.IsVariable = 1
		
		
		 IF @lFeeSetupId IS NOT NULL
		 BEGIN
		 UPDATE sFee.tFeeAllocation SET VariableAmount = VariableAmount - @rCharge WHERE FeeSetupId = @lFeeSetupId
		 AND SourceTypeId = @lSourceTypeId AND SourceId = @lSourceId
		 
		 DELETE FROM sFee.tFeeAllocation WHERE FeeSetupId = @lFeeSetupId
		 AND SourceTypeId = @lSourceTypeId AND SourceId = @lSourceId
		 AND (VariableAmount - DiscountAmount-NotApplicableAmount+AdditionalAmount <= 0)
		 
		 END
END



	 
	 IF(@rIsDelete=1)
	 BEGIN
		 
		Insert into sFee.tReceiptDeleted Select 
		Id,SourceTypeId,SourceId,ReceiptNumber,ReceiptDate,ReceiptAmount,PayTypeId,ChequeNo,BankName,
		ReceiptBookId,Remark,IsObsolete,BatchId,OrgGroupBatchId,CreatedUserId,
		CreatedDateTime,TotalReceiptAmount,DiscountAmount,
		IsChequeCleared,ChequeClearDate,ChequeDate,FeeInvoiceId,CollectionGroupId,
		AmountAfterDiscount,CGSTPercentage,SGSTPercentage,CGSTAmount,SGSTAmount,
		DepositedLedgerId,PaymentTransactionId,@rUserId,sCommon.fGetDate()
		From sFee.tReceipt where Id=@rReceiptId 
		
		Insert INTO sFee.tReceiptDetailDeleted Select
		ReceiptId,FeeSetupId,Amount
		From sFee.tReceiptDetail Where ReceiptId=@rReceiptId 
		
	    Delete From sFee.tReceiptDetail where ReceiptId=@rReceiptId 
		Delete From sFee.tReceipt where Id=@rReceiptId 
		
		
		SELECT 1 AS Result
	 END
	 ELSE
	 BEGIN 

		UPDATE  sFee.tReceipt
	    SET
			IsObsolete=1,
			CancelStatusRemark = @rCancelRemark
		WHERE Id=@rReceiptId
		
		
	SELECT 1 AS Result
	 END
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	

END
GO
PRINT N'Altering [sFee].[pRptDepositSummaryFeeHeadWise]...';


GO
 
ALTER PROC [sFee].[pRptDepositSummaryFeeHeadWise]
	     
	  @rOrgId int,          
      @rDepositHeadId int=0,         
      @rFromDate date='',
      @rToDate date='',           
      @rStudentName nvarchar(100)='',
	  @rStudentCode nvarchar(100)='',
	  @rClassId int=0,
	  @rDivisionId int=0,
	  @rIsBasedOnSUId bit = 0,
	  @rDepartmentId int=0,
	  @rSUId nvarchar(20)='',
	  @rBatchId int=0,
	  @rBuilder1 nvarchar(max)='',
      @rBuilder2 nvarchar(max)=''
   
AS
BEGIN
		SELECT 
			 DAJ.AdjustmentDate As DepositDate,
			 ISnull (DAJ.Amount,0)  AS Amount,
		     VA.Code As Code,
		     VA.Name As StudentName, 
		     VA.StudentId AS StudentId,
		     VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     'Adjustment' AS GroupType,
		     ES.Title As ExpenseType,
		     DAJ.Id As GroupID,
		     @rBuilder1 As builder1,
		     ES.Id AS ExpenseTypeId,
		     VA.DepartmentId,
	         VA.ClassId,
	         VA.DepartmentName,
	         VA.ClassOrderIndex,
	         @rFromDate AS FromDate,
	         @rToDate AS ToDate
		    
		FROM  sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ES ON ES.Id=DAJ.FeeDepositExpenseTypeId
		Where 
			  ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			  AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			  AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			  AND ((VA.ClassId = @rClassId) OR (@rClassId = 0))
		      AND ((VA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		      AND ((VA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		      AND ((VA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		      AND (VA.OrgId=@rOrgId OR @rOrgId=0)
		      AND (DAJ.DepositHeadId = @rDepositHeadId)
		      AND ((DAJ.AdjustmentDate >= ISNULL(@rFromDate,'')) OR (ISNULL(@rFromDate,'')=''))
		      AND ((DAJ.AdjustmentDate <= ISNULL(@rToDate,'')) OR (ISNULL(@rToDate,'')=''))
END
GO
PRINT N'Altering [sFee].[pRptFeeCircularDetailsGet]...';


GO


ALTER PROCEDURE [sFee].[pRptFeeCircularDetailsGet]
		
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rFeeGroupId int=0,
		@rCollectionGroupId int = 0,
		@rOrgIds nvarchar(max) = '',
		@rClassStatusId int=0  
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	-- Fee Setup
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0) AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		0 AS PaidAmount,
		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)-0AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeId,
		FS.FeeName,
		FS.FeeOrderIndex,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(CGM.OrderIndex,0) AS CollectionGroupOrderIndex,
		0 AS ReceiptNumber,
		'' AS ReceiptDate,
		'' AS PayTypeTitle,
		'' AS ChequeNo,
		'' AS BankName,
		'' AS ChequeDate,
		SA.BatchName
  FROM 
  
			 sStudent.vStudentAcademic SA
		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,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
				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,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
			 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)) 
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	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 ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND	((CGM.Id=@rCollectionGroupId) OR (@rCollectionGroupId=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))
	UNION ALL
	
	-- Fee Receipt
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		0 AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		0 AS FAAmount,
		0 AS DiscountAmount,
		0 AS AdditionalAmount,
		0 AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeId,
		FS.FeeName,
		FS.FeeOrderIndex,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		@rFeeGroupId As FeeGroup,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		ISNULL(CGM.OrderIndex,0) AS CollectionGroupOrderIndex,
		ISNULL(R.ReceiptNumber,0) AS ReceiptNumber,
		R.ReceiptDate,
		R.PayTypeTitle,
		R.ChequeNo,
		R.BankName,
		R.ChequeDate,
		SA.BatchName
  FROM 
  
			 sStudent.vStudentAcademic SA
		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,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.CreatedUserId=@rUserId) OR (@rUserId=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,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId,
				FS1.CollectionGroupId,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  	
				AND ((FS1.CreatedUserId=@rUserId) OR (@rUserId=0))      
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		INNER  JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,
					RD.FeeSetupId,
					R.SourceId,
					R.ReceiptNumber,
					R.ReceiptDate,
					PTM.Title AS PayTypeTitle,
					R.ChequeNo,
					R.BankName,
					R.ChequeDate
		    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)
			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 ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (R.ReceiptDate <= @rUptoDate)
				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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  	     
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=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 SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON FS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
			 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)) 
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	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 ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND	((CGM.Id=@rCollectionGroupId) OR (@rCollectionGroupId=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))  	     
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
			
			
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)=''
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

		SELECT  @lAmountInWord = sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(@lReceiptAmount,0.00),1,2,@lOrgGroupId)
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@lOrgGroupId) 
		SELECT  @lCurrencyTitle = [sFinanceCommon].[fDefaultCurrencyTitleGet](@lOrgGroupId) 
	END
	ELSE
	BEGIN
		SELECT  @lCurrencyCode = [sFinanceCommon].[fDefaultCurrencyCodeGet](@rOrgGroupId) 
	END

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) +' - '+ CONVERT(nvarchar(20),PT.BankTransactionId) END AS ChequeNo,
			--ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,			
			
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN @lAmountInWord 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,
			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  U.SourceTypeId = 2003 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			--ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0  THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	
				  
			  
			(CASE WHEN  RBM.ReportId = 20576
			      THEN -- HM patel report
				  [sFee].[fReceiptMonthDetailGet](FR.ID,0)
			      WHEN RBM.ReportId = 30457 
			      THEN
				  [sFee].[fReceiptMonthDetailGet](FR.ID,1)		
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    

 
			--FS.FeeDuration AS FeeDuration,
			
			Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
			sFee.tReceipt FR1				
			INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
			INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
			--Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			 Order By FS.StartDate
			FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' ) AS FeeDuration,
			
			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
	        ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,

			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
			SC.ParentContactNo,
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName
	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.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 = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC

--For Dataset




END
GO
PRINT N'Altering [sFee].[pRptFeeSummaryGet]...';


GO
 
 
ALTER PROCEDURE [sFee].[pRptFeeSummaryGet]
		
	@rReportId int,
	@rReceiptBookId int,
	@rAdmissionCategoryId int,
	@rClassId int,
	@rDivisionId int,
	@rUptoDate date,
	@rBatchId int,
	@rUserId bigint,
	@rBuilder1 nvarchar(max),
	@rBuilder2 nvarchar(max),
	@rIsDetail bit,
	@rOrgId int,
	@rOrgGroupBatchId int,
	@rIsExemption bit =0,
	@rStatusId int = 0,
	@rCommonBatch nvarchar(100),
	@rDepartmentId int,
	@rFromRollNo int,
    @rToRollNo int,
    @rCode nvarchar(20),
    @rIsFilter bit,
	@rIsHeader bit,
	@rCreatedUserName nvarchar(100)='',
	@rFeeHeadId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0,
	@rExemptionTypeId int=0,
	@rFeeId nvarchar(max) = '',
	@rFilterId int=0,
	@rFeeGroupId int=0,
	@rOrgGroupId int=0,
	@rOrgIds nvarchar(max) = '',
	@rIsReceiptBookGroup bit=0,
	@rClassStatusId int=0   
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN
	
	IF(@rReportId=20624 OR @rReportId=20842 OR @rReportId=10150 OR @rReportId=30714 OR @rReportId=30831)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			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,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			FS.FeeOrderIndex,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount,
			SM.Title AS Status
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			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,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					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,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId,
					FM.OrderIndex AS FeeOrderIndex
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			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 sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 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 sStudent.tStatusMaster SM ON SA.StatusId = SM.Id
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			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 ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by  FHM.OrderIndex,FS.FeeOrderIndex,SA.RollNo
	END
	ELSE IF(@rReportId=30655)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			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,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			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,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					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,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			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 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 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)) 
			WHERE	
			((@rIsExemption = 0 AND  ISNULL(FA.NotApplicableAmount,0) > 0) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			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 ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=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))  	
		Order by SA.RollNo
	END
	ELSE IF(@rReportId=30799)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R1.PaidAmount,0) AS PaidAmount,
			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(R1.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			ISNULL(R2.TotalReceiptAmount,0.00) AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			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,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					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,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				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 sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R1 ON R1.FeeSetupId = FS.Id AND SA.AcademicId = R1.SourceId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount
				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 sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 1) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					AND (tSA.AdmissionDate <= @rUptoDate)
						GROUP BY FeeSetupId,R.SourceId,R.TotalReceiptAmount
			
			) R2 ON R2.FeeSetupId = FS.Id AND SA.AcademicId = R2.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 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)) 
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			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 ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		AND (tSA.AdmissionDate <= @rUptoDate)
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo 
	END
	ELSE IF(@rReportId=30825)
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			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,
			ISNULL(FA.Remark,'') AS Remark,
			FS.ReceiptBookId,
			FS.FeeName,
			FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount,
			0.00 AS Discount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			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,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					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,
					SA1.AcademicId,
					FM.Title AS FeeName,
					FM.Code As FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			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 sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
					--AND (tSA.AdmissionDate <= @rUptoDate)
					AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA1.StatusId = 1))
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 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)) 
			WHERE	
			((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			--AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			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 ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
		--AND (tSA.AdmissionDate <= @rUptoDate)
		AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null AND SA.StatusId = 1))
		 --AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
		Order by SA.RollNo 
	END
	--ELSE IF(@rReportId=30821)
	--BEGIN
	--	SELECT 
	--		@rBuilder1 AS Builder1,
	--		@rBuilder2 AS Builder2,
	--		@rIsDetail AS IsDetail,
	--		@rIsFilter As IsFilter,
	--		@rIsHeader As IsHeader, 
	--		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
	--		SA.AcademicId,
	--		SA.RollNo,
	--		SA.Name,
	--		SA.Code,
	--		SA.ClassId,
	--		SA.DivisionId,
	--		SA.ClassName,
	--		SA.DivisionName,
	--		SA.DivisionOrder AS DivisionOrderIndex,
	--		SA.ClassOrderIndex AS ClassOrderIndex,
	--		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
	--		FS.Id AS FeeSetupId,
	--		ISNULL(FS.IsVariable,0)AS IsVariable,
	--		ISNULL(FS.Amount,0)AS Amount,
	--		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
	--		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
	--		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
	--		ISNULL(R.DiscountAmount,0.00)AS DiscountAmount,
	--		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
	--		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
	--		ISNULL(R.PaidAmount,0) AS PaidAmount,
	--		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,
	--		ISNULL(FA.Remark,'') AS Remark,
	--		FS.ReceiptBookId,
	--		FS.FeeName,
	--		FS.FeeCode,
	--		SA.OrgId,
	--		O.DisplayTitle AS OrgName,
	--		O.OrderIndex AS OrgOrderIndex,
	--		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
	--		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
	--		SA.DepartmentId,
	--		SA.DepartmentName,
	--		SA.ExemptionTypeId,
	--		ISNULL(ETM.Title,'') AS ExemptionType,
	--		FHM.Id AS FeeHeadId,
	--		FHM.Title AS FeeHeadName,
	--		FHM.OrderIndex AS FeeHeadOrderIndex,
	--		@rFeeGroupId As FeeGroup,
	--		SA.OrgGroupBatchId AS BatchId,
	--		SA.BatchName AS BatchName,
	--		0.00 AS CancelAmount,
	--		(Select ISNULL(SUM(R.DiscountAmount),0) FROM  sFee.tReceipt R Where R.SourceId=SA.AcademicId)AS Discount
	--  FROM 
	--		sStudent.vStudentAcademic SA
	--		INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
	--		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,
	--				SA1.AcademicId,
	--				FM.Title AS FeeName,
	--				FM.Code AS FeeCode,
	--				FM.FeeHeadId
	--			FROM sFee.tFeeSetup FS1
	--			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	--			WHERE 
	--				((FS1.ClassId=@rClassId) OR (@rClassId=0))
	--				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	--				AND (FS1.IsOptional=0)
	--				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				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,
	--				SA1.AcademicId,
	--				FM.Title AS FeeName,
	--				FM.Code As FeeCode,
	--				FM.FeeHeadId
	--			FROM sFee.tFeeSetup FS1
	--		INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
	--		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	--		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
	--		AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	--			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
	--			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--		WHERE
	--			((FS1.ClassId=@rClassId) OR (@rClassId=0))
	--			AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--			AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	--			AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
	--			AND (FS1.IsOptional=1)
	--			AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--			AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
	--			AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
	--			AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
	--		) FS ON FS.AcademicId=SA.AcademicId
	--		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
	--		LEFT JOIN
	--		(
	--			SELECT 
	--					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.DiscountAmount
	--			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 sStudent.tStudentAdmission tSA ON tSA.StudentId = SA1.StudentId
	--				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
	--				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
	--			WHERE		
	--				(R.SourceTypeId = 2001)
	--				AND (R.IsObsolete = 0) 
	--				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
	--				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	--				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
	--				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
	--				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
	--				AND (R.ReceiptDate <= @rUptoDate)
	--				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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
	--				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--				--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--				AND (tSA.AdmissionDate <= @rUptoDate)
	--					GROUP BY FeeSetupId,R.SourceId,R.DiscountAmount
			
	--		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
	--		 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
	--		 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
	--		 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
	--		 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
	--		 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)) 
	--		WHERE	
	--		((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
	--		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
	--		AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
	--		AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	--		--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	--		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 ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	--		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	--		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
	--	AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
	--	--AND ((tSA.LeftDate > @rUptoDate) OR (tSA.LeftDate Is null))
	--	AND (tSA.AdmissionDate <= @rUptoDate)
	--	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
	--	Order by SA.RollNo 
	--END
	ELSE
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.StatusId,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			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,
			ISNULL(FA.Remark,'') AS Remark,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

			CASE WHEN ISNULL(DiscountRemark,'') ='' THEN ''
			ELSE
			(STUFF((SELECT  ','+DiscountRemark	FROM sFee.tFeeAllocation WHERE SourceId = FA.SourceId	
			ORDER BY DiscountRemark	FOR XML PATH('')), 1, 1,NULL)) END as ExampltedRemark,

			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId) END  as ExampltedRemark,

			--CASE WHEN ISNULL(FA.AdditionalRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,3) END as AdditionalRemark,
			''  AdditionalRemark,
			--CASE WHEN ISNULL(FA.NotApplicableRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,4) END as NotApplicableRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			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,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
					AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
					AND (FS1.IsOptional=0)
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
					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,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			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 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					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 (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 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)) 
			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			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 ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=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 (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=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))  	
		Order by SA.RollNo
	END
	
	
	
END
GO
PRINT N'Altering [sHrm].[pEmployeeCustomSearchGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pEmployeeCustomSearchGet]
(
	@rPageIndex int = null,
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'Number',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName[nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',
	@rEmployeeGroupId[nvarchar](50)='',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rLeftFromDate Date = '0001-01-01',
	@rLeftToDate Date = '9999-12-31',
	@rProbationUptoDate Date ,
	@rAhdocUptoDate Date ,
	@rPermanentDate Date ,
	@rDropDownStatusId int,
	
	@rNumber int = null,
	@rCustomTagId nvarchar(max) = '',
	@rDateOfResignation Date = '',
	@rIsOtherUser int=0

 )
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Sql nvarchar(MAX)
	
	if @rDOBToDate = '9999-12-31'
	begin
		select @rDOBToDate = null
	end
	
	if @rLeftToDate = '9999-12-31'
	begin
		select @rLeftToDate = null
	end
	
	 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempEMP')
	 BEGIN		
		DROP Table sHrm.tTempEMP
	 END

	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	

	IF (@rCustomTagId <> '')
	BEGIN
		SELECT DISTINCT EM.Id AS EmployeeId1	
		INTO sHrm.tTempEMP
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeCustomTag ECT ON ECT.EmployeeId=EM.Id AND ISNULL(EM.IsOtherUser,0) = @rIsOtherUser 
		WHERE EM.OrgId = @rOrgId AND ISNULL(EM.IsOtherUser,0) = 0 AND (ISNULL(ECT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS EmployeeId1
		INTO sHrm.tTempEMP
	END



	SELECT * into sHrm.tTempEmployee1
	FROM sHrm.vEmployeeCustomSearch ECS 
	INNER JOIN sHrm.tTempEMP T2 ON ECS.EmployeeId = T2.EmployeeId1 OR @rCustomTagId = ''
	WHERE ECS.OrgId = @rOrgId
	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
	AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
	AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
	AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
	AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
	AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))
	AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
	AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='')
	AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
	AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='')
	AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='')
	AND (ISNULL(ECS.EmployeeGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupId,','))OR @rEmployeeGroupId='')
	AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
	AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
	AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='')
	AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((ECS.Number = @rNumber) OR (ISNULL(@rNumber,0) = 0))
	AND ((ECS.ProbationUptoDate = @rProbationUptoDate) OR (ISNULL(@rProbationUptoDate,'')=''))
	AND ((ECS.AhdocUptoDate = @rAhdocUptoDate) OR (ISNULL(@rAhdocUptoDate,'')=''))
	AND ((ECS.PermanentDate = @rPermanentDate) OR (ISNULL(@rPermanentDate,'')=''))
	AND ((ECS.DateofResignation = @rDateOfResignation) OR (ISNULL(@rDateOfResignation,'')=''))
	--AND ISNULL(ECS.IsOtherUser,0) = 0
	AND ISNULL(ECS.IsOtherUser,0) = @rIsOtherUser
	ORDER BY ECS.Number
	
	SET @rOrderBy=Replace(@rOrderBy,'Number','Number')
	Print @rOrderBy
	SET @sql='SELECT EmployeeId,Code AS Code,Name,EmployeeType,OrganizationDepartment AS OrganizationDepartment,
	StatusName FROM sHrm.tTempEmployee1 ORDER BY '+@rOrderBy
	exec(@Sql)
	
	create table #EMPLOYEETEMP
	(
		tid int identity(1,1),t_EmployeeId bigint
	)
	select @Sql = 'insert into #EMPLOYEETEMP
	SELECT EmployeeId FROM sHrm.tTempEmployee1 ORDER BY ' + @rOrderBy
	
	exec (@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lTotalRecords int,@lPageSize int = 10,@lResult varchar(max) = '',@lPaging varchar(max) = ''
	
	select @lTotalRecords = COUNT(*) FROM #EMPLOYEETEMP
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
	
	select @lResult = @lResult + '<tr><td><a style="cursor:pointer;" onclick="SelectEmp(' + convert(varchar,EmployeeId) + ',''' + isnull(Code,'') + ''')">Select</a></td>
	<td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td><td>' + isnull(EmployeeType,'') + '</td>
	<td>' + isnull(StatusName,'') + '</td><td>' + isnull(OrganizationDepartment,'') + '</td></tr>'	
	from sHrm.tTempEmployee1,#EMPLOYEETEMP
	where t_EmployeeId = EmployeeId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	order by tid
	
	select @lResult as EmpList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP TABLE #EMPLOYEETEMP
	DROP Table sHrm.tTempEmployee1
	DROP Table sHrm.tTempEMP
END
GO
PRINT N'Altering [sHrm].[pEmployeeDataModify]...';


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

--BEGIN TRY
--BEGIN TRANSACTION

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'Gender' OR @rSubCategoryField = 'Religion' OR @rSubCategoryField = 'BloodGroup'
	OR @rSubCategoryField = 'MaritalStatus' OR @rSubCategoryField = 'OrganizationDepartment' OR @rSubCategoryField = 'EmployeeType' OR @rSubCategoryField = 'EmployeeBusinessHead'
			OR @rSubCategoryField = 'EmployeeGroup' OR @rSubCategoryField = 'EmployeeGrade' OR @rSubCategoryField = 'Relationship' OR  @rSubCategoryField = 'EmployeeDesignation'
			OR  @rSubCategoryField = 'Payroll' OR  @rSubCategoryField = 'PayrollGroup'  OR  @rSubCategoryField = 'OrgGroupDepartment' OR  @rSubCategoryField = 'EmployeeManager' 
			)
	BEGIN
		SET @rSubCategoryField = @rSubCategoryField + 'Id'
	END
	ELSE IF (@rSubCategoryField = 'CasteCategory' )
		BEGIN
			SET @rSubCategoryField = Replace(@rSubCategoryField,'Caste','Cast')+'Id'
		END
	ELSE IF(@rSubCategoryField = 'NotEmployee')
		 BEGIN
		 SET @rSubCategoryField = Replace(@rSubCategoryField,'NotEmployee','IsOtherUser')
		 END
		
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,EmployeeId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeCommunications) 
		
		set @sql='INSERT INTO sHrm.tEmployeeCommunications 
					(EmployeeId,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql
		set @sql='UPDATE sHrm.tEmployeeCommunications set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeCommunications EC 
					INNER JOIN ListofData LD ON EC.EmployeeId=LD.EmployeeId AND IsExist=0'
		
		Exec sp_executesql @sql
		
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END
	    
	Else IF(@rCategoryId= 2)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeePersonalDetail) 
		
		IF(@rSubCategoryField = 'DateOfBirth')
		BEGIN			
					
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeePersonalDetail SET '+@rSubCategoryField+' = null WHERE DateOfBirth=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			
			 				
			set @sql='UPDATE sHrm.tEmployeePersonalDetail set '+@rSubCategoryField+' = LD.SubCategory,
						UpdatedUserId=LD.UpdatedUserId,
						UpdatedDateTime=sCommon.fGetDate()  
						from sHrm.tEmployeePersonalDetail EPD 
						INNER JOIN ListofData LD ON EPD.EmployeeId=LD.EmployeeId'
			
			Exec sp_executesql @sql
		END
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	Else IF(@rCategoryId= 3)
	
		BEGIN
	 
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		IF(@rSubCategoryField = 'EmployeeManagerId' )
			BEGIN

		set @sql='UPDATE sHrm.tEmployeeJobDetail set '+@rSubCategoryField+' = (SELECT EmployeeId FROM sHrm.vExtEmployeeMaster WHERE CODE=LD.SubCategory AND ISNULL(IsOtherUser,0) = 0 ),
				  UpdatedUserId=LD.UpdatedUserId,
				  UpdatedDateTime=sCommon.fGetDate()  
				  from sHrm.tEmployeeJobDetail EJ	
				  INNER JOIN ListofData LD ON LD.EmployeeId=EJ.EmployeeId'
				  Exec sp_executesql @sql
		END

		ELSE
		BEGIN
	
		set @sql='UPDATE sHrm.tEmployeeJobDetail set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeJobDetail EJ 
					INNER JOIN ListofData LD ON EJ.EmployeeId=LD.EmployeeId'
		
		Exec sp_executesql @sql
		END
		IF(@rSubCategoryField = 'DateOfJoining' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfJoining=''1900-01-01'''
			Exec sp_executesql @sql
		END
		
		IF(@rSubCategoryField = 'DateOfleaving' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfleaving=''1900-01-01'''
			Exec sp_executesql @sql
		END		
		IF(@rSubCategoryField = 'PermanentDate' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE PermanentDate=''1900-01-01'''
			Exec sp_executesql @sql
		END	
		IF(@rSubCategoryField = 'ProbationUptoDate' )
		BEGIN

		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE ProbationUptoDate=''1900-01-01'''
			Exec sp_executesql @sql
		END	
		IF(@rSubCategoryField = 'AhdocUptoDate' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE AhdocUptoDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		IF(@rSubCategoryField = 'DateOfResignation' )
		BEGIN
		SET @sql='UPDATE sHrm.tEmployeeJobDetail SET '+@rSubCategoryField+' = null WHERE DateOfResignation=''1900-01-01'''
			Exec sp_executesql @sql
		END		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
  Else IF(@rCategoryId= 4)
	BEGIN
		
		
		IF(@rSubCategoryField = 'CustomTag')
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId, SubCategory, UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeMaster WHERE  ISNULL(IsOtherUser,0) = 0 ) 

			 
			DELETE FROM sHrm.tEmployeeCustomTag WHERE EmployeeId In (SELECT EmployeeId FROM ListofData WHERE IsExist=0)
			set @sql = '
				        INSERT INTO sHrm.tEmployeeCustomTag (EmployeeId,CustomTagId)
						SELECT
							LD.EmployeeId,
							CTM.Id
						FROM sHrm.tCustomTagMaster CTM INNER JOIN ListofData LD ON CTM.Title = LD.SubCategory 
						INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = LD.EmployeeId 
						INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID 
						INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId  
						WHERE IsExist = 0 AND CTM.OrgGroupId = OGM.Id'
			 
		END
		ELSE
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 	

		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeMaster WHERE  ISNULL(IsOtherUser,0) = 0 ) 
		set @sql='UPDATE sHrm.tEmployeeMaster set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeMaster HEM 
					INNER JOIN ListofData LD ON HEM.Id=LD.EmployeeId AND IsExist=0 AND ISNULL(HEM.IsOtherUser,0) = 0 ' 
		END
		Print @sql
		Exec sp_executesql @sql
		Drop Table ListofData
			SELECT 1 AS StatusId
	    END
	    
	    Else IF(@rCategoryId= 5)
		BEGIN
		insert into ListofData
		select 0,E.EmployeeId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT EmployeeId,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Employees/Employees', 2)
				WITH (
						EmployeeId BIGINT, 
						SubCategory nvarchar(100),
						UpdatedUserId bigint)	
						)E 
						
		UPDATE ListofData SET IsExist=1 WHERE EmployeeId NOT IN(SELECT EmployeeId FROM sHrm.tEmployeeStatutoryAndOther) 
		
		set @sql='INSERT INTO sHrm.tEmployeeStatutoryAndOther 
					(EmployeeId,'+@rSubCategoryField+',IsVPFDeduction,UpdatedUserId,UpdatedDateTime)
					SELECT
						LD.EmployeeId,Ld.SubCategory,0,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
		Exec sp_executesql @sql			
		
		
		IF(@rSubCategoryField = 'EPFJoinDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE EPFJoinDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE IF(@rSubCategoryField = 'IncrementDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE IncrementDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
			ELSE IF(@rSubCategoryField = 'RetirementDate')
		BEGIN			
		    set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'			
			Exec sp_executesql @sql
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther SET '+@rSubCategoryField+' = NULL WHERE RetirementDate=''1900-01-01'''
			Exec sp_executesql @sql
		END
		ELSE
		BEGIN
			set @sql='UPDATE sHrm.tEmployeeStatutoryAndOther set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sHrm.tEmployeeStatutoryAndOther ESO 
					INNER JOIN ListofData LD ON ESO.EmployeeId=LD.EmployeeId'

			Exec sp_executesql @sql
		END
		
		
		Drop Table ListofData
			 SELECT 1 AS StatusId
	    END	
	    
	    
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	Drop Table ListofData
	--	SELECT -1 AS Result
	--END CATCH

GO
PRINT N'Altering [sHrm].[pEmployeeGenerateReport]...';


GO
 
 
ALTER PROCEDURE [sHrm].[pEmployeeGenerateReport]	
	@rId bigint,
	@rTitle nvarchar(50),
	@rColumnName nvarchar(max) = '',
	@rOrderBy nvarchar(max) = 'Code',
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',	 
	@rDOBFromDate Date = '',
	@rDOBToDate Date = '',
	@rDOJFromDate Date = '',
	@rDOJToDate Date = '',
	@rIsCommon bit,
	@rCreatedUserId bigint,
	@rDropDownStatusId int,
	@rIsCommonForOrg bit,
	@rLeftFromDate Date = '',
	@rLeftToDate Date = '',
	@rNumber int,
	@rProbationUptoDate Date = '',
	@rAhdocUptoDate Date = '',
	@rPermanentDate Date = '',
	@rCustomTagId nvarchar(max) = '',
	@rDateOfResignation Date = '',
	@rIsOtherUser int=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	
	--if @rColumnName <> ''
	--begin
	--	select @rColumnName = left(@rColumnName,len(@rColumnName)-1)
	--end
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate=''
	IF(@rDOJFromDate IS NULL)
		SET @rDOJFromDate=''
	IF(@rLeftFromDate IS NULL)
		SET @rLeftFromDate=''
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate=''
	IF(@rDOJToDate IS NULL)
		SET @rDOJToDate=''
	IF(@rLeftToDate ='9999-12-31 00:00:00')
		SET @rLeftToDate=''

	
	IF(@rTitle != '' AND @rId = 0)
	BEGIN

		DECLARE @lNextNumber BIGINT 
		EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomSearch', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sHrm.tEmployeeCustomSearch
			(
				Id,Title,ColumnName,OrgId,Code,FirstName,LastName,EmployeeTypeId,StatusId,OrganizationDepartmentId,ReligionId,
				MaritalStatusId,Qualification,GenderId,EmployeeDesignationId,BloodGroupId,DOBFromDate,DOBToDate,DOJFromDate,
				DOJToDate,IsCommon,CreatedUserId,CreatedDateTime,IsCommonForOrg,CustomTag)
		VALUES
			(
				@lNextNumber,@rTitle,@rColumnName,@rOrgId,@rCode,@rFirstName,@rLastName,@rEmployeeTypeId,@rStatusId,@rOrganizationDepartmentId,@rReligionId,
				@rMaritalStatusId,@rQualification,@rGenderId,@rEmployeeDesignationId,@rBloodGroupId,@rDOBFromDate,@rDOBToDate,@rDOJFromDate,
				@rDOJToDate,@rIsCommon,@rCreatedUserId,sCommon.fGetDate(),@rIsCommonForOrg,@rCustomTagId)
			--SELECT @lNextNumber AS Result
	END
	
	IF(@rId > 0)
	BEGIN

		Select
				@rColumnName=ColumnName,
				@rOrgId=OrgId,
				@rCode=Code,
				@rFirstName=FirstName,	
				@rLastName=LastName,
				@rEmployeeTypeId=EmployeeTypeId,
				@rStatusId=StatusId,
				@rOrganizationDepartmentId=OrganizationDepartmentId,
				@rReligionId=ReligionId,
				@rMaritalStatusId=MaritalStatusId,
				@rQualification=Qualification,
				@rGenderId=GenderId,
				@rEmployeeDesignationId=EmployeeDesignationId,
				@rBloodGroupId=BloodGroupId,					 
				@rDOBFromDate=DOBFromDate,
				@rDOBToDate=DOBToDate,
				@rDOJFromDate=DOJFromDate,
				@rDOJToDate=DOJToDate,
				@rCustomTagId=CustomTag
				
		FROM
			sHrm.tEmployeeCustomSearch
		WHERE
			Id=@rId
	END
	
	DECLARE @Sql nvarchar(MAX)
	SET @rColumnName=Replace(@rColumnName,',ID No',',Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')

	SET @rColumnName=Replace(@rColumnName,',GR No',',Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
 
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	 IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempEmployee')
	 BEGIN		
		DROP Table sHrm.tTempEmployee
	 END
	  IF  EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='tTempEmployee13')
		 BEGIN
			DROP Table sHrm.tTempEmployee13
		 END
	 IF (@rCustomTagId <> '')
	BEGIN
		SELECT DISTINCT EM.Id AS EmployeeId1	
		INTO sHrm.tTempEmployee
		FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeCustomTag ECT ON ECT.EmployeeId=EM.Id  AND ISNULL(EM.IsOtherUser,0) = @rIsOtherUser 
		WHERE EM.OrgId = @rOrgId AND (ISNULL(ECT.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS EmployeeId1
		INTO sHrm.tTempEmployee
	END
	
	 DECLARE @lAvailableEmployeeColumns nvarchar(max)=''
			DECLARE @lAvailableEmployeeCustomRes nvarchar(max)=''
			Declare @Title as nvarchar(max)
			DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
		
            DECLARE @rOrgGroupId smallint
             SET @rOrgGroupId = (Select orggroupid from sSetup.tOrganizationMaster where Id=@rOrgId)           
             
			SET @lAvailableEmployeeColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
								from sHrm.tEmployeeCustomFieldMaster PP  WHERE PP.OrgGroupId = @rOrgGroupId  
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					Print @lAvailableEmployeeColumns
	        IF(@lAvailableEmployeeColumns IS NOT NULL)
	        BEGIN														
				set @query = 'SELECT  EmployeeId AS EmployeeId13 ,' + @lAvailableEmployeeColumns + ' into sHrm.tTempEmployee13 from 
					 (
						select PPE.FieldTitle,PP.EmployeeId,FieldData 
						FROM
						sHrm.tEmployeeCustomFieldData PP 
							INNER JOIN sHrm.tEmployeeCustomFieldMaster PPE ON PPE.Id = PP.EmployeeCustomFieldId AND PPE.IsObsolete=0
							INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = PP.EmployeeId						
							WHERE EM.OrgId='''+convert(varchar(20),@rOrgId)+''' 
					) x 
					pivot 
					(
						Max(FieldData)
						for FieldTitle in (' +@lAvailableEmployeeColumns  + ')
					) p'
			END
				
                execute(@query)

		


		SELECT  *  into sHrm.tTempEmployee2
		FROM sHrm.vEmployeeCustomSearch ECS
		INNER JOIN sHrm.tTempEmployee T2 ON (ECS.EmployeeId = T2.EmployeeId1 OR @rCustomTagId = '')
		LEFT JOIN  sHrm.tTempEmployee13 T13 ON ECS.EmployeeId= T13.EmployeeId13
		
		WHERE
		 ECS.OrgId = @rOrgId 
		AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
		AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
		AND ((ISNULL(ECS.DateOfBirth,'') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(ECS.DateOfBirth,'') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
		AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
		AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
		AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
		AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
		AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 			
		AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
		AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
		AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
		AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
		AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
		AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))			
		AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
		AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((ECS.Number = @rNumber) OR (@rNumber=0))
		AND ((ECS.ProbationUptoDate = @rProbationUptoDate) OR (ISNULL(@rProbationUptoDate,'')=''))
		AND ((ECS.AhdocUptoDate = @rAhdocUptoDate) OR (ISNULL(@rAhdocUptoDate,'')=''))
		AND ((ECS.PermanentDate = @rPermanentDate) OR (ISNULL(@rPermanentDate,'')=''))
		AND ((ECS.DateOfResignation = @rDateOfResignation) OR (ISNULL(@rDateOfResignation,'')=''))
		 AND ISNULL(ECS.IsOtherUser,0) = @rIsOtherUser 
 
	
		 
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sHrm.tTempEmployee2 ORDER BY '+@rOrderBy
		--SELECT @sql

		 
		exec(@Sql)
		
		DROP Table sHrm.tTempEmployee2
		DROP Table sHrm.tTempEmployee
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [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 INT = 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
	 
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
			)
		VALUES
			(
				@lNextNumber,
				@rCode,
				@rFirstName,
				@rMiddleName,
				@rLastName,
				@rShortName,
				@rStatusId,
				@rIsObsolete,
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rCreatedUserId,
				sCommon.fGetDate(),
				@rOrgId,
				@rNumber,
				@rIsOtherUser
			)
	    
		 
				
		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
	          
	     Execute sHrm.pEmployeePersonalDetailAdd @rOrgId,@lNextNumber,'',@rDateOfBirth,@rGenderId,@rReligionId,
	     0,'',@rBloodGroupId,@rQualification,@rCreatedUserId,@rFamilyCast,@rCastCategoryId
	     
	      
	     
		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 [sHrm].[pEmployeeUploadedDocumentListGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pEmployeeUploadedDocumentListGet]
	 
	 @rSourceId bigint,
	 @rOrgId int = 0,
	 --@rDivisionId int = 0,
	 --@rBatchId int,
	 @rSyncedUploadResultId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	--IF (@rSourceId!=0)
	--BEGIN
	--	SELECT @rDivisionId=DivisionId FROM sStudent.tAcademic		
	--	 WHERE StudentId=@rSourceId AND BatchId = @rBatchId
	--END


	SELECT @rSourceId AS SourceId,
			EDU.Id,
			EDU.Title,
			EDTM.Title AS DocumentType,
			EM.Code,
			EDU.DocumentUploadDate,
			EM.OrgId	  
	  FROM [sCommunication].[tEmployeeDocumentUpload] EDU
	  JOIN sCommunication.tEmployeeDocumentTypeMaster EDTM ON EDTM.Id=EDU.EmployeeDocumentTypeId
	  JOIN sHrm.tEmployeeMaster EM ON EM.OrgId=EDU.OrgId
  
	  WHERE EDU.IsObsolete=0 AND EM.Id = @rSourceId
			AND EM.OrgId=@rOrgId 
			AND ( EDU.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
			AND EDU.DocumentUploadDate <= REPLACE(CONVERT(VARCHAR, sCommon.fGetDate(), 111), '/','-') 
	ORDER BY EDU.DocumentUploadDate,EM.Code DESC

--		SELECT 
--			@rSourceId AS SourceId,
--			SDU.Id,
--			SDU.Title,
--			SDTM.Title AS DocumentType,
--			S.Code,
--			SDU.DocumentUploadDate,
--			 BM.OrgId
--		FROM 
--			sCommunication.tStudentDocumentUpload SDU  
--			INNER JOIN sStudent.vStudentAcademic S ON S.DivisionId = SDU.DivisionId AND SDU.BatchId = S.BatchId 
--			AND S.StudentId = @rSourceId AND S.BatchId = @rBatchId
--			INNER JOIN sCommunication.tStudentDocumentTypeMaster SDTM ON SDTM.Id = SDU.StudentDocumentTypeId
--			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = S.BatchId
--		WHERE 
--			SDU.DivisionId=@rDivisionId
--			AND SDU.BatchId=@rBatchId
--			AND SDU.IsObsolete=0
--			AND ( SDU.Id > @rSyncedUploadResultId OR @rSyncedUploadResultId = 0)
--			and SDU.DocumentUploadDate <= replace(convert(varchar, sCommon.fGetDate(), 111), '/','-') 
--				order by SDU.DocumentUploadDate,S.RollNo,S.Code DESC
END
GO
PRINT N'Altering [sHrm].[pGetDropDowns]...';


GO
-- exec [sHrm].[pGetDropDowns]
-- drop proc [sHrm].[pGetDropDowns]
ALTER proc [sHrm].[pGetDropDowns]
@rOrgId int,
@rUserId bigint,
@rOrgGroupId int = 1101,
@rPayrollYearId int = null
as
begin
	declare @lStatusRes varchar(max)='',@lColumnRes varchar(max)='',@lReportList varchar(max)=''
	declare @lOrganizationRes varchar(max) = '',@lPayRollYear varchar(max) = '',@lPayrollColumn varchar(max) = ''
	declare @lPayrollReportList varchar(max) = '', @lSavedReport nvarchar(max)='', @lSavedReport1 nvarchar(max)=''
	declare @lCustomtagdrop nvarchar(max)=''
	
	select @lOrganizationRes = @lOrganizationRes + '<option value="0"> -- ALL -- </option>'
	select @lOrganizationRes = @lOrganizationRes + '<option value="' + convert(varchar,Id) + '">' + DisplayTitle + '</option>'
	from sSetup.vUserOrganization where IsObsolete = 0 AND OrgGroupId = isnull(@rOrgGroupId,0) and UserId = @rUserId
	order by OrderIndex
	
	select @lPayRollYear = @lPayRollYear + '<option value="0"> -- Select -- </option>'
	select top 1 @lPayRollYear = @lPayRollYear + '<option value="' + convert(varchar,YearNumber) + '">' + convert(varchar,YearNumber) + '</option>'
	from sPayroll.fMonthYearForPayrollGet(@rPayrollYearId)
	
	select @lStatusRes = @lStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lStatusRes = @lStatusRes + '<option value="7">Active</option>'
	select @lStatusRes = @lStatusRes + '<option value="9">Left</option>'
	select @lStatusRes = @lStatusRes + '<option value="8">Suspended</option>'
	select @lStatusRes = @lStatusRes + '<option value="8">Unknown</option>'
	
	select @lColumnRes = @lColumnRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sHrm' AND TABLE_NAME='vEmployeeColumnName'
	
	select @lPayrollColumn = @lPayrollColumn + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sPayroll' AND TABLE_NAME='vPayrollColumnName'
	
	select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="/Images/Del.png"></i></a></td></tr>'
	from sHrm.tEmployeeCustomSearch SCS
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	LEFT JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1  OR SCS.IsCommonForOrg = 1)
	
	select @lPayrollReportList = @lPayrollReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="/Images/Del.png"></i></a></td></tr>'
	from sPayroll.tPayrollCustomSearch SCS
	INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	AND SCS.OrgId = @rOrgId
	
	select @lSavedReport = @lSavedReport + '<option value="0"> -- Select -- </option>'
	select @lSavedReport =  @lSavedReport + '<option value="' + convert(varchar,ECS.Id)+ '">' + ECS.Title + '</option>'
	from sHrm.tEmployeeCustomSearch  ECS
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = ECS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	WHERE (ECS.CreatedUserId = @rUserId OR ECS.IsCommon = 1 OR ECS.IsCommonForOrg = 1)

	select @lSavedReport1 = @lSavedReport1 + '<option value="0"> -- Select -- </option>'
	select @lSavedReport1 =  @lSavedReport1 + '<option value="' + convert(varchar,PCS.Id)+ '">' + PCS.Title + '</option>'
	from sPayroll.tPayrollCustomSearch  PCS
	LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id = PCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	WHERE (PCS.CreatedUserId = @rUserId OR PCS.IsCommon = 1 OR PCS.IsCommonForOrg = 1)
	

	select @lCustomtagdrop  = @lCustomtagdrop  + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
	from sHrm.tCustomTagMaster where IsObsolete =0  and OrgGroupId = @rOrgGroupId

	DECLARE @lAvailableEmployeeColumns nvarchar(max)=''
	 DECLARE @lAvailableEmployeeCustomRes nvarchar(max)=''
	 Declare @Title as nvarchar(max)


	   SET @lAvailableEmployeeColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
						from sHrm.tEmployeeCustomFieldMaster PP WHERE PP.IsObsolete=0 AND PP.OrgGroupId =@rOrgGroupId
				FOR XML PATH(''), TYPE
				).value('.', 'NVARCHAR(MAX)') 
			,1,1,'')
	        
		DECLARE @lEmployeeCustomFields TABLE
		(
		  Title nvarchar(max)
		)
		 INSERT INTO  @lEmployeeCustomFields      
		select Item AS Title from sCommon.fnSplit(@lAvailableEmployeeColumns , ',')

	        
		select @lAvailableEmployeeCustomRes = @lAvailableEmployeeCustomRes +'<option class=EmployeeCustom value="|' + Title + '||">|' + Title + '||</option>'
		from @lEmployeeCustomFields
	
	select @lStatusRes as StatusRes,@lColumnRes as AvailableRes,@lReportList as ReportList,
	@lOrganizationRes as OrganizationRes,@lPayRollYear as PayRollYear,@lPayrollColumn as PayrollColumn,
	@lPayrollReportList as PayrollReportList, @lSavedReport AS SavedReportList,@lCustomtagdrop AS customtaghklist,@lAvailableEmployeeCustomRes as AvailableEmployeeCustomRes
	
end
GO
PRINT N'Altering [sPayroll].[pPayrollCustomSearchGet]...';


GO
-- exec [sPayroll].[pPayrollCustomSearchGet]
-- drop proc [sPayroll].[pPayrollCustomSearchGet]
ALTER PROCEDURE [sPayroll].[pPayrollCustomSearchGet] 
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'Code',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName[nvarchar](50) = '',
	@rEmployeeTypeId[nvarchar](50) = '',
	@rStatusId[nvarchar](50) = '',
	@rOrganizationDepartmentId[nvarchar](50) = '',
	@rReligionId[nvarchar](50) = '',
	@rMaritalStatusId[nvarchar](50) = '',
	@rQualification[nvarchar](50) = '',
	@rGenderId[nvarchar](50) = '',
	@rEmployeeDesignationId[nvarchar](50) = '',
	@rBloodGroupId[nvarchar](50) = '',
	@rEmployeeGroupId[nvarchar](50)='',
	@rDOBFromDate Date = '0001-01-01',
	@rDOBToDate Date = '9999-12-31',
	@rDOJFromDate Date = '0001-01-01',
	@rDOJToDate Date = '9999-12-31',
	@rDropDownStatusId int,
	@rPayrollId int,
	@rPageIndex int = null
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Sql nvarchar(MAX)
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	
	SELECT PCS.*
	into sPayroll.tTempPayroll1
	FROM sPayroll.vPayrollCustomSearch PCS
	WHERE ((PCS.OrgId = @rOrgId) OR (@rOrgId = 0))
	AND PCS.PayrollId = @rPayrollId
	AND ((PCS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((PCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((PCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(PCS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
	AND ((PCS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
	AND ((PCS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
	AND ((PCS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
	AND ((PCS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
	AND (ISNULL(PCS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='')
	AND (ISNULL(PCS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
	AND (ISNULL(PCS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='')
	AND (ISNULL(PCS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='')
	AND (ISNULL(PCS.EmployeeGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupId,','))OR @rEmployeeGroupId='')
	AND (ISNULL(PCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
	AND (ISNULL(PCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
	AND (ISNULL(PCS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='')
	AND (ISNULL(PCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
	AND ((PCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ISNULL(PCS.IsOtherUser,0) = 0
	
	SET @rOrderBy=Replace(@rOrderBy,'Code','Code')
	SET @sql='SELECT EmployeeId,Code AS Code,Name,EmployeeType,
	OrganizationDepartment AS OrganizationDepartment,StatusName,
	OrgName,0 AS SalaryMonth
	FROM sPayroll.tTempPayroll1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	create table #TEMPPay
	(
		tid int identity(1,1),t_EmpId bigint
	)
	SET @sql='insert into #TEMPPay SELECT EmployeeId FROM sPayroll.tTempPayroll1 ORDER BY '+ @rOrderBy
	exec(@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lPageSize int = 10,@lTotalRecords int,@lPaging varchar(max)='',@lResult varchar(max)=''
	
	select @lTotalRecords = count(1) from #TEMPPay
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lTotalRecords,@lPageSize)
	
	select @lResult = @lResult + '<tr><td>' + isnull(OrgName,'') + '</td><td>' + isnull(OrganizationDepartment,'') + '</td>
	<td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td><td>' + isnull(EmployeeType,'') + '</td>
	<td>' + isnull(StatusName,'') + '</td></tr>'
	from sPayroll.tTempPayroll1,#TEMPPay where EmployeeId = t_EmpId
	and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	
	select @lTotalRecords as TotalRecords,@lResult as EmpList,@lPaging as Paging
	
	DROP Table sPayroll.tTempPayroll1
END
GO
PRINT N'Altering [sSetup].[pMastedDataModify]...';


GO


ALTER PROCEDURE [sSetup].[pMastedDataModify]	 
	@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

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'InchargeEmployee') 	
		SET @rSubCategoryField = @rSubCategoryField + 'Id'	
		
	IF(@rSubCategoryField = 'DisplayTitle' AND @rCategoryId = 9) 	
		SET @rSubCategoryField = 'ExamSubGroupDisplayTitle'
	
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
			DROP TABLE ListofData
		
	CREATE TABLE ListofData(Id int,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)  
		BEGIN
		
		insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
						
		select *from ListofData				
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tOrganizationMaster ) 
		
		set @sql='INSERT INTO sSetup.tOrganizationMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tOrganizationMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tOrganizationMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
	else IF(@rCategoryId= 2)     
	 
	 BEGIN
	 
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tClassMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tClassMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tClassMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tClassMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  END
	  
	  
	  else IF(@rCategoryId= 3)
	  BEGIN
	     
	     insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tDivisionMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tDivisionMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tDivisionMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tDivisionMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		--print @sql
		--return
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    
	  
	  END    
	  
	  else IF(@rCategoryId= 4)
	  BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tSubjectMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tSubjectMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tSubjectMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tSubjectMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  
	  END 
	    
	 else IF(@rCategoryId= 5)
	 
	 BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tOrgGroupBatchMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tOrgGroupBatchMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tOrgGroupBatchMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tOrgGroupBatchMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id 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,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tBatchMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tBatchMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tBatchMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tBatchMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	  
	else IF(@rCategoryId= 7)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tDepartmentMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tDepartmentMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tDepartmentMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tDepartmentMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	  
	  
 else IF(@rCategoryId= 8)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sCommon.tOrgGroupDepartmentMaster ) 
	    
	    set @sql='INSERT INTO sCommon.tOrgGroupDepartmentMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sCommon.tOrgGroupDepartmentMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sCommon.tOrgGroupDepartmentMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	    
	   else IF(@rCategoryId= 9)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sAssessment.tExamSubGroupMaster ) 
	    
	    set @sql='INSERT INTO sAssessment.tExamSubGroupMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sAssessment.tExamSubGroupMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sAssessment.tExamSubGroupMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 

	   else IF(@rCategoryId= 10)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sCommon.tReligionMaster ) 
	    

	    set @sql='INSERT INTO sCommon.tReligionMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sCommon.tReligionMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sCommon.tReligionMaster RM 
					INNER JOIN ListofData LD ON RM.Id=LD.Id 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 [sStudent].[pDigitalFormCustomFieldApprove]...';


GO
 
ALTER PROCEDURE [sStudent].[pDigitalFormCustomFieldApprove]	 
	@rId Bigint = 0,
	@rOldValue NVarchar(500)='',
	@rNewValue NVarchar(500)='',
	@rActionRemark nvarchar(500) = '',
	@rActionUserId BigInt,
	@rActionDateTime DateTime,
	@rStatusId int,
	@rRequestId int =0,
	@rOrgId int = 0,
	@rCustomFieldId nvarchar(100)
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
BEGIN
	IF EXISTS(SELECT 1 FROM sStudent.vStudentAcademic WHERE AcademicId = @rId)
	BEGIN
		 DECLARE @lStudentId BigInt
		 SET @lStudentId = (SELECT StudentId FROM sStudent.vStudentAcademic WHERE AcademicId = @rId)

		 Declare @Sql nvarchar(max)
		 DECLARE @lResult int
		 IF OBJECT_ID('ListofData') IS NOT NULL	
				BEGIN 
					DROP TABLE ListofData
				END	

		IF(@rStatusId = 550)
			BEGIN
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),CustomFieldId int,UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rNewValue,@rCustomFieldId,@rActionUserId,0)
	 SELECT * FROM ListofData
		UPDATE LD SET IsExist=1 
		   FROM sStudent.tStudentCustomFieldData SC
		      LEFT JOIN ListofData LD ON SC.StudentId=LD.StudentId 
		      AND  EXISTS (SELECT StudentCustomFieldId FROM sStudent.tStudentCustomFieldData WHERE StudentId=LD.StudentId AND StudentCustomFieldId = LD.CustomFieldId) 
		
		
		set @sql='INSERT INTO sStudent.tStudentCustomFieldData
					(StudentId,StudentCustomFieldId,FieldData,CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,ISNULL('+@rCustomFieldId+',0),LD.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=0'
			
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCustomFieldData set FieldData = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCustomFieldData SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND SC.StudentCustomFieldId=LD.CustomFieldId AND IsExist=1'
		print @sql
		Exec sp_executesql @sql
	
		Drop Table ListofData
			 SET @lResult = 1;
	      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
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),CustomFieldId int,UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rOldValue,@rCustomFieldId,@rActionUserId,0)
	 
		UPDATE LD SET IsExist=1 
		   FROM sStudent.tStudentCustomFieldData SC
		      LEFT JOIN ListofData LD ON SC.StudentId=LD.StudentId 
		      AND  EXISTS (SELECT StudentCustomFieldId FROM sStudent.tStudentCustomFieldData WHERE StudentId=LD.StudentId AND StudentCustomFieldId = LD.CustomFieldId) 
		
		
		set @sql='INSERT INTO sStudent.tStudentCustomFieldData
					(StudentId,StudentCustomFieldId,FieldData,CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,ISNULL('+@rCustomFieldId+',0),LD.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=0'
			
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCustomFieldData set FieldData = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCustomFieldData SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND SC.StudentCustomFieldId=LD.CustomFieldId AND IsExist=1'
		print @sql
		Exec sp_executesql @sql
	
		Drop Table ListofData
			 SET @lResult = 1;
	      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
	END
GO
PRINT N'Altering [sStudent].[pGetDropDownLists]...';


GO
 
ALTER proc [sStudent].[pGetDropDownLists]
@rBatchId int =0,
@rOrgId int =0,
@rUserId bigint,
@rDepartmentId int =0,
@rOrgGroupBatchId int=0,
@rOrgGroupId int=0
as
begin
	declare @lStatusRes nvarchar(max)='',@lClassRes Nvarchar(max)='',@lEnrollmentStatusRes nvarchar(max)=''
	declare @lDepartmentRes nvarchar(max)='',@lDivisionRes Nvarchar(max)='',@lAvailableRes nvarchar(max)=''
	declare @lReportList nvarchar(max)='',@lExamRes nvarchar(max)='',@lGeneralExamRes nvarchar(max)='',@lcastdropdown nvarchar(max)=''
	declare @lExamReportList nvarchar(max)=''
	declare @lclassdropdown nvarchar(max)='',@lStatusdropdown nvarchar(max)='',@lGenderdropdown nvarchar(max)='',@lReligiondropdown nvarchar(max)=''
	declare @lCitydropdown nvarchar(max)='',@lAreadropdown nvarchar(max)='',@lNationalitydropdown nvarchar(max)='',@lTranspotrmodedropdown nvarchar(max)='',@lbusrouedropdown nvarchar(max)=''
	declare @lbusrotedestinationdrop nvarchar(max)='',@lblooddropdown nvarchar(max)='',@lhousedropdown nvarchar(max)='',@lmothertoungedropdown nvarchar(max)='',@lpriviousschooldropdown nvarchar(max)=''
	declare @lfatherqadrop nvarchar(max)='',@lmotherqadropdown nvarchar(max)='',@lfatherocdropdown nvarchar(max)='',@lmotherocdropdown nvarchar(max)='',@lfeescategorydropdown nvarchar(max)=''
	declare @lCustomtagdrop nvarchar(max)='',@lcustomgroupdropdown nvarchar(max)='',@lclubdropdown nvarchar(max)='',@lhosteldropdown nvarchar(max)='',@lstudentgroupdropdown nvarchar(max)=''
	declare @lstudentothergroupdropdown nvarchar(max)='',@lExaminationtypedropdown nvarchar(max)=''
	declare @lSavedReport nvarchar(max)='',@lSavedReport1 nvarchar(max)=''
	declare @lRecordtagdrop nvarchar(max)=''
	declare @lOrgGroupRes nvarchar(max)='',@lOrganizationRes nvarchar(max)='',@lBatchRes nvarchar(max)=''

	
	select @lDivisionRes = @lDivisionRes + '<option value="0"> -- ALL -- </option>'
	
	select @lStatusRes = @lStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lStatusRes = @lStatusRes + '<option value="1">Active</option>'
	select @lStatusRes = @lStatusRes + '<option value="2">InActive</option>'
	select @lStatusRes = @lStatusRes + '<option value="3">Left</option>'
	
	select @lOrgGroupRes = @lOrgGroupRes + '<option value="0"> -- Select -- </option>'
	select @lOrgGroupRes = @lOrgGroupRes + '<option ' + case when Id = @rOrgGroupBatchId then 'selected="selected"' else '' end + ' value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.tOrgGroupBatchMaster where IsObsolete = 0 AND IsHistory = 0 AND OrgGroupId = @rOrgGroupId
	order by OrderIndex
	
	select @lOrganizationRes = @lOrganizationRes + '<option value="0"> -- ALL -- </option>'
	select @lOrganizationRes = @lOrganizationRes + '<option ' + case when Id = @rOrgId then 'selected="selected"' else '' end + ' value="' + convert(varchar,Id) + '">' + DisplayTitle + '</option>'
	from sSetup.tOrganizationMaster where IsObsolete = 0 AND OrgGroupId = @rOrgGroupId
	order by OrderIndex

	select @lBatchRes = @lBatchRes + '<option value="0"> -- ALL -- </option>'

	select @lClassRes = @lClassRes + '<option value="0"> -- ALL -- </option>'
	select @lClassRes = @lClassRes + '<option value="' + convert(varchar,ClassId) + '">' + ClassName + '</option>'
	from sSetup.vBatchClass where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex
	
	select @lEnrollmentStatusRes = @lEnrollmentStatusRes + '<option value="0"> -- ALL -- </option>'
	select @lEnrollmentStatusRes = @lEnrollmentStatusRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sStudent.tEnrollmentStatusMaster where IsObsolete = 0 order by Title
	
	select @lDepartmentRes = @lDepartmentRes + '<option value="0"> -- ALL -- </option>'
	select @lDepartmentRes = @lDepartmentRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sSetup.vDepartment where IsObsolete = 0 AND OrgId = @rOrgId and UserId = @rUserId
	and (Id = @rDepartmentId or @rDepartmentId = 0) order by Title
	
	select @lAvailableRes = @lAvailableRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sStudent' AND TABLE_NAME='vStudentColumnName' AND COLUMN_NAME <> 'GR No'
	
	
	DECLARE @lAvailableStudentColumns nvarchar(max)=''
	 DECLARE @lAvailableStudentCustomRes nvarchar(max)=''
	 Declare @Title as nvarchar(max)


	   SET @lAvailableStudentColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
						from sStudent.tStudentCustomFieldMaster PP WHERE PP.IsObsolete=0 AND PP.OrgGroupId =@rOrgGroupId
				FOR XML PATH(''), TYPE
				).value('.', 'NVARCHAR(MAX)') 
			,1,1,'')
	        
		DECLARE @lStudentCustomFields TABLE
		(
		  Title nvarchar(max)
		)
		 INSERT INTO  @lStudentCustomFields      
		select Item AS Title from sCommon.fnSplit(@lAvailableStudentColumns , ',')

	        
		select @lAvailableStudentCustomRes = @lAvailableStudentCustomRes +'<option class=StudentCustom value="|' + Title + '||">|' + Title + '||</option>'
		from @lStudentCustomFields
		
		--select @lAvailableStudentCustomRes = @lAvailableStudentCustomRes +'<option class=StudentCustom value="''[' + Title + ']''">''[' + Title + ']''</option>'
		--from @lStudentCustomFields  
		
		--print @lAvailableStudentCustomRes
	
	
	
	select @lGeneralExamRes = @lGeneralExamRes + '<option value="' + COLUMN_NAME + '">' + COLUMN_NAME + '</option>'
	from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA='sAssessment' AND TABLE_NAME='vGeneralExamColumnName'
	
	--select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	--<td style="width:670px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	--<td style="width:80px; word-wrap:break-word;"><a onclick="ViewReport(' + convert(varchar(20),SCS.Id) + ',''' + convert(varchar(20),SCS.Title) + ''',''' + convert(varchar(max),SCS.ColumnName) +''');">View</a></td>
	--<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	--<td style="width:50px; word-wrap:break-word;text-align: center;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="../../Images/Del.png"></a></td></tr>'
	--from sStudent.tStudentCustomSearch SCS
	--INNER JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId
	--WHERE (SCS.CreatedUserId = @rUserId OR SCS.IsCommon = 1)
	--AND SCS.IsCommonForOrg = 0 OR SCS.IsCommonForOrg IS NULL
	--AND SCS.OrgId = @rOrgId
	
	select @lReportList = @lReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:670px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:80px; word-wrap:break-word;"><a onclick="ViewReport(' + convert(varchar(20),SCS.Id) + ',''' + convert(varchar(20),SCS.Title) + ''',''' + convert(varchar(max),SCS.ColumnName) +''');">View</a></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;text-align: center;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="../../Images/Del.png"></a></td></tr>'
	from sStudent.tStudentCustomSearch SCS
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	LEFT JOIN sSecurity.tUser U ON U.Id = SCS.CreatedUserId   
	WHERE SCS.CreatedUserId = @rUserId OR (SCS.IsCommon = 1) OR (SCS.IsCommonForOrg = 1)
	
	
	select @lExamReportList = @lExamReportList + '<tr><td style="width:100px; word-wrap:break-word;">' + SCS.Title + '</td>
	<td style="width:700px; word-wrap:break-word;">' + SCS.ColumnName + '</td>
	<td style="width:50px; word-wrap:break-word;"><a onclick="ViewReport(' + convert(varchar(20),SCS.Id) + ',''' + convert(varchar(20),SCS.Title) + ''',''' + convert(varchar(max),SCS.ColumnName) +''');">View</a></td>
	<td style="width:100px; word-wrap:break-word;">' + U.DisplayTitle + '</td>	
	<td style="width:50px; word-wrap:break-word;"><a onclick="DeleteReport(' + convert(varchar,SCS.Id) + ');"><img src="/Images/Del.png"></i></a></td></tr>'
	from sAssessment.tGeneralExamCustomSearch SCS
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
	LEFT JOIN sSecurity.tUser U ON U.Id = SCS.CreatedUserId 
	WHERE (SCS.CreatedUserId = @rUserId) OR (SCS.IsCommon = 1) OR ( SCS.IsCommonForOrg = 1)
		
	select @lExamRes = @lExamRes + '<option value="0"> -- ALL -- </option>'
	select @lExamRes = @lExamRes + '<option value="' + convert(varchar,Id) + '">' + Title + '</option>'
	from sAssessment.tExamSubGroupMaster where OrgId = @rOrgId
	
					--select @lclassdropdown=@lclassdropdown+'<option value="0"> -- ALL -- </option>'
					select @lclassdropdown = @lclassdropdown + '<option value="' + convert(varchar,DivisionId) + '">' + ClassDivisionName + '</option>'
					from sSetup.vBatchClassDivision where IsObsolete = 0 and BatchId = @rBatchId order by OrderIndex

					select @lStatusdropdown = @lStatusdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sStudent.tStatusMaster where IsObsolete = 0

					select @lGenderdropdown = @lGenderdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sCommon.tGenderMaster where IsObsolete = 0
					select @lReligiondropdown = @lReligiondropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sCommon.tReligionMaster where IsObsolete = 0 
					and OrgGroupId = @rOrgGroupId

					select @lcastdropdown = @lcastdropdown + '<option value="' +convert(varchar,Id) + '">' + Title + '</option>'
					from sCommon.tCastCategoryMaster where IsObsolete = 0 
					and OrgGroupId = @rOrgGroupId
					order by OrderIndex

					select @lCitydropdown = @lCitydropdown + '<option value="' +convert(varchar,OrgId)+ '">' + City + '</option>'
					from sStudent.vCity where OrgId = @rOrgId

					select @lAreadropdown = @lAreadropdown + '<option value="' +convert(varchar,OrgId)+ '">' + Area + '</option>'
					from sStudent.vArea where OrgId = @rOrgId

					select @lNationalitydropdown = @lNationalitydropdown + '<option value="' +convert(varchar,Id)+ '">' + Nationality + '</option>'
					from sCommon.tCountryMaster where IsObsolete = 0 
					and OrgGroupId = @rOrgGroupId

					select @lTranspotrmodedropdown = @lTranspotrmodedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tTransportModeMaster where IsObsolete = 0

					select @lbusrouedropdown = @lbusrouedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sTransport.tBusRouteMaster where IsObsolete = 0  and OrgGroupBatchId = @rOrgGroupBatchId

					select @lbusrotedestinationdrop  = @lbusrotedestinationdrop  + '<option value="' +convert(varchar,BDM.Id)+ '">' + BDM.Title + '</option>'
					from sTransport.tBusRouteMaster BM inner join sTransport.tBusRouteDestinationMaster BDM ON BM.Id= BDM.BusRouteId
					where BDM.IsObsolete = 0  and OrgGroupBatchId = @rOrgGroupBatchId


					select @lblooddropdown = @lblooddropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tBloodGroupMaster where IsObsolete = 0

					select @lhousedropdown = @lhousedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sActivity.tHouseMaster where IsObsolete = 0 and OrgId = @rOrgId

					select @lmothertoungedropdown = @lmothertoungedropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tMotherTongueMaster where IsObsolete = 0 and OrgGroupId = @rOrgGroupId

					select @lpriviousschooldropdown = @lpriviousschooldropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tPreviousSchoolMaster where IsObsolete = 0 and OrgGroupId = @rOrgGroupId

			
		
					select @lfatherqadrop = @lfatherqadrop + '<option value="' +convert(varchar,OrgId)+ '">' + Qualification + '</option>'
					from sStudent.vQualification where OrgId = @rOrgId

					select @lmotherqadropdown  = @lmotherqadropdown  + '<option value="' +convert(varchar,OrgId)+ '">' + Qualification + '</option>'
					from sStudent.vQualification where OrgId = @rOrgId
			
			
					select @lfatherocdropdown = @lfatherocdropdown + '<option value="' +convert(varchar,OrgId)+ '">' + Occupation + '</option>'
					from sStudent.vOccupation where OrgId = @rOrgId

					select @lmotherocdropdown = @lmotherocdropdown + '<option value="' +convert(varchar,OrgId)+ '">' + Occupation + '</option>'
					from sStudent.vOccupation where OrgId = @rOrgId


					select @lfeescategorydropdown = @lfeescategorydropdown + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tAdmissionCategoryMaster where IsObsolete = 0 and OrgGroupId = @rOrgGroupId
			
			
					select @lCustomtagdrop  = @lCustomtagdrop  + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tCustomTagMaster where IsObsolete = 0  and OrgGroupId = @rOrgGroupId

					select @lcustomgroupdropdown  = @lcustomgroupdropdown  + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommunication.tCustomGroup where  OrgGroupId = @rOrgGroupId

					select @lclubdropdown   = @lclubdropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sActivity.tClubMaster where  OrgGroupId = @rOrgGroupId

					select @lhosteldropdown   = @lhosteldropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sHostel.tHostelMaster where  OrgGroupId = @rOrgGroupId

					select @lstudentgroupdropdown   = @lstudentgroupdropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tStudentGroupMaster  where  OrgGroupId = @rOrgGroupId

					select @lstudentothergroupdropdown   = @lstudentothergroupdropdown   + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sStudent.tStudentOtherGroupMaster where  OrgGroupId = @rOrgGroupId

					select @lExaminationtypedropdown    = @lExaminationtypedropdown    + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sFee.tExemptionTypeMaster where  OrgGroupId = @rOrgGroupId
			
					select @lSavedReport = @lSavedReport + '<option value="0"> -- Select -- </option>'
					select @lSavedReport =  @lSavedReport + '<option value="' + convert(varchar,SCS.Id)+ '">' + SCS.Title + '</option>'
					from sStudent.tStudentCustomSearch SCS
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SCS.OrgId AND OM.OrgGroupId = @rOrgGroupId
					LEFT JOIN sSecurity.tUser U ON U.Id=SCS.CreatedUserId 
					WHERE (SCS.CreatedUserId = @rUserId) OR (SCS.IsCommon = 1) OR (SCS.IsCommonForOrg = 1)
					
					select @lSavedReport1 = @lSavedReport1 + '<option value="0"> -- Select -- </option>'
					select @lSavedReport1 =  @lSavedReport1 + '<option value="' + convert(varchar,GES.Id)+ '">' + GES.Title + '</option>'
					from sAssessment.tGeneralExamCustomSearch GES
					INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = GES.OrgId AND OM.OrgGroupId = @rOrgGroupId
					LEFT JOIN sSecurity.tUser U ON U.Id=GES.CreatedUserId 
					where  (GES.CreatedUserId = @rUserId) OR (GES.IsCommon = 1) OR  (GES.IsCommonForOrg = 1)
					
					select @lRecordtagdrop  = @lRecordtagdrop  + '<option value="' +convert(varchar,Id)+ '">' + Title + '</option>'
					from sCommon.tStatusMaster where IsObsolete = 0  AND StatusTypeId=102
								 

	select @lStatusRes as StatusRes,@lClassRes as ClassRes,@lDivisionRes as DivisionRes,
	@lEnrollmentStatusRes as EnrollStatusRes,@lDepartmentRes as DepartmentRes,
	@lAvailableRes as AvailableRes,@lAvailableStudentCustomRes as AvailableStudentCustomRes,@lReportList as ReportList,@lExamRes as ExamRes,
	@lGeneralExamRes as GeneralExamAvailRes,@lExamReportList as ExamReportList,@lclassdropdown as classChechboxlist,@lStatusdropdown As statusChechboxlist,
	@lGenderdropdown As Gendercheckboxlist,@lReligiondropdown As Religionchklist,@lcastdropdown as castcategorychklist,@lCitydropdown as Citychklist,
	@lAreadropdown AS Areachklist,@lNationalitydropdown As Nationalitychklist,@lTranspotrmodedropdown AS Transportmodechklist,@lbusrouedropdown AS busroutechklist,
	@lbusrotedestinationdrop AS Busroutedestinationchklist,@lblooddropdown AS bloodgrpchklist,@lhousedropdown AS Housechklist,
	@lmothertoungedropdown AS Mothertoungechklist,@lpriviousschooldropdown AS priviousschoolchklist,@lfatherqadrop  AS fatherqachklist,
	@lmotherqadropdown AS motherqachklist,@lfatherocdropdown AS fatherocuupationchklist,@lmotherocdropdown AS motherocuupationchklist,@lfeescategorydropdown AS feescategorychklist,
	@lCustomtagdrop AS customtaghklist,@lcustomgroupdropdown AS customgroupchklist,@lclubdropdown  AS clubchklist,@lhosteldropdown AS Hostelchklist,
	@lstudentgroupdropdown AS studentgroupchklist,@lstudentothergroupdropdown AS studentothergroupchklist,@lExaminationtypedropdown  as ExaminationTypechklist,
	@lSavedReport AS SavedReportList, @lSavedReport1 AS SavedReportList1,@lRecordtagdrop AS recordtaghklist,@lOrgGroupRes as OrgGroupRes,@lOrganizationRes as OrganizationRes,@lBatchRes as BatchRes
end
GO
PRINT N'Altering [sStudent].[pStudentCustomSearchGet]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentCustomSearchGet]
(
	@rPageIndex int = null,
	@rOrgId smallint,
	@rOrderBy nvarchar(max) = 'RollNo',
	@rCode nvarchar(max) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',
	@rCountry [nvarchar](50) = '',
	@rState [nvarchar](50) = '',
	@rCity nvarchar(max) = '',
	@rArea nvarchar(max) = '',
	--@rClassId 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 = '9990-12-31',
	@rDOAFromDate Date = '0001-01-01',
	@rDOAToDate Date = '9990-12-31',
	@rDOLFromDate Date = '0001-01-01',
	@rDOLToDate Date = '9990-12-31',
	@rIsPysicalDeformity bit,
	@rIsMajorIllness bit,
	@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,
	@rStudentStatus Smallint=0,
	@rHostelId nvarchar(max) = '',
	@rFatherName nvarchar(50)='',
	@rMotherName nvarchar(50)='',
	@rStudentGroupId nvarchar(max) = '',
	@rStudentOtherGroupId nvarchar(max) = '',
	@rOrgGroupBatchId int,
	@rBusRouteId nvarchar(max) = '',
	@rFeeExemption  nvarchar(max) = '',
	@rLCNumber nvarchar(20) = '',
	@rStudentNotAssigned int,
	@rRecordTagId nvarchar(max) = '',
	@rContactNo nvarchar(50) = ''
 )
AS
SET NOCOUNT ON
BEGIN

    TRUNCATE Table [sStudent].[TempStudentDetails]
	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
	

	DECLARE @Sql nvarchar(MAX)
	
	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(@rDOLFromDate IS NULL)
		SET @rDOLFromDate='0001-01-01'
	IF(@rDOLToDate IS NULL)
		SET @rDOLToDate='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 @rDOLToDate <> '9999-12-31'
		SET @rDOLToDate = DATEADD(d,1,@rDOLToDate)
	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 ='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 ='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 ='tTempStudent1')
 BEGIN
	DROP Table sStudent.tTempStudent1
 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 StudentId8,SF.IsFatherExStudent,SF.IsMotherExStudent, SF.FatherOrganization, SF.FatherDesignation,
						 SF.MotherOrganization, SF.MotherDesignation, SF.RelativeOrganization, SF.RelativeDesignation
		INTO sStudent.tTempStudent12
		FROM sStudent.tStudentMaster SM
			 LEFT JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND ((SM.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((A.BatchId=@BatchId) OR (@BatchId = 0))
			 LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SM.Id
		
		SELECT  DISTINCT SM.Id AS StudentId9, SH.IsAllergy,SH.AllergyRemark 
		INTO sStudent.tTempStudent13
		FROM sStudent.tStudentMaster SM
			 LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId = SM.Id
		 
	-- For Custom Tag
	IF (@rCustomTagId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId1		
		INTO sStudent.tTempStudent2
		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.tTempStudent2
	END
	-- For Custom Group
	IF (@rCustomGroupId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId2
		INTO sStudent.tTempStudent3
		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.tTempStudent3
	END
	-- For Club Group
	IF (@rClubId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId3
		INTO sStudent.tTempStudent4
		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.tTempStudent4
	END
	-- For Hostel
	IF (@rHostelId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId4
		INTO sStudent.tTempStudent8
		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 A.BatchId = @BatchId
		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.tTempStudent8
	END
	--Transport
	IF (@rBusRouteId <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId5
		INTO sStudent.tTempStudent9
		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.tTempStudent9
	END
	IF (@rFeeExemption <> '')
	BEGIN
		SELECT DISTINCT SM.Id AS StudentId6
		INTO sStudent.tTempStudent10
		FROM sStudent.tStudentMaster SM
		INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id
		INNER JOIN sFee.tExemptionTypeMaster AT ON AT.Id = A.ExemptionTypeId
		WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))
		AND (ISNULL(AT.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
	END
	ELSE
	BEGIN
		SELECT DISTINCT NULL AS StudentId6
		INTO sStudent.tTempStudent10
	END
	-- Not Assign	
	IF (@rStudentNotAssigned <> 0)
	BEGIN
		IF @rStudentNotAssigned = 1  -- Hostel Not Assign
		BEGIN
		 IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='sStudent.tTempStudent11')
		 Begin
			SELECT DISTINCT SM.Id AS StudentId7
			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)) AND A.StudentID Not in 
			(
			SElect SourceId from sHostel.tAssignRoom AR 
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			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
		END 

		IF @rStudentNotAssigned = 2 -- Transport Not Assign
		BEGIN
			 IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='sStudent.tTempStudent11')
			 Begin
				SELECT DISTINCT SM.Id AS StudentId7
				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)) AND A.StudentID Not in
				(Select SourceId FRom sTransport.tAssignRoute AT
				INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id = AT.PickupDestinationId AND AT.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id = BM.BusRouteId 
				AND  (ISNULL(BRM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
				AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)))
				WHERE ((SM.OrgId = @rOrgId) OR (@rOrgId = 0))
			END			
		END 
		
	END
	ELSE
	BEGIN		
		SELECT DISTINCT NULL AS StudentId7 INTO sStudent.tTempStudent11
		
		
	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
	
	--
	SELECT *,SCS.ClassName+'-'+SCS.DivisionName AS ClassName1
	INTO sStudent.tTempStudent1
	FROM sStudent.vStudentCustomSearch SCS
	INNER JOIN sStudent.tTempStudent2 T2 ON SCS.StudentId = T2.StudentId1 OR @rCustomTagId = ''
	INNER JOIN sStudent.tTempStudent3 T3 ON SCS.StudentId = T3.StudentId2 OR @rCustomGroupId = ''
	INNER JOIN sStudent.tTempStudent4 T4 ON SCS.StudentId = T4.StudentId3 OR @rClubId = ''
	INNER JOIN sStudent.tTempStudent8 T8 ON SCS.StudentId = T8.StudentId4 OR @rHostelId = ''
	INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId5 OR @rBusRouteId = ''
	INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId6 OR @rFeeExemption = ''
	INNER JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId7 OR @rStudentNotAssigned = 0
	LEFT JOIN sStudent.tTempStudent12 T12 ON SCS.StudentId = T12.StudentId8
	INNER JOIN sStudent.tTempStudent14 T14 ON SCS.StudentId = T14.StudentId14 OR @rRecordTagId = ''
	--INNER JOIN sStudent.tTempStudent13 T13 ON SCS.StudentId = T13.StudentId9
	
	WHERE ((SCS.OrgId = @rOrgId) OR (@rOrgId = 0)) AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0))
	AND SCS.OrgGroupBatchId = @rOrgGroupBatchId
	--AND ((SCS.Code Like @rSpecificCode + '%') OR (@rSpecificCode = ''))
	AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%')OR(@rCountry = ''))
	AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
	AND (( SCS.DateOfBirth  >= @rDOBFromDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
	AND (( SCS.DateOfBirth  < @rDOBToDate) OR (ISNULL(SCS.DateOfBirth,'') = ''))
	AND (( SCS.AdmissionDate >= @rDOAFromDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))
	AND (( SCS.AdmissionDate < @rDOAToDate) OR (ISNULL(SCS.AdmissionDate,'') = ''))
	AND (( SCS.LeftDate  >= @rDOLFromDate) OR (ISNULL(SCS.LeftDate,'') = ''))
	AND (( SCS.LeftDate   < @rDOLToDate) OR (ISNULL(SCS.LeftDate,'') = ''))
	AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
	AND ((SCS.RepeatCount=@rRepeatCount)OR (@rRepeatCount=0))
	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,1) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount=1)
	AND (ISNULL(SCS.StudentStatusId,'') IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatus,','))OR @rStudentStatus='')
	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 ((SCS.Code >= @rFromCode) OR (@rFromCode=''))
	AND ((SCS.Code <= @rToCode) OR (@rToCode=''))
	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 ((SCS.MiddleName Like @rFatherName  + '%') OR (@rFatherName = ''))
	AND ((SCS.MotherName Like @rMotherName  + '%') OR (@rMotherName = ''))
	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.LCNumber=@rLCNumber)OR (@rLCNumber=''))
	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=''))
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'PhysicalDeformityRemark','PysicalDeformityRemark')
	SET @rOrderBy=Replace(@rOrderBy,'IsPhysicalDeformity','IsPysicalDeformity')
	
	SET @sql='SELECT StudentId,Code AS Code,Name,ClassName1 AS ClassName,StatusName,
	ParentContactNo
	FROM sStudent.tTempStudent1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	
	select @Sql = 'insert into [sStudent].[TempStudentDetails]
	SELECT StudentId,Code,ClassName,StatusName,ParentContactNo FROM sStudent.tTempStudent1 ORDER BY ' + @rOrderBy
	exec (@Sql)
	
	create table #STUDENTTEMP
	(
		tid int identity(1,1),t_StudentId bigint
	)
	select @Sql = 'insert into #STUDENTTEMP
	SELECT StudentId FROM sStudent.tTempStudent1 ORDER BY ' + @rOrderBy
	
	exec (@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lTotalRecords int,@lPageSize int = 10,@lResult nvarchar(max) = '',@lPaging nvarchar(max) = ''
	
	select @lTotalRecords = COUNT(*) FROM #STUDENTTEMP
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
	
	select @lResult = @lResult + '<tr><td><a style="cursor:pointer;" onclick="SelectStudent(' + convert(varchar,StudentId) + ',''' + isnull(Code,'') + ''')">Select</a></td>
	<td>' + isnull(Organization,'') + '</td><td>' + isnull(Batch,'') + '</td><td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td>
	<td>' + isnull(ClassName,'') + '-' + isnull(DivisionName,'') + '</td><td>' + isnull(StatusName,'') + '</td></tr>'	
	from sStudent.tTempStudent1,#STUDENTTEMP
	where t_StudentId = StudentId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	order by tid
	
	select @lResult as StudentList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP Table sStudent.tTempStudent1
	DROP Table sStudent.tTempStudent2
	DROP Table sStudent.tTempStudent3
	DROP Table sStudent.tTempStudent4
	DROP Table sStudent.tTempStudent8
	DROP Table sStudent.tTempStudent9
	DROP Table sStudent.tTempStudent10
	DROP Table sStudent.tTempStudent11
	DROP Table sStudent.tTempStudent12
	DROP Table sStudent.tTempStudent13
	DROP Table sStudent.tTempStudent14
	
END
GO
PRINT N'Altering [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')
	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 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
 
		
		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		
				
		
		
		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 != 'AdmissionCategoryId')
		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 = 'AdmissionCategoryId')
		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 [sWorkflow].[pStudentDataChangeApprove]...';


GO


ALTER  PROCEDURE [sWorkflow].[pStudentDataChangeApprove]
			@rId Bigint = 0,
			@rUpdateFieldId int=0,
			@rSourceTypeId int,
			@rSourceId BigInt,
			@rOldValue NVarchar(500)='',
			@rNewValue NVarchar(500)='',
			@rActionRemark nvarchar(500) = '',
			@rActionUserId BigInt,
			@rActionDateTime DateTime,
			@rStatusId int,
			@rRequestId int =0
			 
	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

			DECLARE @lUpdateField NVARCHAR(100)
			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 = 'Nationality')
			BEGIN
			SET @lUpdateField =@lUpdateField + 'Id'
			END

			IF(@lUpdateField = 'CasteCategory' )
			BEGIN
			SET @lUpdateField = Replace(@lUpdateField,'Caste','Cast') + 'Id'
			END
			

			Declare @Sql nvarchar(max)

			IF OBJECT_ID('ListofData') IS NOT NULL	
			BEGIN 
				DROP TABLE ListofData
			END	
			
			IF(@rStatusId = 550)
			BEGIN
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rNewValue,@rActionUserId,0)

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

			
			IF(@lSubFunctionality = 'Communication')  ----Communication
				BEGIN
			
				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
					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
		
					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
		
						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
						 SET @lResult = 1;
					END			 
	 
			IF(@lResult = 1)
			BEGIN
				UPDATE sWorkFlow.tStudentDataChange
				SET
					StatusId = @rStatusId
					,ActionRemark = @rActionRemark
					,ActionUserId = @rActionUserId
					,ActionDateTime = @rActionDateTime
				WHERE 
					AutoId = @rRequestId
			END
			SELECT 1 AS Result
			END
			ELSE IF(@rStatusId = 551)
			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
			
				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
					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
		
					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
		
						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
						 SET @lResult = 1;
					END			 
	 
			IF(@lResult = 1)
			BEGIN
				UPDATE sWorkFlow.tStudentDataChange
				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'Creating [sAcademic].[pOnlineLearningAllAttendanceListGet]...';


GO
CREATE PROCEDURE [sAcademic].[pOnlineLearningAllAttendanceListGet]

	@rOnlineLearningIds nvarchar(max)='' ,
	--@rClassId bigint,
	@rBatchId bigint
 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

CREATE TABLE #OnlineLearningIds
  ( 
     Id INT IDENTITY (1, 1), 
     OnlineLearningId bigint
  )
  INSERT INTO #OnlineLearningIds
SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rOnlineLearningIds,',')

--Select * from #OnlineLearningIds
	
	CREATE TABLE #StudentData
	(
	OnlineLearningId bigint,
	Class nvarchar(200),
	Code nvarchar(200),
	RollNo bigint,
	StudentName nvarchar(200),
	IsPresent nvarchar(100),
	InCount int,
	ClassID bigint,
	DivisionId bigint,
	AcademicId bigint,
	IsLoggedIn nvarchar(100),
	FirstInDateTime datetime,
	IsPresentAbsent nvarchar(100),
	StartDateTime nvarchar(200),
	SubjectId bigint
	--StartTime nvarchar(200)
	)

	DECLARE @lCountIds int,@Id int,@lOnlineLearningId bigint

	SELECT @lCountIds=COUNT(Id) FROM #OnlineLearningIds
	SELECT Top 1 @Id=Id FROM #OnlineLearningIds
	WHILE @Id <= @lCountIds
	BEGIN
	SELECT @lOnlineLearningId=OnlineLearningId FROM #OnlineLearningIds WHERE Id=@Id
	CREATE TABLE #SourceTypeId
	(
		Id int IDENTITY,
		SourceTypeId bigint
	)

	INSERT INTO #SourceTypeId
	Select Distinct  SourceTypeId from [sAcademic].[tOnlineLearningScope] Where OnlineLearningId=@lOnlineLearningId
	
	DECLARE @lCountSourceTypeId int,@lSourceTypeId int,@lId int

	SELECT @lCountSourceTypeId=COUNT(SourceTypeId) FROM #SourceTypeId
		SELECT Top 1 @lId=Id FROM #SourceTypeId

WHILE @lId <= @lCountSourceTypeId
	BEGIN
	SELECT @lSourceTypeId=SourceTypeId FROM #SourceTypeId WHERE Id=@lId

	--StudnetId
	IF(@lSourceTypeId=2003)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			OL.Id AS OnlineLearningId ,
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @lOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),0)AS IsPresentAbsent,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR,OL.StartTime,108)AS StartDateTime,
			OL.SubjectId
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.StudentId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@lOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate,OL.StartTime,OL.Id,OL.SubjectId
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--AcademicId
	IF(@lSourceTypeId=2001)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			OL.Id AS OnlineLearningId ,
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @lOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),0)AS IsPresentAbsent,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR,OL.StartTime,108)AS StartDateTime,
			OL.SubjectId
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.AcademicId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@lOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate,OL.StartTime,OL.Id,OL.SubjectId
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--ClassId
	ELSE IF(@lSourceTypeId=2016)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			OL.Id AS OnlineLearningId ,
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @lOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),0)AS IsPresentAbsent,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR,OL.StartTime,108)AS StartDateTime,
			OL.SubjectId
		
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.ClassId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@lOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate,OL.StartTime,OL.Id,OL.SubjectId
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--DeparmentId
	ELSE IF(@lSourceTypeId=2017)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			OL.Id AS OnlineLearningId ,
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @lOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),0)AS IsPresentAbsent,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR,OL.StartTime,108)AS StartDateTime,
			OL.SubjectId
			
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.DepartmentId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@lOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate,OL.StartTime,OL.Id,OL.SubjectId
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--OrgId
	ELSE IF(@lSourceTypeId=2021)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			OL.Id AS OnlineLearningId ,
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @lOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),0)AS IsPresentAbsent,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR,OL.StartTime,108)AS StartDateTime,
			OL.SubjectId
			--OL.StartDate  AS StartDate,
			--OL.StartTime AS StartTime
			--CONVERT(NVARCHAR,OL.StartDate,103) as StartDate,
			--CONVERT(NVARCHAR(5),OL.StartTime,108) as StartTime

			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.OrgId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId
			AND SA.BatchId = OL.BatchId
			WHERE 
			OLS.OnlineLearningId=@lOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate,OL.StartTime,OL.Id,OL.SubjectId
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END
	--Division
	ELSE IF(@lSourceTypeId=2005)
	BEGIN
	INSERT INTO #StudentData
	SELECT 
			OL.Id AS OnlineLearningId ,
			SA.ClassName+'-'+SA.DivisionName AS Class,
			SA.Code,
			SA.RollNo,
			SA.FirstName +' '+SA.MiddleName +' '+SA.LastName As StudentName ,
			ISNULL((SELECT (CASE WHEN OLA.IsPresent=1 THEN 'P' ELSE 'N' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'N')AS IsPresent,
			(SELECT COUNT(OLAL.Academicid ) FROM sAcademic.tOnlineLearningAttendanceLog OLAL WHERE OLAL.AcademicId=SA.AcademicId
			 AND OLAL.OnlineLearningId = @lOnlineLearningId  
			)As InCount ,
			SA.ClassID,
			SA.DivisionId,
			SA.AcademicId,
			ISNULL((SELECT (CASE WHEN OLA.IsLoggedIn=1 THEN 'ON' ELSE 'OFF' END)  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),'OFF')AS IsLoggedIn,
			ISNULL((SELECT   OLA.FirstInDateTime  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),OL.StartDate)AS FirstInDateTime,
			ISNULL((SELECT  OLA.IsPresent  FROM sAcademic.tOnlineLearningAttendance OLA 
			WHERE OLA.AcademicId=SA.AcademicId AND OLA.OnlineLearningId=@lOnlineLearningId),0)AS IsPresentAbsent,
			CONVERT(NVARCHAR,OL.StartDate,103)+' '+CONVERT(NVARCHAR,OL.StartTime,108)AS StartDateTime,
			OL.SubjectId
			--OL.StartDate  AS StartDate,
			--OL.StartTime AS StartTime
			--CONVERT(NVARCHAR,OL.StartDate,103) as StartDate,
			--CONVERT(NVARCHAR(5),OL.StartTime,108) as StartTime
			
			
  FROM		sStudent.vStudentAcademic SA
			INNER JOIN sAcademic.tOnlineLearningScope OLS ON SA.DivisionId=OLS.SourceId
			INNER JOIN [sAcademic].[tOnlineLearning] OL ON OL.Id=OLS.OnlineLearningId 
			AND SA.BatchId = OL.BatchId
			
			WHERE 
			OLS.OnlineLearningId=@lOnlineLearningId
			AND OL.BatchId=@rBatchId AND SA.StatusId = 1
			GROUP BY --OLAL.OnlineLearningId,
			SA.StudentId,SA.FirstName ,SA.MiddleName,SA.LastName,--OLA.IsPresent,
			SA.ClassName,SA.Code,SA.RollNo,SA.RollNo,--OLAL.Academicid,
			SA.DivisionName,SA.ClassID,
			SA.DivisionId,SA.AcademicId,OL.StartDate,OL.StartTime,OL.Id,OL.SubjectId
			ORDER BY SA.ClassID,SA.DivisionId,SA.RollNo
	END

	SET @lId=@lId+1
	END
	
	DROP TABLE #SourceTypeId
	SET @Id=@Id+1

	END
	--Select * from #StudentData
	Select ROW_NUMBER() OVER (PARTITION BY SD.AcademicId ,SD.ClassId,CONVERT(Date,SD.StartDateTime,103) ORDER BY CONVERT(Varchar,SD.StartDateTime,20) ASC) AS PeriodNo,*
	from #StudentData SD 
	Order By SD.StartDateTime,SD.ClassId ASC
	
	--Select * from #OnlineLearningIds
	
	DROP TABLE #StudentData
	DROP TABLE #OnlineLearningIds
				
END
GO
PRINT N'Creating [sAcademic].[pOnlineLearningAllStudentAttendanceAdd]...';


GO

CREATE PROCEDURE [sAcademic].[pOnlineLearningAllStudentAttendanceAdd]
	
	@rStrXml nvarchar(MAX),
	@rEmployeeId bigint,
    @rAttendanceTypeId tinyint,
    --@rSubjectId int=0,
    @rRepeatCount tinyint=0,
    @rAttendanceGroupId int=0,
    --@rPeriodNo int=0 ,
	@rAbsentReasonId int=0,
	@rAttendanceRemark nvarchar(10)='',
	@rAttendanceTagId int=0,
	@rCreatedUserId bigint
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	
	 
	 INSERT INTO sAttendance.tStudentRegister 
		(
			AcademicId,
			EmployeeId,
			AttendanceTypeId,
			AttendanceDate,
			SubjectId,
			RepeatCount,
			IsPresent,
			AbsentReasonId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			AttendanceTagId,
			PeriodNo,
			AttendanceGroupId,
			AttendanceRemark
			)
		SELECT	
		DISTINCT	
			AcademicId,
			@rEmployeeId,
			@rAttendanceTypeId,
		    AttendanceDate,
			SubjectId,
			ISNULL(@rRepeatCount,0),
			IsPresent,
			ISNULL(@rAbsentReasonId,0),
			@rCreatedUserId,
			sCommon.fGetDate(),
			'',
			'',
			@rAttendanceTagId,
			PeriodNo,
			@rAttendanceGroupId,
			@rAttendanceRemark
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				AcademicId bigint,
				AttendanceDate Date,
				IsPresent bit,
				PeriodNo int,
				SubjectId bigint
				
			  ) A 
		WHERE NOT EXISTS (
        SELECT AcademicId,PeriodNo,SubjectId
        FROM sAttendance.tStudentRegister 
        WHERE AcademicId = A.AcademicId AND AttendanceDate=A.AttendanceDate AND PeriodNo=A.PeriodNo AND SubjectId=A.SubjectId
        )
        SELECT 1 AS Result
	
	
		
		
END
GO
PRINT N'Creating [sAssetManagement].[pMovementSearchGet]...';


GO
 
CREATE PROCEDURE [sAssetManagement].[pMovementSearchGet]
	@rOrgId int,
	@rId int = 0,
	@rMovementDate Date = '',
	@rFromDepartmentId int = 0,
	@rFromLocationId int = 0,
	@rToDepartmentId int = 0,
	@rToLocationId int = 0,
	@rOwnerEmployeeId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT M.Id,
			M.Number,
			CONVERT(varchar, M.MovementDate, 105) as MovementDate,
			ISNULL(M.Remark,''),
			ISNULL(EM.EmployeeName, '') EmployeeName,
			ISNULL(M.OwnerId, 0) OwnerId,
			ISNULL((SELECT Title FROM sSetup.tDepartmentMaster WHERE Id = M.FromDepartmentId),'') as FromDepartment,
			ISNULL((SELECT Title FROM sSetup.tDepartmentMaster WHERE Id = M.ToDepartmentId),'') as ToDepartment,
			ISNULL((SELECT Title FROM sFixedAsset.tLocationMaster WHERE Id = M.FromLocationId),'') as FromLocation,
			ISNULL((SELECT Title FROM sFixedAsset.tLocationMaster WHERE Id = M.ToLocationId),'') as ToLocation,
			AM.Code as AssetTag,
			AM.Title as AssetTitle
	FROM 
		sAssetManagement.tMovement M
		INNER JOIN sAssetManagement.tMovementDetail MD ON M.Id = MD.MovementId
		INNER JOIN sAssetManagement.tAssetMaster AM ON MD.AssetId = AM.Id
		LEFT JOIN sCommon.vEmployeeMaster EM ON EM.Id = M.OwnerId		
	WHERE 
		((M.Id = @rId) OR (@rId = 0)) AND M.OrgId = @rOrgId
		AND ((M.MovementDate = @rMovementDate) OR (@rMovementDate = ''))
		AND ((M.FromDepartmentId = @rFromDepartmentId) OR (@rFromDepartmentId = 0))
		AND ((M.FromLocationId = @rFromLocationId) OR (@rFromLocationId = 0))
		AND ((M.ToDepartmentId = @rToDepartmentId) OR (@rToDepartmentId = 0))
		AND ((M.ToLocationId = @rToLocationId) OR (@rToLocationId = 0))
		AND ((M.OwnerId = @rOwnerEmployeeId) OR (@rOwnerEmployeeId = 0))
END
GO
PRINT N'Creating [sAttendance].[MISStudentSubjectAttendanceDashboardGet]...';


GO
 
 
CREATE PROCEDURE [sAttendance].[MISStudentSubjectAttendanceDashboardGet]

@rOrgGroupId int = 0,
@rOrgId int = 0,
@rCommonOrgGroupBatchId int = 0,
@rTypeId int = 0,
@rIsPercent bit = 0,
@rPresentId int = 2,
@rGenderId tinyint = 0,
@rDivisionId int = 0,
@rSubjectId int = 0,
@rAcademicId bigint = 0,
@rFromDate date = '',
@rToDate date = ''



WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rTypeId = 1)-------------LEVEL 1
	BEGIN
		IF(@rIsPercent = 0)
		BEGIN
		SELECT 
				OM.Id AS OrgId,
				OM.Title AS OrganizationName,
				COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)As PresentCount,
				COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)As AbsentCount,
				COUNT(SR.IsPresent) AS Total
			FROM 
				sAttendance.tStudentRegister SR
				INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
			WHERE OM.OrgGroupId = @rOrgGroupId AND COGBM.Id = @rCommonOrgGroupBatchId
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			GROUP BY OM.Id,OM.Title
		END
		ELSE IF(@rIsPercent = 1)
		BEGIN
			SELECT 
				OM.Id AS OrgId,
				OM.Title AS OrganizationName,
				CAST(CAST(COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)AS DECIMAL) * 100 / CAST(COUNT(SA.AcademicId) AS DECIMAL)AS DECIMAL(5,2)) AS PresentPercentage,
				CAST(CAST(COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)AS DECIMAL) * 100 / CAST(COUNT(SA.AcademicId) AS DECIMAL)AS DECIMAL(5,2)) AS AbsentPercentage,
				'100' AS Total 
			FROM 
				sAttendance.tStudentRegister SR
				INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
				INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
			WHERE OM.OrgGroupId = @rOrgGroupId AND COGBM.Id = @rCommonOrgGroupBatchId 
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			GROUP BY OM.Id,OM.Title
		END
	END
	ELSE IF(@rTypeId = 2)-------------LEVEL 2
	BEGIN
		SELECT		
		SA.DivisionId,
		SA.ClassName + '-' + SA.DivisionName AS ClassName,
		SM.Id AS SubjectId,
		SM.Title AS SubjectName,
		COUNT(SA.AcademicId) AS Total,
		COUNT(CASE WHEN SO.GenderId = 1 THEN SA.AcademicId END) AS Male,
		COUNT(CASE WHEN SO.GenderId = 2 THEN SA.AcademicId END) AS Female
	FROM		
		sAttendance.tStudentRegister SR
		INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
		INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA.ClassId = CS.ClassId
		INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
	WHERE 
		SA.OrgId = @rOrgId AND COGBM.Id = @rCommonOrgGroupBatchId 
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SR.IsPresent = @rPresentId OR @rPresentId = 2)
	GROUP BY 
		SA.DivisionId,SA.ClassName,SA.DivisionName,SM.Id,SM.Title
	ORDER BY 
		SA.ClassName,SA.DivisionName,SM.Id
	END
	ELSE IF(@rTypeId = 3)-------------LEVEL 3
	BEGIN
		SELECT
		SA.AcademicId, 
		SA.Code,
		SA.Name AS StudentName,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		CAST(CAST(COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)AS DECIMAL) * 100 / CAST(COUNT(SA.AcademicId) AS DECIMAL)AS DECIMAL(5,2)) AS PresentPercentage
	FROM sAttendance.tStudentRegister SR
		INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
		INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA.ClassId = CS.ClassId
		INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
	WHERE 
		SA.OrgId = @rOrgId AND SA.DivisionId = @rDivisionId AND  CS.SubjectId = @rSubjectId AND COGBM.Id = @rCommonOrgGroupBatchId 
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SO.GenderId = @rGenderId OR @rGenderId = 0)
	GROUP BY 
		SA.AcademicId,SA.Code,SA.Name,SA.ClassName,SC.ParentContactNo
	ORDER BY 
		SA.AcademicId,SA.Code,SA.Name,SA.ClassName,SC.ParentContactNo
	END
	ELSE IF(@rTypeId = 4)-------------LEVEL 4
	BEGIN
	IF(@rIsPercent = 0)
		BEGIN
			SELECT
			SM.Id AS SubjectId,
			SM.Title AS SubjectName,
			COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)As PresentCount,
			COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)As AbsentCount,
			COUNT(SA.AcademicId) AS Total
		FROM sAttendance.tStudentRegister SR
			INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
			INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA.ClassId = CS.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId			
		WHERE 
			SA.OrgId = @rOrgId AND COGBM.Id = @rCommonOrgGroupBatchId
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))		
			AND SA.AcademicId = @rAcademicId
		GROUP BY 
			SM.Id,SM.Title
		ORDER BY 
			SM.Id,SM.Title
		END
	ELSE IF(@rIsPercent = 1)
		BEGIN
			SELECT
			SM.Id AS SubjectId,
			SM.Title AS SubjectName,
			CAST(CAST(COUNT(CASE WHEN  SR.IsPresent=1 THEN 1 END)AS DECIMAL) * 100 / CAST(COUNT(SA.AcademicId) AS DECIMAL)AS DECIMAL(5,2)) AS PresentPercentage,
			CAST(CAST(COUNT(CASE WHEN  SR.IsPresent=0 THEN 1 END)AS DECIMAL) * 100 / CAST(COUNT(SA.AcademicId) AS DECIMAL)AS DECIMAL(5,2)) AS AbsentPercentage,
			'100' AS Total
		FROM sAttendance.tStudentRegister SR
			INNER JOIN sStudent.vStudentAcademic SA ON SR.AcademicId = SA.AcademicId 
			INNER JOIN sSetup.tClassSubject CS ON SR.SubjectId = CS.SubjectId AND SA.ClassId = CS.ClassId
			INNER JOIN sSetup.tSubjectMaster SM ON CS.SubjectId = SM.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = SA.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id = OGBM.CommonOrgGroupBatchId
		WHERE 
			SA.OrgId = @rOrgId AND COGBM.Id = @rCommonOrgGroupBatchId
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))		
			AND SA.AcademicId = @rAcademicId
		GROUP BY 
			SM.Id,SM.Title
		ORDER BY 
			SM.Id,SM.Title
		END
	END
END
GO
PRINT N'Creating [sFee].[pAssignOptionalFeeHeadHistoryAdd]...';


GO
 
CREATE PROCEDURE [sFee].[pAssignOptionalFeeHeadHistoryAdd]
		  
           @rSourceTypeId int,
           @rSourceId bigint,
           @rBatchId int,
           @rClassId int,
           @rAdmissionCategoryId int,
           @rFeeHeadId int,
		   @rCreatedUserId bigint,
		   @rHistoryTypeId tinyint,
		   @rIsOptional bit

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY
	 BEGIN TRANSACTION	
	 
	 IF(@rClassId=0)
	 BEGIN 
		SELECT @rClassId = ClassId FROM sStudent.vStudentAcademic SA WHERE AcademicId = @rSourceId
	 END 
	 
	INSERT INTO sFee.tFeeAllocationHistory
		(
		   FeeSetupId,
		   SourceTypeId,
		   SourceId,
		   VariableAmount,
		   DiscountAmount,
		   UserId,
		   LogDateTime,
		   HistoryTypeId,
		   IsOptional
		)
	 
			SELECT
				FS.Id,  
				@rSourceTypeId,
				@rSourceId,	
				0,
				0,	
				@rCreatedUserId,
				sCommon.fGetDate(),
			    @rHistoryTypeId,
			    @rIsOptional
			FROM 
				sFee.tFeeSetup FS
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id	 
				
	WHERE
		FHM.Id = @rFeeHeadId
		AND FS.BatchId = @rBatchId
		AND FS.ClassId = @rClassId
		AND FS.AdmissionCategoryId =@rAdmissionCategoryId 
		AND FS.IsOptional=1
		
		SELECT 1 AS Result
		
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sFee].[pAssignOptionalFeeHistoryAdd]...';


GO
 
CREATE PROCEDURE [sFee].[pAssignOptionalFeeHistoryAdd]
	 
		   @rFeeSetupId int,
           @rSourceTypeId int,
           @rSourceId bigint,
		   @rCreatedUserId bigint,
		   @rHistoryTypeId tinyint,
		   @rIsOptional bit

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
 
  BEGIN
	INSERT INTO sFee.tFeeAllocationHistory
		(
		   FeeSetupId,
		   SourceTypeId,
		   SourceId,
		   VariableAmount,
		   DiscountAmount,
		   UserId,
		   LogDateTime,
		   HistoryTypeId,
		   IsOptional
		)
	VALUES
		(
			@rFeeSetupId,
			@rSourceTypeId,
			@rSourceId,
			0,
			0,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rHistoryTypeId,
			@rIsOptional
		)
		SELECT 1 AS Result
		             
	END	 
	 
	
	COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sHrm].[pEmployeeCustomFieldAdd]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeCustomFieldAdd]
		 
	@rId int,
	@rOrgId int,
	@rFieldTitle nvarchar(500),
	@rFieldTypeId tinyint,
	@rFieldList nvarchar(500),
	@rIsFieldMandatory bit,
	@rFieldGroup nvarchar(200),
	@rFieldOrder smallint,
	@rCreatedUserId bigint,	
	@rCreatedDateTime datetime,
	@rUpdatedUserId bigint,
	@rUpdatedDateTime datetime,
	@rIsObsolete int =0,
	@rDataTypeId int = 1

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

BEGIN TRY
BEGIN TRANSACTION	

DECLARE @lOrgGroupId int=0
SELECT @lOrgGroupId= OrgGroupId FROM sSetup.tOrganizationMAster WHERE Id = @rOrgId
 
IF(@rId = 0)	
BEGIN
    IF NOT EXISTS(SELECT 2 FROM sHrm.tEmployeeCustomFieldMaster WHERE FieldTitle=@rFieldTitle AND FieldGroup=@rFieldGroup AND DataId=@rDataTypeId )
    --IF NOT EXISTS(SELECT 2 FROM sStudent.tStudentCustomFieldMaster WHERE FieldTitle=@rFieldTitle)
	BEGIN
	      DECLARE @lNextNumber int
	      EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tEmployeeCustomFieldMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
Print @lNextNumber
	      INSERT INTO sHrm.tEmployeeCustomFieldMaster
	      (
		    Id
		   ,FieldTitle
		   ,FieldTypeId
		   ,FieldList
		   ,IsFieldMandatory
		   ,FieldGroup
		   ,FieldOrder
		   ,CreatedUserId
		   ,CreatedDateTime
		   ,OrgGroupId
		   ,IsObsolete
		   ,DataId
	      )
	     VALUES
	     (
		   @lNextNumber
		  ,@rFieldTitle
		  ,@rFieldTypeId
		  ,@rFieldList
		  ,@rIsFieldMandatory
		  ,@rFieldGroup
		  ,@rFieldOrder
		  ,@rCreatedUserId
		  ,@rCreatedDateTime
		  ,@lOrgGroupId
		  ,@rIsObsolete
		  ,@rDataTypeId
	     )
     END
	 ELSE
	 SELECT -101 As RESULT
END
	 	 
ELSE
BEGIN
	SET @lNextNumber = @rId

	
	
		UPDATE sHrm.tEmployeeCustomFieldMaster
		SET 
		FieldTitle = @rFieldTitle
		,FieldTypeId = @rFieldTypeId
		,FieldList=@rFieldList
		,IsFieldMandatory=@rIsFieldMandatory
		,IsObsolete=@rIsObsolete
		,FieldGroup=@rFieldGroup
		,FieldOrder=@rFieldOrder
		,UpdatedUserId=@rUpdatedUserId
		,UpdatedDateTime=@rUpdatedDateTime
		,DataId = @rDataTypeId
		WHERE Id = @rId 
	
	
END  
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sHrm].[pEmployeeCustomFieldDelete]...';


GO
 
CREATE PROCEDURE [sHrm].[pEmployeeCustomFieldDelete]

@rId int,
@rOrgId smallint=0,
@rOrgGroupId int=0
AS
BEGIN
 	 
	 IF NOT EXISTS(Select 1 from sHrm.tEmployeeCustomFieldData ECF 
	          INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=ECF.EmployeeId
	          INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId 
	        WHERE ECF.EmployeeCustomFieldId=@rId AND StatusId=7 AND OM.OrgGroupId=@rOrgGroupId
	           AND (ECF.FieldData <> '0' AND ECF.FieldData<>'' AND ECF.FieldData IS NOT NULL))
	 BEGIN
        
        DELETE ECF FROM sHrm.tEmployeeCustomFieldData ECF 
           INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=ECF.EmployeeId
	       INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId 
        WHERE ECF.EmployeeCustomFieldId=@rId AND StatusId=1 AND OM.OrgGroupId=@rOrgGroupId
         
		DELETE	FROM sHrm.tEmployeeCustomFieldMaster WHERE Id=@rId 
		SELECT 1 AS RESULT
	  END 

	  ELSE

	    SELECT -101 As RESULT

 
END
GO
PRINT N'Creating [sHrm].[pEmployeeCustomFieldDetailsGet]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeCustomFieldDetailsGet]	 
	@rOrgGroupId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
	SELECT 
		Id,
	    FieldTitle,	
		FieldGroup,	
		FieldTypeId,
		FieldList,
		IsFieldMandatory,
		IsObsolete,
		FieldOrder,
		ISNULL(DataId,0) DataId
	FROM 
		 sHrm.tEmployeeCustomFieldMaster

	WHERE 
		OrgGroupId = @rOrgGroupId
		
END
GO
PRINT N'Creating [sHrm].[pEmployeeCustomFieldFieldAdd]...';


GO
CREATE PROCEDURE [sHrm].[pEmployeeCustomFieldFieldAdd]
	  
	@rEmployeeId bigint=0,
	@rStrXml nvarchar(max) 
		
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
		
	
	UPDATE sHrm.tEmployeeCustomFieldData 
			SET 
				EmployeeCustomFieldId=A.EmployeeCustomFieldId,
				FieldData=A.FieldData,				
				UpdatedUserId=A.UpdatedUserId,
				UpdatedDateTime=sCommon.fGetDate()
			FROM (
			SELECT
				EmployeeCustomFieldId,FieldData,UpdatedUserId,EmployeeId,AutoId	
				FROM OPENXML (@loDoc, '/Table/EmployeeCustomField', 1)
			WITH
			(
				AutoId int '@AutoId',		
				EmployeeId Bigint '@EmployeeId',
				EmployeeCustomFieldId INT '@EmployeeCustomFieldId',
				FieldData nvarchar(max) '@FieldData',
				CreatedUserId bigint,
				UpdatedUserId bigint
			))A 
			INNER JOIN sHrm.tEmployeeCustomFieldData ECM ON  ECM.EmployeeId=A.EmployeeId AND ECM.AutoID=A.AutoId 
	
	
	  INSERT INTO sHrm.tEmployeeCustomFieldData
		(
		    
			EmployeeId,
			EmployeeCustomFieldId,
			FieldData,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime
		)
		SELECT
				A.EmployeeId,A.EmployeeCustomFieldId,A.FieldData,A.CreatedUserId,sCommon.fGetDate(),A.UpdatedUserId,sCommon.fGetDate()	
				FROM OPENXML (@loDoc, '/Table/EmployeeCustomField', 1)
			WITH
			(		
			    AutoId int '@AutoId',		
				EmployeeId Bigint '@EmployeeId',
				EmployeeCustomFieldId INT '@EmployeeCustomFieldId',
				FieldData nvarchar(max) '@FieldData',
				CreatedUserId bigint,
				UpdatedUserId bigint
			)A 
			LEFT JOIN sHrm.tEmployeeCustomFieldData ECM ON ECM.EmployeeId=A.EmployeeId AND ECM.AutoID=A.AutoId 
			WHERE ECM.EmployeeId IS NULL 
			
	
		
	SELECT 1 As Result
	END TRY
	BEGIN CATCH 
	SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sHrm].[pEmployeeMasterListingBatchWiseGet]...';


GO
 
 
CREATE PROCEDURE [sHrm].[pEmployeeMasterListingBatchWiseGet]
(
	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rName [nvarchar](50) = '',	
	@rSurName[nvarchar](50) = '',
	@rEmployeeTypeId int = 0,
	@rStatusId int = 0,
	@rDepartmentId int = 0,
	@rOrgGroupId int = 0,
	@rUserId bigint=0,
	@rFilterId smallint = 0,
	@rIsOtherUser smallint = 0,
	@rBatchId int = 0
 )
AS
SET NOCOUNT ON

BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rName = sCommon.fSearchStringGet(@rName)
		SET @rSurName = sCommon.fSearchStringGet(@rSurName)
 	
		IF @rFilterId = 0
		BEGIN
		SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				OM.DisplayTitle,
				OM.Id AS OrgId
		FROM 
				sHrm.tEmployeeMaster EM			
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017
			INNER JOIN [sHrm].[tEmployeeBatch] EB ON EB.EmployeeId=EM.Id
			--AND U.UserId = EM.Id
		WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
			AND	((EB.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((EM.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			AND ((U.UserId = @rUserId) OR (ISNULL(@rUserId,0) = 0))
			AND ((ISNULL(EM.IsOtherUser,0) = @rIsOtherUser))
			--AND ISNULL(EM.IsOtherUser,0) = 0 
			 
		Order By EM.Number
		
		END
		ELSE
		BEGIN
		SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				OM.DisplayTitle,
				OM.Id AS OrgId
		FROM 
				sHrm.tEmployeeMaster EM				
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017
			INNER JOIN [sHrm].[tEmployeeBatch] EB ON EB.EmployeeId=EM.Id
			--AND U.UserId = EM.Id
		WHERE 
			((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
			AND	((EB.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((EM.Code Like @rCode + '%') OR (@rCode = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			AND ((U.UserId = @rUserId) OR (ISNULL(@rUserId,0) = 0))
			AND (EM.ID NOT IN (SELECT ID FROM sHrm.tBatchEmployeeMaster))
			AND ((ISNULL(EM.IsOtherUser,0) = @rIsOtherUser))
			--AND ISNULL(EM.IsOtherUser,0) = 0 
		Order By EM.Number
		END	
END
GO
PRINT N'Creating [sHrm].[pEmployeeMasterListingImportAdd]...';


GO
 
 
CREATE PROCEDURE [sHrm].[pEmployeeMasterListingImportAdd] --1101,0
(
	@rOrgId int=0,	
	@rEmployeeId bigint,	
	@rBatchId int,	
	@rDepartmentId int = 0,
	@rOrgGroupId int = 0,
	@rUserId bigint=0,
	@rStatusId int = 0,
	@rCode nvarchar(20) = '',
	@rIsObsolete bit = 0

 )
AS
SET NOCOUNT ON

BEGIN
		
	IF(@rEmployeeId=0)
	BEGIN
		DELETE FROM sHrm.tEmployeeBatch WHERE EmployeeId IN (
		SELECT EM.Id FROM 
				sHrm.tEmployeeMaster EM
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
				INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
				INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
				--AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
				--AND ((U.UserId = @rUserId) OR (ISNULL(@rUserId,0) = 0))	
				)
		INSERT INTO sHrm.tEmployeeBatch(EmployeeId,BatchId) 
			SELECT EM.Id,@rBatchId FROM 
				sHrm.tEmployeeMaster EM
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
				INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
				INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
				INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
				INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
				--AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
				--AND ((U.UserId = @rUserId) OR (ISNULL(@rUserId,0) = 0))	
	END
	ELSE IF EXISTS(SELECT 1 FROM sHrm.tEmployeeBatch WHERE EmployeeId=@rEmployeeId)
	BEGIN
		DELETE FROM sHrm.tEmployeeBatch WHERE EmployeeId = @rEmployeeId
		INSERT INTO sHrm.tEmployeeBatch(EmployeeId,BatchId) VALUES (@rEmployeeId,@rBatchId)
	END
	ELSE
	BEGIN
		INSERT INTO sHrm.tEmployeeBatch(EmployeeId,BatchId) VALUES (@rEmployeeId,@rBatchId)
	END
		
END
GO
PRINT N'Creating [sHrm].[pEmployeeMasterListingImportGet]...';


GO
 
 
CREATE PROCEDURE [sHrm].[pEmployeeMasterListingImportGet] --1101,0
(
	@rOrgId smallint,	
	@rCode [nvarchar](20) = '',
	@rName [nvarchar](50) = '',	
	@rSurName[nvarchar](50) = '',
	@rEmployeeTypeId int = 0,
	@rStatusId int = 0,
	@rDepartmentId int = 0,
	@rOrgGroupId int = 0,
	@rUserId bigint=0,
	@rFilterId smallint = 0,
	@rIsOtherUser smallint = 0

 )
AS
SET NOCOUNT ON

BEGIN
		
	SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				--EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				--EJD.EmployeeGroupId,
				--OM.DisplayTitle,
				OM.Id AS OrgId
		FROM 
				sHrm.tEmployeeMaster EM
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			--AND	((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			--AND ((U.UserId = @rUserId) OR (ISNULL(@rUserId,0) = 0))
			 
		--ORDER BY EM.Number
		
END
GO
PRINT N'Creating [sHrm].[pEmployeeMasterListWithPhotoBatchWiseGet]...';


GO
 
 
 
CREATE PROCEDURE [sHrm].[pEmployeeMasterListWithPhotoBatchWiseGet]

	@rOrgId smallint,
	@rCode [nvarchar](20) = '',
	@rName [nvarchar](50) = '',	
	@rSurName[nvarchar](50) = '',
	@rEmployeeTypeId int = 0,
	@rStatusId int = 0,
	@rDepartmentId int = 0,
	@rUserId bigint=0,
	@rIsOtherUser smallint = 0,
	@rMultiCode nvarchar(max)='',
	@rIsEmployeePhoto bit=1,
	@rBatchId int = 0

AS
SET NOCOUNT ON

BEGIN
		SET @rCode = sCommon.fSearchStringGet(@rCode)
		SET @rName = sCommon.fSearchStringGet(@rName)
		SET @rSurName = sCommon.fSearchStringGet(@rSurName)
		--SELECT @rCode
		IF(@rIsEmployeePhoto =1)
			BEGIN
				SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				ISNULL(EI.EmployeePhoto, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto,
				OM.DisplayTitle,
				OM.Id As OrgId
		FROM 
				sHrm.tEmployeeMaster EM				
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017
			INNER JOIN [sHrm].[tEmployeeBatch] EB ON EB.EmployeeId=EM.Id
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId= EM.Id

		WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND	((EB.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((EM.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			AND U.UserId = @rUserId
			AND ((EM.IsOtherUser = @rIsOtherUser) OR (@rIsOtherUser = -1))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND (ISNULL(EM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,'.')) OR ISNULL(@rMultiCode,'')='')
			--Order By EM.Code	
			Order By EM.Number
			END
			ELSE
			BEGIN
				SELECT 
				EM.Id AS EmployeeId,
				EM.Code AS Code,
				ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name,
				ISNULL(ETM.Id,0) AS EmployeeTypeId,			
				ISNULL(ETM.Title,'') As EmployeeType,
				ISNULL(SM.Id,0) AS StatusId,
				ISNULL(SM.Title,'') AS Status,
				EJD.OrganizationDepartmentId,
				EJD.EmployeeGradeId,
				ODM.Title AS OrganizationDepartment,
				EM.IsObsolete AS IsObsolete,
				EJD.EmployeeGroupId,
				ISNULL(EI.EmployeeSign, CONVERT(VARBINARY(MAX), 0)) AS EmployeePhoto,
				OM.DisplayTitle,
				OM.Id As OrgId
		FROM 
				sHrm.tEmployeeMaster EM			
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
			INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EJD.OrganizationDepartmentId AND U.SourceTypeId=2017
			INNER JOIN [sHrm].[tEmployeeBatch] EB ON EB.EmployeeId=EM.Id
			LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId= EM.Id
		WHERE 
				((EM.OrgId = @rOrgId) OR (@rOrgId=0))
			AND	((EB.BatchId = @rBatchId) OR (@rBatchId=0))
			AND ((EM.Code Like @rCode + '%') OR (ISNULL(@rCode,'') = ''))
			AND ((EM.FirstName Like @rName  + '%') OR (@rName = ''))	 			 
			AND ((EM.LastName Like @rSurName + '%')OR(@rSurName = ''))
			AND ((EJD.OrganizationDepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))	
			AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))			
			AND ((EJD.EmployeeTypeId = @rEmployeeTypeId) OR (@rEmployeeTypeId = 0))	
			AND U.UserId = @rUserId
			AND ((EM.IsOtherUser = @rIsOtherUser) OR (@rIsOtherUser = -1))
			AND ISNULL(EM.IsOtherUser,0) = 0 
			AND (ISNULL(EM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,'.')) OR ISNULL(@rMultiCode,'')='')
			--Order By EM.Code	
			Order By EM.Number
			END
END
GO
PRINT N'Creating [sProcurement].[pRptStockIssueEmployee]...';


GO
 
CREATE PROCEDURE [sProcurement].[pRptStockIssueEmployee]
 
	@rId int = 0,
	@rStoreLocationId int = 0,
	@rMainGroupId int=0,
	@rSubGroupId int=0,
	@rItemCode nvarchar(50)='',
	@rItemName nvarchar(50)='',
	@rOrgGroupId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rStockItemCategoryId int=0,
	@rFromDate date='',
	@rTodate date='',
	@rToDepartmentId int =0,
	@rNumber nvarchar(10)='',
	@rEmployeeId bigint = 0,
	@rOrgId smallint = 0,
	@rBatchId int = 0
	
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

       SELECT  
			@rBuilder1 AS Builder1,
			SIM.Code AS ItemNumber,
			SIM.Title AS ItemName,		
			SI.IssuedByName,	
			SI.Number, 	
			SI.CreatedDateTime AS IssuedDate,
			ID.IssuedQuantity,
			ID.RequestedQuantity,
			EM.FirstName +' '+EM.MiddleName As EmployeeName,
			EM.Code AS EmployeeCode,
			SG.Code AS ItemSubGroup,
			SG.Id AS ItemSubGroupId,
			OM.DisplayTitle,
			EM.DepartmentName AS Department,
			(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
		    WHERE SB.StockItemId = SIM.Id 
		    AND ((SB.StorelocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
			) AS Quantity ,
			EM.OrgID,
			ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0') AS WeightedAverageCost
		FROM  
			sProcurement.tStockIssue SI		
			INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
			INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
			LEFT JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
			INNER JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId = SI.IssueToSourceId
			INNER JOIN sIp.tItemSubGroupMaster SG ON SG.Id=SIM.ItemSubGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgID
			 
		WHERE 
			 ((SI.Id = @rId) OR (@rId=0))
			 AND SI.FromStoreLocationId =@rStoreLocationId
			 AND ((SIM.ItemSubGroupId= @rSubGroupId) OR (@rSubGroupId=0))
			 AND ((SIM.Code = @rItemCode) OR (@rItemCode=''))	
			 AND ((SIM.Title = @rItemName) OR (@rItemName=''))
			 AND ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
			 AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
			 AND SI.OrgGroupId = @rOrgGroupId
			 AND ((SI.ToOrganizationDepartmentId=@rToDepartmentId) OR (@rToDepartmentId=0))
			 AND ((SI.Number like @rNumber) OR  (ISNULL(@rNumber,'')= ''))
			 AND ((SI.IssueToSourceId= @rEmployeeId) OR (ISNULL(@rEmployeeId,0)=0))
			 AND SI.IssueToSourceTypeId = 95
			 AND ((EM.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			 
END
GO
 
 
 
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('20.10.30',201030,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO