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

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


GO
ALTER TABLE [sAdmission].[tAdmissionForm]
    ADD [OriginalStudentPhoto] VARBINARY (MAX) NULL;


GO
PRINT N'Altering [sAdmission].[tAdmissionFormFamilyDetail]...';


GO
ALTER TABLE [sAdmission].[tAdmissionFormFamilyDetail]
    ADD [OriginalFatherPhoto]   VARBINARY (MAX) NULL,
        [OriginalMotherPhoto]   VARBINARY (MAX) NULL,
        [OriginalRelativePhoto] VARBINARY (MAX) NULL;


GO
PRINT N'Altering [sAssessment].[tStudentRemark]...';


GO
ALTER TABLE [sAssessment].[tStudentRemark] ALTER COLUMN [Achievements] NVARCHAR (1000) NULL;


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


GO
ALTER TABLE [sFee].[tReceiptBookMaster]
    ADD [IsDisplayPendingFeeAmount] BIT NULL;


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


GO
ALTER TABLE [sHrm].[tLeaveBalance]
    ADD [LastYearBalanceLeave] DECIMAL (8, 2) NULL,
        [CurrentBalanceLeave]  DECIMAL (8, 2) NULL;


GO
PRINT N'Altering [sStudent].[tStudentImages]...';


GO
ALTER TABLE [sStudent].[tStudentImages]
    ADD [OriginalStudentPhoto]  VARBINARY (MAX) NULL,
        [OriginalFatherPhoto]   VARBINARY (MAX) NULL,
        [OriginalMotherPhoto]   VARBINARY (MAX) NULL,
        [OriginalRelativePhoto] VARBINARY (MAX) NULL;


GO
PRINT N'Creating [siTax].[tForm16SubDetail]...';


GO
CREATE TABLE [siTax].[tForm16SubDetail] (
    [AutoId]                 BIGINT          IDENTITY (1, 1) NOT NULL,
    [Form16Id]               BIGINT          NOT NULL,
    [IncomeTaxSubSubgroupId] INT             NOT NULL,
    [GrossAmount]            DECIMAL (10, 2) NULL,
    [QualifyingAmount]       DECIMAL (10, 2) NULL,
    [DeductibleAmount]       DECIMAL (10, 2) NULL,
    [IsObsolete]             BIT             NOT NULL,
    [CreatedUserId]          BIGINT          NOT NULL,
    [CreatedDateTime]        DATETIME        NOT NULL,
    [UpdatedUserId]          BIGINT          NULL,
    [UpdatedDateTime]        DATETIME        NULL
);


GO
PRINT N'Creating PK_tForm16SubDetail...';


GO
ALTER TABLE [siTax].[tForm16SubDetail]
    ADD CONSTRAINT [PK_tForm16SubDetail] 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 UK_tForm16SubDetail...';


GO
ALTER TABLE [siTax].[tForm16SubDetail]
    ADD CONSTRAINT [UK_tForm16SubDetail] UNIQUE NONCLUSTERED ([Form16Id] ASC, [IncomeTaxSubSubgroupId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF) ON [PRIMARY];


GO
PRINT N'Creating [siTax].[tStaticIncomeTaxSubSubGroup]...';


GO
CREATE TABLE [siTax].[tStaticIncomeTaxSubSubGroup] (
    [Id]                        INT             NOT NULL,
    [StaticIncomeTaxSubGroupId] INT             NOT NULL,
    [SubSubGroupName]           NVARCHAR (250)  NOT NULL,
    [SubSubGroupCode]           NVARCHAR (50)   NOT NULL,
    [OrderIndex]                INT             NOT NULL,
    [SubSubGroupRemark]         NVARCHAR (250)  NOT NULL,
    [QualifyingLimit]           DECIMAL (10, 2) NULL,
    [IsEditable]                BIT             NULL
);


GO
PRINT N'Creating PK_tStaticIncomeTaxSubSubGroup...';


GO
ALTER TABLE [siTax].[tStaticIncomeTaxSubSubGroup]
    ADD CONSTRAINT [PK_tStaticIncomeTaxSubSubGroup] 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 [sSecurity].[tAssignSubRole]...';


GO
CREATE TABLE [sSecurity].[tAssignSubRole] (
    [AutoId]    BIGINT IDENTITY (1, 1) NOT NULL,
    [RoleId]    INT    NOT NULL,
    [SubRoleId] INT    NOT NULL
);


GO
PRINT N'Creating PK_tAssignSubRole...';


GO
ALTER TABLE [sSecurity].[tAssignSubRole]
    ADD CONSTRAINT [PK_tAssignSubRole] 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 UK_tAssignSubRole...';


GO
ALTER TABLE [sSecurity].[tAssignSubRole]
    ADD CONSTRAINT [UK_tAssignSubRole] UNIQUE NONCLUSTERED ([RoleId] ASC, [SubRoleId] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF) ON [PRIMARY];


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


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

 

GO
 
GO
PRINT N'Creating [sFee].[fPendingFeeAmountReceiptBookwiseGet]...';


GO
CREATE FUNCTION [sFee].[fPendingFeeAmountReceiptBookwiseGet] (@rAcademicId bigint,@rReceiptBookId int)
RETURNS decimal(12,0) WITH EXECUTE AS CALLER
AS 
BEGIN
    DECLARE @rReceiptAmount decimal(12,0),@lClassId int, @lDivisionId int, @lAdmissionCategoryId int, @rBatchId int, @rOrgId int, @rOrgGroupBatchId int
    SELECT @rOrgGroupBatchId=OrgGroupBatchId,@rOrgId=OrgId,@rBatchId=BatchId,@lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId = @rAcademicId
    
    (
    SELECT 
		@rReceiptAmount = SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))
    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			 
			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=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=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 
				
			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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND SA1.AcademicId = @rAcademicId
				AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId AND SA.AcademicId = @rAcademicId
		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.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND SA1.AcademicId = @rAcademicId
				AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId=0)
				GROUP BY FeeSetupId,R.SourceId
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0)) 
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			)
			
	RETURN @rReceiptAmount
END
GO
PRINT N'Altering [sHrm].[vEmployeeColumnName]...';


GO
 
 
ALTER VIEW [sHrm].[vEmployeeColumnName]  
  
AS  
  
SELECT 	
	   --EM.OrgId
    --  ,EM.Id AS EmployeeId
       EM.Code
      ,EM.FirstName
      ,EM.MiddleName
      ,EM.LastName
      ,ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name
      --,EM.StatusId
      ,SM.Title AS StatusName
      --,EM.IsObsolete
      --,EJD.Id AS EmployeeJobDetailId
      --,EJD.EmployeeDesignationId
      ,EDM.Title AS EmployeeDesignation
      --,EJD.OrganizationDepartmentId
      ,ODM.Title AS OrganizationDepartment
      ,EJD.DateOfJoining
      --,EJD.EPFNumber
      --,EJD.ESINumber
      --,EJD.EmployeeTypeId
      ,ETM.Title AS EmployeeType
      ,EGM.Title AS EmployeeGroup
      ,EJD.DateOfleaving
      ,EJD.ReasonOfleaving
      ,EJD.Subjects
      --,ELM.StreetOne
      --,ELM.StreetTwo
      --,ELM.StreetThree
      --,ELM.CityName
      --,ELM.StateName
      --,ELM.CountryName
      --,ELM.ZipCode
      --,ELM.PhoneNo
      --,ELM.FaxNo
      --,ELM.NameOfOccupier
      --,ELM.AddressOfOccupier
      --,ELM.SmallAddress1
      --,ELM.SmallAddress2
      --,ELM.RegistrationNumber
      --,ELM.LicenceNumber
      --,ELM.EsicNumber
      --,ELM.EsicAddress1
      --,ELM.EsicAddress2
      --,ELM.NatureOfIndustry
      --,ELM.ByProduct
      --,ELM.DangerousOperation
      --,ELM.NatureOfTest
      --,ELM.NatureOfTestNonHazardous
      --,ELM.RowMaterialUsed
      --,ELM.HazardousProcess
      --,ELM.Cmo
      --,ELM.NicNumber
      --,ELM.CountryId
      --,ELM.StateId
      --,EPD.Id AS EmployeePersonalDetailId
      ,EPD.UIDNumber
      ,EPD.DateOfBirth
      ,EPD.Qualification
      ,EPD.FamilyCast
      ,CCM.Title AS CastCategory
      --,EPD.GenderId
      ,GM.Title AS Gender
      --,EPD.ReligionId
      ,RM.Title AS Religion
      --,EPD.MaritalStatusId
      ,MSM.Title AS MaritalStatus
      ,EPD.IdentificationMark1
      --,EPD.BloodGroupId
      ,BGM.Title AS BloodGroup,
      EC.MobileNumber,
      EC.PersonalEmail
      ,EC.CompanyEmail
      ,EC.PhoneNoCompany
      ,EC.ExtensionNo
      ,EC.PresentStreetOne
      ,Ec.PresentStreetTwo
      ,Ec.PresentStreetThree
      ,Ec.PresentCountry
      ,Ec.PresentState
      ,Ec.PresentCity
      ,Ec.PresentZipCode
      ,Ec.PresentContactNo
      ,Ec.PermanentStreetOne
      ,Ec.PermanentStreetTwo
      ,Ec.PermanentStreetThree
      ,Ec.PermanentCountry
      ,Ec.PermanentState
      ,Ec.PermanentCity
      ,Ec.PermanentZipCode
      ,Ec.PermanentContactNo
      ,Ec.EmergencyStreetOne
      ,Ec.EmergencyStreetTwo
      ,Ec.EmergencyStreetThree
      ,Ec.EmergencyCountry
      ,Ec.EmergencyState
      ,Ec.EmergencyCity
      ,Ec.EmergencyZipCode
      ,Ec.EmergencyContactNo
      ,ES.EPFNumber
      ,ES.ESINumber
      ,ES.AccountNumber
      ,ES.BankName
      ,ES.Branch
      ,ES.IFSCNumber
      ,ES.PanNumber
      ,ES.BasicPay
      ,ES.IncrementDate
      ,ES.EPFJoinDate
      ,ISNULL(ES.Payscale,'') AS Payscale
      ,ISNULL(EPD.AdhaarNumber,'') AS AdhaarNumber
      ,ISNULL(ES.RetirementDate,'') AS RetirementDate
	  ,EM.Number
      ,ISNULL(EJD.ProbationUptoDate,'') As ProbationUptoDate
	  ,ISNULL(EJD.AhdocUptoDate,'') As AhdocUptoDate
	  ,ISNULL(EJD.PermanentDate,'') As PermanentDate
	  ,ISNULL(EJD.DateOfResignation,'') As DateOfResignation
	  ,STUFF( (SELECT DISTINCT ',' + CTM.Title FROM sHrm.tEmployeeCustomTag ECT INNER JOIN sHrm.tCustomTagMaster CTM ON ECT.CustomTagId=CTM.Id 
							WHERE ECT.EmployeeId = EM.Id FOR XML PATH ('')), 1, 1, '')  AS CustomTag
  FROM sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		--LEFT JOIN sHrm.tEmployeeJobTitleMaster EJTM ON EJTM.Id=EJD.EmployeeJobTitleId
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
		INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
		INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId = EM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = EPD.CastCategoryId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=EPD.GenderId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EPD.ReligionId
		LEFT JOIN sCommon.tMaritalStatusMaster MSM ON MSM.Id=EPD.MaritalStatusId
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=EPD.BloodGroupId
		--LEFT JOIN sHrm.tQualificationMaster QM ON QM.Id=EPD.HigestQualificationId
		INNER JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id = EJD.EmployeeTypeId
		INNER JOIN sCommon.tStatusMaster SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ES ON ES.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id = EJD.EmployeeGroupId
GO
PRINT N'Altering [sHrm].[vEmployeeCustomSearch]...';


GO


/*LEFT JOIN sHrm.tEmployeeCustomTag ECT ON EM.Id=ECT.EmployeeId*/
ALTER VIEW [sHrm].[vEmployeeCustomSearch]
AS
SELECT        EM.OrgID, EM.Id AS EmployeeId, EM.Code, EM.FirstName, EM.MiddleName, EM.LastName, ISNULL(EM.FirstName, '') + ' ' + ISNULL(EM.MiddleName, '') + ' ' + ISNULL(EM.LastName, '') AS Name, EM.StatusId, 
                         SM.Title AS StatusName, EM.IsObsolete, 0 AS EmployeeJobDetail, EJD.EmployeeDesignationId, EDM.Title AS EmployeeDesignation, EJD.OrganizationDepartmentId, ODM.Title AS OrganizationDepartment, 
                         CONVERT(VARCHAR(10), EJD.DateOfJoining, 111) AS DateOfJoining, EJD.EmployeeTypeId, ETM.Title AS EmployeeType, EGM.Title AS EmployeeGroup, CONVERT(VARCHAR(10), EJD.DateOfleaving, 111) AS DateOfleaving, 
                         EJD.ReasonOfleaving, EJD.Subjects, 0 AS EmployeePersonalDetailId, EPD.UIDNumber, CONVERT(VARCHAR(10), EPD.DateOfBirth, 111) AS DateOfBirth, EPD.GenderId, GM.Title AS Gender, EPD.ReligionId, RM.Title AS Religion, 
                         EPD.MaritalStatusId, MSM.Title AS MaritalStatus, EPD.IdentificationMark1, EPD.BloodGroupId, BGM.Title AS BloodGroup, EPD.Qualification, EPD.FamilyCast, CCM.Title AS CastCategory, EJD.EmployeeGroupId, 
                         EC.MobileNumber, EC.PersonalEmail, EC.CompanyEmail, EC.PhoneNoCompany, EC.ExtensionNo, EC.PresentStreetOne, EC.PresentStreetTwo, EC.PresentStreetThree, EC.PresentCountry, EC.PresentState, EC.PresentCity, 
                         EC.PresentZipCode, EC.PresentContactNo, EC.PermanentStreetOne, EC.PermanentStreetTwo, EC.PermanentStreetThree, EC.PermanentCountry, EC.PermanentState, EC.PermanentCity, EC.PermanentZipCode, 
                         EC.PermanentContactNo, EC.EmergencyStreetOne, EC.EmergencyStreetTwo, EC.EmergencyStreetThree, EC.EmergencyCountry, EC.EmergencyState, EC.EmergencyCity, EC.EmergencyZipCode, EC.EmergencyContactNo, 
                         ES.EPFNumber, ES.ESINumber, ES.AccountNumber, ES.BankName, ES.Branch, ES.IFSCNumber, ES.PanNumber, ES.BasicPay, CONVERT(VARCHAR(10), ES.IncrementDate, 111) AS IncrementDate, CONVERT(VARCHAR(10), 
                         ES.EPFJoinDate, 111) AS EPFJoinDate, ISNULL(ES.Payscale, '') AS Payscale, ISNULL(EPD.AdhaarNumber, '') AS AdhaarNumber, ISNULL(CONVERT(VARCHAR(50), ES.RetirementDate, 103), '') AS RetirementDate, 
                         ISNULL(EM.Number, 0) AS Number, CONVERT(VARCHAR(10), EJD.ProbationUptoDate, 111) AS ProbationUptoDate, CONVERT(VARCHAR(10), EJD.AhdocUptoDate, 111) AS AhdocUptoDate, CONVERT(VARCHAR(10), 
                         EJD.PermanentDate, 111) AS PermanentDate, CONVERT(VARCHAR(10), EJD.DateOfResignation, 111) AS DateOfResignation, EM.IsOtherUser,
						 (SELECT STUFF( (SELECT DISTINCT ',' + CTM.Title FROM sHrm.tEmployeeCustomTag ECT INNER JOIN sHrm.tCustomTagMaster CTM ON ECT.CustomTagId=CTM.Id 
							WHERE ECT.EmployeeId = EM.Id FOR XML PATH ('')), 1, 1, '')  AS CustomTag FROM sHrm.tEmployeeMaster EM1 WHERE EM1.Id = EM.Id GROUP BY EM1.Id) AS CustomTag
FROM            sHrm.tEmployeeMaster AS EM INNER JOIN
                         sHrm.tEmployeeJobDetail AS EJD ON EJD.EmployeeId = EM.Id LEFT OUTER JOIN
                         sHrm.tEmployeeDesignationMaster AS EDM ON EDM.Id = EJD.EmployeeDesignationId INNER JOIN
                         sSetup.tDepartmentMaster AS ODM ON ODM.Id = EJD.OrganizationDepartmentId INNER JOIN
                         sHrm.tEmployeePersonalDetail AS EPD ON EPD.EmployeeId = EM.Id LEFT OUTER JOIN
                         sCommon.tCastCategoryMaster AS CCM ON CCM.Id = EPD.CastCategoryId LEFT OUTER JOIN
                         sCommon.tGenderMaster AS GM ON GM.Id = EPD.GenderId LEFT OUTER JOIN
                         sCommon.tReligionMaster AS RM ON RM.Id = EPD.ReligionId LEFT OUTER JOIN
                         sCommon.tMaritalStatusMaster AS MSM ON MSM.Id = EPD.MaritalStatusId LEFT OUTER JOIN
                         sCommon.tBloodGroupMaster AS BGM ON BGM.Id = EPD.BloodGroupId INNER JOIN
                         sHrm.tEmployeeTypeMaster AS ETM ON ETM.Id = EJD.EmployeeTypeId INNER JOIN
                         sCommon.tStatusMaster AS SM ON SM.Id = EM.StatusId AND SM.StatusTypeId = 4 LEFT OUTER JOIN
                         sHrm.tEmployeeCommunications AS EC ON EC.EmployeeId = EM.Id LEFT OUTER JOIN
                         sHrm.tEmployeeStatutoryAndOther AS ES ON ES.EmployeeId = EM.Id LEFT OUTER JOIN
                         sHrm.tEmployeeGroupMaster AS EGM ON EGM.Id = EJD.EmployeeGroupId
GO
PRINT N'Altering [sStudent].[vStudentColumnName]...';


GO
 

/******************************************************************************  
 Purpose          : To get Batch Wise  Class
 Created date     : 21 Nov 2013
 Author           : Kundan Patel 
 Copyright©       : Copyright © Sapphire Software Solutions
 ******************************************************************************/  
ALTER VIEW [sStudent].[vStudentColumnName]  
  
AS 
 
 
SELECT 	
	  --SA.AcademicId,	  
	  --SA.ClassId,
	  --SA.DivisionId,
	  SA.RollNo,
	  --SA.OrgId,
	  --SA.BatchId,
	  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.FatherOfficeAddress,
	  SF.FatherIncome,
	  SF.MotherName,
	  SF.MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
      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
           
           
	  
  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
GO
PRINT N'Altering [sStudent].[vStudentCustomSearch]...';


GO
 

ALTER VIEW [sStudent].[vStudentCustomSearch]  
  
AS  
  
SELECT 	
	  SA.AcademicId,	  
	  SA.ClassId,
	  SA.DivisionId,
	  SA.RollNo,
	  SA.OrgId,
	  SA.BatchId,
	  BM.Title AS Batch,
	  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.MotherName,
	 CONVERT(VARCHAR(10),  SF.MotherDateOfBirth,111) AS MotherDateOfBirth,
	  SF.MotherQualification,
	  SF.MotherOccupation,
      SF.MotherContactNo,
      SF.MotherMail,
      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
     
	  	  	   
  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
GO

 
GO
PRINT N'Altering [sAdmission].[pAdmissionFormAdd]...';


GO

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

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

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

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


GO

ALTER PROCEDURE [sAdmission].[pAdmissionFormFamilyDetailAdd]
		 @rId bigint,
		 @rFatherName nvarchar(100),
		 @rFatherDateOfBirth date,
		 @rFatherOccupation nvarchar(50),
		 @rFatherQualification nvarchar(50),
		 @rFatherContactNo nvarchar(50),
		 @rFatherMail nvarchar(50),
		 @rFatherOfficeAddress nvarchar(300),
		 @rFatherIncome int,
		 
		 @rMotherName nvarchar(100),
		 @rMotherDateOfBirth date,
		 @rMotherOccupation nvarchar(50),
		 @rMotherQualification nvarchar(50),
		 @rMotherContactNo nvarchar(50),
		 @rMotherMail nvarchar(50),
		 @rMotherOfficeAddress nvarchar(300),
		 @rMotherIncome int,
		
		 @rRelationshipName nvarchar(100),
		 @rGuardianName nvarchar(100),
		 @rGuardianDateOfBirth date,
		 @rGuardianOccupation nvarchar(50),
		 @rGuardianQualification nvarchar(50),
		 @rGuardianContactNo nvarchar(50),
		 @rGuardianMail nvarchar(50),
		 @rGuardianOfficeAddress nvarchar(300),
		 @rGuardianIncome int,
		 @rCreatedUserId bigint,
		 @rCreatedDateTime date,
		 --@rUpdatedUserId bigint,
		 --@rUpdatedDateTime date,
		 @rFatherPhoto varbinary(max)=0,
		  @rMotherPhoto varbinary(max)=0,
		 @rGuardianPhoto varbinary(max)=0,
		 @rFatherOrganization nvarchar(200)='',
		 @rFatherDesignation nvarchar(100)='',
		 @rFatherOfficePhone nvarchar(100)='',
		 @rMotherOrganization nvarchar(200)='',
		 @rMotherDesignation nvarchar(100)='',
		 @rMotherOfficePhone nvarchar(100)='',
		 @rRelativeOrganization nvarchar(200)='',
		 @rRelativeDesignation nvarchar(100)='',
		 @rRelativeOfficePhone nvarchar(100)='',
		 @rLiveWithId smallint=0,
		 @rIsFatherExStudent bit=0,
		 @rFatherPassOutYear nvarchar(50)='',
		 @rIsMotherExStudent bit=0,
		 @rMotherPassOutYear nvarchar(50)='',
		 @rIsRelativeExStudent bit=0,
		 @rRelativePassOutYear nvarchar(50)='',
		 @rFatherAdhaarNumber nvarchar(50),
		 @rOriginalFatherPhoto varbinary(max),
		 @rOriginalMotherPhoto varbinary(max),
		 @rOriginalRelativePhoto varbinary(max)
		 
		 
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	

	
 BEGIN TRANSACTION	
	
	IF NOT EXISTS (Select AdmissionFormId from sAdmission.tAdmissionFormFamilyDetail where AdmissionFormId = @rId)
	BEGIN
	INSERT INTO sAdmission.tAdmissionFormFamilyDetail
		(
		AdmissionFormId,
		 FatherName,
		 FatherDateOfBirth,
		 FatherOccupation,
		 FatherQualification,
		 FatherContactNo,
		 FatherAdhaarNumber,
		 FatherMail,
		 FatherOfficeAddress,
		 FatherIncome,
		 MotherName,
		 MotherDateOfBirth,
		 MotherOccupation,
		 MotherQualification,
		 MotherContactNo,
		 MotherMail,
		 MotherOfficeAddress,
		 MotherIncome,
		 
		 RelationshipName,
		 RelativeName,
		 RelativeDateOfBirth,
		 RelativeOccupation,
		 RelativeQualification,
		 RelativeContactNo,
		 RelativeMail,
		 RelativeOfficeAddress,
		 RelativeIncome,
		 CreatedUserId,
		 CreatedDateTime,
		 FatherPhoto,
		 MotherPhoto,
		 RelativePhoto,
		 FatherOrganization,
		 FatherDesignation,
		 FatherOfficePhone,
		 MotherOrganization,
		 MotherDesignation,
		 MotherOfficePhone,
		 RelativeOrganization,
		 RelativeDesignation,
		 RelativeOfficePhone,
		 LiveWithId,
		 IsFatherExStudent,
		 FatherPassOutYear,
		 IsMotherExStudent,
		 MotherPassOutYear,
		 IsRelativeExStudent,
		 RelativePassOutYear,
		 OriginalFatherPhoto,
		 OriginalMotherPhoto,
		 OriginalRelativePhoto
		)
	VALUES
		(
	     @rId,
		 @rFatherName,
		 @rFatherDateOfBirth,
		 @rFatherOccupation,
		 @rFatherQualification,
		 @rFatherContactNo,
		 @rFatherAdhaarNumber,
		 @rFatherMail,
		 @rFatherOfficeAddress,
		 @rFatherIncome,
		 
		 @rMotherName,
		 @rMotherDateOfBirth,
		 @rMotherOccupation,
		 @rMotherQualification,
		 @rMotherContactNo,
		 @rMotherMail,
		 @rMotherOfficeAddress,
		 @rMotherIncome,
		 
		 @rRelationshipName,
		 @rGuardianName,
		 @rGuardianDateOfBirth,
		 @rGuardianOccupation,
		 @rGuardianQualification,
		 @rGuardianContactNo,
		 @rGuardianMail,
		 @rGuardianOfficeAddress,
		 @rGuardianIncome,
		 
		 @rCreatedUserId,
		 @rCreatedDateTime,
		 
		 @rFatherPhoto,
		 @rMotherPhoto,
		 @rGuardianPhoto,
		 @rFatherOrganization,
		 @rFatherDesignation,
		 @rFatherOfficePhone,
		 @rMotherOrganization,
		 @rMotherDesignation,
		 @rMotherOfficePhone,
		 @rRelativeOrganization,
		 @rRelativeDesignation,
		 @rRelativeOfficePhone,
		 @rLiveWithId,
		 @rIsFatherExStudent,
		 @rFatherPassOutYear,
		 @rIsMotherExStudent,
		 @rMotherPassOutYear,
		 @rIsRelativeExStudent,
		 @rRelativePassOutYear,
		 @rOriginalFatherPhoto,
		 @rOriginalMotherPhoto ,
		 @rOriginalRelativePhoto 
		  
		)
		             
	END	 
	 ELSE
	 BEGIN

	    UPDATE  sAdmission.tAdmissionFormFamilyDetail
	    SET

	     AdmissionFormId = @rId,
		 FatherName = @rFatherName,
		 FatherDateOfBirth = @rFatherDateOfBirth,
		 FatherOccupation = @rFatherOccupation,
		 FatherQualification = @rFatherQualification,
		 FatherContactNo = @rFatherContactNo,
		 FatherAdhaarNumber = @rFatherAdhaarNumber,
		 FatherMail = @rFatherMail,
		 FatherOfficeAddress = @rFatherOfficeAddress,
		 FatherIncome = @rFatherIncome,
		 MotherName = @rMotherName,
		 MotherDateOfBirth = @rMotherDateOfBirth,
		 MotherOccupation = @rMotherOccupation,
		 MotherQualification = @rMotherQualification,
		 MotherContactNo = @rMotherContactNo,
		 MotherMail = @rMotherMail,
		 MotherOfficeAddress = @rMotherOfficeAddress,
		 MotherIncome = @rMotherIncome,
		 RelationshipName = @rRelationshipName,
		 RelativeName = @rGuardianName,
		 RelativeDateOfBirth = @rGuardianDateOfBirth,
		 RelativeOccupation = @rGuardianOccupation,
		 RelativeQualification = @rGuardianQualification,
		 RelativeContactNo = @rGuardianContactNo,
		 RelativeMail = @rGuardianMail,
		 RelativeOfficeAddress = @rGuardianOfficeAddress,
		 RelativeIncome = @rGuardianIncome,
		 UpdatedUserId = @rCreatedUserId,
		 UpdatedDateTime = sCommon.fGetDate(),
		 FatherPhoto = @rFatherPhoto,
		 MotherPhoto = @rMotherPhoto,
		 RelativePhoto = @rGuardianPhoto,
		 FatherOrganization=@rFatherOrganization,
	      FatherDesignation =@rFatherDesignation,
	      FatherOfficePhone=@rFatherOfficePhone,
	      MotherOrganization=@rMotherOrganization,
	      MotherDesignation=@rMotherDesignation,
	    MotherOfficePhone=@rMotherOfficePhone,
	    RelativeOrganization=@rRelativeOrganization,
	    RelativeDesignation=@rRelativeDesignation,
	    RelativeOfficePhone=@rRelativeOfficePhone ,
	    LiveWithId=@rLiveWithId,
	    IsFatherExStudent =@rIsFatherExStudent ,
	    FatherPassOutYear = @rFatherPassOutYear,
	    IsMotherExStudent = @rIsMotherExStudent,
	    MotherPassOutYear = @rMotherPassOutYear,
	    IsRelativeExStudent =@rIsRelativeExStudent,
	    RelativePassOutYear = @rRelativePassOutYear,
	    OriginalFatherPhoto = @rOriginalFatherPhoto,
		OriginalMotherPhoto = @rOriginalMotherPhoto,
		OriginalRelativePhoto = @rOriginalRelativePhoto
	    
			
	      WHERE AdmissionFormId = @rId 	   
	 END  
		SELECT @rId AS Result
	
		COMMIT TRANSACTION
		
	
	
		
END
GO
PRINT N'Altering [sAdmission].[pAdmissionInquiryGet]...';


GO

ALTER PROCEDURE [sAdmission].[pAdmissionInquiryGet]
	
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rId bigint = 0,
	 
	 @rForClassId int = 0,
	 @rClassId int = 0,
	 @rBatchId int = 0,
	 @rStatusId int =0,
	-- @rStatusId smallint,
	 @rInquiryStatusMasterId int = 0,
	 @rOrgId int,
	 @rFirstName nvarchar(100) = '',
	 @rLastName nvarchar(100) = '',
	 @rFromDate datetime='',
	 @rToDate datetime='',
	 @rForBatchId int = 0,
	 @rDepartmentId int,
	 @rFromMeritMarks decimal(10,2) = 0,
	 @rToMeritMarks decimal(10,2)=0,
	 @rInquiryModeId smallint=0,
	 @rInquiryReferenceId int=0,
	 @rNumber bigint=0,
	 @rOrgGroupBatchId int = 0,
	 @rFollowUpdate datetime='',
	 @rIsTransportRequired int=0,
	 @rIsHostelRequired int=0,
	 @rOrderBy int =0,
	 @rIsGivenAdmissionForm int =0,
	 @rContactNo nvarchar(100)=''
	  --@rIsGivenAdmissionFormNew int =0
	 --@rIsSearch bit = 1
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	IF(@rIsGivenAdmissionForm=1)
		SET @rIsGivenAdmissionForm = 1
  	IF(@rIsGivenAdmissionForm=2)
		SET @rIsGivenAdmissionForm =0
	 
	 
	 SET @rToDate = DATEADD(d,1,@rToDate)
	 --IF @rIsSearch = 1
		BEGIN
			SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName= sCommon.fSearchStringGet(@rLastName)
			--SET @rContactNo= sCommon.fSearchStringGet(@rContactNo)
		END
	
	SELECT 
	
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			 AI.Id
			,AI.ForBatchId
			,AI.ForClassId
			,AI.StatusId
			,ISNULL(SM.Id,0) AS InquiryStatusMasterId
			,ISNULL(AI.GenderId,0) AS GenderId
			,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
			,ISNULL(IMM.Title,'') AS InquiryMode
			,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		    ,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		    ,AI.OrgId
		    ,ISNULL(AI.Number,0) AS InquiryNumber
		    ,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		    ,OM.DisplayTitle AS OrgName
		    ,BM.Title AS ForBatch
			,ISNULL(CM.Title,'') AS ClassName	
			,AI.FirstName
			,AI.MiddleName
			,AI.LastName
			,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
			,ISNULL(AI.DateOfBirth,'') As DateOfBirth
			,ISNULL(GM.Title,'') As Gender			
			,AI.ContactNo
			,AI.ContactEmail			
			,AI.StreetOne
			,AI.StreetTwo
			,AI.StreetThree
			,AI.Country
			,AI.State
			,AI.City
			,AI.ZipCode
			,ISNULL(AI.Remark,'') AS Remark						
		    ,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
			,ISNULL(AI.MeritMarks,0) AS MeritMarks
			,ISNULL(AI.MeritGrade,'') AS MeritGrade
			,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
			,SM.Title as StatusName	
			--,cast(replace(FollowupDate,'/','-') as date) As FollowupDate
			,ISNULL(AI.FollowupDate,'') As FollowupDate
			,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
			,ISNULL(IRM.Title ,'') AS InquiryReference	
			,ISNULL(SCM.Title,'') AS AdmissionCategory		
			,ISNULL(AI.HandledBy,'') AS HandledBy
			,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
			,ISNULL(AI.StudentId,0) AS StudentId,
			ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
			ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
			ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
			CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
			--ISNULL(AI.IsGivenAdmissionForm,0) AS IsGivenAdmissionForm,
			ISNULL(SM.HighlightColor,'') AS HighlightColor,
			ISNULL(SA.PreviousStandard,'') As PreviousStandard,
			AI.AlternateContactNo,
			AI.AlternateContactEmail
			,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString
  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
           --INNER JOIN sCommon.tStatusMaster SM ON SM.Id=AI.StatusId AND StatusTypeId=104
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  --AND ((AI.StatusId=@rStatusId) OR (@rStatusId=0))
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  
	  AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=0)OR (@rIsGivenAdmissionForm=-1))

	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	  
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1
                         END)
	 --AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
      --AND (AI.IsGivenAdmissionForm = CASE @rIsGivenAdmissionForm WHEN 0 THEN ISNULL(AI.IsGivenAdmissionForm,0) WHEN 2 THEN 1 WHEN 1 THEN 0 END)
	 AND ((AI.ContactNo = @rContactNo) OR (@rContactNo=''))
	  --AND ((AI.IsTransportRequired=@rIsTransportRequired) OR (@rIsTransportRequired=0))	   
	    --AND ((AI.IsHostelRequired =@rIsHostelRequired) OR (@rIsHostelRequired=0))
	  Order by Case @rOrderBy When 1 then AI.MeritMarks END desc ,
			    Case @rOrderBy when 0 then AI.Number Else 
			    AI.Number  END  
			    
END
GO
PRINT N'Altering [sAlert].[pAppNotificationGet]...';


GO
ALTER PROCEDURE [sAlert].[pAppNotificationGet]     
   
 @rOSTypeId tinyint,  
 @rEventId int,  
 @rSourceTypeId smallint,  
 @rFromDate date,  
 @rToDate date,  
 @rCode nvarchar(max),  
 @rReceiverSourceTypeId int,
 @rOrgGroupId int = 0
  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
  
BEGIN  
  
IF(@rCode IS NULL OR @rCode='')  
BEGIN  
 IF(@rReceiverSourceTypeId=2003)  
 BEGIN   
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.SourceTypeId=@rReceiverSourceTypeId    
   AND OM.OrgGroupId=@rOrgGroupId
   ORDER BY NL.CreatedDateTime DESC  
 END   
 ELSE IF(@rReceiverSourceTypeId=95)  
 BEGIN   
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   tEM.Code AS Code    
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId 
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND NL.SourceTypeId=@rReceiverSourceTypeId
   AND ISNULL(tEM.IsOtherUser,0) = 0  
   AND OM.OrgGroupId=@rOrgGroupId   
   ORDER BY NL.CreatedDateTime DESC  
 END  
 ELSE  
 BEGIN   
   SELECT DISTINCT * From
   (SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   SA.Code AS Code     
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId 
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId 
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND NL.SourceTypeId=2003
   AND OM.OrgGroupId=@rOrgGroupId
   
   UNION 
   
   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   tEM.Code AS Code    
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')='')) 
   AND NL.SourceTypeId=95
   AND OM.OrgGroupId=@rOrgGroupId
    AND ISNULL(tEM.IsOtherUser,0) = 0
    
  -- UNION 
   
  -- SELECT   
  -- NL.Id,  
  -- NL.CreatedDateTime AS Date,  
  -- OT.Title AS OSType,  
  -- 'Custom Alert' AS EventName,  
  -- ST.Title AS SourceType,  
  -- NL.MessageTitle,  
  -- NL.NotificationMessage AS Message,
  -- '' AS Code    
     
  --FROM  
  -- sAlert.tNotificationLog NL    
  -- INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
  -- INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
  -- INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId 
  -- INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LEFT(NL.Id,4)
  --WHERE  
  -- ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
  -- AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
  -- AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
  -- AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
  -- AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
  -- AND OM.OrgGroupId=@rOrgGroupId
   
   UNION 
   
   SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,
   '' AS Code    
     
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LEFT(NL.Id,4)  
   
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))    
   AND OM.OrgGroupId=@rOrgGroupId
   AND (NL.SourceTypeId!=2003 AND NL.SourceTypeId!=95)
   )AS tmp
   
   ORDER BY tmp.Date DESC 
 END  
END  
ELSE  
BEGIN  
 IF(@rReceiverSourceTypeId=95)  
 BEGIN  
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,  
   tEm.Code AS Code  
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=NL.SourceId AND NL.SourceTypeId=@rReceiverSourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId  
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='')     
   AND ISNULL(tEM.IsOtherUser,0) = 0
   AND OM.OrgGroupId=@rOrgGroupId
   ORDER BY NL.CreatedDateTime DESC   
  END   
  Else IF(@rReceiverSourceTypeId=2003)  
  BEGIN   
     
  SELECT   
   NL.Id,  
   NL.CreatedDateTime AS Date,  
   OT.Title AS OSType,  
   EM.Title AS EventName,  
   ST.Title AS SourceType,  
   NL.MessageTitle,  
   NL.NotificationMessage AS Message,  
   SA.Code AS Code
  FROM  
   sAlert.tNotificationLog NL    
   INNER JOIN sAlert.tOSType OT ON OT.ID =NL.OSTypeId  
   INNER JOIN sAlert.tEventMaster EM ON EM.Id=NL.EventId  
   INNER JOIN sCommon.tSourceTypeMaster ST ON ST.Id=NL.SourceTypeId  
   INNER JOIN sStudent.tStudentMaster SA ON SA.Id=NL.SourceId AND NL.SourceTypeId=@rReceiverSourceTypeId
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId  
  WHERE  
   ((NL.OSTypeId=@rOSTypeId) OR (@rOSTypeId=0))  
   AND ((NL.EventId=@rEventId) OR (@rEventId=0))  
   AND ((NL.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))    
   AND ((CONVERT(date,NL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
   AND ((CONVERT(date,NL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
   AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')   
   AND OM.OrgGroupId=@rOrgGroupId
  
  ORDER BY NL.CreatedDateTime DESC  
 END  
END
END
GO
PRINT N'Altering [sAlert].[pFeeDueGet]...';


GO
ALTER PROCEDURE [sAlert].[pFeeDueGet]

		 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rReceiptBookId int,
	 	 @rToDate date,
	 	 @rMailSubject nvarchar(500)='',
	 	 @rAdmissionCategoryId int=0,
	 	 @rIdNos nvarchar(500)='',
		 @rDepartmentId int=0,
		 @rCollectionGroupId int=0
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	CREATE TABLE #TempOptional (
		Id int,
		Amount decimal(12,2),
		StartDate date,
		EndDate date,
		ReceiptBookId int,
		AcademicId bigint
	)
	
	CREATE TABLE #TempReceipt (
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint
	)
	
	INSERT INTO #TempOptional
	SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=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 ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			
			UNION ALL

			SELECT 
				FS1.Id,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId
			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 SA1.BatchId = FS1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=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 ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))

	
	INSERT INTO #TempReceipt
	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 sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.ClassId=@rClassId OR @rClassId=0) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0) 
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND (SA1.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
				AND ((SA1.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND ((R.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))
			GROUP BY 
				FeeSetupId,R.SourceId
	
	SELECT 
		D.AcademicId,
		D.RollNo,
		D.Name,
		D.Code,
		D.MobileNo,	
		D.EmailId,
		D.StudentContactNo,
		D.StudentEmail,
		D.FatherContactNo,
		D.FatherMail,
		D.MotherContactNo,
		D.MotherMail,
		SUM(D.PendingAmount) As PendingAmount,
		REPLACE (
		REPLACE(REPLACE(REPLACE(@rTemplate,'[Name]',D.Name),
		'[Class]',D.ClassName),
		'[Division]',D.DivisionName),
		'[PendingAmount]',CONVERT(int,(SUM(D.PendingAmount))))
		AS Template,
		@rMailSubject AS [Subject]
	FROM
	(
	SELECT
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.ClassName,
		SA.DivisionName,
		SA.Code,
		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,
		SA.DivisionOrder,
		((ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00))-((ISNULL(FA.NotApplicableAmount,0.00) + ISNULL(FA.DiscountAmount,0.00)+ISNULL(R.PaidAmount,0.00))))  AS PendingAmount
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN  #TempOptional FS ON FS.AcademicId=SA.AcademicId 
		LEFT JOIN sFee.tFeeAllocation FA
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #TempReceipt	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  sStudent.vStudentCommunication SC ON SC.AcademicId = SA.AcademicId
	WHERE	
		SA.StatusId = 1 AND SC.IsBlockAllAlert=0 
		AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
		AND ((FS.StartDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		
		AND ((ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00)) - (ISNULL(FA.DiscountAmount,0.00)+ISNULL(FA.NotApplicableAmount,0.00)+ISNULL(R.PaidAmount,0.00)) >0)			
		AND (SA.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		AND (SC.Code IN (SELECT item from sCommon.fnSplit(@rIdNos, ',')) OR ISNULL(@rIdNos,'')='')
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		
		) D
	GROUP BY 
		D.AcademicId,D.RollNo,D.Name,D.ClassName,D.DivisionName,D.Code,
		D.MobileNo,D.EmailId,D.StudentContactNo,D.StudentEmail,D.FatherContactNo,D.FatherMail,D.MotherContactNo,D.MotherMail,D.DivisionOrder
	ORDER BY 
		D.DivisionOrder,D.Rollno	

	DROP TABLE #TempOptional
	DROP TABLE #TempReceipt
END
GO
PRINT N'Altering [sAlert].[pFeeReceiptEntryGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pFeeReceiptEntryGet]
	 	 
	 	 @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)='',
	 	 @rIsObsolete bit=0,
		 @rCollectionGroupId int = 0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	IF CHARINDEX('[PendingAmount]',@rTemplate) > 0   
	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)),
				'[PendingAmount]',ISNULL([sFee].[fPendingFeeAmountForAlertGet](SC.AcademicId),0))
				 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=@rIsObsolete
				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
	ELSE
	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(@rTemplate,'[Name]',SC.Name),
				'[Class]',SC.ClassName),
				'[Division]',SC.DivisionName),
				'[ReceiptNumber]',R.ReceiptNumber),
				'[ReceiptDate]',convert(varchar,R.ReceiptDate,103)),
				'[PaidAmount]',convert(int,R.ReceiptAmount))
				 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=@rIsObsolete
				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
	
	
	
END
GO
PRINT N'Altering [sAlert].[pOnlineAdmissionGet]...';


GO

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

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

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

END
GO
PRINT N'Altering [sAlert].[pSMSHistoryGet]...';


GO
ALTER PROCEDURE [sAlert].[pSMSHistoryGet]
	
	@rOrgId smallint,
	@rStatusId int,
	@rContactId nvarchar(50),
	@rEventId int,
	@rSourceEvent nvarchar(50),
	@rUserName nvarchar(100),
	@rAlertModeId tinyint,
	@rFromDate date,
	@rToDate date,
	@rOrgGroupId int,
	@rCode nvarchar(max),
	@rReceiverSourceTypeId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF(@rCode IS NULL OR @rCode='')
BEGIN
	IF(@rReceiverSourceTypeId=0)
	BEGIN	
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId) 
			ORDER BY AL.CreatedDateTime DESC
	END	
	
	ELSE IF(@rReceiverSourceTypeId=2003)
	BEGIN	
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId	
			
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)	
			ORDER BY AL.CreatedDateTime DESC
	END
	ELSE IF(@rReceiverSourceTypeId=95)
	BEGIN	
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 					
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			AND (AL.ReceiverSourceTypeId=@rReceiverSourceTypeId)	
			ORDER BY AL.CreatedDateTime DESC
	END
	ELSE 
	BEGIN
		SELECT DISTINCT tmp1.* From(
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				SA.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=2003			
			AND OM.OrgGroupId = @rOrgGroupId	
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId 
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND AL.ReceiverSourceTypeId=2001
		AND OM.OrgGroupId = @rOrgGroupId		
	
	UNION
	SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				tEM.Code AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 	
			Left JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId 
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND AL.ReceiverSourceTypeId=95			
			AND OM.OrgGroupId = @rOrgGroupId	
		
		UNION
		
		SELECT 
				AL.Id AS Id,
				AL.ContactId,
				AL.AlertMessage,
				AL.AlertSubject,
				CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
				--AL.ResultMessage
				EM.Title AS EventName,
				AL.SourceEvent,
				U.DisplayTitle AS UserName,
				AL.CreatedDateTime,
				OM.Id AS OrgId,
				OM.DisplayTitle AS Organization,
				'' AS Code				
		FROM
				sAlert.tAlertLog AL
			INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
			LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 		
		WHERE
				((AL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
			AND ((AL.EventId=@rEventId) OR (@rEventId=0))
			AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
			AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
			AND ((U.DisplayTitle like @rUserName) OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND OM.OrgGroupId = @rOrgGroupId	
			
			--AND (AL.ReceiverSourceTypeId NOT IN (95,2001,2003))
			
			AND ((AL.ReceiverSourceTypeId=0 OR @rReceiverSourceTypeId=0))	
			--ORDER BY AL.CreatedDateTime DESC	
	
	)AS tmp1				
			ORDER BY tmp1.CreatedDateTime DESC
	END
END

ELSE
BEGIN
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			tEM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((tEM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
		
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SM.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tAcademic A ON A.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SM.Code LIKE @rCode) OR ISNULL(@rCode,'')='') 
	
	UNION
	
	SELECT 
			AL.Id AS Id,
			AL.ContactId,
			AL.AlertMessage,
			AL.AlertSubject,
			CASE WHEN AL.ResultMessage='' THEN 'Pending' ELSE AL.ResultMessage END AS ResultMessage,
			--AL.ResultMessage
			EM.Title AS EventName,
			AL.SourceEvent,
			U.DisplayTitle AS UserName,
			AL.CreatedDateTime,
			OM.Id AS OrgId,
			OM.DisplayTitle AS Organization,
			SA.Code AS Code
	FROM
			sAlert.tAlertLog AL
		INNER JOIN sAlert.tEventMaster EM ON EM.Id=AL.EventId
		LEFT JOIN sSecurity.tUser U ON U.Id=AL.CreatedUserId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AL.OrgId 
		INNER JOIN sStudent.tStudentMaster SA ON SA.Id=AL.ReceiverSourceId AND AL.ReceiverSourceTypeId=@rReceiverSourceTypeId
	WHERE
			((AL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND	((AL.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((AL.ContactId=@rContactId) OR (ISNULL(@rContactId,'')=''))
		AND ((AL.EventId=@rEventId) OR (@rEventId=0))
		AND ((AL.SourceEvent=@rSourceEvent) OR (ISNULL(@rSourceEvent,'')=''))
		AND ((AL.AlertModeId=@rAlertModeId) OR (@rAlertModeId=0))
		AND ((U.DisplayTitle like @rUserName) OR (ISNULL(@rUserName,'')='') OR (U.DisplayTitle IS NULL) OR (ISNULL(U.DisplayTitle,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((CONVERT(date,AL.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND OM.OrgGroupId = @rOrgGroupId
		AND ((SA.Code LIKE @rCode) OR ISNULL(@rCode,'')='')
END		
		
--SELECT DISTINCT OM.Title, D.Code,OM.OrderIndex,D.OrderIndex FROM sSetup.tDivisionMaster D
--INNER JOIN ssetup.tOrganizationMaster OM
--ON D.OrgId = OM.Id
--WHERE D.Id IN
--(
--select DivisionId from sStudent.tAcademic A INNER JOIN
--sStudent.tStudentCommunication SC ON A.StudentId = SC.StudentId
--INNER JOIN SAlert.tAlertLog AL ON SC.ParentContactNo = AL.ContactId
--AND AL.OrgId IN (SELECT Id From sSetup.tOrganizationMaster WHERE OrgGroupId = 1141 )
--AND AL.AlertModeId = 2)
--order by  OM.OrderIndex,D.OrderIndex


END
GO
PRINT N'Altering [sAssessment].[pExamMasterGet]...';


GO
ALTER PROCEDURE [sAssessment].[pExamMasterGet]
	 @rTitle nvarchar(100),
	 @rExamGroupId int,
	 @rClassId int,
	 @rOrgId int ,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
	SELECT 
		Distinct 
		EM.Id,
		EM.ClassID,
		EGM.Title as ExamGroup,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		ISNULL(IsProcessResult,0) AS IsProcessResult,
		IsNull(IsMarksInDecimal,0) AS IsMarksInDecimal,
		ISNULL(ISNegativeMarks,0) AS ISNegativeMarks ,
		ISNULL(IsIncludeCoScholastic,0) AS IsIncludeCoScholastic,
		ISNULL(IsIncludeSubExam,0) AS IsIncludeSubExam ,
		ISNULL(EM.IsPublished,0) AS IsPublished,
		isnull(EM.IsPublishExamSchedule,0) AS IsPublishExamSchedule
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		--LEFT JOIN sAssessment.vExamClassDivision ECD ON ECD.Id=EM.Id AND ECD.ClassId=EM.ClassId AND ECD.ExamSubGroupId=EGM.Id AND ECD.BatchId=@rBatchId
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) AND (EM.BatchId=@rBatchId)
		AND (EGM.Id=@rExamGroupId OR @rExamGroupId=0)
		AND (CM.Id=@rClassId or @rClassId=0)
		AND ESGM.IsObsolete=0 
	ORDER BY 
		EGM.Title ,ESGM.Title
END
GO
PRINT N'Altering [sAssessment].[pExamScheduleDateWiseGet]...';


GO
ALTER PROCEDURE [sAssessment].[pExamScheduleDateWiseGet]	 
	 @rOrgId int ,
	 @rBatchId int,
	 @rExamDate Date,
	 @rUserId bigint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

	DECLARE @lEmployeeId bigint=0
	SELECT @lEmployeeId=SourceId FROM sSecurity.tUser WHERE Id=@rUserId

	DECLARE @lMarkEntryBasedOn nvarchar(50)=''
	SELECT @lMarkEntryBasedOn=ItemValue FROM [sConfig].[tConfigurationSetup] where ConfigurationId=188 and SourceId=@rOrgId

IF(@lMarkEntryBasedOn = 'Class Teacher' AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,
		SM.Title AS SubjectName,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId,				
		ISNULL(ED.ExamDate,'') as ExamDate,
		ISNULL(ED.ExamTime,'') as ExamTime,
		ISNULL(ED.ExamTopic,'') as ExamTopic		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON CM.Id = DM.ClassId
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 
		AND ((ED.ExamDate=@rExamDate) OR (ISNULL(@rExamDate,'')=''))
		AND (DM.InchargeemployeeID=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
	ORDER BY 
		ExamDate
END
ELSE IF(@lMarkEntryBasedOn = 'Class Teacher Batch'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,
		SM.Title AS SubjectName,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId,				
		ISNULL(ED.ExamDate,'') as ExamDate,
		ISNULL(ED.ExamTime,'') as ExamTime,
		ISNULL(ED.ExamTopic,'') as ExamTopic		
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON CM.Id = DM.ClassId
		INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 
		AND ((ED.ExamDate=@rExamDate) OR (ISNULL(@rExamDate,'')=''))
		AND (DIE.EmployeeId=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
	ORDER BY 
		ExamDate
END
ELSE IF(@lMarkEntryBasedOn = 'Academic Setup'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT 
		DISTINCT		 
		EM.Id AS ExamId,
		SM.Title AS SubjectName,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId,				
		ISNULL(ED.ExamDate,'') as ExamDate,
		ISNULL(ED.ExamTime,'') as ExamTime,
		ISNULL(ED.ExamTopic,'') as ExamTopic		
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id	
		INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.ClassId = CM.Id AND vTSD.SubjectId = SM.Id 
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 
		AND ((ED.ExamDate=@rExamDate) OR (ISNULL(@rExamDate,'')=''))
		AND (vTSD.EmployeeId=@lEmployeeId OR ISNULL(@lEmployeeId,0)=0)
	ORDER BY 
		ExamDate
END

ELSE IF(@lMarkEntryBasedOn = 'User Access'  AND @lMarkEntryBasedOn IS NOT NULL)
BEGIN
	SELECT DISTINCT		 
		EM.Id AS ExamId,
		SM.Title AS SubjectName,
		ESGM.Title as ExamName,
		CM.DisplayTitle As ClassName,
		CM.Id AS ClassId,				
		ISNULL(ED.ExamDate,'') as ExamDate,
		ISNULL(ED.ExamTime,'') as ExamTime,
		ISNULL(ED.ExamTopic,'') as ExamTopic		
		
	FROM	
		[sAssessment].[tExamMaster] EM			
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=EM.ClassId
		INNER Join sSetup.tClassSubject CS ON EM.ClassId=CS.ClassId	
		INNER JOIN sSetup.tSubjectMaster SM on CS.SubjectId=SM.Id
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.ID = EM.ExamSubGroupId
		INNER JOIN sAssessment.tExamGroupMaster EGM ON EGM.Id=ESGM.ExamGroupId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ClassSubjectId = CS.Id AND ED.ExamId=EM.Id		
		INNER JOIN sSetup.tDivisionMaster DM ON CM.Id = DM.ClassId
		INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND SourceTypeId = 2005
	WHERE
		(CM.OrgId = @rOrgId  OR @rOrgId=0) 
		AND (EM.BatchId=@rBatchId)		
		AND ESGM.IsObsolete=0 
		AND ((ED.ExamDate=@rExamDate) OR (ISNULL(@rExamDate,'')=''))
		AND (U.UserId=@rUserId OR ISNULL(@rUserId,0)=0)
	ORDER BY 
		ExamDate
END
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].[pRptResultSheetCoScholasticSubCombineGet]...';


GO





ALTER PROCEDURE [sAssessment].[pRptResultSheetCoScholasticSubCombineGet]
	 
	 

	 --@rAcademicIdTextText bigint,
	 --@rExamIdTextText bigint
	  @rAcademicId bigint,
	 @rExamId bigint ,
	 @rCoScholasticScopeId int=0,
	 @rBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
--DECLARE
--@rAcademicIdText bigint,
--@rExamIdText int
--SET @rAcademicIdText = convert(bigint, @rAcademicIdTextText)
--SET @rExamIdText = convert(bigint, @rExamIdTextText)
DECLARE
@lIsCoScholasticGrade	bit,
@lIsCoScholasticGradeIndicator bit, 
@lIsCoScholasticGradeDesIndicator bit,
@lIsCoScholasticCombine bit	 	 

--@lCoScholasticScopeId tinyint

SELECT @lIsCoScholasticGrade = IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator=IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator=IsCoScholasticGradeDesIndicator,
@lIsCoScholasticCombine = IsCoScholasticCombine 
FROM sAssessment.tExamMaster WHERE Id = @rExamId
 

DECLARE 
@Exam1 int,
@Exam2 int,
@Exam3 int


--@Grade2 nvarchar(50),
--@GradeIndicator1 nvarchar(50),
--@Grade2 nvarchar(50),
--@CategoryID int,
--@BrandID 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 @Exam3 = SubExamId From sAssessment.tExamCombine WHERE ExamId = @rExamId AND ExamOrder = 3

SELECT
Convert(nvarchar(10),@rExamId) AS ExamIdText,
Convert(nvarchar(20),@rAcademicId) AS   AcademicIdText,
  
Convert(nvarchar(20),@rBatchId) AS   BatchIdText,
@rAcademicId AS AcademicId,
--(CASE Term1.AcademicId  WHEN  null THEN Convert(nvarchar(10),Term2.AcademicId)
--ELSE Convert(nvarchar(10),Term1.AcademicId) END) AS   AcademicIdText,
@rExamId AS ExamId, 
Convert(nvarchar(20), @rCoScholasticScopeId ) AS CoScholasticScopeIdText,

--(CASE Term1.AcademicId  WHEN  null THEN Term2.AcademicId
--ELSE Term1.AcademicId END) AS   AcademicId ,
(CASE Term1.CoSubject  WHEN  null THEN Term2.CoSubject
ELSE Term1.CoSubject END) AS   CoSubject ,
(CASE Term1.CoSubjectGroup  WHEN  null THEN Term2.CoSubjectGroup
ELSE Term1.CoSubjectGroup END) AS   CoSubjectGroup ,
(CASE Term1.CoSubjectGroupOrder  WHEN  null THEN Term2.CoSubjectGroupOrder
ELSE Term1.CoSubjectGroupOrder END) AS   CoSubjectGroupOrder ,
(CASE Term1.CoSubjectOrder  WHEN  null THEN Term2.CoSubjectOrder
ELSE Term1.CoSubjectOrder END) AS   CoSubjectOrder , 
ISNULL(Term1.Grade,'') AS Grade1,
ISNULL(Term1.GradeIndicator,'') AS GradeIndicator1,
ISNULL(Term1.DescriptiveIndicator,'') AS DescriptiveIndicator1,
ISNULL(Term2.Grade,'') AS Grade2,
ISNULL(Term2.GradeIndicator,'') AS GradeIndicator2,
ISNULL(Term2.DescriptiveIndicator,'') AS DescriptiveIndicator2,
ISNULL(Term3.Grade,'') AS Grade3,
ISNULL(Term3.GradeIndicator,'') AS GradeIndicator3,
ISNULL(Term3.DescriptiveIndicator,'') AS DescriptiveIndicator3,
@lIsCoScholasticGrade AS IsCoScholasticGrade,
@lIsCoScholasticGradeIndicator AS IsCoScholasticGradeIndicator,
@lIsCoScholasticGradeDesIndicator AS IsCoScholasticGradeDesIndicator,
ISNULL(Term1.GroupTypeId,0) AS GroupTypeId,
ISNULL(Term1.GroupType,0) AS GroupType ,

ISNULL(Term1.ExamName,'') AS ExamTerm1,
ISNULL(Term2.ExamName,'') AS ExamTerm2,
ISNULL(Term3.ExamName,'') AS ExamTerm3,
Term1.CoScholasticTitle AS CoScholasticTitle


 

FROM 

	(
	SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType ,
			 ESM.Title AS ExamName,
			 EM.CoScholasticTitle 
			
	FROM 
			sAssessment.tCCECSExamScore cceCSS	
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
			 INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
	WHERE 
		     cceCSS.ExamId=@Exam1		     
		     AND cceCSS.AcademicId=@rAcademicId
		     AND CCC.BatchID=@rBatchId	) Term1
		     
		     FULL OUTER JOIN

		 	(
			SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			ESM.Title AS ExamName 
			 --EM.CoScholasticTitle 
			
			 
			
			
			    
	FROM 
			sAssessment.tCCECSExamScore cceCSS		 
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
	WHERE 
		     cceCSS.ExamId=@Exam2		     
		     AND cceCSS.AcademicId=@rAcademicId
		     AND CCC.BatchID=@rBatchId	) Term2
		     ON Term1.CoSubjectId = Term2.CoSubjectId    
		     
		     
			FULL OUTER JOIN

		 	(
			SELECT			
			cceCSS.AcademicId,
			cceCSS.ExamId,
			cceCSS.Grade,
			cceCSS.GradeIndicator, 
			cceCSS.DescriptiveIndicator,
			cceCSM.Title AS CoSubject,
			cceCSGM.Title AS CoSubjectGroup,
			cceCSM.Id AS CoSubjectId,
			cceCSM.OrderIndex AS CoSubjectOrder,
			cceCSGM.OrderIndex AS CoSubjectGroupOrder,
			cceCST.Id AS GroupTypeId,
			cceCST.Title AS GroupType,
			ESM.Title AS ExamName 
			 --EM.CoScholasticTitle 	
			    
	FROM 
			sAssessment.tCCECSExamScore cceCSS		 
			INNER JOIN sAssessment.tCCECSMaster cceCSM ON cceCSM.Id=cceCSS.CCECSId
			INNER JOIN sAssessment.tCCECSGroupMaster cceCSGM ON cceCSGM.Id=cceCSM.CCECAGroupId
			INNER  JOIN sAssessment.tCCECSGroupTypeMaster cceCST ON cceCST.Id = cceCSGM.CCECSGroupTypeId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = cceCSS.ExamID
			INNER JOIN sAssessment.tExamSubGroupMaster ESM ON ESM.Id = EM.ExamSubGroupId
			INNER JOIN sStudent.tAcademic A ON A.Id = cceCSS.AcademicId 
			INNER JOIN sAssessment.tCCECSClass CCC ON CCC.ClassId = A.ClassId AND CCC.CCECSGroupId = cceCSGM.Id 
	WHERE 
		     cceCSS.ExamId=@Exam3		     
		     AND cceCSS.AcademicId=@rAcademicId
		     AND CCC.BatchID=@rBatchId	) Term3
		     ON Term1.CoSubjectId = Term3.CoSubjectId    

		     
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
	
	 
	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
		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
	
	 
	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
		order by A.RollNo,ExamDate2
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardGetwithResultDetailOther]...';


GO
ALTER PROCEDURE [sAssessment].[pRptResultSheetStandardGetwithResultDetailOther]
	 
	 @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
	
	 
	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,
		RDO.TotalCount,
		RDO.PresentCount,
		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
		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 sAssessment.tResultDetailOther RDO ON  RDO.ExamId = EM.Id AND R.Academicid =RDO.AcademicId AND ED.ClassSubjectId = RDO.ClassSubjectId
	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))
		order by A.RollNo,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
	
	 --,@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(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(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),
	)	
	 --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 
	)
	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
		
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)) 
	    
	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 AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
		
	--	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 ,
		
	--	--MaximumMark1 decimal(8,2),		
	--	'' As SubjectGrade1 ,
	--	--Obtain1 decimal(8,2),
	--	--ExamMaximum1 decimal(8,2),
	--	0 As IsPresent1,
						
	--	0 As MaximumMark2 ,	
	--	'' As SubjectGrade2 ,
	--	0 As Obtain2 ,
	--	0 As ExamMaximum2 ,
	--	0 As IsPresent2,
				
	--	0 As MaximumMark3 ,
	--	'' As SubjectGrade3 ,
	--	0 As Obtain3 ,
	--	0 As ExamMaximum3 ,
	--	0 As IsPresent3 ,		
		
	--	0 As MaximumMark4 ,	
	--	'' As SubjectGrade4 ,
	--	0 As Obtain4 ,
	--	0 As ExamMaximum4 ,
	--	0 As IsPresent4 ,	
				
	--	0 As MaximumMark5 ,		
	--	'' As SubjectGrade5 ,
	--	0 As Obtain5 ,
	--	0 As ExamMaximum5 ,
	--	0 As IsPresent5 ,	
				
	--	0 As MaximumMark6 ,		
	--	'' As SubjectGrade6,
	--	0 As Obtain6 ,
	--	0 As ExamMaximum6 ,
	--	0 As IsPresent6 ,	
		
	--	0 As MaximumMark7 ,		
	--	'' As SubjectGrade7,
	--	0 As Obtain7 ,
	--	0 As ExamMaximum7 ,
	--	0 As IsPresent7 ,	
	
	--	0 As MaximumMark8 ,	
	--	'' As SubjectGrade8,
	--	0 As Obtain8 ,
	--	0 As ExamMaximum8 ,
	--	0 As IsPresent8 ,	
		
	--	'' As SubjectGradeTerm1,
	--	'' As SubjectGradeTerm2 ,
	--	0 As IsMarksInDecimal ,
	--	0 As column_visible ,
	--	--Obtain decimal(5,2),
	--	0 As Percentile,
	--	--ClassSubject nvarchar(100),
	--	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 TotalMarkTerm1 ,
	--	 0 As TotalObtainTerm1 ,
	--	0 As PercentageTerm1,
	--	0 As RankNumberTerm1 ,
	--	'' As ResultGradeTerm1,
	--	0 As PercentileTerm1 ,
	--	'' As ResultStatusTerm1,		   
	--	0 As TotalMarkTerm2 ,
	--	0 As TotalObtainTerm2 ,
	--	0 As PercentageTerm2 ,
	--	0 As RankNumberTerm2 ,
	--	'' As ResultGradeTerm2 ,
	--	0 As PercentileTerm2 ,
	--	'' As ResultStatusTerm2 , 
	--	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 Exam1Name ,		
	--	0 As TotalMarks1 ,		
	--	0 As TotalObtain1 ,
	--	0 As Percentage1 ,
	--	0 As RankNumber1 ,
	--	'' As ResultGrade1,
	--	0 As Percentile1 ,
	--	'' As ResultStatus1 ,
		
	--	'' As SubActivityGrade1,
	--	'' As ActivityGrade1,
		
	--	'' As Exam2Name ,	
	--	0 As TotalMarks2 ,
	--	0 As TotalObtain2 ,
	--	0 As Percentage2 ,
	--	0 As RankNumber2 ,
	--	'' As ResultGrade2 ,
	--	0 As Percentile2 ,
	--	'' As ResultStatus2 ,
		
	--	'' As SubActivityGrade2,
	--	'' As ActivityGrade2 ,
		
	--	'' As Exam3Name ,	
	--	0 As TotalMarks3 ,
	--	0 As TotalObtain3 ,
	--	0 As Percentage3 ,
	--	0 As RankNumber3 ,
	--	'' As ResultGrade3 ,
	--	0 As Percentile3 ,		
	--	'' As ResultStatus3,
		
	--	'' As SubActivityGrade3 ,
	--	'' As ActivityGrade3 ,
		
	--	'' As Exam4Name ,	
	--	0 As TotalMarks4 ,
	--	0 As TotalObtain4,
	--	0 As Percentage4 ,
	--	0 As RankNumber4 ,
	--	'' As ResultGrade4 ,
	--	0 As Percentile4 ,
	--	'' As ResultStatus4 ,
		
	--	'' As SubActivityGrade4,
	--	'' As ActivityGrade4 ,
		
	--	'' As Exam5Name ,		
	--	0 As TotalMarks5 ,
	--	0 As TotalObtain5 ,
	--	0 As Percentage5 ,
	--	0 As RankNumber5 ,
	--	'' As ResultGrade5 ,
	--	0 As Percentile5 ,
	--	'' As ResultStatus5 ,
		
	--	'' As SubActivityGrade5 ,
	--	'' As ActivityGrade5 ,
		
	--	'' As Exam6Name ,	
	--	0 As TotalMarks6 ,
	--	0 As TotalObtain6,
	--	0 As Percentage6 ,
	--	0 As RankNumber6 ,
	--	'' As ResultGrade6 ,
	--	0 As Percentile6 ,
	--	'' As ResultStatus6 ,
		
	--	'' As SubActivityGrade6 ,
	--	'' As ActivityGrade6 ,
		
	--	'' As Exam7Name ,		
	--	0 As TotalMarks7 ,
	--	0 As TotalObtain7,
	--	0 As Percentage7 ,
	--	0 As RankNumber7 ,
	--	'' As ResultGrade7,
	--	0 As Percentile7 ,
	--	'' As ResultStatus7 ,
		
	--	--SubActivityGrade7 nvarchar(10),
		
	--	'' As Exam8Name,
	--	0 As TotalMarks8 ,
	--	0 As TotalObtain8 ,
	--	0 As Percentage8,
	--	0 As RankNumber8 ,
	--	'' As ResultGrade8 ,
	--	0 As Percentile8,
	--	'' As ResultStatus8,
	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,
	--	0 As TotalDays ,
	--	0 As PresentDays ,
	--	0 As StudentHeight,
	--	0 As StudentWeight ,
	--	'' As ExamSeatNo ,
	--0 As ExamId ,
	--	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 ActivityName ,
	--	'' As SubActivityName ,
	--	0 As SubActivityId ,
	--	0 As ActivityId ,
	--	 '' As SubActivityGrade,
	--	 '' As ActivityGrade ,
	--	'' As SubActivityGradeIndicator ,
	--	'' As SubActivityDescriptiveIndicator,
	--	0 As SubjectActivityOrderIndex ,
	--	0 As SubActivityOrderIndex ,
	--	0 As ColumnSubjectCount ,
	--	0x As MarksheetHeaderA4 ,
	--	0 As IsImageHeader ,
	--	0 As Height1 ,
	--	0 As Height2 ,
	--	0 As Height3,
	--	0 As Height4 ,
	--	0 As Height5,
	--	0 As Height6 ,
	--	0 As Weight1 ,
	--	0 As Weight2 ,
	--	0 As Weight3 ,
	--	0 As Weight4,
	--	0 As Weight5 ,
	--	0 As Weight6 ,
	--	0 As TotalDays1 ,
	--	0 As PresentDays1 ,
	--	0 As TotalDays2 ,
	--	0 As PresentDays2 ,
	--	0 As TotalDays3 ,
	--	0 As PresentDays3 ,
	--	0 As TotalDays4 ,
	--	0 As PresentDays4 ,
	--	0 As TotalDays5 ,
	--	0 As PresentDays5 ,
	--	0 As TotalDays6 ,
	--	0 As PresentDays6 ,
	--	'' As MyActivity1,
	--	'' As MyActivity2 ,
	--	'' As MyActivity3,
	--	'' As MyActivity4 ,
	--	'' As MyActivity5,
	--	'' As MyActivity6,
	--	'' As GeneralRemark1,
	--	'' As GeneralRemark2 ,
	--	'' As GeneralRemark3 ,
	--	'' As GeneralRemark4,
	--	'' As GeneralRemark5,
	--	'' As GeneralRemark6,
	--	'' As PresentAddress ,
	--	'' As  MobileNo,
	--	'' As House ,
		 
	--	0 As AttendanceTerm1  ,
	--	0 As AttendanceTerm2 ,
	--	0 As WorkingDaysTerm1 ,
	--	0 As WorkingDaysTerm2 ,
	--	  '' As BloodGroup ,
	--	  '' As GradeSetIdText ,
	--	  '' As IsDisplayMonthlyAttendanceText ,
	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
	--	'' As ParentEmail

	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
	
	 --,@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))
	    
	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
	 --,@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
	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
		 
	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
			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
	
	 
	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
		order by A.RollNo,ED.DisplayOrder
		--AND A.id = 1005000000007
END
GO
PRINT N'Altering [sAssessment].[pRptResultSheetSubjectAcivityMultiExamGet]...';


GO

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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 
-- --drop table sAssessment.tTempAllExam	

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

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


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

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

	IF (@IsIncludeSubExam = 0)
	BEGIN	
	INSERT INTO #tempcombineExam (ExamID) 
	SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC
 	END
 	ELSE
 	BEGIN
 	-- if we want to display result for both the term with all exam select this option
 	INSERT INTO #tempcombineExam (ExamID) 
	SELECT C.SUBEXAMID FROM sAssessment.tExamCombine C
	INNER JOIN (SELECT SUBEXAMID,ExamOrder FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId) E
	ON C.SubExamId = E.SubExamId
	ORDER BY E.ExamOrder,C.ExamOrder
	END
	 
	--ON 
	
	-- Order By ExamOrder ASC
	--WHERE ExamId in (SELECT SUBEXAMID FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId Order By ExamOrder ASC)
	
	DECLARE @lCount int,@query  AS NVARCHAR(MAX),@lSubExamId int,@lCount1 int  
	Select @lCount = MAX(Id) from #tempcombineExam	
	DECLARE @ExamTitle nvarchar(150)
	while (@lCount > 0)
	begin
		select @lSubExamId = ExamID from #tempcombineExam Where Id = @lCount
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		set @query ='update T SET
					
					 IsPresent' + convert(nvarchar(15),@lCount)+'=RD.IsPresent,					
					 SubjectGrade' + convert(nvarchar(15),@lCount)+ '=RD.SubjectGrade,
					 Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
					 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
					 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
					 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
					 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
					 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark 
					 									
					 From
						 
						 sAssessment.tResult R 
						INNER JOIN  sAssessment.tResultDetail RD ON RD.ResultId = R.Id						
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 							
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
	 execute(@query)
 
	 set @query ='update T SET
					
					 
					 SubActivityGrade' + convert(nvarchar(15),@lCount)+ '=SSA.Grade	
					 						
					 From
						sAssessment.tCCESubjectSubActivityExamScore SSA				
						inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	 					
						WHERE SSA.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
 
  set @query ='update T SET
					
					  ActivityGrade' + convert(nvarchar(15),@lCount)+ '=SAS.Grade	
					 						
					 From
						sAssessment.tCCESubjectActivityExamScore SAS				
						inner JOIN 	#TempAllExam  T ON T.ActivityId = SAS.SubjectActivityId And T.AcademicId = SAS.AcademicId	 					
						WHERE SAS.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
	-- set @query ='update T SET
					
	--				 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
	--				 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
	--				 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
	--				 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
	--				 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
	--				 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark
	--				 From
	--					sAssessment.tCCESubjectSubActivityExamScore SSA
						
	--					inner JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	--					inner JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	--					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	--					inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	
	--					LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 					
	--					WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
 ----PRINT(@QUERY)	
 --  EXECUTE(@query)
	
						
		/*	set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	execute(@query)*/
		
		
	set @lCount = @lCount -1
	end
	SELECT @rBuilder1 , T.*
	FROM #TempAllExam T
	
	
		
	drop table #tempcombineExam
	Drop table #TempAllExam
	--Select 
	-- '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
		
	--	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 ,
		
	--	--MaximumMark1 decimal(8,2),		
	--	'' As SubjectGrade1 ,
	--	--Obtain1 decimal(8,2),
	--	--ExamMaximum1 decimal(8,2),
	--	0 As IsPresent1,
						
	--	0 As MaximumMark2 ,	
	--	'' As SubjectGrade2 ,
	--	0 As Obtain2 ,
	--	0 As ExamMaximum2 ,
	--	0 As IsPresent2,
				
	--	0 As MaximumMark3 ,
	--	'' As SubjectGrade3 ,
	--	0 As Obtain3 ,
	--	0 As ExamMaximum3 ,
	--	0 As IsPresent3 ,		
		
	--	0 As MaximumMark4 ,	
	--	'' As SubjectGrade4 ,
	--	0 As Obtain4 ,
	--	0 As ExamMaximum4 ,
	--	0 As IsPresent4 ,	
				
	--	0 As MaximumMark5 ,		
	--	'' As SubjectGrade5 ,
	--	0 As Obtain5 ,
	--	0 As ExamMaximum5 ,
	--	0 As IsPresent5 ,	
				
	--	0 As MaximumMark6 ,		
	--	'' As SubjectGrade6,
	--	0 As Obtain6 ,
	--	0 As ExamMaximum6 ,
	--	0 As IsPresent6 ,	
		
	--	0 As MaximumMark7 ,		
	--	'' As SubjectGrade7,
	--	0 As Obtain7 ,
	--	0 As ExamMaximum7 ,
	--	0 As IsPresent7 ,	
	
	--	0 As MaximumMark8 ,	
	--	'' As SubjectGrade8,
	--	0 As Obtain8 ,
	--	0 As ExamMaximum8 ,
	--	0 As IsPresent8 ,	
		
	--	'' As SubjectGradeTerm1,
	--	'' As SubjectGradeTerm2 ,
	--	0 As IsMarksInDecimal ,
	--	0 As column_visible ,
	--	--Obtain decimal(5,2),
	--	0 As Percentile,
	--	--ClassSubject nvarchar(100),
	--	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 TotalMarkTerm1 ,
	--	 0 As TotalObtainTerm1 ,
	--	0 As PercentageTerm1,
	--	0 As RankNumberTerm1 ,
	--	'' As ResultGradeTerm1,
	--	0 As PercentileTerm1 ,
	--	'' As ResultStatusTerm1,		   
	--	0 As TotalMarkTerm2 ,
	--	0 As TotalObtainTerm2 ,
	--	0 As PercentageTerm2 ,
	--	0 As RankNumberTerm2 ,
	--	'' As ResultGradeTerm2 ,
	--	0 As PercentileTerm2 ,
	--	'' As ResultStatusTerm2 , 
	--	0 As TermScopeId ,		 
	--	'' 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 Exam1Name ,		
	--	0 As TotalMarks1 ,		
	--	0 As TotalObtain1 ,
	--	0 As Percentage1 ,
	--	0 As RankNumber1 ,
	--	'' As ResultGrade1,
	--	0 As Percentile1 ,
	--	'' As ResultStatus1 ,
		
	--	'' As SubActivityGrade1,
	--	'' As ActivityGrade1,
		
	--	'' As Exam2Name ,	
	--	0 As TotalMarks2 ,
	--	0 As TotalObtain2 ,
	--	0 As Percentage2 ,
	--	0 As RankNumber2 ,
	--	'' As ResultGrade2 ,
	--	0 As Percentile2 ,
	--	'' As ResultStatus2 ,
		
	--	'' As SubActivityGrade2,
	--	'' As ActivityGrade2 ,
		
	--	'' As Exam3Name ,	
	--	0 As TotalMarks3 ,
	--	0 As TotalObtain3 ,
	--	0 As Percentage3 ,
	--	0 As RankNumber3 ,
	--	'' As ResultGrade3 ,
	--	0 As Percentile3 ,		
	--	'' As ResultStatus3,
		
	--	'' As SubActivityGrade3 ,
	--	'' As ActivityGrade3 ,
		
	--	'' As Exam4Name ,	
	--	0 As TotalMarks4 ,
	--	0 As TotalObtain4,
	--	0 As Percentage4 ,
	--	0 As RankNumber4 ,
	--	'' As ResultGrade4 ,
	--	0 As Percentile4 ,
	--	'' As ResultStatus4 ,
		
	--	'' As SubActivityGrade4,
	--	'' As ActivityGrade4 ,
		
	--	'' As Exam5Name ,		
	--	0 As TotalMarks5 ,
	--	0 As TotalObtain5 ,
	--	0 As Percentage5 ,
	--	0 As RankNumber5 ,
	--	'' As ResultGrade5 ,
	--	0 As Percentile5 ,
	--	'' As ResultStatus5 ,
		
	--	'' As SubActivityGrade5 ,
	--	'' As ActivityGrade5 ,
		
	--	'' As Exam6Name ,	
	--	0 As TotalMarks6 ,
	--	0 As TotalObtain6,
	--	0 As Percentage6 ,
	--	0 As RankNumber6 ,
	--	'' As ResultGrade6 ,
	--	0 As Percentile6 ,
	--	'' As ResultStatus6 ,
		
	--	'' As SubActivityGrade6 ,
	--	'' As ActivityGrade6 ,
		
	--	'' As Exam7Name ,		
	--	0 As TotalMarks7 ,
	--	0 As TotalObtain7,
	--	0 As Percentage7 ,
	--	0 As RankNumber7 ,
	--	'' As ResultGrade7,
	--	0 As Percentile7 ,
	--	'' As ResultStatus7 ,
		
	--	--SubActivityGrade7 nvarchar(10),
		
	--	'' As Exam8Name,
	--	0 As TotalMarks8 ,
	--	0 As TotalObtain8 ,
	--	0 As Percentage8,
	--	0 As RankNumber8 ,
	--	'' As ResultGrade8 ,
	--	0 As Percentile8,
	--	'' As ResultStatus8,
	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,
	--	0 As TotalDays ,
	--	0 As PresentDays ,
	--	0 As StudentHeight,
	--	0 As StudentWeight ,
	--	'' As ExamSeatNo ,
	--0 As ExamId ,
	--	0 As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	0 As IsShowSubjectMark , 
	--	0 As IsOptionalSubject ,
	--	0 As CoScholasticScopeId ,
	--	0 As IsDisplayPrincipalSign ,
	--	0 As IsDisplayTeacherSign ,
	--	'' As EmployeeSign,
		
	--	'' As ActivityName ,
	--	'' As SubActivityName ,
	--	0 As SubActivityId ,
	--	0 As ActivityId ,
	--	 '' As SubActivityGrade,
	--	 '' As ActivityGrade ,
	--	'' As SubActivityGradeIndicator ,
	--	'' As SubActivityDescriptiveIndicator,
	--	0 As SubjectActivityOrderIndex ,
	--	0 As SubActivityOrderIndex ,
	--	0 As ColumnSubjectCount ,
	--	'' As MarksheetHeaderA4 ,
	--	0 As IsImageHeader ,
	--	0 As Height1 ,
	--	0 As Height2 ,
	--	0 As Height3,
	--	0 As Height4 ,
	--	0 As Height5,
	--	0 As Height6 ,
	--	0 As Weight1 ,
	--	0 As Weight2 ,
	--	0 As Weight3 ,
	--	0 As Weight4,
	--	0 As Weight5 ,
	--	0 As Weight6 ,
	--	0 As TotalDays1 ,
	--	0 As PresentDays1 ,
	--	0 As TotalDays2 ,
	--	0 As PresentDays2 ,
	--	0 As TotalDays3 ,
	--	0 As PresentDays3 ,
	--	0 As TotalDays4 ,
	--	0 As PresentDays4 ,
	--	0 As TotalDays5 ,
	--	0 As PresentDays5 ,
	--	0 As TotalDays6 ,
	--	0 As PresentDays6 ,
	--	'' As MyActivity1,
	--	'' As MyActivity2 ,
	--	'' As MyActivity3,
	--	'' As MyActivity4 ,
	--	'' As MyActivity5,
	--	'' As MyActivity6,
	--	'' As GeneralRemark1,
	--	'' As GeneralRemark2 ,
	--	'' As GeneralRemark3 ,
	--	'' As GeneralRemark4,
	--	'' As GeneralRemark5,
	--	'' As GeneralRemark6,
	--	'' As PresentAddress ,
	--	'' As  MobileNo,
	--	'' As House ,
		 
	--	0 As AttendanceTerm1  ,
	--	0 As AttendanceTerm2 ,
	--	0 As WorkingDaysTerm1 ,
	--	0 As WorkingDaysTerm2 ,
	--	  '' As BloodGroup ,
	--	  '' As GradeSetIdText ,
	--	  '' As IsDisplayMonthlyAttendanceText ,
	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
	--	'' As ParentEmail

	END

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


GO


ALTER PROCEDURE [sAssessment].[pRptResultWithSubjectAnalysisBatchwise]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 --@rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 --@rExamId int,
     --@rExamSubGroupId1 int=0,
     --@rExamSubGroupId2 int=0,
	 @rCode nvarchar(20),
	 @rFromRollNo int =0,
	 @rToRollNo int =0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rResultStatus nvarchar(20)='',
	 @rDepartmentId int=0,
	 @rExamId1 int ,
	 @rExamId2 int ,
	 @rBatchId1 int,
	 @rBatchId2 int,
	 @rClassStatusId int=0 ,
	 @rIsDisplayAvgTotal bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
 
	BEGIN
	
	CREATE TABLE #Temp_StudentId (StudentId bigint);
	INSERT INTO #Temp_StudentId
	SELECT A1.StudentId From sStudent.tAcademic A1 
	INNER JOIN
	sStudent.tAcademic A2 ON A1.StudentId = A2.StudentId 
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A1.StudentId
	WHERE A1.BatchId =  @rBatchId1 AND A2.BatchId = @rBatchId2
	AND (A1.ClassId=@rClassId OR @rClassId=0) 
	AND (A1.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND ((A1.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((A1.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SM.Code=@rCode) OR (@rCode=''))
	AND SM.StatusId = 1
	AND ((A1.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	
	
CREATE TABLE #Temp_Academic (tempAcademicId bigint);
INSERT INTO #Temp_Academic 
SELECT  A.Id As tempAcademicId FROM sAssessment.tResult R 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		WHERE BM.Id = @rBatchId2 AND R.ExamId =@rExamId2
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		  
	--SELECT * FROM #temp
	--RETURN 	
		
	SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			SR.PresentDays,
			SR.TotalDays
			
			--RD.SubjectGrade AS TermSubjectGrade,
			--RD.SubjectGrade AS SubjectGrade
			--1 As ExamNo
	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 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 #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId=EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			
	WHERE 
			
		EM.BatchId = @rBatchId1
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@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 ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId1 = 0))		
		AND ((EM.Id=@rExamId1 )	OR (@rExamId1 = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	A.BatchId = @rBatchId1
		--AND BM.Id = @rBatchId1
		AND R.ExamId = @rExamId1
		 AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))

UNION 
	
		SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A2.RollNo,
			--temp.tempAcademicId,
			A2.Id AS AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM2.DisplayTitle AS Class,
			Cm2.Id AS ClassId,
			DM2.DisplayTitle AS Division,
			DM2.Id AS DivisionId,
			DM2.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM2.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			SR.PresentDays,
			SR.TotalDays

			--2 As ExamNo
	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 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 #Temp_Academic temp ON temp.tempAcademicId= A.Id  
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId=EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			INNER JOIN sStudent.tAcademic A2 ON A2.StudentId = TEMP2.StudentId AND A2.BatchId = @rBatchId1
			INNER JOIN sSetup.tClassMaster CM2 ON CM2.Id=A2.ClassId
			INNER JOIN sSetup.tDivisionMaster DM2 ON DM2.Id=A2.DivisionId
	WHERE 
			
		EM.BatchId = @rBatchId2
		--AND (A.ClassId=@rClassId OR @rClassId=0)  
		--AND (A.ClassId=temp.tempClassId )
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0))
		--AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		--AND (A.DivisionId=temp.tempDivisionId )
		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 = @rExamSubGroupId2) OR (@rExamSubGroupId2 = 0))		
		AND ((EM.Id=@rExamId2 )	OR (@rExamId2 = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	((A.BatchId = @rBatchId2 ))
		--AND ((BM.Id = @rBatchId2))
		AND R.ExamId = @rExamId2
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by A.RollNo,ClassOrderIndex
	--	SELECT * FROM #temp
	--RETURN 
		END
		DROP Table #Temp_Academic
		DROP Table #Temp_StudentId
		
		----For Report Dataset
		--SELECT 
		--	@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2,
		--	EM.DisplayTitle AS Exam,
		--	EM.Id AS ExamId,
		--	StuM.Code,
		--	[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		--	A.RollNo,
		--	--temp.tempAcademicId,
		--	R.AcademicId,
		--	RD.Obtain,
		--	R.ResultStatus,
		--	CM.DisplayTitle AS Class,
		--	Cm.Id AS ClassId,
		--	DM.DisplayTitle AS Division,
		--	DM.Id AS DivisionId,
		--	DM.OrderIndex AS DivisinOrderIndex,
		--	R.TotalMarks,
		--	R.TotalObtain,
		--	R.Percentage,
		--	R.RankNumber,
		--	R.ResultGrade,
		--	SM.Title AS ClassSubject,
		--	RD.Id AS ResultDetailId,
		--	R.Id AS ResultId,
		--	CS.Id AS SubjectId,
		--	ED.Maximum,
		--	RD.SubjectGrade, 
			
		--	EM.IsMarksInDecimal,
		--	--SM.OrderIndex AS SubjectCode,
		--	SM.Code AS SubjectCode,
		--	ED.DisplayOrder AS SubjectOrderIndex,
		--	CM.OrderIndex AS ClassOrderIndex,
		--	RD.IsPresent,
		--	EM.IsGrade,
		--	EM.IsPercentage,
		--	EM.IsResultStatus,
		--	EM.IsRankNo ,
		--	ED.Minimum,
		--	RD.GraceMark,
		--	EM.DecimalFormat,
		--	CS.IsOptional,
		--	SR.PresentDays,
		--	SR.TotalDays,
		--	BM.Id As BatchId,
		--	BM.Title As BatchName
		--	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 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.tBatchMaster BM ON A.BatchId = BM.Id 
		--	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
		--	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		--	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			
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
	 
	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
		ORDER BY 
			SA.RollNo ASC,
			SAM.OrderIndex ASC,
			SSA.OrderIndex ASC;
END
GO
PRINT N'Altering [sAttendance].[pMonthlyRegisterStudentviewGet]...';


GO
 
ALTER PROCEDURE [sAttendance].[pMonthlyRegisterStudentviewGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 @rAttendanceTypeId tinyint
	 	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
declare @lAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid1 nvarchar(max)=''

IF NOT EXISTS(select 1 From sAttendance.tMonthlyRegister where AcademicId=@rAcademicId and ForMonth=Month(GETDATE()) and ForYear=Year(GETDATE()))
BEGIN

--Current Month Details Add
		DECLARE @PresentCount DECIMAL(10,2)
		DECLARE @AbsentCount DECIMAL(10,2)
		DECLARE @AveragePresence DECIMAL(10,2)
		DECLARE @CurrentMonthDays DECIMAL(10,2)
		DECLARE @AttendanceCount INT 
		SET @CurrentMonthDays = (SELECT DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,getdate()),0))))
		DECLARE @YearNumber INT
		DECLARE @AbsentDays nvarchar(max)

		SET @YearNumber =Year(GETDATE())



		SET @PresentCount = (select count(AttendanceDate) AS PresentCount from sAttendance.tStudentRegister 
		where IsPresent=1 and AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()))		

		SET @AbsentCount = (select count(AttendanceDate) AS AbsentCount from sAttendance.tStudentRegister 
		where IsPresent=0 and AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()))		


		SET @AttendanceCount = (select count(AttendanceDate) AS PresentCount from sAttendance.tStudentRegister 
		where AcademicId=@rAcademicId and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate()))		

		SET @AveragePresence= (@PresentCount/@AttendanceCount)*100

		SET @AbsentDays=(SELECT SUBSTRING(
		(SELECT ',' + CONVERT(varchar(10), Day(AttendanceDate))
		FROM  sAttendance.tStudentRegister s
		where AcademicId=@rAcademicId and IsPresent=0 and Month(AttendanceDate) =Month(Getdate()) and Year(AttendanceDate)=Year(Getdate())		

		ORDER BY AcademicId
		FOR XML PATH('')),2,200000) AS CSV
)
END


SET 
	@lCuurentMonthAttedanceGrid = @lCuurentMonthAttedanceGrid + '<tr>
	<td align="left" scope="col">' + Isnull(LEFT(DATENAME(MONTH,Getdate()),10),'')  + '</td>
	<td align="left" scope="col">' +convert(varchar, isnull( @YearNumber,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(@AttendanceCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(CAST(@PresentCount as INTEGER),0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(CAST(@AbsentCount as INTEGER),0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(@AveragePresence,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(@AbsentDays,0)) + '</td>
	<tr>'


	Select 
	@lAttedanceGrid = @lAttedanceGrid + '<tr>
	<td align="left" scope="col">' + Isnull(MY.MonthTitle,'')  + '</td>
	<td align="left" scope="col">' +convert(varchar, isnull( MY.YearNumber,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AttendanceCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.PresentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AbsentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AveragePresence,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AbsentDays,0),103) + '</td>
	<tr>'
		
	From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND MR.AttendanceTypeId=@rAttendanceTypeId
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	WHERE
		SN.AcademicId=@rAcademicId
	
	ORDER BY MY.YearNumber,MY.MonthNumber
 
		SELECT  isnull(@lAttedanceGrid ,'') + isnull(@lCuurentMonthAttedanceGrid ,'') AS AttedanceGrid
		
		
		
END
GO
PRINT N'Altering [sAttendance].[pRptAttendanceSubjectwiseGet]...';


GO
ALTER PROCEDURE [sAttendance].[pRptAttendanceSubjectwiseGet]  
         
   @rBuilder1 nvarchar(max)='',  
   @rBuilder2 nvarchar(max)='',   
   @rOrgId smallint,  
   @rBatchId int,  
   @rClassId int,  
   @rDivisionId int,  
   @rSubjectId int,  
   @rFromDate date,  
   @rToDate date,  
   @rStudentCode nvarchar(20),  
   @rReportId int,  
   @rDepartmentId int,  
   @rStatusId int=0  
      
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
SET @rToDate = DATEADD (d,1,@rToDate)  
 Select   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  SA.AcademicId,  
  SA.Name,  
  SA.Code,  
  SA.RollNo,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SR.AttendanceDate,  
  --SA.TotalCount,  
  --SA.PresentCount,  
  --SA.AbsentDays,  
  --SA.AbsentCount,  
  ISNULL(SM.Id,0) AS SubjectId,  
  ISNULL(SM.Code,'') AS SubjectCode,  
  ISNULL(SM.Title,'') AS SubjectName,  
  ISNULL(SR.PeriodNo,'') As PeriodNo,
  --CAST(ISNULL(SR.IsPresent,'') as int) AS IsPresent
  
  case when SR.IsPresent = 1 then 1 when SR.IsPresent = 0 then 0 else '' end AS IsPresent
 
   
 From   
 sAttendance.tStudentRegister SR    
 INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=SR.AcademicId  
 INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=SR.SubjectId  
 WHERE  
  ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))  
  AND (SA.OrgId=@rOrgId)  
  AND (SA.BatchId = @rBatchId)   
  AND ((SA.ClassId=@rClassId) OR (@rClassId=0))  
  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
  ----AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))  
  AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))  
  AND ((SR.AttendanceDate < @rToDate) OR (ISNULL(@rToDate,'')=''))  
  --AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))  
  AND ((@rReportId = 20463 AND SR.IsPresent = 1) OR (@rReportId = 20466 AND SR.IsPresent = 0) 
  OR (@rReportId = 30718))  
  AND SR.AttendanceTypeId = 5  
  AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))  
  AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((SA.StatusID=@rStatusId) OR (@rStatusId=0))  
  --AND (SA.StatusId != 3)  
   
END
GO
PRINT N'Altering [sAttendance].[pRptStudentAttendanceLateCountList]...';


GO
 
 
ALTER PROCEDURE [sAttendance].[pRptStudentAttendanceLateCountList]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rDepartmentId int,
	@rClassId int,
	@rDivisionId int,
	@rAttendanceTagId int,
	@rFromDate date,
	@rToDate date,
	@rBatchId int,
	@rOrgId int	 
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lAttendanceDate nvarchar(MAX)
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		
		SA.AcademicId,
		ISNULL(SA.RollNo,0) as RollNo,
		SA.Name,
		SA.Code,
		CM.ID AS ClassId,
		CM.Title AS Class,
		CM.OrderIndex AS ClassOrderIndex,
		DM.Id AS DivisionId,
		DM.Title AS Division,
		SA.DepartmentName As Department,
		DM.OrderIndex AS DivisionOrderIndex,
		SA.ClassName + '-'+ SA.DivisionName AS ClassDivision,
		ISNULL(AR.AttendanceTagCount,0) AS AttendanceTagCount,
		STUFF(
         (SELECT DISTINCT  ', ' + CONVERT(NVARCHAR(MAX),SR.AttendanceDate,105)
           FROM
				sStudent.vStudentAcademic A INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.AcademicId  
			WHERE 
				 A.AcademicId = SA.AcademicId
				AND (SR.AttendanceDate >= @rFromDate  AND SR.AttendanceDate <= @rToDate)
				AND SR.AttendanceTagId>0
				AND (SR.AttendanceTagId = @rAttendanceTagId OR @rAttendanceTagId=0)
			GROUP BY SR.AcademicId,AttendanceDate
          FOR XML PATH (''))
          , 1, 1, '')  AS DATE
		 
	FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = SA.DivisionId
		 
		LEFT JOIN
		(
			SELECT 
				SR.AcademicId,COUNT(SR.AttendanceTagId) AS AttendanceTagCount 
			FROM 
				sStudent.vStudentAcademic A
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.AcademicId 
				INNER JOIN sStudent.tStudentAdmission SA  ON SA.StudentId = A.StudentId
			WHERE 
				((A.ClassId=@rClassId) OR (@rClassId=0))
				AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((A.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				AND (A.OrgId = @rOrgId)
				AND (A.BatchId = @rBatchID)
				AND (SR.AttendanceDate >= @rFromDate  AND SR.AttendanceDate <= @rToDate)
				AND A.StatusId=1
				AND SR.AttendanceTagId>0
				AND (SR.AttendanceTagId = @rAttendanceTagId OR @rAttendanceTagId=0)
			GROUP BY SR.AcademicId
		) AR ON AR.AcademicId = SA.AcademicId
		
	WHERE 
		(SA.OrgId = @rOrgId)
		AND (SA.BatchId = @rBatchId)
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND (AD.LeftDate > @rFromDate OR ISNULL(AD.LeftDate,'')= '')
		AND (AD.AdmissionDate <= @rFromDate)
		AND SA.StatusId=1
END
GO
PRINT N'Altering [sAttendance].[pRptStudentRegisterGet]...';


GO
 
ALTER PROCEDURE [sAttendance].[pRptStudentRegisterGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rStatus int=0,
	 @rDepartmentId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SA.DivisionOrder
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StatusId=@rStatus) OR (@rStatus=0))
		AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
END
GO
PRINT N'Altering [sAttendance].[pStudentAttendaceDashboardGet]...';


GO
 
ALTER PROCEDURE [sAttendance].[pStudentAttendaceDashboardGet]
	 
	 @rTypeId smallint,
	 @rUptoDate date='',
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDivisionId int=0,
	 @rClassId int =0,
	 @rGenderType int=0,
	 @rCommonOrgGroupBatchId int=0,
	 @rSyncDate int =0,
	 @rUserId Bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF @rClassId=0
  BEGIN
--Orggroup wise Attendance
   IF @rTypeId=1 
   BEGIN
--Update Attendance
	IF(@rSyncDate =1) 
		BEGIN 
			DELETE  sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			IF EXISTS (SELECT 1 FROM sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))
							BEGIN
							IF(@rOrgGroupId !=0)
									INSERT INTO sAttendance.tTempStudentAttendance
--Total Student All Orggroup
				   SELECT 
					OGM.Id AS OrgGroupId,
					OGM.Title As OrgGroupTitle,
					0 As OrgId,'' As OrgTitle,       
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
						 ) AS Total,       
--PresentStudent All Orggroup
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id 
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						) AS PresentStudent,
--AbsentStudent All Orggroup
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						) AS AbsentStudent,
--LessThen70 % All Orggroup
				   (select Count(StudentID) from(
						select  (SMD.Id)StudentID
						 
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						  GROUP BY SMD.Id
					--GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
					
					--HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
					)  As LessThen70,
--100% Attendance All Orggroup
				  (select Count(StudentID) from  (
					select  
						  OGMEL.Id AS OrgGroupId,
						  OGMEL.Title AS OrgGroupTitle,
						  OMEL.Id AS OrgId,
						  (OMEL.Title) As OrgTitle ,
						  DM.Code AS DivisionCode,
						  (SMD.Id)StudentID,
						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
						  (SC.ParentContactNo) AS ContactNo,
						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId						
						   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
					) AS HundredPer,
--Absent>3 All Orggroup
				   (SELECT COUNT(AcademicId) FROM(
					  SELECT 
						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
						AcademicId,AttendanceDate
					  FROM sAttendance.tStudentRegister d 		
						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
					  WHERE
						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
						 IsPresent IN(0) 
						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
						 and IsPresent=0
					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
					  ) AS AbsentCount,
--Leave Request All Orggroup
					(SELECT 
						COUNT(AcademicId) AS LeaveRequest
					 FROM sAttendance.tStudentLeaveRequest STSL
						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
					) AS LeaveRequest,
--AttnNotTakenClass All Orggroup
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
					 WHERE 
						 OGM.Id = OGMR.Id  and SM1.statusid =1 AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
					As AttnNotTakenClass,

				@rUptoDate,@rCommonOrgGroupBatchId,GetDate()
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND ISNULL(OGM.IsObsolete,0) = 0
				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0 ORDER BY OrgGroupId
							END
						ELSE
							BEGIN
									INSERT INTO sAttendance.tTempStudentAttendance
--Total Student All Orggroup
				   SELECT 
					OGM.Id AS OrgGroupId,
					OGM.Title As OrgGroupTitle,
					0 As OrgId,'' As OrgTitle,       
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
						 ) AS Total,       
--PresentStudent All Orggroup
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id 
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						) AS PresentStudent,
--AbsentStudent All Orggroup
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						) AS AbsentStudent,
--LessThen70 % All Orggroup
				   (select Count(StudentID) from(
						select  
						 OGMEL.Id AS OrgGroupId,
						 OGMEL.Title AS OrgGroupTitle,
						 OMEL.Id AS OrgId,
						 (OMEL.Title) AS OrgTitle ,
						 DM.Code As DivisionCode,
						 (SMD.Id)StudentID,
						 (SMD.FirstName + ' ' + SMD.LastName) AS StudentName,
						 (SC.ParentContactNo) AS ContactNo,
						 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY 
						 OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
					)  As LessThen70,
--100% Attendance All Orggroup
				  (select Count(StudentID) from  (
					select  
						  OGMEL.Id AS OrgGroupId,
						  OGMEL.Title AS OrgGroupTitle,
						  OMEL.Id AS OrgId,
						  (OMEL.Title) As OrgTitle ,
						  DM.Code AS DivisionCode,
						  (SMD.Id)StudentID,
						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
						  (SC.ParentContactNo) AS ContactNo,
						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId						
						   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
					) AS HundredPer,
--Absent>3 All Orggroup
				   (SELECT COUNT(AcademicId) FROM(
					  SELECT 
						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
						AcademicId,AttendanceDate
					  FROM sAttendance.tStudentRegister d 		
						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
					  WHERE
						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
						 IsPresent IN(0) 
						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
						 and IsPresent=0
					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
					  ) AS AbsentCount,
--Leave Request All Orggroup
					(SELECT 
						COUNT(AcademicId) AS LeaveRequest
					 FROM sAttendance.tStudentLeaveRequest STSL
						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
					) AS LeaveRequest,
--AttnNotTakenClass All Orggroup
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
					 WHERE 
						 OGM.Id = OGMR.Id  and SM1.statusid =1 AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
					As AttnNotTakenClass,

				@rUptoDate,@rCommonOrgGroupBatchId,GetDate()
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND ISNULL(OGM.IsObsolete,0) = 0
				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0 ORDER BY OrgGroupId
							END
--			INSERT INTO sAttendance.tTempStudentAttendance
----Total Student All Orggroup
--				   SELECT 
--					OGM.Id AS OrgGroupId,
--					OGM.Title As OrgGroupTitle,
--					0 As OrgId,'' As OrgTitle,       
--					(Select count(SM1.ID)
--					 FROM sStudent.tStudentMaster SM1
--						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
--						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					 WHERE 
--						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
--						 ) AS Total,       
----PresentStudent All Orggroup
--					 (select count(*) from sAttendance.tStudentRegister SME 
--						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id 
--						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
--						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
--						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
--						INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
--						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
--						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					  WHERE 
--						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
--						) AS PresentStudent,
----AbsentStudent All Orggroup
--					 (select count(*) from sAttendance.tStudentRegister SME 
--						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
--						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
--						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId 
--						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
--						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
--						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
--						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
--					  WHERE 
--						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
--						) AS AbsentStudent,
----LessThen70 % All Orggroup
--				   (select Count(StudentID) from(
--						select  
--						 OGMEL.Id AS OrgGroupId,
--						 OGMEL.Title AS OrgGroupTitle,
--						 OMEL.Id AS OrgId,
--						 (OMEL.Title) AS OrgTitle ,
--						 DM.Code As DivisionCode,
--						 (SMD.Id)StudentID,
--						 (SMD.FirstName + ' ' + SMD.LastName) AS StudentName,
--						 (SC.ParentContactNo) AS ContactNo,
--						 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
--					FROM sAttendance.tStudentRegister SMEL
--						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
--						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
--						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
--						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
--						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
--						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
--						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
--						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
--						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
--					where 
--						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
--						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
--					GROUP BY 
--						 OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
--					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
--					)  As LessThen70,
----100% Attendance All Orggroup
--				  (select Count(StudentID) from  (
--					select  
--						  OGMEL.Id AS OrgGroupId,
--						  OGMEL.Title AS OrgGroupTitle,
--						  OMEL.Id AS OrgId,
--						  (OMEL.Title) As OrgTitle ,
--						  DM.Code AS DivisionCode,
--						  (SMD.Id)StudentID,
--						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
--						  (SC.ParentContactNo) AS ContactNo,
--						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
--					FROM sAttendance.tStudentRegister SMEL
--						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
--						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
--						   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId						
--						   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
--						   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
--						   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
--						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
--						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
--					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
--						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
--					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
--					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
--					) AS HundredPer,
----Absent>3 All Orggroup
--				   (SELECT COUNT(AcademicId) FROM(
--					  SELECT 
--						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
--						AcademicId,AttendanceDate
--					  FROM sAttendance.tStudentRegister d 		
--						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
--						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		
--					  WHERE
--						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
--						 IsPresent IN(0) 
--						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
--						 and IsPresent=0
--					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
--					  ) AS AbsentCount,
----Leave Request All Orggroup
--					(SELECT 
--						COUNT(AcademicId) AS LeaveRequest
--					 FROM sAttendance.tStudentLeaveRequest STSL
--						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
--						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
--						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
--						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
--						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
--						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
--						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
--						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
--						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
--					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
--					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
--					) AS LeaveRequest,
----AttnNotTakenClass All Orggroup
--					(Select count(SM1.ID)
--					 FROM sStudent.tStudentMaster SM1
--						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
--						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
--						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
--						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
--						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
--						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
--					 WHERE 
--						 OGM.Id = OGMR.Id  and SM1.statusid =1 AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
--					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
--					As AttnNotTakenClass,

--				@rUptoDate,@rCommonOrgGroupBatchId,GetDate()
--				FROM sSetup.tOrgGroupMaster OGM 
--				WHERE OGM.Id<>1 AND OGM.IsObsolete = 0
--				AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))	
--			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0 ORDER BY OrgGroupId
		END
	ELSE
		BEGIN
			IF  Exists(select 1 from sAttendance.tTempStudentAttendance   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND StudentAttendanceDate=  CONVERT(date,@rUptoDate,102) AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
			SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0
			 ORDER BY OrgGroupId
			 	
			return
			END
ELSE
			
--Temp Atble Attendance
			BEGIN
			DELETE  sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId  AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			IF EXISTS (SELECT 1 FROM sAttendance.tTempStudentAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))
							BEGIN
							IF(@rOrgGroupId !=0)
								INSERT INTO sAttendance.tTempStudentAttendance
--Total Student All Orggroup Temp		
				   SELECT 
					OGM.Id AS OrgGroupId,
					OGM.Title As OrgGroupTitle,
					0 As OrgId,'' As OrgTitle,       
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
						 ) AS Total,       
--PresentStudent All Orggroup Temp
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						) AS PresentStudent,
--AbsentStudent All Orggroup Temp
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						) AS AbsentStudent,
--LessThen70 All Orggroup Temp
				   (select Count(StudentID) from(
						select  
						 OGMEL.Id AS OrgGroupId,
						 OGMEL.Title AS OrgGroupTitle,
						 OMEL.Id AS OrgId,
						 (OMEL.Title) AS OrgTitle ,
						 DM.Code As DivisionCode,
						 (SMD.Id)StudentID,
						 (SMD.FirstName + ' ' + SMD.LastName) AS StudentName,
						 (SC.ParentContactNo) AS ContactNo,
						 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY 
						 OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
					)As LessThen70,
--100 % HundredPer All Orggroup Temp
				  (select Count(StudentID) from  (
					select  
						  OGMEL.Id AS OrgGroupId,
						  OGMEL.Title AS OrgGroupTitle,
						  OMEL.Id AS OrgId,
						  (OMEL.Title) As OrgTitle ,
						  DM.Code AS DivisionCode,
						  (SMD.Id)StudentID,
						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
						  (SC.ParentContactNo) AS ContactNo,
						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId						
						   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1					
						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
					) AS HundredPer,
--AbsentCount All Orggroup Temp
				   (SELECT COUNT(AcademicId) FROM(
					  SELECT 
						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
						AcademicId,AttendanceDate
					  FROM sAttendance.tStudentRegister d 		
						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					  WHERE
						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
						 IsPresent IN(0) 
						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
						 and IsPresent=0
					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
					  ) AS AbsentCount,
--LeaveRequest All Orggroup Temp
					(SELECT COUNT(AcademicId) AS LeaveRequest
					FROM sAttendance.tStudentLeaveRequest STSL
						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
					) AS LeaveRequest,
--AttnNotTakenClass All Orggroup Temp
					(Select count(SM1.ID)
					FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  
						 and SM1.statusid =1 
						 AND COGBM.Id=@rCommonOrgGroupBatchId 
						 AND A.Id  not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
					As AttnNotTakenClass,
					
					
					
					
					@rUptoDate,@rCommonOrgGroupBatchId,GetDate()
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0
							END
						ELSE
							BEGIN
								INSERT INTO sAttendance.tTempStudentAttendance
--Total Student All Orggroup Temp		
				   SELECT 
					OGM.Id AS OrgGroupId,
					OGM.Title As OrgGroupTitle,
					0 As OrgId,'' As OrgTitle,       
					(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
						 ) AS Total,       
--PresentStudent All Orggroup Temp
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGME.Id AND COGBM.Id=@rCommonOrgGroupBatchId and SME.IsPresent=1 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						) AS PresentStudent,
--AbsentStudent All Orggroup Temp
					 (select count(*) from sAttendance.tStudentRegister SME 
						INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
						INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
						INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
						INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					  WHERE 
						OGM.Id = OGMEA.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.IsPresent=0 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
						) AS AbsentStudent,
--LessThen70 All Orggroup Temp
				   (select Count(StudentID) from(
						select  
						 OGMEL.Id AS OrgGroupId,
						 OGMEL.Title AS OrgGroupTitle,
						 OMEL.Id AS OrgId,
						 (OMEL.Title) AS OrgTitle ,
						 DM.Code As DivisionCode,
						 (SMD.Id)StudentID,
						 (SMD.FirstName + ' ' + SMD.LastName) AS StudentName,
						 (SC.ParentContactNo) AS ContactNo,
						 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1					
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY 
						 OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70) AS Tmp
					)As LessThen70,
--100 % HundredPer All Orggroup Temp
				  (select Count(StudentID) from  (
					select  
						  OGMEL.Id AS OrgGroupId,
						  OGMEL.Title AS OrgGroupTitle,
						  OMEL.Id AS OrgId,
						  (OMEL.Title) As OrgTitle ,
						  DM.Code AS DivisionCode,
						  (SMD.Id)StudentID,
						  (SMD.FirstName+' '+SMD.LastName) AS StudentName,         
						  (SC.ParentContactNo) AS ContactNo,
						  ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
					FROM sAttendance.tStudentRegister SMEL
						   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId						
						   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1					
						   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
					GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100) AS Tmp
					) AS HundredPer,
--AbsentCount All Orggroup Temp
				   (SELECT COUNT(AcademicId) FROM(
					  SELECT 
						ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
						AcademicId,AttendanceDate
					  FROM sAttendance.tStudentRegister d 		
						 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
						 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
					  WHERE
						 OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
						 IsPresent IN(0) 
						 AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
						 and IsPresent=0
					  GROUP BY AcademicId,AttendanceDate) as AbsCnt WHERE rowno=3
					  ) AS AbsentCount,
--LeaveRequest All Orggroup Temp
					(SELECT COUNT(AcademicId) AS LeaveRequest
					FROM sAttendance.tStudentLeaveRequest STSL
						INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
						INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEL.OrgGroupBatchId
						INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
						INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
						INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					WHERE OGM.Id = OGMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
					CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate
					) AS LeaveRequest,
--AttnNotTakenClass All Orggroup Temp
					(Select count(SM1.ID)
					FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
					 WHERE 
						 OGM.Id = OGMR.Id  
						 and SM1.statusid =1 
						 AND COGBM.Id=@rCommonOrgGroupBatchId 
						 AND A.Id  not in (select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
					As AttnNotTakenClass,
					
					
					
					
					@rUptoDate,@rCommonOrgGroupBatchId,GetDate()
				FROM sSetup.tOrgGroupMaster OGM 
				WHERE OGM.Id<>1 AND  ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sAttendance.tTempStudentAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND Total !=0
							END
			
			END
		END
	END

--Organization wise Attendance

ELSE IF @rTypeId=2
    BEGIN
    SELECT 
       OGMT.Id As OrgGroupId,
       OM.Id AS OrgId, 
       OM.Title AS OrgTitle,
       OGMT.Title As OrgGroupTitle,
       
--Total Organization wise
		   (Select count(SM1.ID)
			FROM sStudent.tStudentMaster SM1
				 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
				 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				 INNER JOIN sSetup.tOrganizationMaster OMR ON OM.Id = BM.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId		
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OMR.Id AND COGBM.Id=@rCommonOrgGroupBatchId
				 ) as Total,

--PresentStudent Organization wise
		 (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
			   INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			   INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
			   INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OME.Id and SME.IsPresent=1 AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			) AS PresentStudent,

--AbsentStudent Organization wise
		  (SELECT count(*) 
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AE.StudentId and SM1.StatusId=1
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			WHERE OM.Id = OME.Id AND SME.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			) AS AbsentStudent,
        
--LessThen70 Organization wise
			(SELECT COUNT(StudentID) 
			   FROM (
				 SELECT   
				   OGMEL.Id as OrgGroupId,
				   OGMEL.Title As OrgGroupTitle,
				   OMEL.Id As OrgId,
				   (OMEL.Title) As OrgTitle ,
				   DM.Code As DivisionCode,
				   (SMD.Id)StudentID,
				   (SMD.FirstName+' '+SMD.LastName) AS StudentName,
					(SC.ParentContactNo) AS ContactNo,
					((COUNT(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
				 FROM sAttendance.tStudentRegister SMEL
					INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
					INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
					INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
					INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId	
					INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
					INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId					
					INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
					INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1					
					LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			     
				WHERE OM.Id = OMEL.Id AND SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
				GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)		
			   HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
			   ) AS Tmp)  
			   As LessThen70,
        
--HundredPer Organization wise
			 (SELECT COUNT(StudentID) from  (
				 SELECT  
				 OGMEL.Id as OrgGroupId,
				 OGMEL.Title As OrgGroupTitle,
				 OMEL.Id As OrgId,
				 (OMEL.Title) As OrgTitle ,
				 DM.Code As DivisionCode,
				 (SMD.Id)StudentID,(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				 (SC.ParentContactNo) AS ContactNo,
				 ((count(CAST((case when IsPresent=1 then 1 end) AS float)))) As IsPresentCount,CAST(Count(AcademicId)AS float) As AcademicCount
			 FROM sAttendance.tStudentRegister SMEL
				 INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
				 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
				 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID	and SMD.StatusId=1						
				 LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			     
			 WHERE OM.Id = OMEL.Id AND
				   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			 GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Id,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
				
				
			 HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
			 ) AS Tmp)  
			 As HundredPer,
        
--AbsentCount Organization wise
			(SELECT COUNT(AcademicId) FROM(
				SELECT 
				  ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				  AcademicId,
				  AttendanceDate
				FROM sAttendance.tStudentRegister d 
				 INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				 INNER JOIN sStudent.tStudentMaster SM1 ON SM1.Id = AEL.StudentId and SM1.StatusId=1
				 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				 INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
				 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId				
				WHERE OM.Id = OMEL.Id AND
				IsPresent IN(0) 
				AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
				AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
				GROUP BY AcademicId,AttendanceDate
				) as sfsf
				WHERE rowno=3) 
				as AbsentCount,
        
--LeaveRequest Organization wise
			 (SELECT 
				COUNT(AcademicId) AS LeaveRequest
				FROM sAttendance.tStudentLeaveRequest STSL
				  INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
				  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
				  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1
				  INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID

				WHERE OM.Id = OMEL.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
				CONVERT(char(10), @rUptoDate,126) between LeaveFromDate AND LeaveToDate) 
				As LeaveRequest,
        
--AttnNotTakenClass Organization wise
			(Select count(SM1.ID)
					 FROM sStudent.tStudentMaster SM1
						 INNER JOIN sStudent.tAcademic A ON A.StudentId= SM1.ID and SM1.StatusId=1
						 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
						 INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
						 INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OMEL.OrgGroupId
						 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
						 INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
         
					 WHERE 
						 OM.Id = OMEL.Id  AND COGBM.Id=@rCommonOrgGroupBatchId AND A.Id  not in 
					(select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),@rUptoDate,126))) 
					As AttnNotTakenClass,
			getdate() AS UpdateDate		  
              
     FROM sSetup.tOrgGroupMaster OGMT 
        INNER join sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId 
        INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
     WHERE OGMT.Id=@rOrgGroupId AND U.UserId = @rUserId
   
    END

ELSE IF @rTypeId=11
	BEGIN
     	SELECT OGMR.Id AS OrgGroupId,
			OGMR.Title AS OrgGroupTitle,
			OM.Id As OrgId,(OM.Title) AS OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			0 AS SourceId,
			COUNT(A.StudentID) AS TotalStudent,
			COUNT(CASE WHEN SOD.GenderID=1 then 1 end) AS Male,
			COUNT(CASE WHEN SOD.GenderID=2 then 1 end) AS Female
		FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
		WHERE OGMR.Id=@rOrgGroupId
			AND COGBM.Id=@rCommonOrgGroupBatchId 
		GROUP BY OGMR.Id ,OGMR.Title,OM.Id ,OM.Title,CM.ID,CM.Code
    END

ELSE IF @rTypeId=21
    BEGIN
		SELECT OGMR.Id as OrgGroupId,
			OGMR.Title As OrgGroupTitle,
			OM.Id As OrgId,(OM.Title) As OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			0 AS SourceId,
			COUNT(A.StudentID) AS TotalStudent,
			COUNT(case when SOD.GenderID=1 then 1 end) AS Male,
			COUNT(case when SOD.GenderID=2 then 1 end) AS Female
		FROM sStudent.tStudentMaster SM
			INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
		WHERE OM.Id=@rOrgId
			AND COGBM.Id=@rCommonOrgGroupBatchId 
		GROUP BY OGMR.Id ,OGMR.Title,OM.Id ,OM.Title,CM.ID,CM.Code
     END
     
ELSE IF @rTypeId=12
    BEGIN
		SELECT OGME.Id as OrgGroupId,
			OGME.Title As OrgGroupTitle,
			OME.Id As OrgId,(OME.Title) As OrgTitle,
			CM.ID AS ClassId,CM.Code AS ClassCode,
			0 AS SourceId,
			COUNT(AE.StudentID) AS TotalStudent,
			COUNT(case when SOD.GenderID=1 then 1 end) AS Male,
			COUNT(case when SOD.GenderID=2 then 1 end) AS Female				 
		FROM sAttendance.tStudentRegister SME 
			INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId		
			INNER JOIN sSetup.tClassMaster CM ON CM.ID=AE.ClassId
			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
			LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		WHERE OGME.Id=@rOrgGroupId and SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId   
			and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
		GROUP BY OGME.Id,OGME.Title,OME.Id,OME.Title,CM.ID,CM.Code
         
    END
   
ELSE IF @rTypeId=22
	BEGIN
          SELECT 
				OGME.Id as OrgGroupId,OGME.Title As OrgGroupTitle,
				OME.Id As OrgId,(OME.Title) As OrgTitle,
				 CM.ID AS ClassId,CM.Code AS ClassCode,
				 0 AS SourceId,
				COUNT(AE.StudentID) AS TotalStudent,
				COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
		  FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=AE.ClassId
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id 
		  WHERE OME.Id=@rOrgId and SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId  
				AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
		  GROUP BY OGME.Id,OGME.Title,OME.Id,OME.Title,CM.ID,CM.Code          
	END
   
ELSE IF @rTypeId=13
      BEGIN
      
          (SELECT 
				OGMEA.Id as OrgGroupId,
				OGMEA.Title As OrgGroupTitle,
				OME.Id As OrgId,
				(OME.Title) As OrgTitle,
				CM.ID As ClassId,
				CM.Code As ClassCode,
				0 AS SourceId,
				COUNT(AE.StudentID) AS TotalStudent,
			    COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=AE.ClassID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
				Left JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			WHERE OGMEA.Id=@rOrgGroupId and SME.IsPresent=0  AND COGBM.Id=@rCommonOrgGroupBatchId  
				 and SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			GROUP BY OGMEA.Id,OGMEA.Title,OME.Id,OME.Title,CM.ID,CM.Code
		 )
       END
       
ELSE IF @rTypeId=23
       BEGIN
          (SELECT 
				OGMEA.Id as OrgGroupId,
				OGMEA.Title As OrgGroupTitle,
				OME.Id As OrgId,
				(OME.Title) As OrgTitle,
				CM.ID AS ClassId,CM.Code AS ClassCode,
				0 AS SourceId,
				COUNT(AE.StudentID) AS TotalStudent,
				COUNT(case when SOD.GenderID=1 then 1 end) as Male,
				COUNT(case when SOD.GenderID=2 then 1 end) as Female
		   FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=AE.ClassId
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		   WHERE OME.Id=@rOrgId 
				AND SME.IsPresent=0 AND SME.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId  
		   GROUP BY OGMEA.Id,OGMEA.Title,OME.Id,OME.Title,CM.ID,CM.Code
		  )
    
       END       
       
ELSE IF @rTypeId=14  
      BEGIN
			
       (SELECT *FROM  (
          SELECT 
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				DM.Code As DivisionCode,
				(SMD.Code)StudentID,
				AEL.Id AS SourceId,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo
					FROM sAttendance.tStudentRegister SMEL
						  INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
						  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId 
						  INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
						  INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
						  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BMEl.OrgGroupBatchId
						  INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
						  INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID						
						  INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1						
						  LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	     
					where 
						  OGMEL.Id=@rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId AND		
						  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
						  --GROUP BY SMD.Id
					 GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
					HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	   ) AS Tmp) 

      END
   
ELSE IF @rTypeId=24     
      BEGIN

      (SELECT *FROM  (
           SELECT 
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DM.Code As DivisionCode,
              (SMD.Code)StudentID,
              AEL.Id AS SourceId,
              (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo
	   FROM sAttendance.tStudentRegister SMEL
			   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId			
			   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
			   LEFT JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		WHERE OMEL.Id=@rOrgId AND
		      SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId  
		GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)

	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))<70
	 ) AS Tmp) 
		
          
      END   
   
ELSE IF @rTypeId=15
	   BEGIN	
		(SELECT *FROM(
              SELECT  
                  OGMEL.Id as OrgGroupId,
                  OGMEL.Title As OrgGroupTitle,
                  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                  DM.Code As DivisionCode,
                  (SMD.Code)StudentID,
                  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				  (SC.ParentContactNo) AS ContactNo,
				  AEL.Id AS SourceId
		      FROM sAttendance.tStudentRegister SMEL
				   INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId --AND BMEL.IsActive = 1
				   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			       INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId						
				   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				   Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			   WHERE OGMEL.Id=@rOrgGroupId AND
				   SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			   GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	    ) AS Tmp) 
	   END
	   
ELSE IF @rTypeId=25
	BEGIN	
	 (SELECT *FROM(
           SELECT  
                OGMEL.Id as OrgGroupId,
                OGMEL.Title As OrgGroupTitle,
                OMEL.Id As OrgId,
                (OMEL.Title) As OrgTitle,
                DM.Code As DivisionCode,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
				AEL.Id AS SourceId
			FROM sAttendance.tStudentRegister SMEL
				INNER JOIN sStudent.tAcademic AEL ON SMEL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		    WHERE OMEL.Id=@rOrgId AND
				  SMEL.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
			GROUP BY AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,SMEL.AcademicId,DM.Code,SMD.Code,(SMD.FirstName+' '+SMD.LastName),(SC.ParentContactNo)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(AcademicId)AS float))*100))=100
	  ) AS Tmp) 

	   END
	   	   
ELSE IF @rTypeId=16   
   BEGIN
        
        (SELECT * FROM 
             (SELECT 
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
				DM.Code As DivisionCode,
				(SMD.Code)StudentID,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo,
						 AEL.Id AS SourceId
			  FROM sAttendance.tStudentLeaveRequest STSL
				INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	
			  WHERE OGMEL.Id=@rOrgGroupId 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				AND CONVERT(char(10), @rUptoDate,126) between LeaveFromDate 
				AND LeaveToDate
		) as a) 
   END
      
ELSE IF @rTypeId=26   
   BEGIN
      
      (SELECT * FROM 
          (SELECT 
			  OGMEL.Id as OrgGroupId,
			  OGMEL.Title As OrgGroupTitle,
			  OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
			  DM.Code As DivisionCode,(SMD.Code)StudentID,
			  (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			  (SC.ParentContactNo) AS ContactNo,
			  AEL.Id AS SourceId
		   FROM sAttendance.tStudentLeaveRequest STSL 
			   INNER JOIN sStudent.tAcademic AEL ON STSL.Academicid=AEL.id
			   INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
			   INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
			   INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			   INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			   INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
			   INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
			   INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID		 
		   WHERE OMEL.Id=@rOrgId 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				AND CONVERT(char(10), @rUptoDate,126) between LeaveFromDate 
				AND LeaveToDate
		) as a) 
   END
   
ELSE IF @rTypeId=17   
   BEGIN
       
       (SELECT OrgGroupId,
                OrgGroupTitle,
                OrgId,
                OrgTitle,
                Code As DivisionCode,
                StudentID,
                SourceId,
                StudentName,
                ContactNo FROM( SELECT ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				AcademicId AS SourceId,
				AttendanceDate, 
				DM.Code,
				(SMD.Code)StudentID,
				(SMD.FirstName+' '+SMD.LastName) AS StudentName,(SC.ParentContactNo) As ContactNo
			 FROM sAttendance.tStudentRegister d 							
		 		INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
		     WHERE
				OGMEL.Id=@rOrgGroupId AND
				IsPresent IN(0) 
				AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate   
				AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
			 Group By AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName),SC.ParentContactNo 
			 ) as T
		WHERE rowno=3) 
   END
      
ELSE IF @rTypeId=27   
   BEGIN
       
        (SELECT OrgGroupId,
                OrgGroupTitle,
                OrgId,OrgTitle, 
                Code As DivisionCode,SourceId,
                StudentID,StudentName,
                ContactNo  FROM(
			SELECT 
				ROW_NUMBER() OVER ( PARTITION BY AcademicId ORDER BY MIN(AttendanceDate) DESC) as rowno,
				OGMEL.Id as OrgGroupId,
				OGMEL.Title As OrgGroupTitle,
				OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
                AcademicId AS SourceId,AttendanceDate, 
                DM.Code,
                (SMD.Code)StudentID,
                (SMD.FirstName+' '+SMD.LastName) AS StudentName,
                (SC.ParentContactNo) As ContactNo		
			FROM sAttendance.tStudentRegister d 		
		 		INNER JOIN sStudent.tAcademic AEL ON d.Academicid=AEL.id
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = AEL.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BMEL.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMEL ON OGMEL.Id=OMEL.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BMEL.OrgGroupBatchId
			    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AEL.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AEL.StudentID and SMD.StatusId=1	
				INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID		
			WHERE
				OMEL.Id=@rOrgId AND
				IsPresent IN(0) 
				AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			    AND IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
			Group By AEL.Id,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,AcademicId,AttendanceDate, DM.Code,(SMD.Code),(SMD.FirstName+' '+SMD.LastName),SC.ParentContactNo
			) as sfsf
	   WHERE rowno=3) 
        
   END
   
ELSE IF @rTypeId=18
   BEGIN
			SELECT 
				OrgGroupId,
				OrgGroupTitle,
				OrgId,
				OrgTitle,
				ClassCode,
				StudentCount,
				SourceId,
				ISNULL(TeacherName,'') AS TeacherName,
				ISNULL(ContactNo,'')AS ContactNo  FROM(SELECT 
				O.Id as OrgGroupId,
				O.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				A.ClassId,
				DM.Code AS ClassCode,
				(SELECT COUNT(A.Id) FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1 WHERE  
				DivisionId= DM.Id AND BatchId = BM.Id) AS StudentCount,
				--(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
				A.Id As SourceId,
				(EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.MobileNumber) AS ContactNo,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
			FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			WHERE  O.id = @rOrgGroupId AND  ISNULL(EM.IsOtherUser,0) = 0 AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in  ( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rUptoDate,126))
				) Temp 
		WHERE rowno=1  
		ORDER BY OrgId,ClassCode desc
   END
     
ELSE IF @rTypeId=28
   
   BEGIN

	SELECT 
				OrgGroupId,
				OrgGroupTitle,
				OrgId,
				OrgTitle,
				ClassCode,
				StudentCount,
				SourceId,
				ISNULL(TeacherName,'') AS TeacherName,
				ISNULL(ContactNo,'')AS ContactNo  FROM(SELECT 
				O.Id as OrgGroupId,
				O.Title As OrgGroupTitle,
				OMEL.Id As OrgId,
				(OMEL.Title) As OrgTitle,
				A.ClassId,
				DM.Code AS ClassCode,
				(SELECT COUNT(Id) FROM sStudent.tAcademic WHERE DivisionId= A.DivisionId AND BatchId = A.BatchId) AS StudentCount,
				A.Id As SourceId,
				(EM.FirstName+' '+Em.LastName) AS TeacherName,(EC.MobileNumber) AS ContactNo,
				ROW_NUMBER() OVER ( PARTITION BY A.DivisionId,A.OrgId order by A.DivisionId) as rowno
				FROM sStudent.tAcademic A
				INNER JOIN sStudent.tStudentMaster SM  ON SM.Id= A.StudentId AND SM.StatusId =1
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OMEL ON OMEL.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
				INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OGBM.OrgGroupId		    
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
				INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.ID=DM.InchargeEmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				WHERE  OMEL.id = @rOrgId AND  ISNULL(EM.IsOtherUser,0) = 0 AND COGBM.Id=@rCommonOrgGroupBatchId AND    A.Id  not in  ( select AcademicId from sAttendance.tStudentRegister SR  WHERE SR.AttendanceDate = CONVERT(char(10),  @rUptoDate,126))
				) Temp 
				WHERE 
				rowno=1  
				ORDER BY OrgId,ClassCode desc
	   
   END

ELSE IF @rTypeId=1110
   BEGIN
	  SELECT 
	      (DM.Id) AS DivisionId,
	       SMD.Code As StudentId,
	       A.Id AS SourceId,
	       (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		   (SC.ParentContactNo) AS ContactNo
							
	  FROM sSetup.tDivisionMaster DM
			INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
			INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID and SMD.StatusId=1	
			INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
	   WHERE DM.ID=@rDivisionId 
			 AND DM.OrgId=@rOrgId
	   ORDER BY A.StudentID														          
   END

ELSE IF @rTypeId=1111
	BEGIN
      SELECT 
         (DM.Id) AS DivisionId,
         SMD.Code As StudentId,
         A.Id AS SourceId,
         (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		 (SC.ParentContactNo) AS ContactNo
								
	  FROM sSetup.tDivisionMaster DM
		 INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID and SMD.StatusId=1	
		 INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		 INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
	   WHERE DM.ID=@rDivisionId 
			AND SOD.GenderID=1 
	   ORDER BY A.StudentID            
	END
	
ELSE IF @rTypeId=1112
	BEGIN	  
	  SELECT 
	    (DM.Id) AS DivisionId,
	    A.Id AS SourceId,
	    SMD.Code As StudentId,
	    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
		(SC.ParentContactNo) AS ContactNo								
	  FROM sSetup.tDivisionMaster DM
		INNER JOIN sStudent.tAcademic A ON A.DivisionID=DM.id
		INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=A.StudentID and SMD.StatusId=1	
		INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
		INNER JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID	
	  WHERE DM.ID=@rDivisionId 
		AND SOD.GenderID=2 
	  ORDER BY A.StudentID
	END 
	
  END
  ELSE
    BEGIN

     if @rTypeId=11 OR @rTypeId=21     
        BEGIN
			SELECT 
				(DM.Id) AS DivisionId,
				DM.Code AS ClassDivision,
				SM.Code As StudentId,
				A.Id AS SourceId,
				(SM.FirstName+' '+SM.LastName) AS StudentName,
				(SC.ParentContactNo) AS ContactNo
			FROM sStudent.tStudentMaster SM 
				INNER JOIN sStudent.tAcademic A ON A.StudentId= SM.ID and SM.StatusId=1 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
				INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGMR ON OGMR.Id=OM.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BM.OrgGroupBatchId
				INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tClassMaster CM ON CM.ID=A.ClassId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=A.DivisionID
				LEFT JOIN sStudent.tStudentOther SOD ON SOD.StudentId=A.StudentId
				Left JOIN sStudent.tStudentCommunication SC on SM.Id=SC.StudentID
			WHERE 
				((@rOrgGroupId <>0 AND OGMR.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OM.Id=@rOrgId))
				AND DM.ClassId=@rClassId AND COGBM.Id=@rCommonOrgGroupBatchId
				AND ((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0))
        END
        
     ELSE IF @rTypeId=12 OR @rTypeId=22
      
        BEGIN
         
            SELECT 				
			   (DM.Id) AS DivisionId,
			   DM.Code AS ClassDivision,
			    SMD.Code As StudentId,
			    AE.Id AS SourceId,
			    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			    (SC.ParentContactNo) AS ContactNo
			FROM sAttendance.tStudentRegister SME 
				INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
				INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId
				INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
				INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
				INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
                INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
				INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
				INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID
				INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id and SMD.StatusId=1	
				Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
			WHERE ((@rOrgGroupId <>0 AND OGME.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OME.Id=@rOrgId))
					AND SME.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
					AND SME.AttendanceDate=CONVERT(char(10), @rUpToDate,126)
					AND DM.ClassId=@rClassId AND COGBM.Id=@rCommonOrgGroupBatchId  
				    AND((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0))
       END  
    
     ELSE IF @rTypeId=13 OR @rTypeId=23
        BEGIN
         (select 
			(DM.Id) AS DivisionId,
			   DM.Code AS ClassDivision,
			    SMD.Code As StudentId,
			    AE.Id AS SourceId,
			    (SMD.FirstName+' '+SMD.LastName) AS StudentName,
			    (SC.ParentContactNo) AS ContactNo
		  FROM sAttendance.tStudentRegister SME 
			 INNER JOIN sStudent.tAcademic AE ON SME.Academicid=AE.id
			 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = AE.BatchId --AND BME.IsActive = 1
			 INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = BME.OrgId
			 INNER JOIN sSetup.tOrgGroupMaster OGMEA ON OGMEA.Id=OME.OrgGroupId
			 INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BME.OrgGroupBatchId
             INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			 INNER JOIN sSetup.tDivisionMaster DM ON DM.ID=AE.DivisionID
			 INNER JOIN sStudent.tStudentMaster SMD ON SMD.Id=AE.StudentID and SMD.StatusId=1	
			 INNER JOIN sStudent.tStudentOther SOD ON SOD.StudentId=SMD.Id
			 Left JOIN sStudent.tStudentCommunication SC on SMD.Id=SC.StudentID
					
		   WHERE ((@rOrgGroupId <>0 AND OGMEA.Id=@rOrgGroupId) OR (@rOrgId<>0 AND OME.Id=@rOrgId))
					AND SME.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId AND COGBM.Id=@rCommonOrgGroupBatchId  
					AND SME.AttendanceDate=CONVERT(char(10), @rUpToDate,126)--@rUptoDate
					AND DM.ClassId=@rClassId AND ((@rGenderType=1 AND SOD.GenderID=1) OR (@rGenderType=2 AND SOD.GenderID=2) OR (@rGenderType=0 AND 0=0)))
        END
    END
END
GO
PRINT N'Altering [sAttendance].[pYearlyRegisterGet]...';


GO
 
 

ALTER PROCEDURE [sAttendance].[pYearlyRegisterGet]

	 
	 @rAcademicId bigint=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0,
	 @rAttendanceTypeId tinyint=1,
	 @rStatus int=0,
	 @rDepartmentId int=0
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

SELECT 
	A.AcademicID,
	A.RollNo,
	A.Code,
	YR.AvergeAttendance,
	YR.TotalDays,
	YR.PresentDays,
	
	YR.Month1,
	YR.PresentDays1,
	YR.TotalDays1,
	
	YR.Month2,
	YR.PresentDays2,
	YR.TotalDays2,
	
	YR.Month3,
	YR.PresentDays3,
	YR.TotalDays3,
	
	YR.Month4,
	YR.PresentDays4,
	YR.TotalDays4,
	
	YR.Month5,
	YR.PresentDays5,
	YR.TotalDays5,
	
	YR.Month6,
	YR.PresentDays6,
	YR.TotalDays6,
	
	YR.Month7,
	YR.PresentDays7,
	YR.TotalDays7,
	
	YR.Month8,
	YR.PresentDays8,
	YR.TotalDays8,
	
	YR.Month9,
	YR.PresentDays9,
	YR.TotalDays9,
	
	YR.Month10,
	YR.PresentDays10,
	YR.TotalDays10,
	
	YR.Month11,
	YR.PresentDays11,
	YR.TotalDays11,
	
	YR.Month12,
	YR.PresentDays12,
	YR.TotalDays12,
	
	--SM.FirstName + ' ' + ' '+ SM.MiddleName+ ' ' + SM.LastName As Name,
	A.Name,
	A.StatusID,
	SO.UIDNumber,
	SO.AdhaarNumber


from
	sAttendance.tYearlyRegister YR
	--INNER JOIN sStudent.tAcademic A ON A.Id=YR.AcademicId
	--INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId 
	INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId=YR.AcademicId
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId
	
where 


	((YR.AcademicId=@rAcademicId) OR (@rAcademicId=0))
	AND(A.BatchId=@rBatchId)
	AND((A.ClassId=@rClassId) OR (@rClassId=0))
	AND((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND ((A.StatusId=@rStatus) OR (@rStatus=0))
	order by A.RollNo 
 
	 END
GO
PRINT N'Altering [sBiometric].[pMonthlyStatusUpdate]...';


GO
ALTER PROCEDURE [sBiometric].[pMonthlyStatusUpdate]
    
    @rAttndanceDate date,
    @rIsDelete bit=0,
    @rOrgGroupId int=0,
    @rBatchId int=0,
    @rOrgId int=0,
    @rUserId bigint=0
    
AS
SET NOCOUNT ON
BEGIN

	IF OBJECT_ID('tempdb..#TempLateCountEntry') IS NOT NULL
		DROP TABLE #TempLateCountEntry
	
	IF(@rIsDelete = 0)
	BEGIN
		IF EXISTS(SELECT 1 FROM sBiometric.tMonthlyStatusUpdate WHERE CONVERT(date,AttndanceDate) = CONVERT(date,@rAttndanceDate) AND Left(EmployeeID,4) =@rOrgId)
		BEGIN
			SELECT -201 AS RESULT 
			RETURN
		END
	END
	--ELSE
	--BEGIN
	--	IF NOT EXISTS(SELECT 1 FROM sBiometric.tMonthlyStatusUpdate WHERE AttndanceDate=@rAttndanceDate)
	--	BEGIN
	--		SELECT -102 AS RESULT
	--		RETURN
	--	END
	--END

	BEGIN TRY
	BEGIN TRANSACTION
	
	IF(@rIsDelete = 0)
	BEGIN
		Declare @Days int 
		DECLARE @rMonth int
		DECLARE @rYear int
		Set @rMonth = MONTH(@rAttndanceDate)
		Set @rYear = Year(@rAttndanceDate)
		select @Days=sCommon.fGetDaysInMonth(@rMonth,@rYear)
		
		INSERT INTO 
		sBiometric.tMonthlyStatusUpdate 
		SELECT            			            
	 Attn_Dt, Mt.EmployeeId, CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,1,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,1,BM.Id,0,BM.OrgId) Else Mt.D01 End D01,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,2,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,2,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D02 End D02,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,3,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,3,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D03 End D03,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,4,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,4,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D04 End D04,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,5,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,5,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D05 End D05,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,6,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,6,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else Mt.D06 End D06,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,7,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,7,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D07 End D07,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,8,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,8,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D08 End D08,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,9,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,9,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D09 End D09,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,10,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,10,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D10 End D10,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,11,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,11,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D11 End D11,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,12,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,12,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D12 End D12,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,13,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,13,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D13 End D13,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,14,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,14,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D14 End D14,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,15,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,15,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D15 End D15,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,16,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,16,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D16 End D16,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,17,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,17,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D17 End D17,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,18,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,18,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D18 End D18,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,19,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,19,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D19 End D19,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,20,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,20,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D20 End D20,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,21,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,21,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D21 End D21,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,22,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,22,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D22 End D22,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,23,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,23,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D23 End D23,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,24,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,24,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D24 End D24,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,25,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,25,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D25 End D25,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,26,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,26,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D26 End D26,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,27,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,27,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D27 End D27,
	 CAse When [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,28,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,28,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D28 End D28,
	 CAse when @Days >= 29 AND [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,29,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,29,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D29 End D29,
	 CAse when @Days >= 30 AND [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,30,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,30,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D30 End D30,
	 CAse when @Days >= 31 AND [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,31,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) != '-' Then [sHrm].[fWeekHOffHolidayGet](Mt.EmployeeId, @rYear,@rMonth,31,BM.Id,ED.OrganizationDepartmentId,BM.OrgId) Else mT.D31 End D31, 
	 D01_IN, D02_IN, D03_IN, D04_IN, D05_IN, D06_IN, D07_IN, D08_IN, D09_IN, D10_IN, D11_IN, D12_IN, D13_IN, D14_IN, D15_IN, D16_IN, D17_IN, D18_IN, D19_IN, D20_IN, D21_IN, D22_IN, 
			D23_IN, D24_IN, D25_IN, D26_IN, D27_IN, D28_IN, D29_IN, D30_IN, D31_IN, D01_OUT, D02_OUT, D03_OUT, D04_OUT, D05_OUT, D06_OUT, D07_OUT, D08_OUT, D09_OUT, D10_OUT, D11_OUT, 
			D12_OUT, D13_OUT, D14_OUT, D15_OUT, D16_OUT, D17_OUT, D18_OUT, D19_OUT, D20_OUT, D21_OUT, D22_OUT, D23_OUT, D24_OUT, D25_OUT, D26_OUT, D27_OUT, D28_OUT, D29_OUT, 
			D30_OUT, D31_OUT, Tot_Attn, Tot_Abs, Tot_WeekOFF, Tot_Holiday, Tot_HD, Tot_Leave
		FROM sBiometric.tMonthTrans Mt  LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Mt.EmployeeId 
		inner join sSetup.tBatchMaster BM ON BM.OrgId = ED.OrgId AND BM.IsActive = 1  AND ED.OrgId = @rOrgId
		WHERE CONVERT(date,Attn_Dt) = CONVERT(date,@rAttndanceDate)
		
	-- Leave Entry
	DECLARE @lIsErrorCaseAsAnAbsent bit=0	
	DECLARE @lErrorCaseAsAnAbsent nvarchar(50)
	
	SELECT @lErrorCaseAsAnAbsent = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 254 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	IF (@lErrorCaseAsAnAbsent IS NULL) OR (@lErrorCaseAsAnAbsent = 'False')
	SET @lIsErrorCaseAsAnAbsent = 0
	ELSE
	SET @lIsErrorCaseAsAnAbsent = 1	 
	
	DECLARE @lIsErrorCaseLeaveEntryDirectly bit=0	
	DECLARE @lErrorCaseLeaveEntryDirectly nvarchar(50)
	
	SELECT @lIsErrorCaseLeaveEntryDirectly = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 255 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	IF (@lIsErrorCaseLeaveEntryDirectly IS NULL) OR (@lIsErrorCaseLeaveEntryDirectly = 'False')
	SET @lErrorCaseLeaveEntryDirectly = 0
	ELSE
	SET @lErrorCaseLeaveEntryDirectly = 1	
	
	DECLARE @lIsAbsentAsLWP bit=0	
	DECLARE @lAbsentAsLWP nvarchar(50)
	
	SELECT @lAbsentAsLWP = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 258 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	IF (@lAbsentAsLWP IS NULL) OR (@lAbsentAsLWP = 'False')
	SET @lIsAbsentAsLWP = 0
	ELSE
	SET @lIsAbsentAsLWP = 1
	
	
	DECLARE @lErrorCaseLeaveDeduction nvarchar(50)
	SELECT @lErrorCaseLeaveDeduction = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 306 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	
	IF((@lIsErrorCaseAsAnAbsent = 1 AND @lIsErrorCaseLeaveEntryDirectly=1) OR (@lIsAbsentAsLWP= 1 AND @lIsErrorCaseLeaveEntryDirectly=1))
	BEGIN 
		
		DECLARE @rFromDate date
		DECLARE @rToDate date
		
		SET @rFromDate = @rAttndanceDate		
		SET @rToDate = CONVERT(date, (CONVERT(nvarchar(4),YEAR(@rAttndanceDate)) +'-'+CONVERT(nvarchar(2),MONTH(@rAttndanceDate)) +'-'+ CONVERT(nvarchar(2),@Days)))
		
		CREATE TABLE #TempMonthlyStatusUpdate
		(
		Id int Identity,
		EmployeeId bigint,	
		AttendanceDate Date,
		PresentStatus nvarchar(50)
		)

		INSERT INTO #TempMonthlyStatusUpdate

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 01) as datetime),D01 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 02) as datetime),D02 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 03) as datetime),D03 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 04) as datetime),D04 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 05) as datetime),D05 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 06) as datetime),D06 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 07) as datetime),D07 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 08) as datetime),D08 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 09) as datetime),D09 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 10) as datetime),D10 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 11) as datetime),D11 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 12) as datetime),D12 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 13) as datetime),D13 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 14) as datetime),D14 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 15) as datetime),D15 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 16) as datetime),D16 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 17) as datetime),D17 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 18) as datetime),D18 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 19) as datetime),D19 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 20) as datetime),D20 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 21) as datetime),D21 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 22) as datetime),D22 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 23) as datetime),D23 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 24) as datetime),D24 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 25) as datetime),D25 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 26) as datetime),D26 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 27) as datetime),D27 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		UNION ALL

		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 28) as datetime),D28 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID

		IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
		BEGIN
		INSERT INTO #TempMonthlyStatusUpdate
		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 29) as datetime),D29 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID
		END

		IF Month(@rFromDate) <> 2
		BEGIN
		INSERT INTO #TempMonthlyStatusUpdate
		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 30) as datetime),D30 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID
		END

		IF Month(@rFromDate) NOT IN (2,4,6,9,11)
		BEGIN
		INSERT INTO #TempMonthlyStatusUpdate
		SELECT EmployeeId,cast(rtrim(YEAR(AttndanceDate) *10000+ Month(AttndanceDate) *100+ 31) as datetime),D31 FROM sBiometric.tMonthlyStatusUpdate WHERE
		AttndanceDate >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND AttndanceDate <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND Left(EmployeeID,4) = @rOrgID
		END
		
		DECLARE @lCount int = 0
		SELECT @lCount = COUNT(Id) FROM #TempMonthlyStatusUpdate

	 --- 3 Late Count means Add 1 Leave START HERE

		DECLARE @lLateCountLeaveType nvarchar(50)
		SELECT @lLateCountLeaveType = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 351 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

		SELECT ROW_NUMBER() OVER(ORDER BY EMPLOYEEID ASC) AS RowNumber,EMPLOYEEID,ATTN_DT,count_late INTO #TempLateCountEntry FROM sBiometric.tMonthTrans 
		where EMPLOYEEID IN(SELECT EMPLOYEEID FROM  #TempMonthlyStatusUpdate WHERE MONTH(AttendanceDate)=@rMonth AND YEAR(AttendanceDate)=@rYear  GROUP BY EMPLOYEEID)
		AND MONTH(ATTN_DT)=@rMonth AND YEAR(ATTN_DT)=@rYear
		
		DECLARE @lMonthTransCount int=0		
		SELECT @lMonthTransCount = COUNT(RowNumber) FROM #TempLateCountEntry

		WHILE (@lMonthTransCount > 0)
		BEGIN 
			DECLARE @lLateCount int = 0
			DECLARE @rEmployeeId bigint = 0
			DECLARE @lAttnDt date
			DECLARE @rLeaveTypeId int = 0
			DECLARE @rTotalLeave int = 0
			DECLARE @FromDt date
			DECLARE @ToDt date
			DECLARE @lNextNumber bigint

			IF(@lLateCountLeaveType IS NOT NULL)
				BEGIN
					SELECT @rEmployeeId=ISNULL(EmployeeId,0) FROM #TempLateCountEntry WHERE RowNumber = @lMonthTransCount 
								
					set @lLateCount= (SELECT ISNULL([sBiometric].[fEmployeeLateCountGet](@rEmployeeId, @rMonth,@rYear),0) AS LateCount)

					IF(@lLateCount >= 3)
					BEGIN
						SELECT @rLeaveTypeId=ISNULL(Id,0) FROM  sHrm.tLeaveTypeMaster WHERE OrgId = @rOrgId AND Code=@lLateCountLeaveType

						SET @rTotalLeave = (SELECT (@lLateCount/3) AS RESULT ) 

						IF(@rLeaveTypeId!=0)
							BEGIN
							SET @lAttnDt = GETDATE()
							
							SET @ToDt =  CONVERT(date, (CONVERT(nvarchar(4),@rYear) +'-'+CONVERT(nvarchar(2),@rMonth) +'-'+ CONVERT(nvarchar(2),@Days)))

							SET @FromDt = (select DATEADD(D,(-@rTotalLeave)+1 ,@ToDt))

							IF NOT EXISTS(SELECT 1 FROM sHrm.tLeave WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND BatchId = @rBatchId AND StatusId=550 and LeaveReason='Late Coming' AND ReportDate=@ToDt)

								BEGIN
								 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sHrm.tLeave', 0, 1, 1,@outNextNumber = @lNextNumber output
							 
								INSERT INTO [sHrm].[tLeave]([Id],[EmployeeId],[ReportDate],[FromDate],[ToDate],[LeavePeriodId],[LeaveTypeId],[LeaveReason],NoOfLeave,BatchId,[OrgId],[CreatedUserId],[CreatedDateTime],[UpdatedUserId],[UpdatedDateTime],[StatusId],[FromTime],[ToTime])
								 VALUES (@lNextNumber,@rEmployeeId,@ToDt,@FromDt,@ToDt ,1,@rLeaveTypeId,'Late Coming',@rTotalLeave,@rBatchId,@rOrgId,@rUserId,sCommon.fGetDate(),@rUserId,sCommon.fGetDate(),550,NULL,NULL)	

								--EXEC [sHrm].[pLeaveAdd] 0,@rEmployeeId,@ToDt,@FromDt,@ToDt ,1,@rLeaveTypeId,'Late Coming',@rTotalLeave,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
								END
							END
					END
			END


			SET @lMonthTransCount = @lMonthTransCount -1
		END
	--- END HERE
		
		WHILE (@lCount > 0)
		BEGIN
			 DECLARE @lEmployeeId bigint = 0
			 DECLARE @lAttendanceDate date
			 DECLARE @lPresentStatus nvarchar(50)
			 DECLARE @lLeaveTypeId int = 0
			 
			 IF(@lIsErrorCaseAsAnAbsent = 1)
			 BEGIN
				SELECT @lEmployeeId=ISNULL(EmployeeId,0),@lAttendanceDate=AttendanceDate,@lPresentStatus=PresentStatus FROM #TempMonthlyStatusUpdate WHERE Id = @lCount AND PresentStatus='E'
					IF(@lEmployeeId!=0)
					BEGIN
						SELECT @lLeaveTypeId=ISNULL(Id,0) FROM  sHrm.tLeaveTypeMaster WHERE OrgId = @rOrgId AND IsLWP=1
						
						IF(@lLeaveTypeId!=0)
						BEGIN
							IF(@lErrorCaseLeaveDeduction='0' OR @lErrorCaseLeaveDeduction='1')
								EXEC [sHrm].[pLeaveAdd] 0,@lEmployeeId,@lAttendanceDate,@lAttendanceDate,@lAttendanceDate ,1,@lLeaveTypeId,'Error Case',1,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
							ELSE IF(@lErrorCaseLeaveDeduction='0.50')
								EXEC [sHrm].[pLeaveAdd] 0,@lEmployeeId,@lAttendanceDate,@lAttendanceDate,@lAttendanceDate ,1,@lLeaveTypeId,'Error Case',0.50,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
						END	
					END
			 END
			 
			 IF(@lIsAbsentAsLWP = 1)
			 BEGIN
				SELECT @lEmployeeId=ISNULL(EmployeeId,0),@lAttendanceDate=AttendanceDate,@lPresentStatus=PresentStatus FROM #TempMonthlyStatusUpdate WHERE Id = @lCount AND PresentStatus='A'
					IF(@lEmployeeId!=0)
					BEGIN
						SELECT @lLeaveTypeId=ISNULL(Id,0) FROM  sHrm.tLeaveTypeMaster WHERE OrgId = @rOrgId AND IsLWP=1
					IF(@lLeaveTypeId!=0)
						EXEC [sHrm].[pLeaveAdd] 0,@lEmployeeId,@lAttendanceDate,@lAttendanceDate,@lAttendanceDate ,1,@lLeaveTypeId,'Error Case',1,@rBatchId,@rOrgId,@rUserId,550,NULL,NULL
				END
			 END
			 
			 SET @lCount = @lCount -1
		END
	END
	END
	ELSE
	BEGIN
		DELETE FROM sBiometric.tMonthlyStatusUpdate WHERE CONVERT(date,AttndanceDate) = CONVERT(date,@rAttndanceDate)
		AND Left(EmployeeID,4)=@rOrgId
	END
	
	SELECT 1 AS RESULT	
	   
	COMMIT TRANSACTION
	END TRY	
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Altering [sCanteen].[pRptCanteenIssueSlipGet]...';


GO

ALTER PROCEDURE [sCanteen].[pRptCanteenIssueSlipGet]
	 @rCanteenId int,
	 @rFromDate date='',
	 @rToDate date='',
	 @ItemCode nvarchar(20)='',
	 @rId bigint=0,
	 @rBuilder1 nvarchar(max)=''
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
DECLARE @lOrgGroupId int = 0

 SELECT @lOrgGroupId = OrgGroupId   FROM sCanteen.tCanteenMaster C
 WHERE C.Id = @rCanteenId
 
	SELECT 
	       
	        CI.IssueDate,
			CID.Quantity,
			CID.ItemPrice,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Name,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.FirstName +' ' + EM.MiddleName + ' ' + EM.LastName ,'') ElSE CI.OtherName
			 END) AS Name,
			 FM.Title As ItemTitle,
			CID.CanteenIssueId,
			CID.FoodItemId,
			sFinanceCommon.fNumberToWordsWithDecimal (ISNULL(CI.TotalAmount,0.00),1,2,@lOrgGroupId) AS TotalAmountInWords,
			CM.Title AS CanteenTitle,
			CI.Id AS Id,
			
			isnull(SMast.RollNo,'') AS RollNo,
			isnull(SMast.ClassName,'') AS ClassName,
			isnull(SMast.DivisionName,'') AS DivisionName,
			isnull(SMast.OrganizationName,'') AS OrganizationName,
			isnull(SMast.BatchName,'') AS BatchName,
			isnull(SMast.Code,'') AS Code
  FROM 
  
            sCanteen.tCanteenIssueDetail CID
            INNER JOIN sCanteen.tCanteenIssue CI ON CI.Id=CID.CanteenIssueId AND CI.CanteenId=@rCanteenId
            INNER JOIN sCanteen.tFoodItemMaster FM ON FM.Id=CID.FoodItemId
            LEFT JOIN sStudent.vStudentLastAcademic SMast ON SMast.StudentId = CI.SourceId AND CI.SourceTypeId = 2003 
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = CI.SourceId AND CI.SourceTypeId = 95
            LEFT JOIN sCanteen.tCanteenMaster CM ON CM.Id=@rCanteenId
            
  WHERE   ((CI.Id = @rId) OR (@rId = 0))
       AND CI.CanteenId = @rCanteenId 
	   AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	   AND ((CI.IssueDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	--AND ((FM.Code = @ItemCode) OR (ISNULL(@ItemCode,'')=''))
	AND  ISNULL(EM.IsOtherUser,0) = 0
	     
END
GO
PRINT N'Altering [sCertificate].[pLeavingAdd]...';


GO
ALTER PROCEDURE [sCertificate].[pLeavingAdd]
			
		@rId bigint
       ,@rAcademicId bigint
       ,@rLCNumber int
       ,@rLCDate date
       ,@rLeftDate date
       ,@rLCCopy tinyint
       ,@rLCRemark nvarchar(200)
       ,@rLCProgress nvarchar(200)
       ,@rLCConduct nvarchar(200)
       ,@rLCReason nvarchar(200)
       ,@rLCBookNumber nvarchar(20)
       ,@rCreatedUserId bigint
       ,@rOrgId int
       ,@rToCollege nvarchar(200)
	   ,@rToCollegeAddress nvarchar(200)
	   ,@rLastExamName nvarchar(200)
	   ,@rLastExamResult nvarchar(200)
	   ,@rRepeatDetail nvarchar(100)
	   ,@rSubjectStudied nvarchar(300)
	   ,@rPromoteToClass nvarchar(50)
	   ,@rFeeDetail nvarchar(100)
	   ,@rFeeConcessionDetail nvarchar(100)
	   ,@rExtraCurricularActivities nvarchar(200)
	   ,@rNCCScoutDetail nvarchar(100)
	   ,@rTermsInInstitute nvarchar(500)
	   ,@rBatchId int
	   ,@rIsNumberBatchWise bit = 0
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	 DECLARE @lNextNumber BIGINT
	 DECLARE @lStudentId bigint
	 DECLARE @lClassId bigint
	 DECLARE @lAdmissionDate Date
	 
	 SELECT @lStudentId=StudentId,@lClassId=ClassId FROM sStudent.tAcademic WHERE Id=@rAcademicId
	 UPDATE sStudent.tAcademic SET BatchStatusId = 1 WHERE BatchStatusId is null
	 
	 If(@rIsNumberBatchWise = 1)
	 BEGIN
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId AND BatchId = @rBatchId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	 ELSE
 	 BEGIN
		IF(@rLCNumber = 0)	
		BEGIN
			SELECT @rLCNumber = ISNULL(MAX(LCNumber),0) + 1 FROM sCertificate.tLeaving WHERE OrgId=@rOrgId
		END	
	 
		IF(@rId = 0)	
		BEGIN
			IF EXISTS (SELECT Id FROM sCertificate.tLeaving WHERE AcademicId = @rAcademicId)-- IN(SELECT Id FROM sStudent.tAcademic WHERE StudentId=@lStudentId))
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
			
			IF EXISTS(SELECT 1 FROM sCertificate.tLeaving WHERE LCNumber=@rLCNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -104 AS Result
				RETURN
			END
		END
	END
			
			IF EXISTS(SELECT 1 FROM sAttendance.tStudentRegister WHERE AttendanceDate>@rLeftDate AND AcademicId=@rAcademicId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END
			
			SELECT @lAdmissionDate = AdmissionDate FROM sStudent.tStudentAdmission WHERE StudentId=@lStudentId
			IF (@lAdmissionDate > @rLCDate)
			BEGIN
				SELECT -105 AS Result
				RETURN
			END
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT Id FROM sCertificate.tLeaving WHERE AcademicId=@rAcademicId AND Id<>@rId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
		
		BEGIN TRANSACTION	
			
		IF(@rId = 0)	
		BEGIN
				EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tLeaving', 0, 1, 1,@outNextNumber = @lNextNumber output
				INSERT INTO sCertificate.tLeaving
				(
					Id
				   ,AcademicId
				   ,LCNumber
				   ,LCDate
				   ,LeftDate
				   ,LCCopy
				   ,LCRemark
				   ,LCProgress
				   ,LCConduct
				   ,LCReason
				   ,LCBookNumber
				   ,OrgId
				   ,CreatedUserId
				   ,CreatedDateTime
				   ,ToCollege
				   ,ToCollegeAddress
				   ,LastExamName 
		           ,LastExamResult 
		           ,RepeatDetail 
		           ,SubjectStudied
		           ,PromoteToClass 
		           ,FeeDetail 
		           ,FeeConcessionDetail
		           ,ExtraCurricularActivities
		           ,NCCScoutDetail 
		           ,TermsInInstitute
		           ,BatchId
				   
				)
				VALUES
				(	@lNextNumber
				   ,@rAcademicId
				   ,@rLCNumber
				   ,@rLCDate
				   ,@rLeftDate
				   ,@rLCCopy
				   ,@rLCRemark
				   ,@rLCProgress
				   ,@rLCConduct
				   ,@rLCReason
				   ,@rLCBookNumber
				   ,@rOrgId
				   ,@rCreatedUserId
				   ,sCommon.fGetDate() 
				   ,@rToCollege
				   ,@rToCollegeAddress
				   ,@rLastExamName 
		           ,@rLastExamResult 
		           ,@rRepeatDetail 
		           ,@rSubjectStudied
		           ,@rPromoteToClass 
		           ,@rFeeDetail 
		           ,@rFeeConcessionDetail
		           ,@rExtraCurricularActivities
		           ,@rNCCScoutDetail 
		           ,@rTermsInInstitute
		           ,@rBatchId
				)	
				SELECT @lNextNumber AS Result 
				 
		END
		
		ELSE
		
		BEGIN
		
			 
			 SET @lNextNumber = @rId
				UPDATE  sCertificate.tLeaving
				SET
					AcademicId=@rAcademicId,
					LCDate=@rLCDate,
					LeftDate=@rLeftDate,
					LCCopy=@rLCCopy,
					LCRemark=@rLCRemark,
					LCProgress=@rLCProgress,
					LCConduct=@rLCConduct,
					LCReason=@rLCReason,
					LCBookNumber=@rLCBookNumber,
					UpdatedUserId=@rCreatedUserId,
					UpdatedDateTime=sCommon.fGetDate(),
					ToCollege=@rToCollege,
				    ToCollegeAddress=@rToCollegeAddress,
				    LastExamName=@rLastExamName 
				    ,LastExamResult=@rLastExamResult 
				    ,RepeatDetail=@rRepeatDetail 
				    ,SubjectStudied=@rSubjectStudied
				    ,PromoteToClass=@rPromoteToClass 
				    ,FeeDetail=@rFeeDetail 
				    ,FeeConcessionDetail=@rFeeConcessionDetail
				    ,ExtraCurricularActivities=@rExtraCurricularActivities
				    ,NCCScoutDetail=@rNCCScoutDetail 
				    ,TermsInInstitute=@rTermsInInstitute
				    ,BatchId = @rBatchId
				WHERE Id = @rId
				
		 
		END 
		
		
				UPDATE sStudent.tStudentAdmission
				SET
				  LeftStandardId=@lClassId,
				  LeftDate = @rLeftDate, 
				  LeftReason = @rLCReason, 
				  LCProgress = @rLCProgress,
				  LCConduct = @rLCConduct, 
				  LCBook = @rLCBookNumber, 
				  LCNumber = @rLCNumber,
				  LCDate = @rLCDate, 
				  LCRemark = @rLCRemark, 
				  LCCopy = @rLCCopy, 
				  LcId = @lNextNumber, 
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE StudentId = @lStudentId 
				
				UPDATE sStudent.tStudentMaster
				SET
				  StatusId=3,
				  UpdatedUserId = @rCreatedUserId, 
				  UpdatedDateTime =sCommon.fGetDate()
				WHERE Id = @lStudentId 
				
			  UPDATE sSecurity.tUser
			   SET IsObsolete=1 
			   WHERE SourceTypeId=2003 AND Sourceid=@lStudentId
			   
		 COMMIT TRANSACTION		
		 
		  --Update Batch Status 
			UPDATE A
			SET BatchStatusId = 3 
			FROM sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
			INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
			WHERE SM.StatusId = 3 AND SM.Id = @lStudentId
		 --Ends

		   --Update Class Status 
			UPDATE A
			SET ClassStatusId = 3 ,
			 UpdatedUserId = @rCreatedUserId, 
		     UpdatedDateTime =sCommon.fGetDate()
			FROM sStudent.tAcademic A
			WHERE A.Id = @rAcademicId
		 --Ends
		 
		  SELECT @lNextNumber AS Result
	
	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
	
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].[pCircularGet]...';


GO

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

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			U.DisplayTitle as CreatedUserName,
			C.AssigneeId,
			AM.Title AS Assignee,
			CTM.Title AS CircularTypeTitle,
			CTM.HighlightColor,
			C.CircularTypeId,
			C.CreatedUserId,
			C.CreatedDateTime,
			ISNULL(C.StatusId,549) AS StatusId
			--CASE WHEN ISNULL(C.StatusId,549) =549 then 'Pending' WHEN C.StatusId=550 then 'Approve' ELSE 'Reject' END AS Status
  FROM 
            sCommunication.tCircular C
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=C.AssigneeId
            INNER JOIN sCommunication.tCircularTypeMaster CTM ON CTM.Id = C.CircularTypeId
  WHERE 
  
		((C.Id = @rId) OR (@rId = 0))
	AND ((C.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((C.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((C.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((C.AssigneeId IN (1,2,3) AND @rAssigneeId=1)  OR
		 (C.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2,3)) OR
		  @rIsSearch = 0)
     AND (C.CircularTypeId=@rCircularTypeId OR @rIsSearch = 0)
    AND (C.CreatedUserId = @rCreatedUserId OR @rCreatedUserId = 0)
	ORDER BY C.StartDate DESC
END
GO
PRINT N'Altering [sCommunication].[pCircularListGet]...';


GO
 
ALTER PROCEDURE [sCommunication].[pCircularListGet]
	 
	 @rOrgGroupBatchId int,
	 @rUserId bigint,
	 @rUserSourceId bigint,
	 @rUserSourceTypeId int,
	 @rSyncedCircularId bigint = 0,
	 @rStartDate date='',
	 @rName nvarchar(200)='',
	 @rFromDate date='',
	 @rToDate date=''
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	
	
	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	 DECLARE @lAcademicId bigint,@lStudentId bigint,@lClassId int,@lDivisionId int,@lOrgId int,@lDepartmentId int,@lEmployeeId bigint
	 
	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsCircularBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 302 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsCircularBasedOnApproval = 0
	ELSE
	SET @lIsCircularBasedOnApproval = 1	
	
	
	if @rUserSourceTypeId   = 95 -- For Employee Login
	
	BEGIN
	
		--DECLARE @lDepartmentId int,@lOrgId int,@lDepartmentId int
		
		SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId,@lEmployeeId = EM.Id FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId
		
	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
			  
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId           
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
             WHERE (((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 95 AND CS.SourceId =@lEmployeeId )) AND CS.AssigneeToId=3)
              AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D
				ON D.CircularId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,3) 
            AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
            AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			AND (C.Title like @rName OR ISNULL(@rName,'')='')			
			AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
           	ORDER BY C.StartDate DESC
			
	
 END
 ELSE IF @rUserSourceTypeId   = 2003 -- For Student Login
 BEGIN
 
 
 SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId
  FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM
	ON A.BatchId = BM.Id 
	--AND BM.IsActive = 1 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId

 
  
 	SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
	 FROM 
            sCommunication.tCircular C 
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId      
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId
            INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
            WHERE (((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR
            (CS.SourceTypeId = 2017 AND CS.SourceId =@lDepartmentId) OR
            (CS.SourceTypeId = 2016 AND CS.SourceId =@lClassId) OR
            (CS.SourceTypeId = 2005 AND CS.SourceId =@lDivisionId) OR
            (CS.SourceTypeId = 2003 AND CS.SourceId =@lStudentId) OR
            (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId) )
            AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0))AND CS.AssigneeToId=2) D
				ON D.CircularId= C.Id
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
            AND C.AssigneeId IN (1,2) 
             AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
             AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
			 AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
			 AND (C.Title like @rName OR ISNULL(@rName,'')='')
			 AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
            ORDER BY C.StartDate DESC

 END
 ELSE
  --For Other Users
 BEGIN
 
 SELECT 	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			ISNULL(CV.UserId,0) AS UserId,
			U.DisplayTitle as CreatedUserName,
			CTM.HighlightColor,
			CTM.Title AS CircularTypeTitle,
			C.OrgGroupId
			
	 FROM 
            sCommunication.tCircular C     
            INNER JOIN sCommunication.tCircularTypeMaster CTM
				ON CTM.Id=C.CircularTypeId  
            LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
             AND C.AssigneeId IN (1,2,3)
             AND ((C.StartDate=convert(date,@rStartDate)) OR (isnull(@rStartDate,'')=''))
             AND (C.StartDate>=convert(date,@rFromDate) OR ISNULL(@rFromDate,'')='')
		     AND (C.StartDate<=convert(date,@rToDate) OR ISNULL(@rToDate,'')='')
		     AND (C.Title like @rName OR ISNULL(@rName,'')='')
		     AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
            ORDER BY C.StartDate DESC

 
 	--SELECT 	
		--	C.Id as CircularId,
		--	C.Title,
		--	C.Remark,
		--	C.StartDate,
		--	CV.UserId,
		--	U.DisplayTitle as CreatedUserName	    
	 --FROM 
  --          sCommunication.tCircular C       
  --          LEFT JOIN sCommunication.tCircularView CV ON CV.CircularId=C.Id AND UserId=@rUserId     
  --          INNER JOIN sCommunication.tCircularScope CS ON CS.CircularId=C.Id 
  --          INNER JOIN ( SELECT A.DivisionId FROM sStudent.tAcademic A            
  --           WHERE A.StudentId = @rUserSourceId ) D
  --          ON D.DivisionId =  CS.SourceId AND CS.SourceTypeId = 2005
  --          INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
  --          INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
  --          WHERE ( C.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
  --          Order by C.CreatedDateTime DESC


 END
 END
GO
PRINT N'Altering [sCommunication].[pCircularQueueGet]...';


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

BEGIN 

 --   DECLARE @lConfigValue nvarchar(50)
	--DECLARE @lIsCircularBasedOnApproval bit=0
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 302 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsCircularBasedOnApproval = 0
	--ELSE
	--SET @lIsCircularBasedOnApproval = 1	




	 IF (@rIsSearch = 1)
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	   
	SELECT 
	
			C.Id as CircularId,
			C.Title,
			C.Remark,
			C.StartDate,
			U.DisplayTitle as CreatedUserName,
			C.AssigneeId,
			AM.Title AS Assignee,
			CTM.Title AS CircularTypeTitle,
			CTM.HighlightColor,
			C.CircularTypeId,
			C.CreatedUserId,
			C.CreatedDateTime,
			ISNULL(C.StatusId,549) AS StatusId,
			CASE WHEN ISNULL(C.StatusId,549) =549 then 'Pending' WHEN C.StatusId=550 then 'Approved' ELSE 'Reject' END AS Status
  FROM 
            sCommunication.tCircular C
            INNER JOIN sSecurity.tUser U ON U.Id=C.CreatedUserId
            INNER JOIN sCommon.tAssigneeMaster AM ON AM.Id=C.AssigneeId
            INNER JOIN sCommunication.tCircularTypeMaster CTM ON CTM.Id = C.CircularTypeId
  WHERE 
  
		((C.Id = @rId) OR (@rId = 0))
	AND ((C.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((C.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((C.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((C.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND ((C.AssigneeId IN (1,2,3) AND @rAssigneeId=1)  OR
		 (C.AssigneeId = @rAssigneeId AND @rAssigneeId IN (2,3)) OR
		  @rIsSearch = 0)
     --AND (C.CircularTypeId=@rCircularTypeId OR @rIsSearch = 0)
	  AND (C.CircularTypeId=@rCircularTypeId OR @rCircularTypeId = 0)
    AND (C.CreatedUserId = @rCreatedUserId OR @rCreatedUserId = 0)
     AND (C.StatusId = @rStatusId OR (@rStatusId = 0))
     --AND ((@lIsCircularBasedOnApproval=0) OR (@lIsCircularBasedOnApproval=1 AND C.StatusId=550))
    
	ORDER BY C.StartDate DESC
END
GO
PRINT N'Altering [sCommunication].[pCircularScopeGet]...';


GO
ALTER PROCEDURE [sCommunication].[pCircularScopeGet]
	 @rCircularId bigint
	 --@rBatchId int
	 --@rOrgId smallint,
	 --@rOrgGroupId smallint
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo
			 
			FROM sCommunication.tCircularScope CS
			INNER JOIN sSetup.tOrganizationMaster OM
				ON CS.SourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2021

			UNION ALL

			SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo
			 
			FROM sCommunication.tCircularScope CS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2017

			UNION ALL

			SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo
			 
			FROM sCommunication.tCircularScope CS
			INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2016

			UNION ALL

			SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo
			 
			FROM sCommunication.tCircularScope CS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId	
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo
			 
			FROM sCommunication.tCircularScope CS
		    INNER JOIN sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo
			 
			FROM sCommunication.tCircularScope CS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2001
			
			UNION ALL
			
			SELECT
			
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo
			
			FROM sCommunication.tCircularScope CS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId	
			WHERE 
			CS.CircularId=@rCircularId AND CS.SourceTypeId=95


END
GO
PRINT N'Altering [sCommunication].[pMyQueryListGet]...';


GO
 
ALTER PROCEDURE [sCommunication].[pMyQueryListGet]	 
	 @rQueryCategoryId int = 0,
	 --@rTitle nvarchar(100),
	 @rOrgGroupBatchId int,
	 @rId bigint,
	 @rCreatedUserId bigint=0,
	 @rSyncedQueryId bigint = 0,
	 @rStatusId int = 0,
	 @rCreatedFromDate date=NULL,
	 @rCreatedToDate date=NULL, 
	 @rFromResolutionDate date=NULL,
	 @rToResolutionDate date=NULL,
	 @rFromSourceTypeId smallint=0,  
	 @rTitle nvarchar(100)='',  
	 @rNumber smallint=0,
	 @rQueryStatus varchar(25)=NULL ,
	 @rAssignedToEmployeeId bigint=0,
	 @rSourceId bigint=0,
	 @FromPage varchar(50)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	  BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  END
	SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ISNULL(EM.IsOtherUser,0) = 0
        
      UNION 
SELECT 
			QM.Id AS QueryId,
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code  ,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName 
			  
			
  FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
       -- INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 --AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
  WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        --AND ((QM.AssignedToEmployeeId=@rSourceId) OR (@rSourceId = 0))
        AND ((QM.FromSourceId=@rSourceId) OR (@rSourceId=0))
        
        
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))        
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')='')) 
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')=''))
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ISNULL(EM.IsOtherUser,0) = 0
        ORDER BY QM.CreatedDateTime DESC
        
END
GO
PRINT N'Altering [sCommunication].[pQueryListGet]...';


GO

ALTER PROCEDURE [sCommunication].[pQueryListGet]
	 
	 
	  @rQueryCategoryId int = 0,
	 --@rTitle nvarchar(100),
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rId bigint,
	 @rCreatedUserId bigint=0,
	 @rSyncedQueryId bigint = 0,
	 @rStatusId int = 0,
	 @rCreatedFromDate date=NULL,
	 @rCreatedToDate date=NULL, 
	 @rFromResolutionDate date=NULL,
	 @rToResolutionDate date=NULL,
	 @rFromSourceTypeId smallint=0,  
	 @rTitle nvarchar(100)='',  
	 @rNumber smallint=0,
	 @rQueryStatus varchar(25)=NULL ,
	 @rAssignedToEmployeeId bigint=0,
	 @rSourceId bigint=0,
	 @FromPage varchar(50)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	  BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
	  END
	SELECT 
			QM.Id AS QueryId,
			VQCM.Id AS QueryCategoryId,
			VQCM.OrgId As OrgId,
			ISNULL(VQCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.IsAssigneeView,
			QM.IsUserView,
			QM.CreatedUserId AS QueryCreatedUserId,
			ISNULL(QM.SubjectId,0) AS SubjectId,
			ISNULL(SubM.Title,'') AS SubjectName,
			ISNULL(QM.Number,0) AS Number,
			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0)
			   ELSE ''
			END AS FromSourceId,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        [sStudent].[vStudentAcademic] A 
			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        DM.Title
			                                                   FROM 
			                                                        sHrm.tEmployeeJobDetail EJD
			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			                                                   WHERE EmployeeId=QM.FromSourceId
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Code,
			CASE 
			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
			                                                   FROM 
			                                                        sStudent.tStudentMaster SM			                                                       
			                                                   WHERE Id=QM.FromSourceId 
			                                                   )
               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
			                                                   FROM 
			                                                        sHrm.tEmployeeMaster EM
			                                                   WHERE Id=QM.FromSourceId AND ISNULL(EM.IsOtherUser,0) = 0
			                                                   )			                                                   
			  
			   ELSE ''
			END AS Name,
			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate  ,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			  
			
  FROM 
			sCommunication.tQuery QM
		--INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
		INNER JOIN sCommunication.vOrgwiseQueryCategory VQCM ON QM.QueryCategoryId=VQCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
  WHERE 
			((VQCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
        AND ((QM.Id=@rId) OR (@rId=0))
        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')=''))
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')='')) 
        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
        AND ((QM.Number=@rNumber) OR (@rNumber=0))
        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((VQCM.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
        ORDER BY QM.CreatedDateTime DESC
        
--        UNION
        
        
        
        
--SELECT 
--			QM.Id AS QueryId,
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.IsAssigneeView,
--			QM.IsUserView,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			ISNULL(QM.SubjectId,0) AS SubjectId,
--			ISNULL(SubM.Title,'') AS SubjectName,
--			ISNULL(QM.Number,0) AS Number,
--			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
--			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
--			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
--			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			
--			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId)
--			   ELSE ''
--			END AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId)
--			   ELSE ''
--			END AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
--			                                                        DM.Title
--			                                                   FROM 
--			                                                        [sStudent].[vStudentAcademic] A 
--			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
--			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
--			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
--			                                                   )
--               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
--			                                                        DM.Title
--			                                                   FROM 
--			                                                        sHrm.tEmployeeJobDetail EJD
--			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
--			                                                   WHERE EmployeeId=QM.FromSourceId
--			                                                   )			                                                   
			  
--			   ELSE ''
--			END AS Code  ,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
--			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
--			                                                   FROM 
--			                                                        sStudent.tStudentMaster SM			                                                       
--			                                                   WHERE Id=QM.FromSourceId 
--			                                                   )
--               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
--			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
--			                                                   FROM 
--			                                                        sHrm.tEmployeeMaster EM
--			                                                   WHERE Id=QM.FromSourceId
--			                                                   )			                                                   
			  
--			   ELSE ''
--			END AS Name,
--			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate
			  
			
--  FROM 
--			sCommunication.tQuery QM
--		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
--        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
--        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
--  WHERE 
--			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
--        AND ((QM.Id=@rId) OR (@rId=0))
--        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
--        AND ((QM.AssignedToEmployeeId=@rSourceId) OR (@rSourceId = 0))
--        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
--        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))        
--        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
--        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')='')) 
--        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
--        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')=''))
--        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
--        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
--        AND ((QM.Number=@rNumber) OR (@rNumber=0))
--        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        
        
--   UNION
        
        
        
        
--SELECT 
--			QM.Id AS QueryId,
--			QCM.Id AS QueryCategoryId,
--			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
--			QM.Title,
--			QM.Remark,
--			QM.CreatedDateTime,
--			QM.StatusId,
--			ISNULL(sm.Title,'') AS StatusMaster,
--			QM.IsAssigneeView,
--			QM.IsUserView,
--			QM.CreatedUserId AS QueryCreatedUserId,
--			ISNULL(QM.SubjectId,0) AS SubjectId,
--			ISNULL(SubM.Title,'') AS SubjectName,
--			ISNULL(QM.Number,0) AS Number,
--			ISNULL(QM.AssignedToEmployeeId,0) AS AssignedToEmployeeId,
--			ISNULL(QM.AssignedToRemark,'') AS AssignedToRemark,
--			ISNULL(EM.Code,'') AS AssignedToEmployeeCode,
--			ISNULL(QM.FromSourceTypeId,0) AS FromSourceTypeId,
			
--			--ISNULL(QM.FromSourceId,0) AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId)
--			   ELSE ''
--			END AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT Code from sStudent.tStudentMaster SM where SM.Id=QM.FromSourceId)
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT Code from sHrm.tEmployeeMaster EM where EM.Id=QM.FromSourceId)
--			   ELSE ''
--			END AS FromSourceId,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
--			                                                        DM.Title
--			                                                   FROM 
--			                                                        [sStudent].[vStudentAcademic] A 
--			                                                         INNER JOIN sSetup.tBatchMaster BM On A.BatchId=BM.Id 
--			                                                         INNER JOIN sSetup.tDivisionMaster DM On A.DivisionId=DM.Id 
--			                                                   WHERE StudentId=QM.FromSourceId and BM.OrgGroupBatchId=@rOrgGroupBatchId
--			                                                   )
--               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
--			                                                        DM.Title
--			                                                   FROM 
--			                                                        sHrm.tEmployeeJobDetail EJD
--			                                                         INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
--			                                                   WHERE EmployeeId=QM.FromSourceId
--			                                                   )			                                                   
			  
--			   ELSE ''
--			END AS Code  ,
--			CASE 
--			   WHEN ISNULL(QM.FromSourceTypeId,0) = 2003 THEN (SELECT 
--			                                                        SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName 
--			                                                   FROM 
--			                                                        sStudent.tStudentMaster SM			                                                       
--			                                                   WHERE Id=QM.FromSourceId 
--			                                                   )
--               WHEN ISNULL(QM.FromSourceTypeId,0) = 95 THEN (SELECT 
--			                                                        EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName 
--			                                                   FROM 
--			                                                        sHrm.tEmployeeMaster EM
--			                                                   WHERE Id=QM.FromSourceId
--			                                                   )			                                                   
			  
--			   ELSE ''
--			END AS Name,
--			ISNULL(QM.TargetResolutionDate,'') AS TargetResolutionDate
			  
			
--  FROM 
--			sCommunication.tQuery QM
--		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
--        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
--        INNER JOIN sSecurity.tUser U ON QM.CreatedUserId = U.Id
--        LEFT JOIN sHrm.tEmployeeMaster EM ON QM.AssignedToEmployeeId=EM.Id
--       -- INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 --AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
--        LEFT JOIN sSetup.tSubjectMaster SubM ON SubM.Id = QM.SubjectId
--  WHERE 
--			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
--        AND	(QM.OrgGroupBatchId=@rOrgGroupBatchId) 
--        AND ((QM.Id=@rId) OR (@rId=0))
--        --AND ((QM.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
--        --AND ((QM.AssignedToEmployeeId=@rSourceId) OR (@rSourceId = 0))
--        AND ((QM.FromSourceId=@rSourceId) OR (@rSourceId=0))
        
        
--        AND ( QM.Id > @rSyncedQueryId OR @rSyncedQueryId = 0)
--        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))        
--        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedFromDate))OR(ISNULL(convert(date,@rCreatedFromDate),'')=''))    
--        AND ((convert(date,QM.CreatedDateTime)>=convert(date,@rCreatedToDate))OR(ISNULL(convert(date,@rCreatedToDate),'')='')) 
--        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rFromResolutionDate))OR(ISNULL(convert(date,@rFromResolutionDate),'')=''))    
--        AND ((convert(date,QM.TargetResolutionDate)>=convert(date,@rToResolutionDate))OR(ISNULL(convert(date,@rToResolutionDate),'')=''))
--        AND ((QM.FromSourceTypeId=@rFromSourceTypeId) OR (@rFromSourceTypeId=0))
--        AND ((QM.Title like '%'+@rTitle+'%') OR (ISNULL(@rTitle,'')=''))
--        AND ((QM.Number=@rNumber) OR (@rNumber=0))
--        AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
        
END
GO
PRINT N'Altering [sCommunication].[pQueryQueueGet]...';


GO

ALTER PROCEDURE [sCommunication].[pQueryQueueGet]
	 
	 @rQueryCategoryId int = 0,
	 --@rCreatedUserId bigint,
	 @rOrgGroupBatchId int,
	 @rOrgGroupId smallint,
	 @rQueryId bigint,
	 @rUserSourceId bigint,
	 @rMyList bit,
	 @rStatusId int = 0,
	 @rSourceId bigint = 0,
	 @rSubjectId int = 0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
IF(@rMyList=0)
BEGIN
	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code AS Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id  
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
        
	WHERE 
  
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId) 
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND ((EJD.EmployeeId=@rSourceId) OR (@rSourceId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			
	FROM 
			sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		
		
	
		UNION
		SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId --AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = 120100101 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QCM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId
		
		UNION
		
		
		SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId  
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = QM.AssignedToEmployeeId 
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	
	 WHERE 
	 
	 ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
	 AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
	 AND (QCM.OrgGroupId=@rOrgGroupId)  
	 AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
	 AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 
	 AND ((QM.AssignedToEmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
	 AND ISNULL(EM.IsOtherUser,0) = 0
	 ORDER BY QM.CreatedDateTime DESC
	 --and QM.FromSourceTypeId=95
		
		
END
ELSE IF(@rMyList=1)
BEGIN

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
			sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId = @rOrgGroupId)
		AND (QM.OrgGroupBatchId = @rOrgGroupBatchId)
	    AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId)
	    AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	    AND (( EJD.EmployeeId=@rSourceId) OR (@rSourceId=0))
		AND ISNULL(EM.IsOtherUser,0) = 0
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  SourceId = @rUserSourceId AND SourceTypeId <> 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
					AND SA.DivisionId IN (SELECT Id FROM sSetup.tDivisionMaster WHERE InchargeEmployeeId=@rUserSourceId)
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId			
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 24 AND SourceTypeId = 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
	UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
			((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		AND (QCM.OrgGroupId=@rOrgGroupId)  
		AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
		AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
		AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
		
		
		
		UNION 

	SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName,
			U.SourceTypeId,
			'Student' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId --AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = 120100101 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
	WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QCM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId
		
		
   UNION
    
    
    
    
    
    SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			SA.ClassName + ' ' + SA.DivisionName  AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			SA.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
			
	FROM 
		sCommunication.tQuery QM
        INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
        INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId = U.SourceId AND U.SourceTypeId = 2003 AND SA.OrgGroupBatchId = @rOrgGroupBatchId
        INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = SA.DivisionId AND (( TSD.EmployeeId = @rUserSourceId) OR (@rUserSourceId=0)) AND QM.SubjectId= TSD.SubjectId                  
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
        
  WHERE 
	       ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
			AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
			AND (QM.OrgGroupId=@rOrgGroupId)  
			AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
			--AND QueryCategoryId IN (select QueryCategoryId FROM sCommunication.tQueryCategoryAssignedTo where  RIGHT(SourceId,2) = 25 AND SourceTypeId = 2015)
			AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((SA.StudentId=@rSourceId) OR (@rSourceId=0))
			AND ((TSD.SubjectId=@rSubjectId) OR (@rSubjectId=0))
			--AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=2003 and QM.OrgGroupBatchId=@rOrgGroupBatchId      
        
	 
	 UNION
    
    SELECT 
			QCM.Id AS QueryCategoryId,
			ISNULL(QCM.Title,'') AS QueryCategoryMaster,
			QM.Title,
			QM.Remark,
			QM.CreatedDateTime,
			QM.StatusId,
			ISNULL(sm.Title,'') AS StatusMaster,
			QM.Id AS QueryId,
			QM.IsUserView,
			QM.IsAssigneeView,
			ODM.Title AS Department,
			U.DisplayTitle AS SourceName, 
			U.SourceTypeId, 
			'Employee' AS SourceType,
			QM.CreatedUserId AS QueryCreatedUserId,
			OM.DisplayTitle AS OrgName,
			EM.Code,
			(SELECT TOP 1 U.DisplayTitle AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND  QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserName,
			(SELECT TOP 1 CONVERT(NVARCHAR,QC.CreatedDateTime,103) AS SourceName FROM sCommunication.tQueryComment QC INNER JOIN sSecurity.tUser U ON U.Id=QC.CreatedUserId WHERE QC.QueryId=QM.Id AND QM.CreatedUserId != QC.CreatedUserId ORDER BY QC.CreatedDateTime DESC) AS AnswerUserDate,
			(CASE WHEN QM.StatusId=210 then  U.DisplayTitle ELSE '' END) AS UserName
	FROM 
		--	sCommunication.tQuery QM
		--INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
  --      INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
  --      INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId
  --      INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = U.SourceId AND U.SourceTypeId = 95
  --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = U.SourceId AND U.SourceTypeId = 95
  --      INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
  --      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = ODM.OrgId
	
	 --WHERE 
	 
	 --      ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
		--    AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
		--    AND (QCM.OrgGroupId = @rOrgGroupId)
	 --       AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 --       AND (( EJD.EmployeeId=@rSourceId) OR (@rSourceId=0))
	        
		--	AND ((QM.FromSourceId=@rUserSourceId) OR (@rUserSourceId=0)) and QM.FromSourceTypeId=95 and QM.OrgGroupBatchId=@rOrgGroupBatchId	
		
		
		sCommunication.tQuery QM
		INNER JOIN sCommunication.tQueryCategoryMaster QCM ON QM.QueryCategoryId=QCM.Id
        INNER JOIN sCommon.tStatusMaster SM ON SM.Id=QM.StatusId
        INNER JOIN sSecurity.tUser U ON U.Id=QM.CreatedUserId  
        INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = QM.AssignedToEmployeeId 
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
        INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId=ODM.Id 
        INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	
	 WHERE 
	 
	 ((QCM.Id = @rQueryCategoryId) OR (@rQueryCategoryId = 0))
	 AND ((QM.Id = @rQueryId) OR (@rQueryId = 0)) 
	 AND (QCM.OrgGroupId=@rOrgGroupId)  
	 AND (QM.OrgGroupBatchId=@rOrgGroupBatchId)
	 AND ((QM.StatusId=@rStatusId) OR (@rStatusId=0))
	 
	 AND ((QM.AssignedToEmployeeId=@rUserSourceId) OR (@rUserSourceId=0))
	 AND ISNULL(EM.IsOtherUser,0) = 0
	 ORDER BY QM.CreatedDateTime DESC	
	 
	 
	 
	 
	 
	 
	 
		
END
END


--SELECT Q.CreatedUserId FROM sCommunication.tQueryCategoryMaster QCM INNER JOIN sCommunication.tQuery Q ON Q.QueryCategoryId = QCM.Id
GO
PRINT N'Altering [sCommunication].[pTempCircularAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pTempCircularAdd]
	 
        @rId bigint,
		@rTitle nvarchar(200),
		@rRemark nvarchar(max),
		@rStartDate date,
		@rCreatedUserId bigint,
        @rOrgGroupId smallint,
        @rOrgGroupBatchId int,
        @rAssigneeId tinyint,
        @rCircularTypeId int,
        @rTempCircularId nvarchar(100)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN TRY
	BEGIN TRANSACTION	
	DECLARE @lNextNumber BIGINT 

	IF(@rId = 0)	
	BEGIN
		
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tCircular', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	 
	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsCircularBasedOnApproval bit=0
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 302 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsCircularBasedOnApproval = 0
	ELSE
	SET @lIsCircularBasedOnApproval = 1	
	
	Declare @StatusId smallint
	IF(@lIsCircularBasedOnApproval=0)
	SET @StatusId=550
	ELSE
	SET @StatusId=549
	
	INSERT INTO sCommunication.tCircular
		(
			Id,
			Title,
			Remark,
			StartDate,
			CreatedUserId,
			CreatedDateTime,
			OrgGroupId,
			OrgGroupBatchId,
			AssigneeId,
			CircularTypeId,
			StatusId
		)
	VALUES
		(
			@lNextNumber,
			@rTitle,
			@rRemark,
			@rStartDate,
			@rCreatedUserId,
			sCommon.fGetDate(), 
			@rOrgGroupId,
			@rOrgGroupBatchId,
			@rAssigneeId,
			@rCircularTypeId,
			@StatusId
		)
		
		SELECT @lNextNumber AS Result  
		    
		INSERT INTO sCommunication.tCircularScope
		SELECT @lNextNumber,SourceTypeId,SourceId,AssigneeToId
		FROM sCommunication.tTempCircularScope 
		WHERE TempCircularId = @rTempCircularId
		
		DELETE FROM sCommunication.tTempCircularScope WHERE TempCircularId = @rTempCircularId
		
		
	END	 

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


GO
ALTER PROCEDURE [sCommunication].[pTempCircularScopeAdd]

			@rTempCircularId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rIsDeleted bit
          ,@rIsAssigneeToId int 
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 

If(@rIsDeleted=1)
BEGIN
	Delete from sCommunication.tTempCircularScope where TempCircularId=@rTempCircularId AND SourceTypeId=@rSourceTypeId AND AssigneeToId= @rIsAssigneeToId
AND SourceId=@rSourceId
	Select @rSourceId as Result
END	
ELSE
BEGIN 
 
	If Exists(select TempCircularId from sCommunication.tTempCircularScope where TempCircularId=@rTempCircularId AND SourceTypeId=@rSourceTypeId
	AND SourceId=@rSourceId AND AssigneeToId= @rIsAssigneeToId)
		BEGIN
			SELECT @rSourceId AS Result
			RETURN
	  END 
	ELSE
			BEGIN
			INSERT INTO sCommunication.tTempCircularScope
			(
				TempCircularId
			   ,SourceTypeId
			   ,SourceId
			   ,AssigneeToId
			)
			VALUES
			(	
				@rTempCircularId
			   ,@rSourceTypeId
			   ,@rSourceId
			   ,@rIsAssigneeToId
			)		
			SELECT 1 AS Result
		 
	END	
END
GO
PRINT N'Altering [sCommunication].[pTempCircularScopeGet]...';


GO
ALTER PROCEDURE [sCommunication].[pTempCircularScopeGet]
	 @rTempCircularId nvarchar(100)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		
		
			 SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 OM.DisplayTitle AS Source,
			 'Organization' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             '' AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             CS.AssigneeToId,
             AM.Title As AssignedTo
			 
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN sSetup.tOrganizationMaster OM ON CS.SourceId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2021

			UNION ALL

			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
			  AM.Title As AssignedTo
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2017

			UNION ALL

			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 CM.DisplayTitle AS Source,
			 'Class' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo
			 
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN  sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2016

			UNION ALL

			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 --DM.DisplayTitle AS Source,
			 DM.Code AS Source,
			 'Division' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DMast.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo
			 
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN   sSetup.tDivisionMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN 	sSetup.tClassMaster CM
				ON DM.ClassId=CM.Id	
			INNER JOIN sSetup.tDepartmentMaster DMast
				ON CM.DepartmentId =DMast.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DMast.OrgId=OM.Id		
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2005


			UNION ALL
			
			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo
			 
			FROM sCommunication.tTempCircularScope CS
		    INNER JOIN sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id
			INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.StudentId AND SA.IsActiveBatch=1 AND SA.StatusId=1		
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SM.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2003
			
			UNION ALL
			
			SELECT
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 SA.Name AS Source,
			 'Student' AS SourceType,
			 SA.RollNo,
             SA.Code,
             SA.ClassName+' - '+SA.DivisionName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo
			 
			FROM sCommunication.tTempCircularScope CS
		   	INNER JOIN  sStudent.vStudentAcademic SA
				ON CS.SourceId=SA.AcademicId AND SA.IsActiveBatch=1 AND SA.StatusId=1
			INNER JOIN sSetup.tOrganizationMaster OM
				ON SA.OrgId = OM.Id	
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId
			WHERE CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=2001
			
			UNION ALL
			
			SELECT
			
			 CS.TempCircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 vEC.FirstName +' '+ vEC.LastName AS Source,
			 'Employee' AS SourceType,
			 '' AS RollNo,
             vEC.Code,
             vEC.DepartmentName AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
              CS.AssigneeToId,
               AM.Title As AssignedTo
			
			FROM sCommunication.tTempCircularScope CS
			INNER JOIN sHrm.vEmployeeCommunication vEC 
				ON CS.SourceId=vEC.EmployeeId AND vEC.StatusId=7
			INNER JOIN sSetup.tOrganizationMaster OM
				ON vEC.OrgId = OM.Id
			LEFT JOIN sCommon.tAssigneeMaster AM ON AM.Id = CS.AssigneeToId		
			WHERE 
			CS.TempCircularId=@rTempCircularId AND CS.SourceTypeId=95


END
GO
PRINT N'Altering [sCommunication].[pTempCircularScopeRemove]...';


GO


ALTER PROCEDURE [sCommunication].[pTempCircularScopeRemove]
			
			@rTempCircularId nvarchar(100)
           ,@rSourceTypeId smallint
           ,@rSourceId bigint
           ,@rAssigneeToId tinyint
           
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	
	BEGIN TRANSACTION	    
	
	Delete from sCommunication.tTempCircularScope where TempCircularId=@rTempCircularId AND SourceTypeId=@rSourceTypeId And AssigneeToId=@rAssigneeToId
      AND SourceId=@rSourceId
      
	Select 1 as Result
		
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH			
END
GO
PRINT N'Altering [sCommunication].[pTempCircularScopeValidate]...';


GO

ALTER PROCEDURE [sCommunication].[pTempCircularScopeValidate]
	 
        @rTempCircularId nvarchar(100),
		@rSourceTypeId smallint,
		@rSourceId bigint,
		@rAssigneeToId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
					/* Source Type Value
					   2021 - Organization
					   2017 - Department
					   2016 - Class
					   2005 - Division
					   2003 - Student */


		If EXISTS(select 1 from sCommunication.tTempCircularScope CS where CS.SourceId=@rSourceId AND
					CS.SourceTypeId=@rSourceTypeId AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId) 
			BEGIN
				select -101 as Result,'Item Already Exists' AS Msg
				RETURN
			END 

	
	IF(@rSourceTypeId = 2021) -- Organization	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2017
				where DM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Department already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tClassMaster CM 
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
				where DM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sStudent.tStudentMaster SM
				ON CS.SourceId=SM.Id AND CS.SourceTypeId= 2003
				where SM.OrgId=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 		
	    END
	
	IF(@rSourceTypeId = 2017) -- Department	
		BEGIN
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN  sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
				where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -102 as Result,'Organization already Exists' AS Msg
						RETURN
					END 
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
			 INNER JOIN sSetup.tClassMaster CM
				ON CS.SourceId=CM.Id AND CS.SourceTypeId= 2016
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Class already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN  sSetup.tDivisionMaster DM 
				ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=DM.ClassId
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Division already Exists' AS Msg
						RETURN
					END 
					
			If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
			 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
			 INNER JOIN sSetup.tClassMaster CM
				ON CM.Id=SA.ClassId
   			 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
				where CM.DepartmentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
					BEGIN
						select -103 as Result,'Student already Exists' AS Msg
						RETURN
					END 			
	    END
	    
    IF(@rSourceTypeId = 2016) -- Class	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.OrgId AND CS.SourceTypeId= 2021
			where CM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
			where CM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.Id AND CS.SourceTypeId= 2005
			where DM.ClassId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Division already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.ClassId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 2005) -- Division	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.OrgId AND CS.SourceTypeId= 2021
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON DM.ClassId=CM.Id
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tDivisionMaster DM 
			ON CS.SourceId=DM.ClassId AND CS.SourceTypeId= 2016
			where DM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.StudentId AND CS.SourceTypeId=2003
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
				
			If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		  INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId=2005
		  INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.DivisionId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -103 as Result,'Student already Exists' AS Msg
					RETURN
				END 
								
    END
    
    IF(@rSourceTypeId = 2003) -- Student	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sStudent.tStudentMaster SM 
			ON CS.SourceId=SM.OrgId AND CS.SourceTypeId= 2021
			where SM.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		 INNER JOIN  sSetup.tClassMaster CM 
			ON CS.SourceId=CM.DepartmentId AND CS.SourceTypeId= 2017
		 INNER JOIN sStudent.tAcademic SA 
				ON CM.Id=SA.ClassId 
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.ClassId AND CS.SourceTypeId= 2016
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Class already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.StudentId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 			
    END
    
    IF(@rSourceTypeId = 95) -- Employee	
	BEGIN
	
	
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS 
		 INNER JOIN  sHrm.tEmployeeMaster EM 
			ON CS.SourceId=EM.OrgId AND CS.SourceTypeId= 2021
			where EM.Id=@rSourceId AND  ISNULL(EM.IsOtherUser,0) = 0  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Organization already Exists' AS Msg
					RETURN
				END 
				
		If EXISTS(select 1 from sCommunication.tTempCircularScope CS 
		 INNER JOIN  sHrm.tEmployeeJobDetail EJD
			ON CS.SourceId=EJD.OrganizationDepartmentId AND CS.SourceTypeId= 2017
			where  EJD.EmployeeId=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Department already Exists' AS Msg
					RETURN
				END 
						
		
		 
	 
    END
    IF(@rSourceTypeId = 2001) -- Academic	
	BEGIN
		If EXISTS(select 1 from  sCommunication.tTempCircularScope CS
		 INNER JOIN sStudent.tAcademic SA 
				ON CS.SourceId=SA.DivisionId AND CS.SourceTypeId= 2005
		 INNER JOIN sSetup.tBatchMaster BM 
   			    ON BM.Id = SA.BatchId AND BM.IsActive=1
			where SA.Id=@rSourceId  AND CS.TempCircularId=@rTempCircularId  AND AssigneeToId=@rAssigneeToId)
				BEGIN
					select -102 as Result,'Division already Exists' AS Msg
					RETURN
				END 		
	END
			select 1 as Result,'' AS Msg
	
END
GO
PRINT N'Altering [sErp].[pLeadMasterGet]...';


GO

ALTER PROCEDURE [sErp].[pLeadMasterGet]
	
	@rId int=0,
	@rOrgId smallint=0,
	@rLeadAffiliationId smallint =0,
	@rTitle nvarchar(200) =null,
	@rAreaName nvarchar(100) =null,
	@rCityName nvarchar(100) =null,
	@rDistrict nvarchar(50) = null,
	@rStateId int =0,
	@rCountryId int=0,
	@rLeadStatusId tinyint =0,
	@rLeadSourceId tinyint =0,
	@rLeadOwnerEmployeeId bigint =0,
	@rFromDate date='',
	@rToDate date='',
	@rIsWildCardSearch bit=0,
	@rVcpId int =0,
	@rLeadInfrastructureId int =0,
	@rFromLeadDate date =NULL,
	@rToLeadDate date =NULL,
	@rContactPerson nvarchar(100) =NULL,
	@rContactMobileNo nvarchar(50)=NULL,
	@rIsSearchHierarchyWise smallint=0,
	@rPlanFromDate date =NULL,
	@rPlanToDate date =NULL,
	@rEmployeeId bigint = 0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
  If @rFromDate IS Null Set @rFromDate = ''
  If @rToDate IS Null Set @rToDate = ''
  
  If @rFromLeadDate IS Null Set @rFromLeadDate = ''
  If @rToLeadDate IS Null Set @rToLeadDate = ''
  
  If @rPlanFromDate IS Null Set @rPlanFromDate = ''
  If @rPlanToDate IS Null Set @rPlanToDate = ''
    IF @rIsSearchHierarchyWise = 2 Set @rLeadOwnerEmployeeId = 0

	CREATE TABLE #TempEmployeeId
    (
		EmployeeId bigint
    )
    
    IF(@rIsSearchHierarchyWise = 1)
	BEGIN
		WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeID
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 WHERE ((EmployeeManagerId = @rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId = 0))
					
					AND ((OrgId = @rOrgId) OR (@rOrgId = 0))

			 UNION ALL

			 SELECT
			  E.EmployeeID
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId
			)
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeID FROM EmployeeCTE E
		WHERE((E.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
    END
    
    ELSE
    BEGIN
		INSERT INTO #TempEmployeeId(EmployeeId)
		SELECT EJD.EmployeeId FROM sHrm.tEmployeeJobDetail EJD 
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		WHERE ((EJD.EmployeeManagerId = @rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId = 0))
			   AND ((OrgId = @rOrgId) OR (@rOrgId = 0))
			   AND((EJD.EmployeeId = @rEmployeeId) OR (@rEmployeeId = 0))
    END

--select * from #TempEmployeeId

	IF @rIsWildCardSearch = 1
	BEGIN
		SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--SET @rCode = sCommon.fSearchStringGet(@rCode)
	END
	
If	@rIsSearchHierarchyWise = 0
BEGIN
	SELECT 
	      LM.Id,
	      LM.OrgId,
	      ISNULL(LM.LeadAffiliationId,0) As LeadAffiliationId,
	      LAM.Title AS Affiliation,
	      LM.Title,
	      LM.StreetDetail,
	      LM.AreaName,
	      LM.CityName,
	      ISNULl( LM.StateId,0) AS StateId,
	      SM.Title AS StateName,
	      ISNULl(  LM.CountryId,0) AS CountryId,
	      CM.Title AS Country,
	      LM.Website,
	      ISNULl(LM.LeadStatusId,0)AS LeadStatusId ,
	      LSM.Title AS LeadStatus,
	      ISNULL(LM.LeadSourceId,0) As LeadSourceId,
	      LS.Title AS LeadSource,
	      ISNULl(LM.LeadOwnerEmployeeId,0) AS LeadOwnerEmployeeId,
	      EM.FirstName +' '+ MiddleName +' '+ LastName AS LeadOwner,
	      ISNULL(LM.NextFollowupDate,'0001/01/01') AS NextFollowupDate,
	      LM.NextFollowupRemark,
	      LM.ContactPerson,
	      LM.ContactMobileNo,
	      LM.ContactDesignation,
	      LM.ContactEmail,
	      LM.ZipCode,
	      LM.PhoneNo,
	      LM.MobileNo,
	      LM.Email AS EMail,
	      LM.district,
	      LM.ContactPerson2,
	      LM.ContactMobileNo2,
	      LM.ContactDesignation2,
		  LM.ContactEmail2,
		   LM.ContactPerson3,
	      LM.ContactMobileNo3,
	      LM.ContactDesignation3,
		  LM.ContactEmail3,
		  LM.ContactPerson4,
	      LM.ContactMobileNo4,
	      LM.ContactDesignation4,
		  LM.ContactEmail4,
		  LM.ContactPerson5,
	      LM.ContactMobileNo5,
	      LM.ContactDesignation5,
		  LM.ContactEmail5,
		  ISNULL(LM.LeadDate,'0001/01/01') AS LeadDate,
		  ISNULl(LM.LeadChannelPartnerId,0) AS LeadChannelPartnerId,
		  ISNULl(LM.LeadInfrastructureId,0) AS LeadInfrastructureId,
		  LM.StreetDetail++LM.AreaName+' '+LM.CityName+' '+SM.Title+' '+ CM.Title AS Address,
		  LM.CreatedUserId,
		  LM.CreatedDateTime,
		  ISNULL(LM.UpdatedUserId,0) AS UpdatedUserId,
		  ISNULL(LM.UpdatedDateTime,'') AS UpdatedDateTime,
		  ISNULL(LM.PlannedDate,'0001/01/01') AS PlannedDate,
		  ISNULL(LM.LatitudeAxis,0) AS LatitudeAxis,
		  ISNULL(LM.LongitudeAxis,0) AS LongitudeAxis
	FROM 
		  sErp.tLeadMaster LM
		  LEFT JOIN sErp.tLeadAffiliationMaster LAM ON LAM.Id=LM.LeadAffiliationId
		  LEFT JOIN sErp.tLeadSourceMaster LS ON  LS.Id=LM.LeadSourceId
		  LEFT JOIN sErp.tLeadStatusMaster LSM ON LSM.Id=LM.LeadStatusId
		  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LM.LeadOwnerEmployeeId
		  LEFT JOIN sCommon.tCountryMaster CM ON  CM.Id = LM.CountryId
		  LEFT JOIN sCommon.tStateMaster SM ON SM.Id=LM.StateId
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		--LEFT JOIN sSecurity.tUser U ON U.SourceId =LM.LeadOwnerEmployeeId AND SourceTypeId = 95
	WHERE 
		  ((LM.Id = @rId) OR (@rId=0))
		  AND((LM.OrgId = @rOrgId) OR(@rOrgId=0))
		  AND ((LM.Title Like '%'+ @rTitle+'%')OR(ISNULL(@rTitle,'') = ''))
		  AND ((LM.AreaName Like '%'+@rAreaName+'%')OR(ISNULL(@rAreaName,'') = ''))
		  AND ((LM.CityName Like '%'+@rCityName+'%')OR(ISNULL(@rCityName,'') = ''))
		  AND	((LM.StateId = @rStateId) OR (@rStateId = 0))
		  AND ((LM.district Like '%'+@rDistrict+'%') OR (ISNULL(@rDistrict,'') = ''))
		  AND	((LM.CountryId = @rCountryId) OR (@rCountryId = 0))
		  AND	((LM.LeadChannelPartnerId = @rVcpId) OR (@rVcpId = 0))
		  AND((LM.LeadInfrastructureId = @rLeadInfrastructureId) OR (@rLeadInfrastructureId =0))
		  AND	((LM.LeadAffiliationId = @rLeadAffiliationId) OR (@rLeadAffiliationId = 0))
		  AND	((LM.LeadStatusId = @rLeadStatusId) OR (@rLeadStatusId = 0))
		  AND	((LM.LeadSourceId = @rLeadSourceId) OR (@rLeadSourceId = 0))
		  AND	((LM.LeadOwnerEmployeeId = @rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId = 0))
		  AND ((LM.NextFollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		  AND ((LM.NextFollowupDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		  AND ((LM.LeadDate >= @rFromLeadDate) OR (ISNULL(@rFromLeadDate,'') = ''))
		   AND ((LM.LeadDate <= @rToLeadDate) OR (ISNULL(@rToLeadDate,'') = ''))
		  AND ((LM.ContactPerson Like'%'+ @rContactPerson+'%') OR (ISNULL(@rContactPerson,'') = ''))
		  AND ((LM.ContactMobileNo Like'%'+ @rContactMobileNo+'%') OR (ISNULL(@rContactMobileNo,'') = ''))
		  -- AND ((LM.PlannedDate = @rPlanDate ) OR (ISNULL(@rPlanDate,'') = ''))
		    AND ((LM.PlannedDate >= @rPlanFromDate) OR (ISNULL(@rPlanFromDate,'') = ''))
		   AND ((LM.PlannedDate <= @rPlanToDate) OR (ISNULL(@rPlanToDate,'') = ''))
		   AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY 
		  LM.NextFollowupDate DESC

END

If	@rIsSearchHierarchyWise != 0
BEGIN
	SELECT 
	      LM.Id,
	      LM.OrgId,
	      ISNULL(LM.LeadAffiliationId,0) As LeadAffiliationId,
	      LAM.Title AS Affiliation,
	      LM.Title,
	      LM.StreetDetail,
	      LM.AreaName,
	      LM.CityName,
	      ISNULl( LM.StateId,0) AS StateId,
	      SM.Title AS StateName,
	      ISNULl(  LM.CountryId,0) AS CountryId,
	      CM.Title AS Country,
	      LM.Website,
	      ISNULl(LM.LeadStatusId,0)AS LeadStatusId ,
	      LSM.Title AS LeadStatus,
	      ISNULL(LM.LeadSourceId,0) As LeadSourceId,
	      LS.Title AS LeadSource,
	      ISNULl(LM.LeadOwnerEmployeeId,0) AS LeadOwnerEmployeeId,
	      EM.FirstName +' '+ MiddleName +' '+ LastName AS LeadOwner,
	      ISNULL(LM.NextFollowupDate,'0001/01/01') AS NextFollowupDate,
	      LM.NextFollowupRemark,
	      LM.ContactPerson,
	      LM.ContactMobileNo,
	      LM.ContactDesignation,
	      LM.ContactEmail,
	      LM.ZipCode,
	      LM.PhoneNo,
	      LM.MobileNo,
	      LM.Email AS EMail,
	      LM.district,
	      LM.ContactPerson2,
	      LM.ContactMobileNo2,
	      LM.ContactDesignation2,
		  LM.ContactEmail2,
		   LM.ContactPerson3,
	      LM.ContactMobileNo3,
	      LM.ContactDesignation3,
		  LM.ContactEmail3,
		  LM.ContactPerson4,
	      LM.ContactMobileNo4,
	      LM.ContactDesignation4,
		  LM.ContactEmail4,
		  LM.ContactPerson5,
	      LM.ContactMobileNo5,
	      LM.ContactDesignation5,
		  LM.ContactEmail5,
		  ISNULL(LM.LeadDate,'0001/01/01') AS LeadDate,
		  ISNULl(LM.LeadChannelPartnerId,0) AS LeadChannelPartnerId,
		  ISNULl(LM.LeadInfrastructureId,0) AS LeadInfrastructureId,
		  LM.StreetDetail++LM.AreaName+' '+LM.CityName+' '+SM.Title+' '+ CM.Title AS Address,
		  LM.CreatedUserId,
		  LM.CreatedDateTime,
		  ISNULL(LM.UpdatedUserId,0) AS UpdatedUserId,
		  ISNULL(LM.UpdatedDateTime,'') AS UpdatedDateTime,
		  ISNULL(LM.PlannedDate,'0001/01/01') AS PlannedDate,
		    ISNULL(LM.LatitudeAxis,0) AS LatitudeAxis,
		  ISNULL(LM.LongitudeAxis,0) AS LongitudeAxis
	FROM 
		  sErp.tLeadMaster LM
		  LEFT JOIN sErp.tLeadAffiliationMaster LAM ON LAM.Id=LM.LeadAffiliationId
		  LEFT JOIN sErp.tLeadSourceMaster LS ON  LS.Id=LM.LeadSourceId
		  LEFT JOIN sErp.tLeadStatusMaster LSM ON LSM.Id=LM.LeadStatusId
		  LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id=LM.LeadOwnerEmployeeId
		  LEFT JOIN sCommon.tCountryMaster CM ON  CM.Id = LM.CountryId
		  LEFT JOIN sCommon.tStateMaster SM ON SM.Id=LM.StateId
		  INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = EM.Id
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
		--LEFT JOIN sSecurity.tUser U ON U.SourceId =LM.LeadOwnerEmployeeId AND SourceTypeId = 95
	WHERE 
		  ((LM.Id = @rId) OR (@rId=0))
		  AND((LM.OrgId = @rOrgId) OR(@rOrgId=0))
		  AND ((LM.Title Like '%'+ @rTitle+'%')OR(ISNULL(@rTitle,'') = ''))
		  AND ((LM.AreaName Like '%'+@rAreaName+'%')OR(ISNULL(@rAreaName,'') = ''))
		  AND ((LM.CityName Like '%'+@rCityName+'%')OR(ISNULL(@rCityName,'') = ''))
		  AND	((LM.StateId = @rStateId) OR (@rStateId = 0))
		  AND ((LM.district Like '%'+@rDistrict+'%') OR (ISNULL(@rDistrict,'') = ''))
		  AND	((LM.CountryId = @rCountryId) OR (@rCountryId = 0))
		  AND	((LM.LeadChannelPartnerId = @rVcpId) OR (@rVcpId = 0))
		  AND((LM.LeadInfrastructureId = @rLeadInfrastructureId) OR (@rLeadInfrastructureId =0))
		  AND	((LM.LeadAffiliationId = @rLeadAffiliationId) OR (@rLeadAffiliationId = 0))
		  AND	((LM.LeadStatusId = @rLeadStatusId) OR (@rLeadStatusId = 0))
		  AND	((LM.LeadSourceId = @rLeadSourceId) OR (@rLeadSourceId = 0))
		 --AND	((LM.LeadOwnerEmployeeId = @rLeadOwnerEmployeeId) OR (@rLeadOwnerEmployeeId = 0))
		  AND ((LM.NextFollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		  AND ((LM.NextFollowupDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))
		  AND ((LM.LeadDate >= @rFromLeadDate) OR (ISNULL(@rFromLeadDate,'') = ''))
		   AND ((LM.LeadDate <= @rToLeadDate) OR (ISNULL(@rToLeadDate,'') = ''))
		  AND ((LM.ContactPerson Like'%'+ @rContactPerson+'%') OR (ISNULL(@rContactPerson,'') = ''))
		  AND ((LM.ContactMobileNo Like'%'+ @rContactMobileNo+'%') OR (ISNULL(@rContactMobileNo,'') = ''))
		   AND ((LM.PlannedDate >= @rPlanFromDate) OR (ISNULL(@rPlanFromDate,'') = ''))
		   AND ((LM.PlannedDate <= @rPlanToDate) OR (ISNULL(@rPlanToDate,'') = ''))
		   AND ISNULL(EM.IsOtherUser,0) = 0
	ORDER BY 
		  LM.NextFollowupDate DESC
END
	
END
GO
PRINT N'Altering [sFee].[pFeePostingDetailGet]...';


GO
 

ALTER PROCEDURE [sFee].[pFeePostingDetailGet]
				
		  -- @rClassId int,
           @rAdmissionCategoryId int=0,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptDate date,
           @rReceiptDateTo date
            
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	SELECT  
			
			AM.FeeSetupId,
			AMast.Id AS AccountId,
			AMast.Title AS AccountName,
			AM.AccountingYearId,
			AYM.Title AS AccountingYearName,
			AM.CreditLedgerId,
			CLM.Title AS CreditLedgerName,
			AM.DebitLedgerId,
			DLM.Title AS DebitLedgerName,
			AM.PayTypeId,
			PTM.Title AS PayTypeName,
			FM.Id AS FeeId,
			FM.Title AS FeeTitle,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FS.ReceiptBookId AS ReceiptBookId,
			RBM.Title AS ReceiptBookTitle,
			SUM(RD.Amount) AS ReceiptAmount,
			R.ReceiptNumber
			
  FROM 
			sFee.tAccountMapping AM
			INNER JOIN sFee.tReceiptDetail RD ON RD.FeeSetupId = AM.FeeSetupId  
			INNER JOIN sFee.tReceipt R ON R.Id = RD.ReceiptId 
				AND R.PayTypeId = AM.PayTypeId
				AND R.ReceiptDate >= @rReceiptDate
				AND R.ReceiptDate <= @rReceiptDateTo				
			INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
			--AND (FS.ClassId=@rClassId) 
				AND (FS.AdmissionCategoryId=@rAdmissionCategoryId Or @rAdmissionCategoryId = 0) 
				AND (R.OrgGroupBatchId=@rBatchId)
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId 
		    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		    INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId	
            INNER JOIN sAccounting.tAccountingYearMaster AYM ON AYM.Id=AM.AccountingYearId
            INNER JOIN sAccounting.tAccountMaster AMast ON AMast.Id=AYM.AccountId
            INNER JOIN sAccounting.tLedgerMaster CLM ON (CLM.Id=AM.CreditLedgerId)  AND CLM.AccountingYearId = AM.AccountingYearId
            INNER JOIN sAccounting.tLedgerMaster DLM ON (DLM.Id=AM.DebitLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = AM.PayTypeId
WHERE 
			FM.OrgGroupId=@rOrgGroupId
			
			GROUP BY 
			AMast.Id,AMast.Title,AM.FeeSetupId,AM.AccountingYearId,AYM.Title,AM.CreditLedgerId,CLM.Title,
			AM.DebitLedgerId,DLM.Title,AM.PayTypeId,PTM.Title,FM.Id,FM.Title,FHM.Id,FHM.Title,FS.ReceiptBookId,
			RBM.Title,R.ReceiptNumber
END
GO
PRINT N'Altering [sFee].[pReceiptAdd]...';


GO
 
 
ALTER PROCEDURE [sFee].[pReceiptAdd]
	
		   @rId bigint,
		   @rSourceTypeId smallint,
		   @rSourceId bigint,
		   @rReceiptNumber int,
		   @rReceiptDate date,
		   @rReceiptAmount decimal(12,2),
		   @rTotalReceiptAmount decimal(12,2),
		   @rDiscountAmount decimal(12,2),
		   @rPayTypeId tinyint,
		   @rChequeNo nvarchar(20),
		   @rBankName nvarchar(200),
		   @rReceiptBookId int,
		   @rIsObsolete bit,
		   @rCreatedUserId bigint,
		   @rOrgId int,
		   @rBatchId int,
		   @rOrgGroupBatchId int,
		   @rRemark nvarchar(200),
		   @rReceiptDetailXml [nvarchar](max),
		   @rChequeDate date,
		   @rCharge decimal(12,2)=0,
		   @rFeeInvoiceId bigint = NULL,
		   @rCollectionGroupId int = 0,
		   @rDepositedLedgerId int = 0,
		   @rPaymentTransactionId bigint = 0,
		   @rReceiptPrintGroupId nvarchar(100)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
DECLARE @lIsCreated INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml

BEGIN
	BEGIN TRY
	
	 SELECT @rOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster where Id = @rBatchId

	 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 339 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)

	 IF @lConfigValue IS NULL 
		SET @lConfigValue = 'ReceiptBookWise'
	 
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
	END
	ELSE
	BEGIN
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId,@rPayTypeId,@lConfigValue)
		Print @rReceiptNumber
	END	
EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rIsCreated = @lIsCreated OUTPUT
 	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output

IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END

	INSERT INTO sFee.tReceipt
		(
		   Id,
		   SourceTypeId,
		   SourceId,
		   ReceiptNumber,
		   ReceiptDate,
		   ReceiptAmount,
		   TotalReceiptAmount,
		   DiscountAmount,
		   PayTypeId,
		   ChequeNo,
		   BankName,
		   ReceiptBookId,
		   Remark,
		   IsObsolete,
		   BatchId,
		   CreatedUserId,
		   CreatedDateTime,
		   OrgGroupBatchId,
		   ChequeDate,
		   FeeInvoiceId,
		   CollectionGroupId,
		   DepositedLedgerId,
		   PaymentTransactionId,
		   ReceiptPrintGroupId
        )
	VALUES
		(
			@lNextNumber,
			@rSourceTypeId,
			@rSourceId,
		    @rReceiptNumber,
		    @rReceiptDate,
		    @rReceiptAmount,
		    @rTotalReceiptAmount,
		    @rDiscountAmount,
		    @rPayTypeId,
		    @rChequeNo,
		    @rBankName,
		    @rReceiptBookId,
		    @rRemark,
		    @rIsObsolete,
		    @rBatchId,
		    @rCreatedUserId,
		    sCommon.fGetDate(),
		    @rOrgGroupBatchId,
		    @rChequeDate,
		    @rFeeInvoiceId,
		    @rCollectionGroupId,
		    @rDepositedLedgerId,
		    @rPaymentTransactionId,
			@rReceiptPrintGroupId
		)
		
		INSERT INTO sFee.tReceiptDetail
		(
		   ReceiptId,
		   FeeSetupId,
		   Amount
        )
        SELECT  	
		  @lNextNumber,
		  FeeSetupId,
		  Amount
		
	FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
		WITH ( 
				FeeSetupId int,
				Amount decimal(12,2)
			  ) 
		
		SELECT @lNextNumber AS Result
		EXEC sp_xml_removedocument @loDoc
		
		IF (@rCharge > 0)
		BEGIN
		EXEC [sFee].[pReceiptChargeAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@rCharge,@rReceiptBookId
		END
	
		DECLARE @lIsServiceTaxApplicable bit
	    DECLARE @lServiceTaxPercentage decimal(6,2)
	
	    SELECT @lIsServiceTaxApplicable = ISNULL(IsServiceTaxApplicable,0),@lServiceTaxPercentage = ISNULL(ServiceTaxPercentage,0) FROM sFee.tReceiptBookMaster where Id = @rReceiptBookId
		
		IF (@lIsServiceTaxApplicable > 0 AND @lServiceTaxPercentage > 0)
		BEGIN
		EXEC [sFee].[pReceiptServiceTaxAdd] @rSourceTypeId,@rSourceId,@lNextNumber,@rCreatedUserId,@rOrgId,@rBatchId,@lServiceTaxPercentage
		END
 END 
	ELSE
	IF EXISTS(SELECT 1 FROM sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND Id = @rId)
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
	SELECT @rId AS RESULT
	END 
	ELSE
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END

		BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptNumber = @rReceiptNumber,
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
	SELECT @rId AS RESULT
	END 
	END
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pReceiptBookMasterAdd]...';


GO
 

ALTER PROCEDURE [sFee].[pReceiptBookMasterAdd]
	 
	        @rId int
	       ,@rCode nvarchar(20)
           ,@rTitle nvarchar(100)
           ,@rFullTitle nvarchar(200)
           ,@rAddress1 nvarchar(200)
           ,@rAddress2 nvarchar(200)
           ,@rBankAccountNumber nvarchar(50)
           ,@rIsObsolete bit
           ,@rRemark1 nvarchar(500)
           ,@rRemark2 nvarchar(500)
           ,@rCreatedUserId bigint           
           ,@rOrgGroupId int
           ,@rIsOnPrePrinted bit
           ,@rReportId int
           ,@rIsSupressLogo bit
           ,@rOrderIndex int
           ,@rIsDisplaySchoolName bit
           ,@rIsMonthDetailOnly bit
           ,@rIsServiceTaxApplicable bit
           ,@rServiceTaxPercentage decimal(6,2)
           ,@rBankName nvarchar(150)=''
           ,@rIsFeeInvoiceHeadwise bit = 0
           ,@rGroupTitle nvarchar(200)=''
           ,@rIsSuppressFeeDetail bit=0
		   ,@rReceiptLogo varbinary(max)=NULL
		   ,@rHeaderDisplayId tinyint
		   ,@rReceiptBookHeader varbinary(max)=NULL
		   ,@rFeeInvoiceHeaderDisplayId tinyint
		   ,@rFeeInvoiceHeader varbinary(max)=NULL
		   ,@rCGSTPercentage decimal(5,2) = 0 
		   ,@rSGSTPercentage decimal(5,2) = 0
		   ,@rIsDisplayPendingFeeAmount bit = 0
		   
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	
	 DECLARE @lNextNumber INT     
	
If Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId) 
BEGIN
	If NOT Exists(select top(1)* from sFee.tReceiptBookMaster where Title=@rTitle AND OrgGroupId=@rOrgGroupId AND Id=@rId)
	BEGIN
		select -101 as Result
	END
	ELSE
	BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete      
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo   
             ,OrderIndex=@rOrderIndex
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
			 ,IsSuppressFeeDetail=@rIsSuppressFeeDetail
			 ,ReceiptLogo = @rReceiptLogo
			 ,ReceiptBookHeader=@rReceiptBookHeader
			 ,HeaderDisplayId=@rHeaderDisplayId
			 ,FeeInvoiceHeader=@rFeeInvoiceHeader
			 ,FeeInvoiceHeaderDisplayId=@rFeeInvoiceHeaderDisplayId
			 ,CGSTPercentage=@rCGSTPercentage
			 ,SGSTPercentage=@rSGSTPercentage
			 ,IsDisplayPendingFeeAmount=@rIsDisplayPendingFeeAmount
             
	      WHERE Id = @rId 	 
	      SELECT @lNextNumber AS Result
	 END  
END
ELSE
BEGIN
IF(@rId = 0)	
BEGIN

	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sFee.tReceiptBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	
	INSERT INTO [sFee].[tReceiptBookMaster]
			   (
			    [Id]
			   ,[Code]
			   ,[Title]
			   ,[FullTitle]
			   ,[Address1] 
			   ,[Address2] 
			   ,[BankAccountNumber] 
			   ,[IsObsolete]
			   ,[Remark1] 
			   ,[Remark2] 
			   ,[CreatedUserId]
			   ,[CreatedDateTime]
			   ,[OrgGroupId]
			   ,IsOnPrePrinted
			   ,ReportId
			   ,IsSupressLogo
			   ,OrderIndex
			   ,IsDisplaySchoolName
			   ,IsMonthDetailOnly
			   ,IsServiceTaxApplicable
			   ,ServiceTaxPercentage
			   ,BankName
			   ,IsFeeInvoiceHeadwise
			   ,GroupTitle
			   ,IsSuppressFeeDetail
			   ,ReceiptLogo
			   ,HeaderDisplayId
			   ,ReceiptBookHeader
			   ,FeeInvoiceHeader
			   ,FeeInvoiceHeaderDisplayId
			   ,CGSTPercentage
			   ,SGSTPercentage
			   ,IsDisplayPendingFeeAmount
			   )
		 VALUES
			   (
				@lNextNumber
			   ,@rCode
			   ,@rTitle
			   ,@rFullTitle
			   ,@rAddress1
			   ,@rAddress2
			   ,@rBankAccountNumber
			   ,@rIsObsolete
			   ,@rRemark1
			   ,@rRemark2
			   ,@rCreatedUserId
			   ,sCommon.fGetDate()
			   ,@rOrgGroupId
			   ,@rIsOnPrePrinted
			   ,@rReportId
			   ,@rIsSupressLogo
			   ,@rOrderIndex
			   ,@rIsDisplaySchoolName
			   ,@rIsMonthDetailOnly
			   ,@rIsServiceTaxApplicable
			   ,@rServiceTaxPercentage
			   ,@rBankName
			   ,@rIsFeeInvoiceHeadwise
			   ,@rGroupTitle
			   ,@rIsSuppressFeeDetail
			   ,@rReceiptLogo
			   ,@rHeaderDisplayId
			   ,@rReceiptBookHeader
			   ,@rFeeInvoiceHeader
			   ,@rFeeInvoiceHeaderDisplayId
			   ,@rCGSTPercentage
			   ,@rSGSTPercentage
			   ,@rIsDisplayPendingFeeAmount
			   )
			   
 
INSERT INTO sSecurity.tUserAccess
           (
            SourceTypeId
            ,SourceId
           ,[UserId]
           
           )
SELECT 
		   2013
		   ,@lNextNumber
		  ,@rCreatedUserId
			   
			   
		    SELECT @lNextNumber AS Result
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
	    UPDATE  [sFee].[tReceiptBookMaster]
	    SET
			  --Code=@rCode
	          Title=@rTitle
	          ,FullTitle=@rFullTitle
	         ,Address1=@rAddress1
	         ,Address2=@rAddress2
	         ,BankAccountNumber=@rBankAccountNumber
	         ,[IsObsolete] = @rIsObsolete          
	         ,[Remark1] = @rRemark1
	         ,[Remark2] = @rRemark2                     
             ,[UpdatedUserId] = @rCreatedUserId
             ,[UpdatedDateTime] = sCommon.fGetDate()   
             ,IsOnPrePrinted=@rIsOnPrePrinted
             ,ReportId=@rReportId
             ,IsSupressLogo=@rIsSupressLogo
             ,OrderIndex=@rOrderIndex              
             ,IsDisplaySchoolName=@rIsDisplaySchoolName
             ,IsMonthDetailOnly=@rIsMonthDetailOnly
             ,IsServiceTaxApplicable=@rIsServiceTaxApplicable
			 ,ServiceTaxPercentage=@rServiceTaxPercentage
			 ,BankName=@rBankName
			 ,IsFeeInvoiceHeadwise=@rIsFeeInvoiceHeadwise
			 ,GroupTitle =@rGroupTitle
			 ,IsSuppressFeeDetail=@rIsSuppressFeeDetail
			 ,ReceiptLogo = @rReceiptLogo
			 ,HeaderDisplayId=@rHeaderDisplayId
			 ,ReceiptBookHeader=@rReceiptBookHeader
              ,FeeInvoiceHeaderDisplayId=@rFeeInvoiceHeaderDisplayId
			 ,FeeInvoiceHeader=@rFeeInvoiceHeader
			 ,CGSTPercentage=@rCGSTPercentage
			 ,SGSTPercentage=@rSGSTPercentage
			 ,IsDisplayPendingFeeAmount=@rIsDisplayPendingFeeAmount
	      WHERE Id = @rId 	   
	      SELECT @lNextNumber AS Result
	 END  
		
	
	END
	If Not Exists(Select 1 from sSystem.tPortalSync where OrgGRoupId=@rOrgGroupId)
	BEGIN
	Insert into sSystem.tPortalSync
	(
		OrgGroupId,
		FeeChange
	)
	Values
	(
		@rOrgGroupId,
		1
	)
	 
	END
	
	Else
	BEGIN
		Update sSystem.tPortalSync 
		Set
			FeeChange=1
		Where OrgGroupId=@rOrgGroupId
	END
	
COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sFee].[pReceiptBookMasterGet]...';


GO
 

ALTER PROCEDURE [sFee].[pReceiptBookMasterGet]
          
           @rId bigint,
           @rCode nvarchar(20),
           @rTitle nvarchar(100),
           @rOrgGroupId int,
           @rIsWildCardSearch bit
 
AS
SET NOCOUNT ON

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

BEGIN
SELECT RBM.Id 
	  ,RBM.Code
      ,RBM.Title
      ,RBM.FullTitle
      ,RBM.Address1
      ,RBM.Address2
      ,RBM.BankAccountNumber
      ,RBM.IsObsolete
      ,RBM.Remark1
      ,RBM.Remark2
      ,ISNULL(RBM.IsOnPrePrinted ,0) AS IsOnPrePrinted
      ,ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo
      ,RBM.ReportId  
       --,RBM.OrderIndex  
      ,ISNULL(RBM.OrderIndex,0) AS OrderIndex
      ,ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName
      ,ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly
      ,ISNULL(RBM.IsServiceTaxApplicable,0) AS IsServiceTaxApplicable
	  ,ISNULL(RBM.ServiceTaxPercentage,0) AS ServiceTaxPercentage
	  ,ISNULL(RBM.BankName,'') AS BankName
	  ,ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise
	  ,ISNULL(RBM.GroupTitle,'') AS GroupTitle
	  ,ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail
	  ,RBM.ReceiptLogo
	  ,ISNULL(RBM.HeaderDisplayId,1) AS HeaderDisplayId
	  ,RBM.ReceiptBookHeader
	  ,ISNULL(RBM.FeeInvoiceHeaderDisplayId,1) AS FeeInvoiceHeaderDisplayId
	  ,RBM.FeeInvoiceHeader
	  ,ISNULL(RBM.CGSTPercentage,0) AS CGSTPercentage
	  ,ISNULL(RBM.SGSTPercentage,0) AS SGSTPercentage
	  ,ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount
      
     
  FROM [sFee].[tReceiptBookMaster] RBM  
        
  WHERE 
		 RBM.Id = @rId OR @rId = 0
	AND ((RBM.Code Like @rCode)OR(ISNULL(@rCode,'') = ''))
	AND ((RBM.Title Like @rTitle)OR(ISNULL(@rTitle,'') = ''))
	AND  RBM.OrgGroupId = @rOrgGroupId 
	--AND  QM.IsObsolete = 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) 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
	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
	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].[pStudentDepositListGet]...';


GO
ALTER PROCEDURE [sFee].[pStudentDepositListGet]
          
	@rOrgGroupId smallint,
	@rOrgId int,          
	@rDepositHeadId int=0,         
	@rFromDate date='',
	@rToDate date='',        
	--@rCode nvarchar(20)='',          
	@rStudentName nvarchar(300)='',
	@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
SET NOCOUNT ON
 
BEGIN
		SET @rStudentName = sCommon.fSearchStringGet(@rStudentName)

SELECT * FROM (


SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rDepositHeadId AS DepositHeadId,
		(SELECT [sFee].[fDepositHeadNameGet](@rDepositHeadId)) AS DepositHeadName,
		ISNULL(SA.StudentId,0) as StudentId,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		ISNULL(DA.Amount,0) AS TransactionAmount,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        SA.DivisionId,
		SA.DivisionOrder,
		SA.DivisionName,
		SA.ClassId,
		SA.ClassName AS ClassName,
		CASE WHEN @rIsBasedOnSUId=0 THEN SA.Code Else ISNULL(SA.suid,'') END AS SUId,
		SA.Code,
		DA.DepositDate AS TransactionDate,
		SA.DepartmentName As DepartmentName,
		SA.ClassName + '-'+ SA.DivisionName As ClassDivision,
		(ISNULL(DA.Amount,0))As Pending,
		'Deposit' As TransactionType,
		ISnull (DA.Amount,0) AS Credit,
		0 AS Debit,
		1 AS OrderIndex,
		DA.DepositNumber AS Number,
		DA.CreatedDateTime
  FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		INNER JOIN sFee.tDepositAdd DA ON DA.AcademicId=SA.AcademicId
		--(SELECT SUM(ISNULL(DA.Amount,0)) AS TotalDeposit,DA.AcademicId,ISNull(DA.DepositHeadId,0) AS DepositHeadId,DA.DepositDate As DepositDate,DA.DepositNumber  As DepositNumber,DA.CreatedDateTime FROM  sFee.tDepositAdd DA INNER JOIN sStudent.tAcademic A ON DA.AcademicId = A.Id  WHERE DA.DepositHeadId=@rDepositHeadId  GROUP  BY DA.AcademicId,DA.DepositHeadId,DA.DepositDate,DA.DepositNumber,DA.CreatedDateTime)D 
		--ON D.AcademicId=SA.AcademicId
		
  WHERE  
		(SA.OrgId=@rOrgId OR @rOrgId=0)
		AND(OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId=0)
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND (((SA.FirstName +' '+SA.MiddleName+' '+ SA.LastName) like @rStudentName) OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		AND (DA.DepositHeadId = @rDepositHeadId) 
		AND (
		((DA.DepositDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((DA.DepositDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		) 

		
UNION ALL

SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rDepositHeadId AS DepositHeadId,
		(SELECT [sFee].[fDepositHeadNameGet](@rDepositHeadId)) AS DepositHeadName,
		ISNULL(SA.StudentId,0) as StudentId,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		ISNULL(A.Amount,0) AS TransactionAmount,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        SA.DivisionId,
		SA.DivisionOrder,
		SA.DivisionName,
		SA.ClassId,
		SA.ClassName AS ClassName,
		CASE WHEN @rIsBasedOnSUId=0 THEN SA.Code Else ISNULL(SA.suid,'') END AS SUId,
		SA.Code,
		A.AdjustmentDate AS TransactionDate,
		SA.DepartmentName As DepartmentName,
		SA.ClassName + '-'+ SA.DivisionName As ClassDivision,
		(ISNULL(A.Amount,0))As Pending,
		'Adjusment' AS TransactionType,
		0  AS Credit,
		ISnull (A.Amount,0)  AS Debit,
		2 AS OrderIndex,
		A.AdjustmentNumber AS Number,
		A.CreatedDateTime
  FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sFee.tDepositAdjustment A ON A.AcademicId=SA.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
  WHERE  
		(SA.OrgId=@rOrgId OR @rOrgId=0)
		AND(OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId=0)
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND (((SA.FirstName +' '+SA.MiddleName+' '+ SA.LastName) like @rStudentName) OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		AND (A.DepositHeadId = @rDepositHeadId)
		AND (
		((A.AdjustmentDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((A.AdjustmentDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		) 
			
		UNION ALL

SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rDepositHeadId AS DepositHeadId,
		(SELECT [sFee].[fDepositHeadNameGet](@rDepositHeadId)) AS DepositHeadName,
		ISNULL(SA.StudentId,0) as StudentId,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		ISNULL(R.RefundAmount,0) TransactionAmount,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        SA.DivisionId,
		SA.DivisionOrder,
		SA.DivisionName,
		SA.ClassId,
		SA.ClassName AS ClassName,
		CASE WHEN @rIsBasedOnSUId=0 THEN SA.Code Else ISNULL(SA.suid,'') END AS SUId,
		SA.Code,
		R.RefundDate AS TransactionDate,
		SA.DepartmentName As DepartmentName,
		SA.ClassName + '-'+ SA.DivisionName As ClassDivision,
		(ISNULL(R.RefundAmount,0))As Pending,
		'Refund' AS TransactionType,
		0  AS Credit,
		ISnull (R.RefundAmount,0)  AS Debit,
		3 AS OrderIndex,
		R.RefundNumber AS Number,
		R.CreatedDateTime
  FROM 		
		sStudent.vStudentAcademic SA
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		INNER JOIN sFee.tDepositRefund R ON R.AcademicId=SA.AcademicId
		--LEFT JOIN 
		--(SELECT SUM(ISNULL(DR.RefundAmount,0)) AS TotalRefund,DR.AcademicId,ISNULL(DR.DepositHeadId,0) AS DepositHeadId,DR.RefundDate As RefundDate,DR.RefundNumber AS RefundNumber,DR.CreatedDateTime FROM sFee.tDepositRefund DR INNER JOIN sStudent.tAcademic A ON DR.AcademicId = A.Id  WHERE   DR.DepositHeadId=@rDepositHeadId GROUP BY DR.AcademicId,DepositHeadId,DR.RefundDate,DR.RefundNumber,DR.CreatedDateTime)R
		--ON R.AcademicId=SA.AcademicId
  WHERE  
		(SA.OrgId=@rOrgId OR @rOrgId=0)
		AND(OM.OrgGroupId=@rOrgGroupId OR @rOrgGroupId=0)
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND (((SA.FirstName +' '+SA.MiddleName+' '+ SA.LastName) like @rStudentName) OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		AND (R.DepositHeadId = @rDepositHeadId)
		AND (
		((R.RefundDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((R.RefundDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		) 	

	) A
	Order by A.OrgId,A.Code,A.TransactionDate

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


GO
ALTER PROCEDURE [sHrm].[pEmployeeMasterModify]
	
	@rId [bigint],
	@rCode [nvarchar](20),
	@rFirstName [nvarchar](100),
	@rMiddleName [nvarchar](100),
	@rLastName [nvarchar](100),
	@rEmployeeTypeId int,
	@rDepartmentId int,
	@rDateOfBirth Date,
	@rDateOfJoining Date,
	@rGenderId int,
	@rStatusId [smallint],
	@rIsObsolete [bit],
	@rUpdatedUserId [bigint],
	@rEmployeePhoto varbinary(max),
	@rEmployeeDesignationId [int],
	@rEmployeeGradeId int,
	@rEmployeeGroupId int,
	@rShortName nvarchar(50),
	@rNumber bigint = 0,
	@rIsOtherUser smallint = 0,
	@rDateOfLeaving Date =NULL 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	DECLARE @lOrgId int
	
	SELECT @lOrgId = OrgId FROM sHrm.tEmployeeMaster WHERE Id=@rId AND ISNULL(IsOtherUser,0) = 0 

	IF EXISTS(SELECT Id FROM sHrm.tEmployeeMaster WHERE Code=@rCode AND OrgId=@lOrgId AND Id<>@rId  )
		BEGIN
		SELECT -101 as Result
		RETURN
	END 
			
	 UPDATE sHrm.tEmployeeMaster
		SET
		    Code = @rCode, 
			FirstName = @rFirstName,
			MiddleName = @rMiddleName,
			LastName = @rLastName,
			StatusId = @rStatusId,
			ShortName=@rShortName,
			IsObsolete = @rIsObsolete,
			UpdatedUserId = @rUpdatedUserId,
			UpdatedDateTime = sCommon.fGetDate(),
			Number = @rNumber,
			IsOtherUser = @rIsOtherUser
	  WHERE 
			Id = @rId 
	  
	SELECT @rId AS RESULT
	
	BEGIN 
	UPDATE sHrm.tEmployeeJobDetail
		SET 
			EmployeeDesignationId = @rEmployeeDesignationId,	
			OrganizationDepartmentId = @rDepartmentId,
			DateOfJoining =	@rDateOfJoining,
			UpdatedUserId = @rUpdatedUserId,
			EmployeeTypeId = @rEmployeeTypeId,
			EmployeeGradeId = @rEmployeeGradeId,
			EmployeeGroupId = @rEmployeeGroupId
		WHERE 
			EmployeeId = @rId
			
		IF(@rStatusId = 9)
		BEGIN
			UPDATE sHrm.tEmployeeJobDetail
			SET
			DateOfLeaving = @rDateOfLeaving
			WHERE 
			EmployeeId = @rId
		END
	
	UPDATE sHrm.tEmployeePersonalDetail
		SET 
			DateOfBirth	=	@rDateOfBirth,
			GenderId	=	@rGenderId,
			UpdatedUserId = @rUpdatedUserId
		WHERE 
			EmployeeId = @rId	
	
	IF @rStatusId = 9
	BEGIN
		UPDATE sSecurity.tUser
			SET 
				IsObsolete = 1,
				UpdatedUserId = @rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			WHERE 
				SourceId = @rId AND SourceTypeId = 95
				
		
	END
	ELSE IF @rStatusId = 7
	BEGIN
		UPDATE sSecurity.tUser
			SET 
				IsObsolete = 0,
				UpdatedUserId = @rUpdatedUserId,
				UpdatedDateTime = sCommon.fGetDate()
			WHERE 
				SourceId = @rId AND SourceTypeId = 95
	END
	
	IF @rStatusId != 9
	BEGIN
		UPDATE sHrm.tEmployeeJobDetail
		SET 
			DateOfleaving = NULL,	
			ReasonOfleaving = NULL
		WHERE 
			EmployeeId = @rId		
	END
	
	
	  
	  --BEGIN
	  --   Execute sHrm.pEmployeeJobDetailModify 
	  --     0,@rId,0,@rEmployeeDesignationId,@rLocationId,@rDepartmentId,@rDateOfJoining,'','',0,0,@rUpdatedUserId,
	  --     0,0,@rEmployeeTypeId,@rProcessTypeId,NULL,NULL,NULL,0,0
	     --Execute sHrm.pEmployeePersonalDetailModify
	     --  0,@rId,'',@rDateOfBirth,@rGenderId,0,0,'','',0,0,'','','','','',0,'',0,'',0,0,@rUpdatedUserId,@rIsBirthDateUnknown
	     
	  END
END
GO
PRINT N'Altering [sHrm].[pLeaveApproveValidate]...';


GO
 
ALTER PROCEDURE [sHrm].[pLeaveApproveValidate]

        @rId bigint,
        @rEmployeeId bigint,
        @rFromDate date,
        @rLeaveTypeId int,
        @rNoOfLeave decimal(5,2),
        @rBatchId int,
        @rOrgId int,
		@rCarryForwardLeave int = 0
        
AS
SET NOCOUNT ON

BEGIN
	IF EXISTS (SELECT 1 FROM  sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId AND isLwp = 0)
	BEGIN
	   DECLARE @lMainLeaveTypeId tinyint
	   SET @lMainLeaveTypeId =0
	   SELECT @lMainLeaveTypeId = ISNULL(MainLeaveTypeId,0) FROM sHrm.tLeaveTypeMaster WHERE Id = @rLeaveTypeId
	   
	   DECLARE @lMaxInMonth decimal(5,2)
	   DECLARE @lNumberOfLeave decimal(5,2)
	   SET @lMaxInMonth =0
	   SET @lNumberOfLeave =0
	   
	   DECLARE @lFirstDate date
	   DECLARE @lLastDate date
	   
	   SET @lFirstDate = DATEADD(mm, DATEDIFF(mm, 0, @rFromDate), 0)
	   SET @lLastDate = DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, @rFromDate) + 1, 0))
	   
	   SELECT @lMaxInMonth = ISNULL(LB.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
	   INNER JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId=EJD.EmployeeId AND LB.BatchId = @rBatchId
	   WHERE EJD.OrgId = @rOrgId AND LB.LeaveTypeId=@rLeaveTypeId AND EJD.EmployeeId=@rEmployeeId
	   
	   -- For Employee Specific 08/11/2017 - by Ramesh Gurjar
	   IF(@lMaxInMonth=0)
	   BEGIN
			SELECT @lMaxInMonth = ISNULL(LTGS.MaxInMonth,0) FROM sHrm.tEmployeeJobDetail EJD 
			INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON EJD.EmployeeGradeId=LTGS.EmployeeGradeId 
			WHERE LTGS.OrgId = @rOrgId 
			AND LTGS.LeaveTypeId=@rLeaveTypeId 
			AND  EJD.EmployeeId=@rEmployeeId
	   END
	   -- End
	   SET @lMaxInMonth = @lMaxInMonth+@rCarryForwardLeave
	   Print @lMaxInMonth
	   SELECT  @lNumberOfLeave= ISNULL(SUM(L.NoOfLeave),0) 
	   FROM     
	   sHrm.tLeave L  
	   WHERE  
	   L.EmployeeId=@rEmployeeId 
	   AND (L.FromDate>=@lFirstDate) AND (L.FromDate<=@lLastDate)
	   AND L.LeaveTypeId=@rLeaveTypeId AND L.StatusId = 550
	   GROUP BY L.EmployeeId
	   
	   IF (@lMaxInMonth < (@lNumberOfLeave+@rNoOfLeave) AND @lMainLeaveTypeId!=3)
	   BEGIN
			SELECT -105  AS RESULT
			RETURN
	   END
	   ELSE
	   BEGIN
			SELECT 1
	   END	
   END
   ELSE 
   SELECT 1
END
GO
PRINT N'Altering [sHrm].[pLeaveBalanceAddGet]...';


GO
ALTER PROCEDURE [sHrm].[pLeaveBalanceAddGet]

	 @rId int,
	 @rCode nvarchar(20),
	 @rName nvarchar(100),
	 @rFromReportDate date,
	 @rToReportDate date,
	 @rLeaveTypeId int,
	 @rBatchId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	BEGIN
		SET @rName = sCommon.fSearchStringGet(@rName)
	END
	
	SELECT 
			LBA.Id,
			LBA.EmployeeId,
			ECD.Code,
			ECD.EmployeeName,
			ECD.DepartmentName,
			LBA.ReportDate,
			LBA.AddBalance,
			LBA.BatchId,
			LBA.AddBalanceRemark,
			LBA.LeaveTypeId,
			LTM.Title AS LeaveTypeName
			
	FROM 
			sHrm.tLeaveBalanceAdd LBA
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = LBA.LeaveTypeId AND LTM.IsLWP=0
			INNER JOIN sHrm.vEmployeeCommonDetail ECD ON LBA.EmployeeId = ECD.EmployeeId
	WHERE 
		(LBA.BatchId = @rBatchId)
		AND	((LBA.Id = @rId) OR (@rId = 0))
		AND ((LBA.ReportDate>=@rFromReportDate) OR (ISNULL(@rFromReportDate,'')=''))
		AND ((LBA.ReportDate<=@rToReportDate) OR (ISNULL(@rToReportDate,'')=''))
		AND ((LBA.LeaveTypeId=@rLeaveTypeId) OR (@rLeaveTypeId=0))
		AND ((ECD.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND ((ECD.EmployeeName like @rName) OR (ISNULL(@rName,'')=''))
		AND  ISNULL(ECD.IsOtherUser,0)=0
		ORDER BY ECD.Code
END
GO
PRINT N'Altering [sHrm].[pLeaveBalanceTypewiseAdd]...';


GO
 
ALTER PROCEDURE [sHrm].[pLeaveBalanceTypewiseAdd]
	 
	@rEmployeeId bigint,
	@rLeaveTypeId int,
	@rBalanceLeave decimal(8,2),
	@rBatchId int,
	@rUserId bigint,
	@rMaxInMonth decimal(5,2) = 0,
	@rLastYearBalanceLeave decimal(8,2) = 0,
	@rCurrentBalanceLeave decimal(8,2) = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
	BEGIN TRANSACTION	
		
		DECLARE @lBalanceLeave decimal(8,2) = 0
		SELECT @lBalanceLeave =  BalanceLeave FROM sHrm.tLeaveBalance WHERE EmployeeId=@rEmployeeId AND LeaveTypeId=@rLeaveTypeId AND BatchId=@rBatchId

		DELETE FROM sHrm.tLeaveBalance WHERE EmployeeId=@rEmployeeId AND LeaveTypeId=@rLeaveTypeId AND BatchId=@rBatchId
		
		INSERT INTO sHrm.tLeaveBalance
			(
				EmployeeId,
				LeaveTypeId,
				BalanceLeave,
				BatchId,
				MaxInMonth,
				LastYearBalanceLeave,
				CurrentBalanceLeave
			)
		VALUES
			(
				@rEmployeeId,
				@rLeaveTypeId,
				@rBalanceLeave,
				@rBatchId,
				@rMaxInMonth,
				@rLastYearBalanceLeave,
				@rCurrentBalanceLeave
			)
			
		INSERT INTO sHrm.tLeaveBalanceLog 
		SELECT @rEmployeeId,@rLeaveTypeId,@lBalanceLeave,2,@rBalanceLeave,
		'Leave Balance',@rBatchId,@rUserId,sCommon.fGetDate()
		
 		SELECT 1 AS Result
	
	COMMIT TRANSACTION		
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH		
END
GO
PRINT N'Altering [sHrm].[pLeaveBalanceTypewiseGet]...';


GO
 
 
ALTER PROCEDURE [sHrm].[pLeaveBalanceTypewiseGet]

	  @rEmployeeTypeId int=0,
	  @rEmployeeGroupId int=0,
	  @rEmployeeGradeId int=0,
	  @rDepartmentId int=0,
	  @rLeaveTypeId int=0,
	  @rOrgId int,
	  @rBatchId int 
	  	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 	    
	SELECT 
		ECD.EmployeeId,
		ECD.Code,
		ECD.EmployeeName,
		ECD.DepartmentName,
		ISNULL(EDM.Title,'') AS EmployeeDesignation, 
		CASE WHEN LB.EmployeeId IS NULL THEN CONVERT(bit,0) ELSE CONVERT(bit,1) END AS IsCheck,
		CASE WHEN LB.BalanceLeave IS NULL THEN ISNULL(LTGS.NoOfLeave,0) ELSE ISNULL(LB.BalanceLeave,0) END AS BalanceLeave,
		CASE WHEN LB.MaxInMonth IS NULL THEN ISNULL(LTGS.MaxInMonth,0) ELSE ISNULL(LB.MaxInMonth,0) END AS MaxInMonth,
		ISNULL(LB.LastYearBalanceLeave,0) AS LastYearBalanceLeave,
		ISNULL(LB.CurrentBalanceLeave,0) AS CurrentBalanceLeave,
	    ISNULL((SELECT TOP 1 BalanceLeave  FROM sHrm.tLeaveBalanceLog WHERE EmployeeId = ECD.EmployeeId AND LeaveTypeId=LTGS.LeaveTypeId AND BatchId = @rBatchId AND BalanceLeave!=0 AND LeaveTransactionId=2 ORDER BY CreatedDateTime ASC),0) AS FirstBalanceLeave
	FROM  
		sHrm.vEmployeeCommonDetail ECD 
		INNER JOIN sHrm.tLeaveTypeGradeSettings LTGS ON LTGS.OrgId = ECD.OrgID AND LTGS.EmployeeGradeId =  ECD.EmployeeGradeId
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id = ECD.EmployeeDesignationId
		LEFT JOIN sHrm.tLeaveBalance LB ON LB.EmployeeId = ECD.EmployeeId  AND LB.LeaveTypeId = @rLeaveTypeId AND LB.BatchId = @rBatchId
	WHERE 
		ECD.EmployeeStatusId = 7
		AND ((ECD.EmployeeTypeId= @rEmployeeTypeId) OR (@rEmployeeTypeId= 0))
		AND ((ECD.EmployeeGroupId= @rEmployeeGroupId) OR (@rEmployeeGroupId= 0))
		AND ((ECD.EmployeeGradeId= @rEmployeeGradeId) OR (@rEmployeeGradeId= 0))
		AND ((ECD.OrgId= @rOrgId) OR (@rOrgId= 0))
		AND ((ECD.DepartmentId= @rDepartmentId ) OR (@rDepartmentId= 0 ))
		AND LTGS.LeaveTypeId = @rLeaveTypeId
		AND ISNULL(ECD.IsOtherUser,0)=0 
	ORDER BY ECD.Number
END
GO
PRINT N'Altering [sHrm].[pLeaveTypeMasterListGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pLeaveTypeMasterListGet]
(
    @rId int = 0,
    @rName nvarchar(20),
  	@rOrgId [smallint], 
	@rCode [nvarchar](20),
	@rIsWildCardSearch bit
 )
AS
SET NOCOUNT ON

BEGIN
    
    IF(@rIsWildCardSearch = 0)
    BEGIN
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rName = sCommon.fSearchStringGet(@rName) 
    END
	SELECT 
		   L.OrgId
		  ,L.Id
		  ,L.Code
		  ,L.Title
		  ,L.IsCarryForward
		  ,L.IsLWP
		  ,L.IsObsolete
		  ,ISNULL(L.MaximumCarryForward,0) AS MaximumCarryForward
		  ,ISNULL(L.MainLeaveTypeId,0) AS MainLeaveTypeId,
		  MLTM.Title AS MainLeaveType
		  ,ISNULL(L.IsMonthCarryForward,0) AS IsMonthCarryForward
		  ,ISNULL(L.MonthCarryForward,0) AS MonthCarryForward
		  
  FROM     
		[sHrm].[tLeaveTypeMaster] L
		LEFT JOIN sHrm.tMainLeaveTypeMaster MLTM ON MLTM.Id = L.MainLeaveTypeId
  WHERE 
		((L.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((L.Id  = @rId) OR (@rId = 0))
		AND ((L.Code Like  @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((L.Title Like @rName) OR (ISNULL(@rName,'')='')) 
END
GO
PRINT N'Altering [sHrm].[pRptDailyStaffAttendanceGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptDailyStaffAttendanceGet]
	 	 
	 	 @rBuilder1 nvarchar(max)='',
		 @rBuilder2 nvarchar(max)='',
	 	 @rDepartmentId int=0,
	 	 @rAttendanceDate date='',
	 	 @rCode nvarchar(20)='',
	 	 @rBatchId int=0,
	 	 @rOrgId int=0,
	 	 @rStatusId int=0,
	 	 @rEmployeeGradeId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  BEGIN
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			EM.DepartmentName,
			EAR.IsPresent as IsPresent,
			ISNULL(EAR.AttendanceDate,'') AS AttendanceDate,
			[sHrm].[fEmployeeLeaveTypeCodeGet] (@rBatchId,EM.EmployeeId,@rAttendanceDate) AS LeaveType,
			ISNULL(EAR.EmployeeId,0) AS EmployeeIdForPresent
		
  FROM 
			sHrm.vExtEmployeeMaster EM
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=EM.EmployeeId 
			AND EAR.AttendanceDate =@rAttendanceDate
			AND (EAR.BatchId = @rBatchId)
    WHERE 
		  ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		  AND ((EM.Code like @rCode) OR (ISNULL(@rCode,'')=''))
		  AND (EM.OrgId = @rOrgId)		  
		  AND ((EM.StatusId = @rStatusId) OR ISNULL(@rStatusId,0)=0)
		  AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR ISNULL(@rEmployeeGradeId,0)=0)
		  --AND (@rAttendanceDate>=EM.DateOfJoining)
		  AND ((EM.DateOfleaving >= @rAttendanceDate) OR ISNULL(EM.DateOfleaving,'') = '')
          AND ((EM.DateOfJoining <= @rAttendanceDate) OR ISNULL(EM.DateOfJoining,'') = '') 
		  AND (EM.StatusId = 7)
		  AND (EM.IsOtherUser = 0)	
          ORDER BY EM.Code
  END
END
GO
PRINT N'Altering [siTax].[pForm16DetailsAdd]...';


GO
/******************************
** Name:  [siTax].[pForm16DetailsAdd] 
** Desc:  Add and Update Record for the [siTax].[tForm16] table 
** Auth:  Savan Vaghela
** Date:  19-January-2017
** Page:  Pages/Hrm/IncomeTax/Form16New.aspx  
************************************************************
** Change History
************************************************************
** PR      Date                Author            Description 
**
** 1    19-January-2017      Savan Vaghela       
************************************************************/

ALTER PROCEDURE [siTax].[pForm16DetailsAdd]   
	@rId bigint,
	@rEmployeeId bigint,
	@rAssesmentYearId bigint,
	@rOrgGroupId int,
	@rCreatedUserId bigint,
	@rGrossAmount VARCHAR(MAX),
	@rQualifyingAmount VARCHAR(MAX),
	@rDeductibleAmount VARCHAR(MAX)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
			DECLARE @lNextNumber BIGINT 

			

			DECLARE @TableGrossAmount      TABLE  (RowID int Identity(1,1),GrossAmount DECIMAL(18,2))
			DECLARE @TableQualifyingAmount TABLE  (RowID int Identity(1,1),QualifyingAmount DECIMAL(18,2))
			DECLARE @TableDeductibleAmount TABLE  (RowID int Identity(1,1),DeductibleAmount DECIMAL(18,2))

			INSERT INTO @TableGrossAmount(GrossAmount)           SELECT CAST(item as DECIMAL(18,2)) FROM scommon.fnSplit(@rGrossAmount,',')
			INSERT INTO @TableQualifyingAmount(QualifyingAmount) SELECT CAST(item as DECIMAL(18,2)) FROM scommon.fnSplit(@rQualifyingAmount,',')
			INSERT INTO @TableDeductibleAmount(DeductibleAmount) SELECT CAST(item as DECIMAL(18,2)) FROM scommon.fnSplit(@rDeductibleAmount,',')

				IF(@rId = 0)	
					BEGIN
						  IF NOT EXISTS(SELECT 1 FROM [siTax].[tForm16] WHERE EmployeeId=@rEmployeeId AND AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId)
							BEGIN
							    EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'siTax.tForm16', 0, 1, 1,@outNextNumber = @lNextNumber output
								INSERT INTO  [siTax].[tForm16]  (Id,EmployeeId,AssesmentYearId,IsObsolete,CreatedUserId,CreatedDateTime,OrgGroupId)
								VALUES (@lNextNumber,@rEmployeeId,@rAssesmentYearId,0,@rCreatedUserId,sCommon.fGetDate(),@rOrgGroupId)

								INSERT INTO  [siTax].[tForm16Detail] (Form16Id,IncomeTaxSubgroupId,GrossAmount,QualifyingAmount,DeductibleAmount,IsObsolete,CreatedUserId,CreatedDateTime)
								SELECT @lNextNumber,StaticIncomeTaxSubGroupId,0,QualifyingLimit,0,0,@rCreatedUserId,sCommon.fGetDate() FROm [siTax].[tIncomeTaxSubGroup] Where AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId


								DECLARE @Count int =0
								SELECT @Count= COUNT(1) FROm [siTax].[tStaticIncomeTaxSubGroup]
								DECLARE @Countter int =0

								WHILE(@Count>@Countter)
									BEGIN
										SET @Countter=@Countter+1
											UPDATE [siTax].[tForm16Detail] SET 
											 GrossAmount=(SELECT GrossAmount FROM @TableGrossAmount WHERE RowID=@Countter)
											,QualifyingAmount=(SELECT QualifyingAmount FROM @TableQualifyingAmount WHERE RowID=@Countter)
											,DeductibleAmount=(SELECT DeductibleAmount FROM @TableDeductibleAmount WHERE RowID=@Countter) 
										WHERE Form16Id=@lNextNumber AND IncomeTaxSubgroupId=@Countter
										PRINt @Countter
									END
								SELECT 1 as Result,@lNextNumber AS Form16Id
								print '1'
							END
							
						ELSE
							BEGIN
								
								SELECT @lNextNumber=Id FROM [siTax].[tForm16] WHERE EmployeeId=@rEmployeeId AND AssesmentYearId=@rAssesmentYearId and OrgGroupId=@rOrgGroupId

								UPDATE [siTax].[tForm16] SET UpdatedUserId=@rCreatedUserId,	UpdatedDateTime=sCommon.fGetDate() WHERE ID=@lNextNumber
								DECLARE @Count1 int =0
								SELECT @Count1= COUNT(1) FROm [siTax].[tStaticIncomeTaxSubGroup]
								DECLARE @Countter1 int =0

								WHILE(@Count1>@Countter1)
									BEGIN
										SET @Countter1=@Countter1+1
											UPDATE [siTax].[tForm16Detail] SET 
											 GrossAmount=(SELECT GrossAmount FROM @TableGrossAmount WHERE RowID=@Countter1)
											,QualifyingAmount=(SELECT QualifyingAmount FROM @TableQualifyingAmount WHERE RowID=@Countter1)
											,DeductibleAmount=(SELECT DeductibleAmount FROM @TableDeductibleAmount WHERE RowID=@Countter1) 
										WHERE Form16Id=@lNextNumber AND IncomeTaxSubgroupId=@Countter1
										PRINt @Countter1
									END
								SELECT 1 as Result,@lNextNumber AS Form16Id
							END
					END	 
				ELSE
					BEGIN
						SET @lNextNumber = @rId
							UPDATE [siTax].[tForm16] SET UpdatedUserId=@rCreatedUserId,	UpdatedDateTime=sCommon.fGetDate() WHERE ID=@lNextNumber
								DECLARE @Count2 int =0
								SELECT @Count2= COUNT(1) FROm [siTax].[tStaticIncomeTaxSubGroup]
								DECLARE @Countter2 int =0

								WHILE(@Count2>@Countter2)
									BEGIN
										SET @Countter2=@Countter2+1
											UPDATE [siTax].[tForm16Detail] SET 
											 GrossAmount=(SELECT GrossAmount FROM @TableGrossAmount WHERE RowID=@Countter2)
											,QualifyingAmount=(SELECT QualifyingAmount FROM @TableQualifyingAmount WHERE RowID=@Countter2)
											,DeductibleAmount=(SELECT DeductibleAmount FROM @TableDeductibleAmount WHERE RowID=@Countter2) 
										WHERE Form16Id=@lNextNumber AND IncomeTaxSubgroupId=@Countter2
										PRINt @Countter2
									END
						SELECT 11 AS Result,@lNextNumber AS Form16Id
					END  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
	ROLLBACK TRANSACTION
	SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [siTax].[pForm16EmployeeDetailGet]...';


GO
ALTER PROCEDURE [siTax].[pForm16EmployeeDetailGet]   
	@rEmployeeId bigint,
	@rAssesmentYearId bigint,
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT ITG.Id as 'GroupID'
		  ,ITSG.Id as 'SubGroupID'
		  ,ISNULL(ITG.GroupCode,'') +'  '+ ISNULL(ITG.DisplayName,'') +'  '+ ISNULL(ITG.ActionName,'') as 'Group'
		  ,ITSG.SubGroupName 
		  ,ISNULL(d.GrossAmount,0)GrossAmount
		  ,ITSG.QualifyingLimit as  QualifyingAmount
		  ,ISNULL(d.DeductibleAmount,0)DeductibleAmount
		  ,ITSG.IsEditable
		  ,d.Form16Id
	FROm [siTax].[tStaticIncomeTaxGroup] AS ITG 
		 LEFT JOIN [siTax].[tStaticIncomeTaxSubGroup] AS ITSG on ITG.Id=ITSG.StaticIncomeTaxGroupId
		 LEFT JOIN (SELECT f.Id AS Form16Id,fd.IncomeTaxSubgroupId,	fd.GrossAmount,	fd.QualifyingAmount,	fd.DeductibleAmount
				    FROm [siTax].[tForm16] as f
					INNER JOIN [siTax].[tForm16Detail] as fd on f.id =fd.Form16Id
	                WHERE f.EmployeeId=@rEmployeeId AND AssesmentYearId=@rAssesmentYearId 
	                AND OrgGroupId=@rOrgGroupId) AS d ON d.IncomeTaxSubgroupId=ITSG.id
	
	ORDER by ITG.OrderIndex,ITSG.OrderIndex


		DECLARE @PayrollId int = 0


		SELECT @PayrollId=ISNULL(ESO.PayrollId,0) FROM sHrm.tEmployeeMaster AS  EMP
		LEFT JOIN [sHrm].[tEmployeeStatutoryAndOther]  AS ESO ON ESO.EmployeeId=EMP.id
		LEFT JOIN sPayroll.tPayrollMaster PM ON PM.id = ESO.PayrollId
		WHERE EMP.id=@rEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
		SELECT ISNULL(ESO.PayrollId,0)PayrollId,ISNULL(PM.Title,'')PayrollName FROM sHrm.tEmployeeMaster AS  EMP
		LEFT JOIN [sHrm].[tEmployeeStatutoryAndOther]  AS ESO ON ESO.EmployeeId=EMP.id
		LEFT JOIN sPayroll.tPayrollMaster PM ON PM.id = ESO.PayrollId
		WHERE EMP.id=@rEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0

		SELECT -1 as ID,'- Select -' AS Code, 0 as OrderIndex union ALL
		SELECT Id,Code,Id as OrderIndex FROM sPayroll.tPayrollYearMaster WHERE IsActive=0 AND PayrollId=@PayrollId
		order by OrderIndex


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


GO
 
 
ALTER PROCEDURE [sProcurement].[pStockIssGet]
	@rOrgGroupId int,
	@rNumber [nvarchar](20) = '',
	@rFromDate date='',
	@rToDate date='',
	@rStoreLocationId int=0,
	@rItemCode nvarchar(100)='',
	@rItemName nvarchar(200)='',
	@rSearchType nvarchar(5)= '1',
	@rIssueToSourceId BIGINT = null,
	@rToDept int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	  
SET @rNumber = sCommon.fSearchStringGet(@rNumber)

	if(@rSearchType='1')
		begin
				SELECT		
				SI.Id,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
				SI.IssuedByName,
				case when SI.TransactionDate is not null  then SI.TransactionDate else  SI.CreatedDateTime End AS IssuedDate,
				 SI.CreatedDateTime as TranjactionDate,
				 '' StockItemCode,
				 '' StockItemName,
				 ISNULL(SI.IssueToSourceId,'') as IssueToSourceId,
				 ISNULL(EM.ShortName,'') as ToEmployeeName,
				 ISNULL(DM.DisplayTitle,'') as ToDepartment,
				 ISNULL(SI.IssueToName,'') as IssueToName
				FROM sProcurement.tStockIssue SI 
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = SI.IssueToSourceId
				LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = SI.ToOrganizationDepartmentId
				WHERE
				SI.OrgGroupId = @rOrgGroupId AND  ISNULL(EM.IsOtherUser,0) = 0
				AND  ((SI.Number like @rNumber) OR (@rNumber = ''))
				AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SI.FromStoreLocationId=@rStoreLocationId 
				AND ((SI.IssueToSourceId = @rIssueToSourceId) OR (ISNULL(@rIssueToSourceId,'')=''))
				AND ((DM.Id = @rToDept) OR (@rToDept = 0))
				Order by SI.CreatedDateTime desc
		end
	else
		begin
				SELECT		
					SI.Id,SI.Number,isnull(SI.StockIssueRequestId,0) as StockIssueRequestId,
					SI.IssuedByName,
					case when SI.TransactionDate is not null  then SI.TransactionDate else  SI.CreatedDateTime End	AS IssuedDate,
					 SI.CreatedDateTime as TranjactionDate,
					 SIM.Code AS StockItemCode,
					SIM.TItle As StockItemName,
					isnull(SI.IssueToSourceId,'') as IssueToSourceId,
					ISNULL(EM.ShortName,'') as ToEmployeeName,
				    ISNULL(DM.DisplayTitle,'') as ToDepartment,
				    ISNULL(SI.IssueToName,'') as IssueToName
				FROM sProcurement.tStockIssue SI 
				Inner join sProcurement.tStockIssueDetail SIDE on SI.ID= SIDE.StockIssueId
				INNER JOIN sIp.tStockItemMaster SIM ON SIM.Id = SIDE.StockItemID
				LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = SI.IssueToSourceId
				LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = SI.ToOrganizationDepartmentId
				WHERE ((SI.Number like @rNumber) OR (@rNumber = ''))
				AND  SI.OrgGroupId = @rOrgGroupId AND  ISNULL(EM.IsOtherUser,0) = 0
				AND (( Convert(Date,SI.CreatedDateTime)>= @rFromDate ) OR (ISNULL(@rFromDate,'')=''))
				AND (( Convert(Date,SI.CreatedDateTime)<= @rToDate ) OR (ISNULL(@rToDate,'')=''))
				AND SI.FromStoreLocationId=@rStoreLocationId 
				AND (SIM.Id = @rItemCode or @rItemCode='')
				AND (SIM.Title = @rItemName or @rItemName='')
				AND ((SI.IssueToSourceId = @rIssueToSourceId) or (ISNULL(@rIssueToSourceId,'')=''))
				AND ((DM.Id = @rToDept) OR (@rToDept = 0))
				Order by SI.CreatedDateTime desc
		end
END
GO
PRINT N'Altering [sSecurity].[pAppPermissionGet]...';


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

	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermissionUser P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706, -- Summarise - Student Summary
			30766, -- Consolidate Pending Fee
			30768, -- Religionwise Strength Dashboard
			30769  -- Exam Schedule Dashboard 
			)
		) TP 
		GROUP BY TP.TaskId
	END
ELSE
	BEGIN
	
		SELECT		
			TP.TaskId AS TaskID,
			CAST(MAX(TP.C) AS BIT) AS [Create],
			CAST(MAX(TP.R) AS BIT) AS [Read],
			CAST(MAX(TP.U) AS BIT) AS [Update],
			CAST(MAX(TP.D) AS BIT) AS [Delete],
			CAST(MAX(TP.S) AS BIT) AS [Search],
			CAST(MAX(TP.P) AS BIT) AS [Print],
			CAST(MAX(TP.X) AS BIT) AS [Execute]
		FROM
		(
			SELECT 	
				P.TaskId					AS	TaskID,
				(Permission & 1) 		AS	C, --[Create],
				(Permission & 2)/2		AS	R, --[Read],
				(Permission & 4)/4		AS	U, --[Update],
				(Permission & 8)/8		AS	D, --[Delete],
				(Permission & 16)/16 	AS	S, --[Search],
				(Permission & 32)/32 	AS	P, --[Print],
				(Permission & 64)/64 	AS	X --[Execute]
			FROM sSecurity.tPermission P
			INNER JOIN sSecurity.tOrganizationTask T ON P.TaskId = T.TaskId And T.OrgGroupId = @rOrgGroupId
			INNER JOIN sSecurity.tTask T1 ON T1.Id=P.TaskId 
			INNER JOIN sSecurity.tModulePermission MP ON MP.ModuleId=T1.ModuleId AND MP.OrgGroupId=@rOrgGroupId
			INNER JOIN (SELECT RoleId FROM sSecurity.tUserRole WHERE IsObsolete = 0 AND UserId = @rUserId) R
			ON R.RoleId = P.RoleId 
			WHERE
			P.OrgGroupId = @rOrgGroupId 
			AND T1.Id in(
			20075, -- Student Register
			20086, -- Circular
			20094, -- Assignment
			20107, -- Query Queue
			20126, -- Behaviour Entry
			20171, -- Assign Task
			20184, -- Add Photo
			20538, -- Leave Listing
			20561, -- Classwork
			20983, -- My Leave
			30032, -- Subjectwise Attendance
			30502, -- Consolidate - Receipt Details
			30501, -- Consolidate - Fee Status
			30505, -- Consolidate - Student Attendance
			30504, -- Consolidate - Assessment
			30508, -- Consolidate - Task - Attendance
			30507, -- Consolidate - Admission form
			30506, -- Consolidate - Staff
			30536, -- My Expense
			30546, -- Student Alert
			30547, -- Employee Alert
			30550, -- Student Birthdays
			30551, -- Employee Birthdays
			30560, -- Lead Master Admin Permission
			30572, -- Add Lead Permission
			30573, -- Consolidate - Admission Inquiry 
			20089, -- New Query
			30607, -- Consolidate - Task - CW/HW
			30621, -- Consolidate - Fee Collection
			30630, -- Payment Transaction Update
			30621, -- Consolidate - Fee Collection
			20555, -- Lesson Plan
			30635, -- Division Wise -  Photo
			30662, -- Data Search
			30663, -- ClassWork - Home Work Dash Board Search
			30664, -- ClassWork HomeWork Queue
			30678, -- Assignment Queue
			30585, -- Circular Queue
			30687, -- Is Allow SMS Alert
			30688, -- Is Allow Email Alert
			30689, -- Is Allow Notification Alert
			30222, -- Circular Admin
			30540, -- Summarise - Security Dashboard
			30541, -- Summarise - Library Dashboard
			30542, -- Summarise - Transport Dashboard
			30703, -- Summarise - Employee Summary
			30706  -- Summarise - Student Summary
			)
		) TP 
		GROUP BY TP.TaskId
	END
END
GO
PRINT N'Altering [sSecurity].[pMobileAppTaskGet]...';


GO
 
ALTER PROCEDURE [sSecurity].[pMobileAppTaskGet]
		@rRoleId bigint,		
		@rOrgGroupId int,
		@rUserId bigint = 0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

    DECLARE @lRoleTitle nvarchar(100)=''
	
	IF(@rUserId=0)
	BEGIN
		SELECT @lRoleTitle = Title FROM sSecurity.tRole WHERE Id=@rRoleId
		IF(@lRoleTitle = 'Student')
		BEGIN
				SELECT  
					T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
					INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
					INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id AND RDM.RoleId =@rRoleId
					INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.Id=T.ResourceTypeId
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
					LEFT OUTER JOIN sSecurity.tPermission P ON T.Id = P.TaskId AND (P.RoleId = @rRoleId OR P.RoleId IS NULL)
					INNER JOIN sSecurity.tAssignSubRole ASR ON ASR.RoleId = P.RoleId AND ASR.SubRoleId = @rRoleId
				WHERE 
				T.IsObsolete = 0 AND T.RoleScopeId IN(0,2)
				ORDER BY T.ModuleId,RTM.Id
		END
		ELSE
		BEGIN
				SELECT  
					T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
					INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
					INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id AND RDM.RoleId =@rRoleId
					INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.Id=T.ResourceTypeId 
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
					LEFT OUTER JOIN sSecurity.tPermission P ON T.Id = P.TaskId AND (P.RoleId = @rRoleId OR P.RoleId IS NULL)
				WHERE 
				T.IsObsolete = 0 AND T.RoleScopeId IN(0,1)
				ORDER BY T.ModuleId,RTM.Id
		END
	END
	ELSE
	BEGIN
		
		SELECT @lRoleTitle = Title FROM sSecurity.tRole R
		INNER JOIN sSecurity.tUserRole UR ON R.Id = UR.RoleId 
		WHERE UR.UserId=@rUserId
		
		IF(@lRoleTitle = 'Student')
		BEGIN
				SELECT  
					T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
					INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
					--INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id AND RDM.RoleId =@rRoleId
					INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.Id=T.ResourceTypeId
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
					LEFT OUTER JOIN sSecurity.tPermissionUser P ON T.Id = P.TaskId AND (P.UserId = @rUserId OR P.UserId IS NULL)
				WHERE 
				T.IsObsolete = 0 AND T.RoleScopeId IN(0,2)
				ORDER BY T.ModuleId,RTM.Id
		END
		ELSE
		BEGIN
				SELECT  
					T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
					INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
					--INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id AND RDM.RoleId =@rRoleId
					INNER JOIN sSecurity.tResourceTypeMaster RTM ON RTM.Id=T.ResourceTypeId 
					INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
					LEFT OUTER JOIN sSecurity.tPermissionUser P ON T.Id = P.TaskId AND (P.UserId = @rUserId OR P.UserId IS NULL)
				WHERE 
				T.IsObsolete = 0 AND T.RoleScopeId IN(0,1)
				ORDER BY T.ModuleId,RTM.Id
		END
	END
	
	
	
END
GO
PRINT N'Altering [sSecurity].[pRoleModulePermissionGet]...';


GO
 
ALTER PROCEDURE [sSecurity].[pRoleModulePermissionGet]
	  
	 @rOrgGroupId smallint,
	 @rRoleId int 
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 352 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

	IF @lConfigValue IS NULL 
		SET @lConfigValue = 'False'
	
	        DECLARE @lDefaultRoleId int=0
			DECLARE @lModuleId int=0
	
			SET @lDefaultRoleId = RIGHT(@rRoleId, 3)
	
			-- Employee
			IF(@lDefaultRoleId = 010) SET @lModuleId = 233
	
			-- Student
			IF(@lDefaultRoleId = 022) SET @lModuleId = 234
	IF(@lConfigValue = 'TRUE')
	 BEGIN
			IF EXISTS(SELECT 1 FROM sSecurity.tAssignSubRole WHERE SubRoleId = @rRoleID)
		      BEGIN
				SELECT * INTO #TmpTable 
				FROM (
				SELECT DISTINCT(ModuleId)
				FROM sSecurity.tRoleModulePermission 
				WHERE RoleId IN (SELECT RoleId FROM sSecurity.tAssignSubRole WHERE SubRoleId = @rRoleID)) AS T

				SELECT 
					MP.ModuleId,
					MM.Title AS ModuleName,
					MP.OrgGroupId,
					CASE WHEN RDM.ModuleId IS NULL THEN Convert(bit,0) ELSE Convert(bit,1) END AS IsChecked
				FROM 
					sSecurity.tModulePermission MP
					INNER JOIN  sCommon.tModuleMaster MM ON MP.ModuleId=MM.Id AND MM.Id!=@lModuleId
					LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId
					INNER JOIN #TmpTable Tmp ON Tmp.ModuleId = MM.Id
			    WHERE 
					MP.OrgGroupId =@rOrgGroupId
			  END
			ELSE
				SELECT 
					MP.ModuleId,
					MM.Title AS ModuleName,
					MP.OrgGroupId,
					CASE WHEN RDM.ModuleId IS NULL THEN Convert(bit,0) ELSE Convert(bit,1) END AS IsChecked
				FROM 
					sSecurity.tModulePermission MP
					INNER JOIN  sCommon.tModuleMaster MM ON MP.ModuleId=MM.Id AND MM.Id!=@lModuleId
					LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId
			    WHERE 
					MP.OrgGroupId =@rOrgGroupId
	 END
	ELSE
	 BEGIN
			SELECT 
				MP.ModuleId,
				MM.Title AS ModuleName,
				MP.OrgGroupId,
				CASE WHEN RDM.ModuleId IS NULL THEN Convert(bit,0) ELSE Convert(bit,1) END AS IsChecked
			FROM 
				sSecurity.tModulePermission MP
				INNER JOIN  sCommon.tModuleMaster MM ON MP.ModuleId=MM.Id AND MM.Id!=@lModuleId
				LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId
		  WHERE 
				MP.OrgGroupId =@rOrgGroupId
	 END
	
END
GO
PRINT N'Altering [sSecurity].[pRolewisePermissionGet]...';


GO
 
ALTER PROCEDURE [sSecurity].[pRolewisePermissionGet]
	
	@rModuleId smallint,
	@rResourceTypeId smallint,
	@rTaskId smallint,		
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 352 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

	 IF @lConfigValue IS NULL 
		SET @lConfigValue = 'False'

	IF(@lConfigValue = 'True')
	 BEGIN
		SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			
			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL) 
			
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)
			LEFT OUTER JOIN (SELECT DISTINCT(p1.TaskId) FROM sSecurity.tAssignSubRole ASR INNER JOIN sSecurity.tPermission p1 ON p1.RoleId = ASR.RoleId) A ON A.TaskId = T.Id
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
			
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId		
		ORDER BY 			
			T.ModuleId
	END
	ELSE
	 BEGIN
		SELECT  
			R.Id,
			R.Title,
			CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
			CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
			CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
			CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
			CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
			CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
			CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
			CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
			CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
			CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
			CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
			CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
			CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
			CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
		FROM
			sSecurity.tRole R
			LEFT JOIN sSecurity.tPermission P ON P.RoleId = R.Id 
				AND R.OrgGroupId = @rOrgGroupId 
				AND (P.TaskId = @rTaskId OR P.TaskId IS NULL)
			LEFT JOIN sSecurity.tTask T	ON T.Id = P.TaskId 
				AND T.IsObsolete = 0 
				AND (T.ModuleId = @rModuleID OR @rModuleID = 0)
				AND (T.ResourceTypeId = @rResourceTypeId OR @rResourceTypeId = 0)
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId=@rTaskId
				AND OT.OrgGroupId = R.OrgGroupId
			LEFT JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = T.ModuleId 
				AND RDM.RoleId = R.Id	
		WHERE 
			R.IsObsolete = 0 
			AND R.OrgGroupId =@rOrgGroupId		
		ORDER BY 			
			T.ModuleId
	 END
END
GO
PRINT N'Altering [sSecurity].[pTaskGet]...';


GO
 
ALTER PROCEDURE [sSecurity].[pTaskGet]
	@rModuleID [smallint],
	@rRoleID [bigint],		
	@rResourceTypeId smallint,
	@rOrgGroupId int,
	@rUserId bigint=0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

 DECLARE @lConfigValue nvarchar(50)=''
	 SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 352 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

	 IF @lConfigValue IS NULL 
		SET @lConfigValue = 'False'

IF(@rUserId=0)
BEGIN
	 IF(@lConfigValue = 'True')
	 BEGIN
		IF EXISTS(SELECT 1 FROM sSecurity.tAssignSubRole WHERE SubRoleId = @rRoleID)
		BEGIN
			 
			SELECT * INTO #TmpTable 
			FROM (
			SELECT DISTINCT(TaskId)
			FROM sSecurity.tPermission 
			WHERE RoleId IN (SELECT RoleId FROM sSecurity.tAssignSubRole WHERE SubRoleId = @rRoleID) AND OrgGroupId = @rOrgGroupId) AS T

			SELECT  T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
			FROM sSecurity.tTask T
			INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
			INNER JOIN sSecurity.tResourceTypeMaster RTM
			ON RTM.Id=T.ResourceTypeId
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
			LEFT OUTER JOIN sSecurity.tPermission P ON T.Id = P.TaskId AND (P.RoleId = @rRoleID OR P.RoleId IS NULL)
			INNER JOIN #TmpTable Tmp ON T.Id = Tmp.TaskId 
			INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId	
			WHERE	((T.ModuleId = @rModuleID) OR (@rModuleID = 0)) AND
					T.IsObsolete = 0 
					AND ((T.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
					ORDER BY T.ModuleId,RTM.Id
		END
		ELSE
		BEGIN
			SELECT  T.Id,
					T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
			FROM sSecurity.tTask T
			INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
			INNER JOIN sSecurity.tResourceTypeMaster RTM
			ON RTM.Id=T.ResourceTypeId
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
			LEFT OUTER JOIN sSecurity.tPermission P
				ON T.Id = P.TaskId AND (P.RoleId = @rRoleID OR P.RoleId IS NULL)
			INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId	
			WHERE	((T.ModuleId = @rModuleID) OR (@rModuleID = 0)) AND
					T.IsObsolete = 0 
					AND ((T.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
					ORDER BY T.ModuleId,RTM.Id
		END
	 END
	 ELSE IF(@lConfigValue = 'False')
	 BEGIN
	 
				SELECT  T.Id,
						T.Title,
						MM.Title AS ModuleName,
						RTM.Title AS ResourceTypeName, 			
						CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
						CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
						CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
						CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
						CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
						CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
						CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
						CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
						CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
						CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
						CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
						CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
						CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
						CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
				FROM sSecurity.tTask T
				INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
				INNER JOIN sSecurity.tResourceTypeMaster RTM
				ON RTM.Id=T.ResourceTypeId
				INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
				LEFT OUTER JOIN sSecurity.tPermission P
					ON T.Id = P.TaskId AND (P.RoleId = @rRoleID OR P.RoleId IS NULL)
				INNER JOIN sSecurity.tRoleModulePermission RDM ON RDM.ModuleId = MM.Id   AND RDM.RoleId =@rRoleId	
				WHERE	((T.ModuleId = @rModuleID) OR (@rModuleID = 0)) AND
						T.IsObsolete = 0 
						AND ((T.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
						ORDER BY T.ModuleId,RTM.Id
		END
END 
ELSE		 
	BEGIN
	       SELECT  T.Id,
				    T.Title,
					MM.Title AS ModuleName,
					RTM.Title AS ResourceTypeName, 			
					CAST(ISNULL((P.Permission & 1), 0) AS BIT) AS [Create],
					CAST(ISNULL((OT.AvailablePermission & 1), 0) AS BIT) AS [CPermission],
					CAST(ISNULL((P.Permission & 2)/2, 0) AS BIT) AS [Read],
					CAST(ISNULL((OT.AvailablePermission & 2)/2, 0) AS BIT) AS [RPermission],
					CAST(ISNULL((P.Permission & 4)/4, 0) AS BIT) AS [Update],
					CAST(ISNULL((OT.AvailablePermission & 4)/4, 0) AS BIT) AS [UPermission],
					CAST(ISNULL((P.Permission & 8)/8, 0) AS BIT) AS [Delete],
					CAST(ISNULL((OT.AvailablePermission & 8)/8, 0) AS BIT) AS [DPermission],
					CAST(ISNULL((P.Permission & 16)/16, 0) AS BIT) AS [Search],
					CAST(ISNULL((OT.AvailablePermission & 16)/16, 0) AS BIT) AS [SPermission],
					CAST(ISNULL((P.Permission & 32)/32, 0) AS BIT) AS [Print],
					CAST(ISNULL((OT.AvailablePermission & 32)/32, 0) AS BIT) AS [PPermission],
					CAST(ISNULL((P.Permission & 64)/64, 0) AS BIT) AS [Execute],
					CAST(ISNULL((OT.AvailablePermission & 64)/64, 0) AS BIT) AS [XPermission]
			FROM sSecurity.tTask T
			INNER JOIN sCommon.tModuleMaster MM ON MM.Id = T.ModuleId
			INNER JOIN sSecurity.tResourceTypeMaster RTM
			ON RTM.Id=T.ResourceTypeId
			INNER JOIN sSecurity.tOrganizationTask OT ON OT.TaskId = T.Id AND OT.OrgGroupId = @rOrgGroupId
			LEFT OUTER JOIN sSecurity.tPermissionUser P
				ON T.Id = P.TaskId AND (P.UserId = @rUserId OR P.UserId IS NULL)
			WHERE	((T.ModuleId = @rModuleID) OR (@rModuleID = 0)) AND
					T.IsObsolete = 0 
					AND ((T.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId = 0))
					ORDER BY T.ModuleId,RTM.Id
	END
END
GO
PRINT N'Altering [sSetup].[pOrgImageAdd]...';


GO
ALTER PROCEDURE [sSetup].[pOrgImageAdd]
	 
	@rOrgId smallint,
	@rOrganizationHead varbinary(max)=null,
    
	@rDeleteOption nvarchar(20) = '',
	@rMarksheetHead varbinary(max)=null,
	@rOrganizationHeadLandScape varbinary(max),
	@rCertificateHead varbinary(max)
	--@rMarkSheetHead varbinary(max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	SET @rDeleteOption = ISNULL(@rDeleteOption,'')
	BEGIN TRANSACTION
	
	IF (@rDeleteOption = '')
	BEGIN
		IF Exists (Select 1 from sSetup.tOrgImages where OrgId=@rOrgId)
		BEGIN
			UPDATE  sSetup.tOrgImages
			SET
				CertificateHeaderA4 = @rOrganizationHead,
				CertificateHeaderA4LandScape = @rOrganizationHeadLandScape,
				CertificateHeaderA4Portrait=@rCertificateHead,
				MarksheetHeaderA4=@rMarksheetHead
				--,
				--ICardBackground = @rIcardBg,
				--ICardBackBackground = @rIcardBackBg
				
			WHERE OrgId = @rOrgId 
		END
		ELSE 
		BEGIN
			INSERT INTO  sSetup.tOrgImages 
			(
				OrgId,
				CertificateHeaderA4,
				MarksheetHeaderA4,
				CertificateHeaderA4LandScape,
				CertificateHeaderA4Portrait
			)
			Values
			(
				@rOrgId,
				@rOrganizationHead,
				@rMarksheetHead,
				@rOrganizationHeadLandScape,
				@rCertificateHead
			)
		END
	END
	
 
	ELSE IF (@rDeleteOption = 'OrganizationHead') 
	BEGIN
		UPDATE  sSetup.tOrgImages
	SET
		CertificateHeaderA4=NULL 
	WHERE OrgId = @rOrgId 
	END
	
	ELSE IF (@rDeleteOption = 'LandscapeA4') 
	BEGIN
		UPDATE  sSetup.tOrgImages
	SET
		CertificateHeaderA4LandScape=NULL 
	WHERE OrgId = @rOrgId 
	END

	ELSE IF (@rDeleteOption = 'CertificateHead') 
	BEGIN
		UPDATE  sSetup.tOrgImages
	SET
		CertificateHeaderA4Portrait=NULL 
	WHERE OrgId = @rOrgId 
	END
	ELSE IF (@rDeleteOption = 'MarkSheetHead') 
	BEGIN
		UPDATE  sSetup.tOrgImages
	SET
		MarksheetHeaderA4=NULL 
	WHERE OrgId = @rOrgId 
	END
	
	
	 SELECT 1 AS Result
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalAssignRouteUpdate]...';


GO
ALTER PROCEDURE [sSetup].[pPortalAssignRouteUpdate]
	 
	@rStrXml [nvarchar](max),
	@rOrgGroupBatchId int=0
	
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
	
	
	SELECT * FROM sTransport.tAssignRoute AR 
	INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId 
	INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId 
	INNER JOIN (
				SELECT SourceId FROM OPENXML (@loDoc, '/Table/RowData', 1)
				WITH(SourceId int '@SourceId')
	)A ON  AR.SourceId = A.SourceId 
	AND BRM.OrgGroupBatchId = @rOrgGroupBatchId
	 return
	--DELETE AR FROM sTransport.tAssignRoute AR 
	--INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId 
	--INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId 
	--WHERE BRM.OrgGroupBatchId = @rOrgGroupBatchId
	
	 BEGIN	
		
		 INSERT INTO sTransport.tAssignRoute
		(
			[SourceTypeId],
			[SourceId],
			[PickupDestinationId],
			[DropDestinationId] 
			)
		SELECT		
			[SourceTypeId],
			[SourceId],
			[PickupDestinationId],
			[DropDestinationId]
			 
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[SourceTypeId] [smallint],
				[SourceId] [bigint],
				[PickupDestinationId] [int],
				[DropDestinationId] [int]
			  )  
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sSetup].[pPortalBusRouteDestinationMasterUpdate]...';


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

	 BEGIN	
	
	UPDATE sTransport.tBusRouteDestinationMaster
		SET
			[Id]=A.Id,
			[BusRouteId]=A.BusRouteId,
			[Title]=A.Title,
			[Amount]=A.Amount,
			[OrderIndex]=A.OrderIndex,
			[IsObsolete]=A.IsObsolete,
			[CreatedUserId]=A.CreatedUserId,
			[CreatedDateTime]=A.CreatedDateTime,
			[UpdatedUserId]=A.UpdatedUserId,
			[UpdatedDateTime]=A.UpdatedDateTime,
			[OrgGroupId]=A.OrgGroupId,
			[PickupTime]=A.PickupTime,
			[DropTime]=A.DropTime,
			[OldImportBusRouteDestinationId]=A.OldImportBusRouteDestinationId,
			[LatitudeAxis]=A.LatitudeAxis,
			[LongitudeAxis]=A.LongitudeAxis
		 
		 FROM
		 (
		SELECT		
			[Id],
			[BusRouteId],
			[Title],
			[Amount],
			[OrderIndex],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime],
			[OrgGroupId],
			[PickupTime],
			[DropTime],
			[OldImportBusRouteDestinationId],
			LatitudeAxis,
			LongitudeAxis
			 
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [int],
				[BusRouteId] [int],
				[Title] [nvarchar](100),
				[Amount] [decimal](12,2),
				[OrderIndex] [smallint],
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[OrgGroupId] [int],
				[PickupTime] [nvarchar](50),
				[DropTime] [nvarchar](50),
				[OldImportBusRouteDestinationId] [int],
				[LatitudeAxis] [nvarchar](20),
				[LongitudeAxis] [nvarchar](20)
			  )) A
			  WHERE sTransport.tBusRouteDestinationMaster.Id = A.Id
		
		
		
		 INSERT INTO sTransport.tBusRouteDestinationMaster
		(
			[Id],
			[BusRouteId],
			[Title],
			[Amount],
			[OrderIndex],
			[IsObsolete],
			[CreatedUserId],
			[CreatedDateTime],
			[UpdatedUserId],
			[UpdatedDateTime],
			[OrgGroupId],
			[PickupTime],
			[DropTime],
			[OldImportBusRouteDestinationId],
			LatitudeAxis,
			LongitudeAxis
			)
		SELECT		
			A.[Id],
			A.[BusRouteId],
			A.[Title],
			A.[Amount],
			A.[OrderIndex],
			A.[IsObsolete],
			A.[CreatedUserId],
			A.[CreatedDateTime],
			A.[UpdatedUserId],
			A.[UpdatedDateTime],
			A.[OrgGroupId],
			A.[PickupTime],
			A.[DropTime],
			A.[OldImportBusRouteDestinationId],
			A.LatitudeAxis,
			A.LongitudeAxis
						
		FROM OPENXML (@loDoc, '/Table/RowData', 1)
		WITH ( 
				[Id] [int],
				[BusRouteId] [int],
				[Title] [nvarchar](100),
				[Amount] [decimal](12,2),
				[OrderIndex] [smallint],
				[IsObsolete] [bit],
				[CreatedUserId] [bigint],
				[CreatedDateTime] [datetime],
				[UpdatedUserId] [bigint],
				[UpdatedDateTime] [datetime],
				[OrgGroupId] [int],
				[PickupTime] [nvarchar](50),
				[DropTime] [nvarchar](50),
				[OldImportBusRouteDestinationId] [int],
				[LatitudeAxis] [nvarchar](20),
				[LongitudeAxis] [nvarchar](20)
			  ) A LEFT JOIN sTransport.tBusRouteDestinationMaster BM
			  ON A.Id = BM.Id WHERE BM.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pRptStudentIcardGet]...';


GO

ALTER PROCEDURE [sStudent].[pRptStudentIcardGet]  
  @rBuilder1 nvarchar(max)='',  
  @rBuilder2 nvarchar(max)='',   
  @rOrgId smallint,  
  @rBatchId int,  
  @rStrCode nvarchar(max),  
  @rClassId int,  
  @rDivisionId int,  
  @rStudentId bigint,  
  @rFromRollNo int,  
  @rToRollNo int,  
  @rStatusId int,  
  @rDateOfBirth int,  
  @rDepartmentId int,  
  @rHouseGroupId int=0,  
  @rIsShowBarcode bit=0,  
  @rOrgGroupBatchId int,
  @rHouseId int=0  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
  
BEGIN   
  
DECLARE @lIcardBorder nvarchar(10)  
DECLARE @lSUIdBarcode nvarchar(50)  
--DECLARE @lIsBarcodeBasedOnSUId bit = 0  
DECLARE @lOrgGroupId int = 0  
Declare @lIDConfigValue nvarchar(50)=''  
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId  
  
SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup  
WHERE ConfigurationId = 236 AND SourceId = @lOrgGroupId  
  
SELECT @lIcardBorder = ItemValue FROM sConfig.tConfigurationSetup WHERE configurationId = 130 AND SourceTypeId = 1016 AND SourceId = @rOrgId --ItemKey = 'sConfig.tConfigurationSetup'   
SELECT @lSUIdBarcode = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 168 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
   
 --IF (@lSUIdBarcode IS NULL) OR (@lSUIdBarcode = 'False')  
 --SET @lIsBarcodeBasedOnSUId = 0  
 --ELSE  
 --SET @lIsBarcodeBasedOnSUId = 1   
   
 SELECT      
   SD.AcademicId,  
   SD.StudentId,   
   SD.ClassId,  
   SD.DivisionId,  
   SD.ClassName,  
   SD.DivisionName,  
   SD.ClassDivision,  
   SD.Batch,  
   SD.Code,  
   SD.Number AS StudentNumber,  
   SD.RegistrationNumber,   
   SD.RollNo,      
   SD.FirstName,  
   SD.MiddleName,     
   SD.LastName,  
   SF.FatherName,
   [sStudent].[fStudentNameGet](SD.FirstName , SD.MiddleName, SD.LastName,OM.StudentNameFormatId ) AS Name,   
   --SD.FirstName + ' ' + SD.MiddleName + ' ' + SD.LastName As Name,     
   SD.StatusId,  
   SD.DateOfBirth,    
   SD.BloodGroup,  
   ISNULL(SD.PresentStreetone,'') AS PresentStreetone,  
   ISNULL(SD.PresentStreetTwo,'') AS PresentStreetTwo,  
   ISNULL(SD.PresentStreetThree,'') AS PresentStreetThree,  
      ISNULL(SD.PresentCity,'') AS PresentCity,  
      ISNULL(SD.PresentZipCode,'') AS PresentZipCode,  
   SD.PresentContactNo,         
   SD.ParentContactNo AS ParentContactNo,  
   SD.StudentContactNo,     
   SD.StudentPhoto,  
   SD.AdmissionCategory,   
   SD.DivisionOrder,    
   ISNULL(SD.FamilyCast,'')AS FamilyCast, 
   ISNull(SD.AdhaarNumber,'')As AdhaarNumber,
   OM.Title AS OrgName,   
   ISNULL(HM.Title,'') AS HouseName,   
   OM.PrincipalSignature,  
   ISNULL(ICO.ICardOrgTitle,'') AS ICardOrgTitle,  
   ISNULL(ICO.ICardAddress1,'') AS ICardAddress1,  
   ISNULL(ICO.ICardAddress2,'') AS ICardAddress2,  
   ISNULL(ICO.ICardAddress3,'') AS ICardAddress3,     
   OM.OrgLogo AS ICardLogo,  
     
   --ISNULL(ICO.ICardBackground,0) AS ICardBackground,   
   --ISNULL(ICO.ICardBackBackground,0) AS ICardBackBackground,   
     
    ICO.ICardBackground  AS ICardBackground,   
    ICO.ICardBackBackground  AS ICardBackBackground,        
       
   ISNULL(ICO.LabelColor,'Black') AS LabelColor,  
   ISNULL(ICO.DetailColor,'Black') AS DetailColor,  
   ISNULL(ICO.HeaderColor,'Black') AS HeaderColor,  
   ISNULL(SF.FatherName,'') AS FatherName,  
   ISNULL(SF.FatherContactNo,'') AS FatherContactNo,  
   ISNULL(SF.MotherName,'') AS MotherName,  
   ISNULL(SF.MotherContactNo,'') AS MotherContactNo,  
   ISNULL(RT.RouteName,'') AS RouteName,  
   ISNULL(RT.PickupPoint,'') AS PickupPoint,  
   ISNULL(RT.DropPoint,'') AS DropPoint,  
     
   @lIcardBorder AS IcardBorder,  
   HM.ColorCode,  
   OM.OrgLogo,  
   OM.SmallAddress1,  
   --@lSUIdBarcode AS IsBarcodeBasedOnSUId,  
   CASE WHEN @lSUIdBarcode = 'True' THEN SD.SUId  ELSE SD.Code END AS BarcodeNumber,  
    ISNULL(SD.EmergencyStreetOne,'') AS EmergencyStreetOne,  
          ISNULL(SD.EmergencyStreetTwo,'') AS EmergencyStreetTwo,  
         ISNULL(SD.EmergencyStreetThree,'') AS EmergencyStreetThree,  
         ISNULL(SD.EmergencyCountry,'') AS EmergencyCountry,  
         ISNULL(SD.EmergencyState,'') As EmergencyState,  
         ISNULL(SD.EmergencyCity,'') AS EmergencyCity,  
         ISNULL(SD.EmergencyZipCode,'') as EmergencyZipCode,  
         SD.EmergencyContactNo AS EmergencyContactNo,  
   ISNULL(SD.SUId,'') As SUId,  
   ISNULL(RT.RouteNumber,0) AS RouteNumber,  
   @rIsShowBarcode As IsShowBarcode,  
   SD.Name,  
   SM.Title AS Stream,  
   SD.AdmissionDate,  
   ISNULL(DM.Title,'') AS DepartmentName,  
   SD.FatherPhoto,  
   SD.MotherPhoto,  
   SD.RelativePhoto,  
   TM.Title AS TransPortMode,  
   @lIDConfigValue AS ItemValue,  
   RT.RouteCode,
   ISNULL(LM.Title,'') AS Medium ,
   ISNULL(HA.Hosteld,'') AS HostelId,
   SD.Gender,
   SI.QRCode
   ,  (Select ToDate from sSetup.tBatchMaster where Id = @rBatchId) as LastBatchDate,

   --STUFF(SELECT  ', ' + Title FROM sActivity.tClubMaster CM INNER JOIN sActivity.tAssignClub AC ON AC.AcademicId=SD.AcademicId FOR XML PATH ('') ),0,0,',') AS Club

    STUFF(
         (SELECT DISTINCT  ', ' + Title 
          FROM sActivity.tClubMaster CM INNER JOIN sActivity.tAssignClub AC ON SD.AcademicId  = AC.AcademicId AND CM.OrgGroupId = LEFT(SD.OrgGroupBatchId,4)
		  
          FOR XML PATH (''))
          , 1, 1, '')  AS Club

   --CM.Title as Club 

 FROM   
   sStudent.vStudentAllDetail SD  
   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId  
   --INNER JOIN sStudent.tStudentOther SO ON SD.StudentId = So.StudentId      
   LEFT JOIN sActivity.tHouseMaster HM ON SD.HouseId = HM.Id   
   LEFT JOIN sActivity.tHouseGroupMaster HGM ON HGM.Id=HM.HouseGroupId  
   LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SD.StudentId 
   LEFT JOIN sHostel.tHostelAdmission HA ON HA.SourceId= SD.StudentId 
   LEFT JOIN  sStudent.tStudentImages SI ON SD.StudentId = SI.StudentId
    LEFT JOIN  
   (SELECT AT.SourceId,ISNULL(BRM.RouteCode,0) AS RouteCode,BRM.Title As RouteName,BRDM.Title As PickupPoint,ISNULL(BRM.RouteNumber,0) AS RouteNumber,ISNULL(BRDM1.Title,'')As DropPoint FROM sTransport.tAssignRoute AT   
   INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AT.PickupDestinationId  
   LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AT.DropDestinationId  
   INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND  AT.SourceTypeId=2003 AND ((BRM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))AND BRM.Id=BRDM1.BusRouteId) RT  
     
   ON RT.SourceId = SD.StudentId AND ((SD.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
    
   --LEFT JOIN sTransport.tAssignRoute AR ON AR.SourceId =SD.StudentId   
   --LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id =AR.PickupDestinationId   
   --LEFT JOIN sTransport.tBusRouteMaster BRM ON BRM.Id =BRDM.BusRouteId  AND(( BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))  
   LEFT JOIN sStudent.tICardOrg ICO ON SD.OrgId = ICO.OrgId  
   LEFT JOIN sSetup.tStreamMaster SM ON SM.Id=SD.StreamId  
   LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id=SD.DepartmentId  
   LEFT JOIN sStudent.tStudentOther SO ON SD.StudentId = SO.StudentId  
   LEFT JOIN sCommon.tTransportModeMaster TM ON so.TransportModeId = TM.Id  
   LEFT JOIN sSetup.tLanguageMaster LM ON OM.LanguageId = LM.Id
   
   
   --LEFT JOIN sSetup.tOrganizationConfiguration OC ON OM.Id = OC.OrgId   
     
 WHERE   
  SD.OrgId=@rOrgId  
  AND SD.BatchId = @rBatchId   
  AND (ISNULL(SD.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStrCode,',')) OR @rStrCode='')   
  AND ((SD.ClassId=@rClassId) OR (@rClassId=0))  
  AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
  AND ((SD.StudentId=@rStudentId) OR (@rStudentId=0))  
  AND ((SD.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
  AND ((SD.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
  AND ((SD.StatusId=@rStatusId)OR(@rStatusId=0))  
  AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
  AND ((HGM.Id=@rHouseGroupId)OR(@rHouseGroupId=0)) 
  AND ((HM.Id=@rHouseId) OR (Isnull(@rHouseId,0)=0)) 
  AND ((SD.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
END
GO
PRINT N'Altering [sStudent].[pStudentBulkImagesAdd]...';


GO
ALTER PROCEDURE [sStudent].[pStudentBulkImagesAdd]
	 
	@rNumber bigint,
	@rCode nvarchar(20),
	@rStudentPhoto varbinary(max),
	@rOrgId smallint,
	@rPhotoType nvarchar(50),
	@rOriginalStudentPhoto varbinary(max)
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DECLARE @lStudentId bigint
	
	SELECT @lStudentId=Id FROM sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId
	
	IF(ISNULL(@lStudentId,'') = '')
	BEGIN
		SELECT 1 AS Result
		RETURN
	END
	
	IF NOT EXISTS(SELECT StudentId FROM sStudent.tStudentImages WHERE StudentId=@lStudentId)
	BEGIN 
	INSERT INTO sStudent.tStudentImages
		(
			StudentId,
			StudentPhoto
		)
	VALUES
		(
			@lStudentId,
			NULL
		)		             
	END	 
	 
	 
	 IF @rPhotoType = 'TempStudentPhotos'
	 BEGIN
	  UPDATE sStudent.tStudentImages  SET StudentPhoto=@rStudentPhoto,OriginalStudentPhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId
	 END 
	 ELSE IF @rPhotoType = 'TempStudentFatherPhotos'
	 BEGIN
	  UPDATE sStudent.tStudentImages  SET FatherPhoto=@rStudentPhoto,OriginalFatherPhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId	 	 
	 END 
	 ELSE IF @rPhotoType = 'TempStudentMotherPhotos' 
	 BEGIN
	  UPDATE sStudent.tStudentImages  SET MotherPhoto=@rStudentPhoto,OriginalMotherPhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId
	 END
	 ELSE IF @rPhotoType = 'TempStudentRelativePhotos' 
	 BEGIN
	 UPDATE sStudent.tStudentImages  SET RelativePhoto=@rStudentPhoto,OriginalRelativePhoto=@rOriginalStudentPhoto,UpdatedDateTime = sCommon.fGetDate() WHERE StudentId=@lStudentId	 
	 END
	 
	 SELECT 1 AS Result
	
	
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END


--select * from sStudent.tStudentMaster where Code = '185' AND OrgId = 1001

--select * from sStudent.tStudentImages where StudentId = 1001000000172
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 [sStudent].[pStudentGenerateReport]...';


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

             
			--print @BatchId
			--print @rOrgId
            DECLARE @rOrgGroupId smallint
             SET @rOrgGroupId = (Select orggroupid from sSetup.tOrganizationMaster where Id=@rOrgId)           
             
			SET @lAvailableStudentColumns=   STUFF((SELECT ',' + QUOTENAME(PP.FieldTitle,'[]'), '' AS FieldTitle, '' AS SalaryMonth
								from sStudent.tStudentCustomFieldMaster PP  WHERE PP.OrgGroupId = @rOrgGroupId  
						FOR XML PATH(''), TYPE
						).value('.', 'NVARCHAR(MAX)') 
					,1,1,'')
					Print @lAvailableStudentColumns
	        IF(@lAvailableStudentColumns IS NOT NULL)
	        BEGIN
				set @query = 'SELECT  StudentId AS StudentId13 ,' + @lAvailableStudentColumns + ' into sStudent.tTempStudent13 from 
					 (
						select PPE.FieldTitle,PP.StudentId,FieldData 
						FROM
						sStudent.tStudentCustomFieldData PP 
							INNER JOIN sStudent.tStudentCustomFieldMaster PPE ON PPE.Id = PP.StudentCustomFieldId AND PPE.IsObsolete=0
							INNER JOIN sStudent.tStudentMaster SM ON SM.Id = PP.StudentId						
							INNER JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND A.BatchId='+convert(varchar(20),@BatchId)+' 
							WHERE SM.OrgId='''+convert(varchar(20),@rOrgId)+''' 
					) x 
					pivot 
					(
						Max(FieldData)
						for FieldTitle in (' +@lAvailableStudentColumns  + ')
					) p'

				 --print @query
                execute(@query)
		   
		   
		
		Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		LEFT JOIN  sStudent.tTempStudent13 T13 ON SCS.StudentId= T13.StudentId13 
		WHERE SCS.OrgId = @rOrgId 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0)) 
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		AND ((SCS.Code >= @rFromCode) OR (@rFromCode=0))
		AND ((SCS.Code <= @rToCode) OR (@rToCode=0))
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		
				
				
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		DROP Table sStudent.tTempStudent13
 
	END 
	 
	ELSE
	BEGIN
	    Select * into sStudent.tTempStudent
		FROM sStudent.vStudentCustomSearch SCS
		INNER JOIN sStudent.tTempStudent5 T5 ON SCS.StudentId = T5.StudentId1 OR @rCustomTagId = ''
		INNER JOIN sStudent.tTempStudent6 T6 ON SCS.StudentId = T6.StudentId2 OR @rCustomGroupId = ''
		INNER JOIN sStudent.tTempStudent7 T7 ON SCS.StudentId = T7.StudentId3 OR @rClubId = ''
		INNER JOIN sStudent.tTempStudent9 T9 ON SCS.StudentId = T9.StudentId4 OR @rHostelId = ''
		INNER JOIN sStudent.tTempStudent10 T10 ON SCS.StudentId = T10.StudentId5 OR @rBusRouteId = ''
		LEFT JOIN sStudent.tTempStudent11 T11 ON SCS.StudentId = T11.StudentId6
		LEFT JOIN  sStudent.tTempStudent12 T12 ON SCS.StudentId= T12.StudentId12 
		
		WHERE SCS.OrgId = @rOrgId 
		AND ((SCS.BatchId = @BatchId) OR (@BatchId = 0)) 
		--AND ((SCS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((SCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
		AND ((SCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((SCS.Hobby Like '%' + @rHobby + '%') OR (@rHobby = ''))
		AND ((ISNULL(SCS.PermanentCountry,'') Like @rCountry + '%') OR(@rCountry = ''))
		AND ((ISNULL(SCS.PermanentState,'') Like @rState + '%')OR(@rState = ''))
		AND ((ISNULL(SCS.DateOfBirth,'0001-01-01') >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ISNULL(SCS.DateOfBirth,'9999-12-31') <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'0001-01-01') >= @rDOAFromDate) OR (ISNULL(@rDOAFromDate,'') = ''))
		AND ((ISNULL(SCS.AdmissionDate,'9999-12-31') <= @rDOAToDate) OR (ISNULL(@rDOAToDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'0001-01-01') >= @rDOLFromDate) OR (ISNULL(@rDOLFromDate,'') = ''))
		AND ((ISNULL(SCS.LeftDate,'9999-12-31') <= @rDOLToDate) OR (ISNULL(@rDOLToDate,'') = ''))
		AND (ISNULL(SCS.PermanentCity,0) IN( SELECT item FROM  sCommon.fnsplit(@rCity,','))OR @rCity='')
		AND (ISNULL(SCS.PermanentStreetThree,0) IN( SELECT item FROM  sCommon.fnsplit(@rArea,','))OR @rArea='')
		AND (SCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
		AND (SCS.StatusId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
		AND (SCS.TransportModeId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rTransportModeId,','))OR @rTransportModeId='')
		AND (ISNULL(SCS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
		AND (ISNULL(SCS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR (@rGenderId=''))
		AND (ISNULL(SCS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
		AND (ISNULL(SCS.CastCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCastCategoryId,','))OR @rCastCategoryId='')
		AND (ISNULL(SCS.HouseId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rHouseId,','))OR @rHouseId='')
		AND (ISNULL(SCS.MotherTongueId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMotherTongueId,','))OR @rMotherTongueId='')
		AND (ISNULL(SCS.NationalityId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rNationalityId,','))OR @rNationalityId='')
		AND (ISNULL(SCS.BusRouteDestinationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteDestinationId,','))OR @rBusRouteDestinationId='')
		AND (ISNULL(SCS.FatherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherQualification,','))OR @rFatherQualification='')
		AND (ISNULL(SCS.FatherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rFatherOccupation,','))OR @rFatherOccupation='')
		AND (ISNULL(SCS.MotherQualification,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherQualification,','))OR @rMotherQualification='')
		AND (ISNULL(SCS.MotherOccupation,'') IN( SELECT item FROM  sCommon.fnsplit(@rMotherOccupation,','))OR @rMotherOccupation='')
		AND (ISNULL(SCS.AdmissionCategoryId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rAdmissionCategoryId,','))OR @rAdmissionCategoryId='')
		AND (ISNULL(SCS.PreviousSchool,'') IN( SELECT item FROM  sCommon.fnsplit(@rPreviousSchool,','))OR @rPreviousSchool='')
		AND (ISNULL(SCS.RepeatCount,0) IN( SELECT item FROM  sCommon.fnsplit(@rRepeatCount,','))OR @rRepeatCount='')
		AND (ISNULL(SCS.StudentStatusId,0) IN( SELECT item FROM  sCommon.fnsplit(@rStudentStatusId,','))OR @rStudentStatusId='')
		AND (ISNULL(SCS.StudentGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentGroupId,','))OR @rStudentGroupId='')
		AND (ISNULL(SCS.StudentOtherGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStudentOtherGroupId,','))OR @rStudentOtherGroupId='')
		AND ((SCS.IsPysicalDeformity=@rIsPysicalDeformity) OR (@rIsPysicalDeformity=0))
		AND ((SCS.IsMajorIllness=@rIsMajorIllness) OR (@rIsMajorIllness=0))
		AND ((SCS.IsBlackList=@rIsBlackList) OR (@rIsBlackList=0))
		AND ((SCS.Code >= @rFromCode) OR (@rFromCode=0))
		AND ((SCS.Code <= @rToCode) OR (@rToCode=0))
		AND ((SCS.Code IN(SELECT Code FROM @ListofCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		AND ((SCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		AND ((SCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
		AND ((SCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
		AND (ISNULL(SCS.BusRouteId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBusRouteId,','))OR @rBusRouteId='')
		AND (ISNULL(SCS.ExemptionTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeExemption,','))OR @rFeeExemption='')
		
		--AND (ISNULL(SCS.CustomTagId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCustomTagId,','))OR @rCustomTagId='')
		--Select * from sStudent.tTempStudent return	
		
				
				
		set @sql = 'SELECT '+ @rColumnName+' FROM sStudent.tTempStudent ORDER BY '+@rOrderBy
		
		
		if(@rColumnName='ID No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [ID No]')
		END
		if(@rColumnName='GR No')
		BEGIN
			SET @sql=Replace(@sql,'SELECT Code','SELECT Code AS [GR No]')
		END
		
		exec(@Sql)
			
		DROP Table sStudent.tTempStudent
		DROP Table sStudent.tTempStudent5
		DROP Table sStudent.tTempStudent6
		DROP Table sStudent.tTempStudent7
		DROP Table sStudent.tTempStudent9
		DROP Table sStudent.tTempStudent10
		DROP Table sStudent.tTempStudent12
		
	    
	    
	END 
	 
	 
END
GO
PRINT N'Altering [sStudent].[pStudentMasterAdd]...';


GO
 
ALTER PROCEDURE [sStudent].[pStudentMasterAdd]
	 
	@rId bigint,
	@rCode nvarchar(20),
	@rRegistrationNumber nvarchar(20),
	@rNumber bigint,
	@rFirstName nvarchar(100),
	@rMiddleName nvarchar(100),
	@rLastName nvarchar(100),
	@rOrgId int,
	--@rDepartmentId int,
	@rAdmissionCategoryId int,
	@rStatusId smallint,
	@rRecordStatusId smallint,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupBatchId int =0,
	@OutStudentId BIGINT = NULL OUTPUT,
	@rSUId nvarchar(20) = '',
	@rOrgGroupId int = 0,
	@rMobileNo nvarchar(50)='',
	@rStudentGroupId int=0,
	@rStudentOtherGroupId int=0,
	@rDateOfBirth Date=NULL,
    @rGenderId int=0,
    @rAcademicId bigint = 0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	--UPDATE sStudent.tAcademic SET ClassStatusId = 1 WHERE ClassStatusId is null WHERE Id = 
	
	--if(@rStatusId=3)
	--UPDATE A
	--	SET ClassStatusId = 3
	--	FROM sStudent.tAcademic A
	--	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
	--	--INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
	--	WHERE SM.StatusId = 3 AND A.Id = @rAcademicId
	--else if(@rStatusId=1)
	--UPDATE A
	--SET ClassStatusId = 1
	--	FROM sStudent.tAcademic A
	--	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId = SM.Id
	--	--INNER JOIN sStudent.tStudentAdmission SA ON A.StudentId = SA.StudentId AND A.ClassId = SA.LeftStandardId
	--	WHERE SM.StatusId = 3 AND A.Id = @rAcademicId
	
	
	
	
	Declare @lStudCap int,@lOrgStudentCap int
	--IF(@rNumber=0)
	--SET @rNumber=NULL
	IF(@rId=0)
	BEGIN		 
	 
		--IF((@rCode = Null) OR (@rCode = ''))	
		--BEGIN

		--	EXECUTE sCommon.pPrefixSetupNextNumberGet @rOrgId = @rOrgId, @rPrefixFunctionalityId = 2001,@rStoreLocationId = 0, @rNextNumber = @rCode OUTPUT

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

		--	IF @rCode = '-300'
		--	BEGIN
		--		 SELECT -300 AS Result, '' AS Code, 0 AS Id 
		--		 RETURN
		--	END
		--END
		--ELSE
		--BEGIN
			Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from
			sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId
			
			Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
			 
			IF(@lOrgStudentCap > @lStudCap )
			BEGIN
				Select -111 AS RESULT, '' AS Code, @lStudCap AS Id 
				Return
			END
		
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
					   WHERE SM.SUId=@rSUId AND OM.OrgGroupId=@rOrgGroupId)
			BEGIN
				SELECT -101 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
			ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId)
			BEGIN
				SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
			ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE ISNULL(@rRegistrationNumber,'')!='' AND RegistrationNumber=@rRegistrationNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -200 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		--END
	END
	ELSE
	BEGIN
	
		Select @lStudCap=ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0) from
		sSetup.tOrgGroupSetting Where OrgGroupId= @rOrgGroupId
		
		Select @lOrgStudentCap=[sSetup].[fStudentCapGet](@rOrgGroupBatchId)
		 
		IF(@lOrgStudentCap > @lStudCap AND (@rStatusId = 1 OR @rStatusId = 2))
		BEGIN
			Select -111 AS RESULT, '' AS Code, @lStudCap AS Id 
			Return
		END
	
		DECLARE @lReferenceSourceId bigint=0
		SELECT @lReferenceSourceId = ISNULL(ReferenceSourceId,0)  FROM sStudent.tStudentMaster WHERE Id = @rId
		
		IF(@lReferenceSourceId=0)
			SELECT @lReferenceSourceId = Id FROM sStudent.tStudentMaster WHERE ReferenceSourceId = @rId
		IF(@lReferenceSourceId = 0)
		BEGIN 
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
						   WHERE SM.SUId=@rSUId AND OM.OrgGroupId=@rOrgGroupId AND SM.Id!=@rId)
			BEGIN
				SELECT -101 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		END
		 
		IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId AND Id!=@rId)
		BEGIN
			SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
			RETURN
		END 
		ELSE IF EXISTS (SELECT Id from sStudent.tStudentMaster WHERE RegistrationNumber=@rRegistrationNumber AND OrgId=@rOrgId AND Id!=@rId)
		BEGIN
			SELECT -200 AS RESULT, '' AS Code, 0 AS Id 
			RETURN
		END 
	END

	BEGIN TRY
	
	 BEGIN TRANSACTION	
	IF(@rId=0)
	BEGIN	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tStudentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output

	IF(@rNumber=0)
	BEGIN
	SET @rNumber=@lNextNumber
	END
	INSERT INTO sStudent.tStudentMaster
		(
			Id,
			Code,
			Number,
			RegistrationNumber,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			--DepartmentId,
			AdmissionCategoryId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			CreatedDateTime,
		    SUId,
		    StudentGroupId,
		    StudentOtherGroupId
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rNumber,
			@rRegistrationNumber,
			@rFirstName,
			@rMiddleName,
			@rLastName,
			@rOrgId,
			--@rDepartmentId,
			@rAdmissionCategoryId,
			@rStatusId,
			@rRecordStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSUId,
			@rStudentGroupId ,
			@rStudentOtherGroupId 
		)
		
		INSERT INTO sStudent.tStudentOther
		(
			StudentId,
			DateOfBirth,
			GenderId,
			CreatedUserId,
			CreatedDateTime
		)
		VALUES
		(
			@lNextNumber,
			@rDateOfBirth,
			@rGenderId,
			@rCreatedUserId,
			sCommon.fGetDate()
		)
		----IF(@rMobileNo!='')
		--BEGIN
			INSERT INTO sStudent.tStudentCommunication
			(
				StudentId,
				ParentContactNo,
				CreatedUserId,
				CreatedDateTime
			)
			VALUES
			(
				@lNextNumber,
				@rMobileNo,
				@rCreatedUserId,
				sCommon.fGetDate()
			)
		--END
		      
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
			IF(@rNumber=0)
			BEGIN
			SET  @rNumber=(SELECT ISnull(Number,0) FROM sStudent.tStudentMaster WHERE  Id=@rId)
			IF(@rNumber=0)
			SET @rNumber=@lNextNumber
			END
	    UPDATE  sStudent.tStudentMaster
	    SET
			--Code=@rCode,
			Number=@rNumber,
			RegistrationNumber=@rRegistrationNumber,
			FirstName=@rFirstName,
			MiddleName=@rMiddleName,
			LastName=@rLastName,
			--OrgId=@rOrgId,
			--DepartmentId=@rDepartmentId,
			AdmissionCategoryId=@rAdmissionCategoryId,
			StatusId=@rStatusId,
			RecordStatusId=@rRecordStatusId,
	        UpdatedUserId=@rUpdatedUserId,
	        UpdatedDateTime=sCommon.fGetDate(),
			SUId=@rSUId,
			StudentGroupId=@rStudentGroupId ,
		    StudentOtherGroupId=@rStudentOtherGroupId
	      
	      WHERE Id = @rId 
	      
	    UPDATE  sStudent.tStudentOther
		SET
			DateOfBirth=@rDateOfBirth,
			GenderId=@rGenderId,
	        UpdatedUserId=@rUpdatedUserId,
	        UpdatedDateTime=sCommon.fGetDate()
	      WHERE StudentId = @rId 
	     
	     
	     IF(@rStatusId=3)
		BEGIN
		    UPDATE sSecurity.tUser
			   SET IsObsolete=1 
			WHERE SourceTypeId=2003 AND SourceId=@rId
		END
	 END  
	 
		SET @OutStudentId = @lNextNumber
	  SELECT 1 AS Result, @rCode AS Code, @lNextNumber AS Id 
		--SELECT @lNextNumber AS Result
	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sTimetable].[pRptDivisionTimeTableGet]...';


GO
 
ALTER PROCEDURE [sTimetable].[pRptDivisionTimeTableGet]

	  --@rBuilder1 nvarchar(max)='',
	  --@rBuilder2 nvarchar(max)='', 
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,
	  @rReportId int=0,
	  @rDate Date=''
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
  IF(@rReportId=10166) -- Teacherwise
  BEGIN
  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	0 As IsPresent,
	'' As WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime

  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	'' AS TimeTableDetail,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	--ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber),'') AS TimeTableDetail
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime
	FROM 
	sTimetable.tTimeTable TT	
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId
	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  
	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TTD.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime
	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			RIGHT JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			WHERE TimeTableSchemaId=@rTimeTableSchemaId  ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
ELSE IF(@rReportId = 30661) --- Absent Teacher Divisionwise
	BEGIN
	  SELECT

	A.TimeTableID,
	A.DivisionName,
	
	A.EmployeeId,
	A.SubjectId,
	
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END  AS EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	ISNULL(L.Title,'') AS DayName,
	ISNULL(L.DayId,0) AS DayId,
	ISNULL(L.LectureNumber,'') AS LactureNumber,
	--ISNULL(A.DayName,'') AS DayName,
	--ISNULL(A.DayId,0) AS DayId,
	--ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	ISNULL(A.ClassDivisionName,'')AS ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	A.TimeTableDetail,
	A.IsPresent,
	'' As WeekOffs,
	0 As FromTime,
	0 As ToTime
  FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EAR.EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	'' AS TimeTableDetail,
	ISNULL(EAR.IsPresent,0) AS IsPresent
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	--ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TT.EmployeeId,TT.DayId,TT.LectureNumber),'') AS TimeTableDetail
	FROM 
	sTimetable.tTimeTable TT	 
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	LEFT JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	RIGHT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')

	  UNION ALL
	  
	  
	  
	  	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(TTD.EmployeeId,0) AS EmployeeId,
	ISNULL(TTD.SubjectId,0) AS SubjectId,

	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	--ISNULL(Em.FirstName,'')  AS EmployeeName,  
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	--(ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') + ISNULL(SM.Title,'')) AS TimeTableDetail
	ISNULL([sTimetable].[fTimeTableDivisionGet](TT.TimeTableSchemaId,TT.Id,TTD.EmployeeId,TT.DayId,TT.LectureNumber,0),'') AS TimeTableDetail,
	ISNULL(EAR.IsPresent,'') As IsPresent
	FROM 
	sTimetable.tTimeTable TT
	INNER JOIN 	sTimetable.tTimeTableDetail TTD ON TTD.TimetableId = TT.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TTD.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TTD.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId = Em.Id

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TTD.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	  AND (EAR.AttendanceDate = @rDate OR @rDate = '')
	  AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '') 
	  
	  --ORDER BY DV.OrderIndex
	  )
	  A
			INNER JOIN (SELECT DISTINCT DayId,LectureNumber,DM.title  FROM sTimetable.tTimeTable
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = DayId
			
			WHERE TimeTableSchemaId=@rTimeTableSchemaId ) L
			ON A.LactureNumber = L.LectureNumber AND A.DayId = L.DayId

	END
 ELSE
 BEGIN
	SELECT

	A.TimeTableID,
	A.DivisionName,
	A.EmployeeId,
	A.SubjectId,
	CASE WHEN A.EmployeeId=-1 THEN '###' WHEN A.EmployeeId=-2 THEN '***' ELSE A.EmployeeName END As EmployeeName,
	CASE WHEN A.SubjectId=-1 THEN '###' WHEN A.SubjectId=-2 THEN '***' ELSE A.Subject END  AS Subject,
	--A.Subject,
	A.DivisionId,
	--ISNULL(L.Title,'') AS DayName,
	--ISNULL(L.DayId,0) AS DayId,
	--ISNULL(L.LectureNumber,'') AS LactureNumber,
	ISNULL(A.DayName,'') AS DayName,
	ISNULL(A.DayId,0) AS DayId,
	ISNULL(A.LactureNumber,'') AS LactureNumber,
	A.DayLacture,
	A.ClassId,
	A.ClassDivisionName,
	A.DivisionOrderIndex,
	A.Code,
	[sTimetable].[fTimeTableDetailGet](A.TimeTableID,0) AS TimeTableDetail,
	0 AS IsPresent,
	A.WeekOffs,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.FromTime ELSE '' END As FromTime,
	CASE WHEN EXISTS (SELECT 1 FROM sTimetable.tTimeTableSchema TS INNER JOIN sTimetable.tTimeTable TT ON TT.TimeTableSchemaId = TS.Id WHERE TS.IsDisplayPeriodTime = 1 AND TS.Id = @rTimeTableSchemaId) THEN A.ToTime ELSE '' END As ToTime,
	ISNULL(IsDiplayPeriodTime,0) As IsDiplayPeriodTime
FROM
(
	SELECT 
	--@rBuilder1 AS Builder1,
	--@rBuilder2 AS Builder2,	 
	TT.Id AS TimeTableID,
	ISNULL(DV.Title,'') AS DivisionName,
	ISNULL(EmployeeId,0) AS EmployeeId,
	ISNULL(SubjectId,0) AS SubjectId,
	ISNULL(Em.FirstName +'  '+Em.LastName,'')  AS EmployeeName,
	ISNULL(SM.Title,'') AS Subject,
	ISNULL(TT.DivisionId,0) AS DivisionId,
	ISNULL(DM.Title,'') AS DayName,
	ISNULL(TT.DayId,0) AS DayId,
	ISNULL(TT.LectureNumber,'') AS LactureNumber,
	ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
	ISNULL(DV.ClassId,0) AS ClassId,
	ISNULL(CM.DisplayTitle,'')+'-'+ISNULL(DV.Title,'') as ClassDivisionName,
	ISNULL(DV.OrderIndex,0) As DivisionOrderIndex,
	ISNULL(SM.Code,'') AS Code,
	ISNULL(TTS.WeekOffs,'') As WeekOffs,
	ISNULL(TTM.FromTime,0) As FromTime,
	ISNULL(TTM.ToTime,0) As ToTime,
	ISNULL(TS.IsDisplayPeriodTime,0) As IsDiplayPeriodTime
	FROM 
	sTimetable.tTimeTable TT  
	LEFT JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
	INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
	LEFT JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
	LEFT JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
	LEFT JOIN sSetup.tClassMaster CM ON CM.Id = DV.ClassId
	LEFT JOIN sTimetable.tTimeTableSchema TTS ON TTS.Id = TT.TimeTableSchemaId
	LEFT JOIN sTimetable.tTimeTableTime TTM ON TTM.TimeTableSchemaId=TT.TimeTableSchemaId AND TTM.DayId = DM.Id AND TTM.DivisionId = TT.DivisionId AND TTM.LectureNumber = TT.LectureNumber AND TTM.IsBreak = 0
	INNER JOIN sTimetable.tTimeTableSchema TS ON TS.Id = TT.TimeTableSchemaId 

	WHERE (ClassId = @rClassId OR @rClassId=0)
	  AND (TT.DivisionId = @rDivisionId OR @rDivisionId=0)	
	  AND (TT.EmployeeId=@rEmployeeId OR @rEmployeeId=0)
	  AND TT.TimeTableSchemaId=@rTimeTableSchemaId
	 AND (TT.DayId = (DATEPART(weekday,@rDate)) OR @rDate = '')
	
	  )
	  A  ORDER BY A.EmployeeName, A.DivisionOrderIndex,A.DayId, A.LactureNumber
		END
END
GO
PRINT N'Altering [sTool].[pDeleteStaticData]...';


GO
 
ALTER PROCEDURE [sTool].[pDeleteStaticData]
 
	 
AS
SET NOCOUNT ON
BEGIN 
 

DELETE FROM sAlert.tEventMaster
DELETE FROM sCommon.tAutoCompleteMaster
DELETE FROM sCommon.tCommonMaster
DELETE FROM sCommon.tDepends
DELETE FROM sCommon.tModuleMaster
DELETE FROM sCommon.tPrefixFunctionality
DELETE FROM sCommon.tRefferedTableForObsoleteCheck
DELETE FROM sCommon.tRefferedTableWithoutForeignKey
DELETE FROM sCommon.tReport
DELETE FROM sCommon.tReportFormatGroupMaster
DELETE FROM sCommon.tReportGroupMaster
DELETE FROM sCommon.tSourceScreenMaster
DELETE FROM sCommon.tSourceTypeMaster
DELETE FROM sCommon.tStatusMaster
DELETE FROM sCommon.tStatusTypeMaster
DELETE FROM sCommon.tTableRowIdMaster
DELETE FROM sCommon.tUpdateFieldMaster
DELETE FROM sCommon.tValidationType
DELETE FROM sConfig.tColorLegendMaster
DELETE FROM sConfig.tConfigurationMaster
DELETE FROM sConfig.tConfigurationValue
DELETE FROM sSecurity.tMenu
DELETE FROM sSecurity.tResourceTypeMaster
DELETE FROM sSecurity.tScreen
DELETE FROM sSecurity.tScreenGroupMaster
DELETE FROM sSecurity.tScreenTypeMaster
DELETE FROM sSecurity.tTask
DELETE FROM sSystem.tTable
DELETE FROM sTool.tObjects
DELETE FROM sCommon.tReportTypeMaster


DELETE FROM sSetup.tAffiliationClassGroup
DELETE FROM sSetup.tAffiliationTypeMaster
DELETE FROM sSetup.tAffiliationMaster	
DELETE FROM sSetup.tStreamMaster

-- temp insert
DELETE FROM sAttendance.tAttendanceForMaster
DELETE FROM sEExam.tEntryModeMaster
DELETE FROM sSetup.tTermScopeMaster	 
 
DELETE FROM sConfig.tConfigurationLevelMaster

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

DELETE FROM sSecurity.tScreenGroupMapping
DELETE FROM sAssessment.tCCEExamMaster
DELETE FROM sSetup.tTermPatternMaster


DELETE FROM sAdmission.tAdmissionStatusMaster
DELETE FROM sAssessment.tCCERptGroup
DELETE FROM sHrm.tEmployeeICardTemplate
DELETE FROM sSecurity.tDashletMaster
DELETE FROM sStudent.tICardTemplate
DELETE FROM sSystem.tCustomQuery

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

DELETE FROM sOp.tPayTypeMaster
DELETE FROM sOp.tTransactionStatusMaster
--DELETE FROM sPayroll.tForm16B
DELETE FROM sStudent.tBatchStatusMaster
DELETE FROM [sFinanceCommon].[tPayTypeMaster]

DELETE FROM sAttendance.tAttendanceTagMaster
DELETE FROM sCommon.tLiveWithMaster
DELETE FROM sConfig.tDisplayFieldMaster

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

DELETE FROM sCommon.tCalculationTypeMaster
DELETE FROM sFee.tApplayAsMaster
DELETE FROM sSecurity.tScreenDependency
DELETE FROM sStudent.tSUIdFieldMaster

DELETE FROM [sAlert].[tAlertModeMaster]
DELETE FROM sCommon.tReportRemarkGroupMaster
DELETE FROM sStudent.tEnrollmentStatusMaster
DELETE FROM [sSetup].[tClassGroupMaster]

DELETE FROM sCommon.tTemplateSourceMaster
DELETE FROM sErp.tCustomerStatusMaster
DELETE FROM sErp.tInstallationTypeMaster
DELETE FROM sRecruitment.tRecruitmentStatusMaster

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

DELETE FROM sCommon.tImportFieldMaster
DELETE FROM sCRM.tHostingTypeMaster
DELETE FROM sHrm.tMainLeaveTypeMaster

DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sHrm.tTravelPeriodMaster
DELETE FROM sLoan.tInsterestTypeMaster

DELETE FROM sAppraisal.tBHRatingStatus
DELETE FROM sAppraisal.tConductIndicatorMaster
DELETE FROM sAppraisal.tKPAMeasureMaster
DELETE FROM sAppraisal.tKPATypeMaster
DELETE FROM sAppraisal.tRatingStatus
DELETE FROM sCommon.tHeaderDisplayMaster
DELETE FROM sCommon.tModuleGroupMaster
DELETE FROM sHrm.tLeaveTransactionMaster
DELETE FROM sCommon.tCheckFrequencyMaster

DELETE FROM sErp.tLeadAffiliationMaster
DELETE FROM sErp.tLeadSourceMaster
DELETE FROM sErp.tLeadStatusMaster

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

DELETE FROM sCommon.tSubmitDocumentFunctionalityMaster
DELETE FROM sSetup.tMandatoryFeild
DELETE FROM sSetup.tMandatoryFeildFunctionalityMaster

DELETE FROM sSystem.tTimeZone
DELETE FROM sTool.tTestCaseTypeMaster

DELETE FROM sAlumni.tEmployeementType

DELETE FROM sErp.tCampusTypeMaster

DELETE FROM sAlert.tMailTypeMaster
DELETE FROM sAlert.tSMSVendorMaster
DELETE FROM sCommon.tWeekOffRules

DELETE FROM sSecurity.tScreenHelp
DELETE FROM sSystem.tSettingInfo

DELETE FROM sProcurement.tOtherLocationSourceTypeMaster

DELETE FROM sCommon.tFieldTypeMaster
DELETE FROM sErp.tLeadInfrastructureMaster

DELETE FROM sHostel.tHostelEventMainTypeMaster

DELETE FROM sCertificate.tCertificateTypeMaster	
DELETE FROM sWorkflow.tActionStatusMaster
DELETE FROM sWorkflow.tApprovingDepartmentMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAcademic.tHomeworkCheckStatusMaster
DELETE FROM sAssessment.tExamTypeMaster

DELETE FROM sErp.tMarketingActivityMaster
DELETE FROM sErp.tMarketingSubActivityMaster
DELETE FROM sSetup.tCommonOrgGroupBatchMaster
DELETE FROM sWorkflow.tWorkflowFunctionalityMaster

DELETE FROM sAudit.tOperationMaster

DELETE FROM sAdmission.tInquiryMainStatusMaster
DELETE FROM sCertificate.tPrintTemplateFunctionalityMaster
DELETE FROM sErp.tTripLogStatusMaster

DELETE FROM sErp.tFollowupTypeMaster
DELETE FROM sErp.tSupportCategoryMaster
DELETE FROM sErp.tSupportPriorityMaster
DELETE FROM sErp.tSupportTicketStatusMaster


DELETE FROM sErp.tPlugInMaster
DELETE FROM sErp.tTagMaster

DELETE FROM sErp.tIssueTypeMaster

DELETE FROM sErp.tScreenFunctionalityMaster

DELETE FROM sHrm.tChangeTypeMaster


DELETE FROM sCommon.tDataMaster
DELETE FROM sCommon.tDataTypeMaster

DELETE FROM siTax.tStaticIncomeTaxSubSubGroup

END
GO
PRINT N'Altering [sTransport].[pRptStudentAttendanceRegister]...';


GO


ALTER PROCEDURE [sTransport].[pRptStudentAttendanceRegister]
	 
	@rMonth nvarchar(100)='',
	@rYear nvarchar(100)='',
	@rOrgGroupBatchId int=0,
	@rOrgGroupId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rRouteId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='' 

	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 
DECLARE @lMonth INT,@lYear INT

SET @lMonth=CAST(@rMonth AS INT)
SET @lYear=CAST(@rYear AS INT)
DECLARE @FirstDay date, @EndDate date


select @FirstDay= DATEADD(month,@lMonth-1,DATEADD(year,@lYear-1900,0))

select @EndDate=DATEADD(day,-1,DATEADD(month,@lMonth,DATEADD(year,@lYear-1900,0)))

 IF OBJECT_ID('#TmpDate') IS NOT NULL
    DROP TABLE #TmpDate

	IF OBJECT_ID('#TEMPTABLE') IS NOT NULL
    DROP TABLE #TEMPTABLE
Create Table #TmpDate
(
MonthDates date
)
INSERT INTO #TmpDate
SELECT DATEADD(DAY,number,@FirstDay) [Date]
FROM master..spt_values
WHERE type = 'P'
AND DATEADD(DAY,number,@FirstDay) <= @EndDate


SELECT DISTINCT
@rBuilder1 AS Builder1,
@rBuilder2 AS Builder2,
tmp.MonthDates,
amt.RollNo,
amt.Code,
amt.DateOfBirth,
amt.Name,
amt.IsPresentPickup,
amt.IsPresentDrop,
amt.ClassName,
amt.DivisionName,
DAY(tmp.MonthDates)AS DayNo,
amt.AttendanceDate,
tmp.MonthDates,
amt.BusRouteId,
amt.BusRoute


FROM #TmpDate tmp
    LEFT JOIN
    (
       SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		VSA.RollNo,
		VSA.Code,
		VSA.DateOfBirth , 
		VSA.FirstName+' '+VSA.MiddleName+' ' +VSA.LastName AS Name,
		AR.AttendanceDate,
		--Month(AR.AttendanceDate) AS MonthNo,
		--AR.IsPresentPickup,
		--AR.IsPresentDrop,
		CASE When AR.IsPresentPickup=1 then 'Y' ELSE 'N' END AS IsPresentPickup,
		CASE When AR.IsPresentDrop=1 then 'Y' ELSE 'N' END AS IsPresentDrop,
		VSA.ClassName,
		VSA.DivisionName,
		Day(AR.AttendanceDate) AS DayNo,
		Day(dateadd(month, Month(AR.AttendanceDate),dateadd(year, Year(AR.AttendanceDate) - 1900, -1))) AS LasDay,
		AR.BusRouteId,
		ISNULL(BR.Title,'') As BusRoute
	
		FROM [sTransport].[tAttendanceRegister] AR 
		INNER JOIN sStudent.vStudentAllDetail VSA ON VSA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
		INNER JOIN sTransport.tBusRouteMaster BR ON BR.Id=AR.BusRouteId
		WHERE 
		
			(YEAR(AR.AttendanceDate)=@rYear OR @rYear='')
			AND ((Month(AR.AttendanceDate)=@rMonth) OR (@rMonth=0))
			--AND ((VSA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((VSA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((VSA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((AR.BusRouteId=@rRouteId) OR (@rRouteId=0))
			AND ((Left(VSA.OrgGroupBatchId,4)=@rOrgGroupId) OR (@rOrgGroupId=0))
			AND  VSA.OrgGroupBatchId=@rOrgGroupBatchId
			
    ) amt
		
        ON tmp.MonthDates = amt.AttendanceDate
		order by tmp.MonthDates
		

	
		Drop table #TmpDate
	--SELECT 
	--		'' AS Builder1,
	--		'' AS Builder2,
	--		'' AS MonthDates,
	--		0 AS RollNo,
	--		0 AS Code,
	--		'' AS DateOfBirth,
	--		'' AS Name,
	--		0 AS IsPresentPickup,
	--		0 AS IsPresentDrop,
	--		'' AS ClassName,
	--		'' AS DivisionName,
	--		'' AS DayNo,
	--		'' AS AttendanceDate,
	--		0 AS BusRouteId,
	--		'' AS BusRoute

			

	END
GO
PRINT N'Creating [sFee].[pPendingFeeDashboardGet]...';


GO
 
CREATE PROCEDURE [sFee].[pPendingFeeDashboardGet]

		@rOrgGroupBatchId int = 0,
		@rType int,
		@rFilterType nvarchar(Max),
		@rFeeType nvarchar(Max),
		@rStudentStatus int = 0,
		@rUptoDate date = '',
		@rDepartmentId int=0,
	    @rOrgId int,
		@rReceiptBookId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
IF (@rType = 1)
 BEGIN
IF(@rFilterType = 'Organizationwise')		
	BEGIN 
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title
			ORDER BY OrgId,FHM.Id
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.OrgId,O.Title,FS.FeeId,FS.FeeName
			ORDER BY OrgId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
				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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.OrgId,O.Title,CGM.Id,CGM.Title
			ORDER BY OrgId,CGM.Id
	 END
	END
ELSE IF(@rFilterType = 'Departmentwise')
	BEGIN
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.DepartmentId,SA.DepartmentName,FHM.Id,FHM.Title
			ORDER BY DepartmentId,FHM.Id
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.DepartmentId,SA.DepartmentName,FS.FeeId,FS.FeeName
			ORDER BY DepartmentId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
				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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.DepartmentId,SA.DepartmentName,CGM.Id,CGM.Title
			ORDER BY DepartmentId,CGM.Id
	 END
	END
ELSE IF(@rFilterType = 'ReceiptBookwise')
	BEGIN
	IF(@rFeeType = 'FeeHeadwise')
	BEGIN
	 SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId
				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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY FS.ReceiptBookId,RBM.Title,FHM.Id,FHM.Title
			ORDER BY ReceiptBookId,FHM.Id
	 END
	ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId
				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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY FS.ReceiptBookId,RBM.Title,FS.FeeId,FS.FeeName
			ORDER BY ReceiptBookId,FS.FeeId
	 END
	ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
				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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) 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.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY FS.ReceiptBookId,RBM.Title,CGM.Id,CGM.Title
			ORDER BY ReceiptBookId,CGM.Id
	 END
	END 
  END
ELSE IF(@rType = 2)
		BEGIN
				SELECT 
					SA.ClassId,
					SA.ClassName,
					SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount
				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.Id AS AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 
						FROM sFee.tFeeSetup FS1
						INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
						INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
						AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE 
							BM.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=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 
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE
							SA1.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=1)
					) 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.tAcademic SA1 ON SA1.Id=R.SourceId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
							 
						WHERE		
							(R.SourceTypeId = 2001)
							AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND (R.IsObsolete = 0) 
							AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
							AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
							AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016
							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
					 LEFT JOIN sFee.tCollectionGroupMaster CGM
						ON FS.CollectionGroupId=CGM.Id	
					 LEFT JOIN sStudent.tStudentCommunication SC 
						ON SC.StudentId = SA.StudentId
					 LEFT JOIN sStudent.tStudentOther SO 
						ON SO.StudentId = SA.StudentId
					 INNER JOIN sFee.tFeeHeadMaster FHM
						ON FHM.Id = FS.FeeHeadId	
				  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	
				 SA.OrgGroupBatchId = @rOrgGroupBatchId
                 AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
                 AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				 AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
				GROUP BY 
						SA.ClassId,SA.ClassName
		END
END
GO
PRINT N'Creating [sFee].[pRptDepositAddSummaryPayTypeWise]...';


GO
CREATE PROCEDURE [sFee].[pRptDepositAddSummaryPayTypeWise]
	     
	 @rDepositHeadId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(20)='',
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rBatchId int,
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
     @rDepartmentId int=0,
     @rClassId int=0,
     @rDivisionId int=0,
     @rStudentName  nvarchar(100)='',
     @rFromDate date='',
     @rToDate date='',
     @rPayTypeId int=0,
     @rIsWithDetails int=0
   
      
AS
BEGIN
	SELECT 			
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Amount,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    'Deposite Add' As GroupType,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    DA.CreatedDateTime,
		    VA.StudentId,
		    @rBuilder1 As builder1,
		    DA.DepositNumber AS Number,		    
		    PTM.Title AS PayType,
		    DA.PayTypeId AS PayTypeId,
		    VA.ClassId AS ClassId,
		    VA.DivisionId AS DivisionId,
		    VA.OrganizationName AS OrgName,
		    DA.ChequeNo AS ChequeNo,
		    DA.BankName	AS BankName,
		    VA.OrgId,
		    @rIsWithDetails AS IsWithDetails,
		    VA.RollNo AS RollNo	    
		    
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DA.PayTypeId
			
			
			Where 
		   ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.DepositHeadId = @rDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
		    AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
		    AND ((convert(date,DA.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    AND ((convert(date,DA.CreatedDateTime)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
		    AND ((DA.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))
	
	Order by VA.ClassId 
END
GO
PRINT N'Creating [sFee].[pRptDepositRefundSummaryPayTypeWise]...';


GO
CREATE PROCEDURE [sFee].[pRptDepositRefundSummaryPayTypeWise]
	     
	 @rDepositHeadId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(20)='',
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rBatchId int,
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
     @rDepartmentId int=0,
     @rClassId int=0,
     @rDivisionId int=0,
     @rStudentName  nvarchar(100)='',
     @rFromDate date='',
     @rToDate date='',
     @rPayTypeId int=0,
     @rIsWithDetails int=0
   
      
AS
BEGIN
	SELECT 
			DR.RefundDate As DepositDate,
			-ISnull (DR.RefundAmount,0) AS Amount,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    'Deposite Refund' As GroupType,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId,
		    DR.CreatedDateTime,
		    VA.StudentId,
		    @rBuilder1 As builder1,
		    DR.RefundNumber AS Number,		    
		    PTM.Title AS PayType,
		    DR.PayTypeId AS PayTypeId,
		    VA.ClassId AS ClassId,
		    VA.DivisionId AS DivisionId,
		    VA.OrganizationName AS OrgName,
		    DR.ChequeNo AS ChequeNo,
		    DR.BankName	AS BankName,
		    VA.OrgId,
		    @rIsWithDetails AS IsWithDetails,
		    VA.RollNo AS RollNo	    	 	    
		     
			FROM 
			sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DR.PayTypeId
			
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.DepositHeadId = @rDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND ((convert(date,DR.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((convert(date,DR.CreatedDateTime)<=@rTodate) OR (ISNULL(@rToDate,'')=''))
			AND ((DR.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))
	
	Order by VA.ClassId
 
END
GO
PRINT N'Creating [siTax].[pForm16SubDetailAdd]...';


GO
CREATE PROCEDURE [siTax].[pForm16SubDetailAdd]   
	@rAutoId bigint,
	@rForm16Id bigint,
	@rEmployeeId bigint,
	@rAssesmentYearId bigint,
	@rOrgGroupId int,
	@rCreatedUserId bigint,
	@rGrossAmount decimal,
	@rQualifyingAmount decimal,
	@rDeductibleAmount decimal,
	@rStaticIncomeTaxSubSubId int =0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION	
		
		IF(@rAutoId=0)
		BEGIN
			INSERT INTO siTax.tForm16SubDetail
			(
			   Form16Id,
			   IncomeTaxSubSubgroupId,		   
			   GrossAmount,
			   QualifyingAmount,
			   DeductibleAmount,			   
			   IsObsolete,
			   CreatedUserId,
			   CreatedDateTime           
			 )
			VALUES
			(
				@rForm16Id,
				@rStaticIncomeTaxSubSubId,
				@rGrossAmount,
				@rQualifyingAmount,
				@rDeductibleAmount,		
				0,		
				@rCreatedUserId,
				getdate()
			)
			Select 1 AS Result
		END
		ELSE
		BEGIN
			Update siTax.tForm16SubDetail 
			SET			
			GrossAmount=@rGrossAmount,
			QualifyingAmount=@rQualifyingAmount,
			DeductibleAmount=@rDeductibleAmount,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=getdate()
			WHERE AutoId=@rAutoId
			
			Select 11 AS Result
		END	
		
 		  	
		COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
	ROLLBACK TRANSACTION
	SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Creating [sSecurity].[pAssignSubRole]...';


GO
 
 
CREATE PROCEDURE [sSecurity].[pAssignSubRole]

		@rRoleId bigint,
        @rSubRoleId bigint,
        @rAssign int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	IF(@rAssign = 1)
	BEGIN
		IF EXISTS(SELECT 1 FROM sSecurity.tAssignSubRole WHERE RoleId = @rRoleId AND SubRoleId = @rSubRoleId)
	BEGIN
		Return 1
	END
	ELSE
	BEGIN
		INSERT INTO sSecurity.tAssignSubRole  (RoleId,SubRoleId) VALUES (@rRoleId,@rSubRoleId)
	END
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT 1 FROM sSecurity.tAssignSubRole WHERE RoleId = @rRoleId AND SubRoleId = @rSubRoleId)
		BEGIN
			DELETE FROM sSecurity.tAssignSubRole WHERE RoleId = @rRoleId AND SubRoleId = @rSubRoleId
		END
	END
END
GO
PRINT N'Creating [sSecurity].[pRoleWiseUserFavoriteScreenAdd]...';


GO
CREATE PROCEDURE [sSecurity].[pRoleWiseUserFavoriteScreenAdd]
	
	@rUserId [bigint],
	@rFavoraiteScreenId int,
	@rIsDelete bit
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  	
 	IF EXISTS(SELECT 1 FROM sSecurity.tUserFavoriteScreen WHERE UserId = @rUserId AND FavoriteScreenId = @rFavoraiteScreenId) AND @rIsDelete = 0
			BEGIN
				Delete From sSecurity.tUserFavoriteScreen WHERE UserId = @rUserId AND FavoriteScreenId = @rFavoraiteScreenId
			END
	ELSE IF NOT EXISTS(SELECT 1 FROM sSecurity.tUserFavoriteScreen WHERE UserId = @rUserId AND FavoriteScreenId = @rFavoraiteScreenId)
			BEGIN 
					INSERT INTO sSecurity.tUserFavoriteScreen
						(
							UserId,		
						    FavoriteScreenId
						)
					VALUES
						(
							@rUserId,
							@rFavoraiteScreenId							 
						) 
			END			
			SELECT 1 AS UserId
END
GO
PRINT N'Creating [sSecurity].[pRoleWiseUserFavoriteScreenGet]...';


GO
CREATE PROCEDURE [sSecurity].[pRoleWiseUserFavoriteScreenGet]
	
	@rRoleId int	
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN  
      SELECT  
           U.UserId,
           FavoriteScreenId AS FavoraiteScreenId,
           S.Title AS UserFavoraiteScreen,
           --CASE WHEN S.ScreenTypeId = 1 THEN S.Page
           --ELSE S.Page + '?MenuID=' +CONVERT(Nvarchar(50),M.Id) END AS PagePath,
            CASE WHEN S.ScreenTypeId = 1 THEN  S.Page + '?MenuID=' +CONVERT(Nvarchar(50),(SELECT Id FROM sSecurity.tMenu M WHERE M.ScreenId = U.FavoriteScreenId AND M.IsObsolete = 0)) 
           ELSE S.Page  END AS PagePath,
           T.ResourceTypeId 
                       
      FROM
 	  sSecurity.tUserFavoriteScreen U 
 	  INNER JOIN sSecurity.tScreen S ON U.FavoriteScreenId = S.Id  
 	  INNER JOIN sSecurity.tUserRole UR On UR.UserId = U.UserId
 	  INNER JOIN sSecurity.tTask T ON S.TaskId = T.Id
		 
	  where UR.RoleId=@rRoleId  
		 
END
GO
 
 
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('20.03.16',200316,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO