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

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


GO
DROP TABLE [sStudent].[tTempStudent11];


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


GO
ALTER TABLE [sAssessment].[tStudentRemark]
    ADD [ExamBlock] NVARCHAR (100) NULL;


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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [TotalCount]   SMALLINT        NULL,
        [PresentCount] SMALLINT        NULL,
        [Remark4]      NVARCHAR (1000) NULL;


GO
PRINT N'Altering [sConfig].[tDisplayFieldOrg]...';


GO
ALTER TABLE [sConfig].[tDisplayFieldOrg]
    ADD [IsFieldMandatory] BIT NULL;


GO
PRINT N'Creating [sAcademic].[tClassworkView]...';


GO
CREATE TABLE [sAcademic].[tClassworkView] (
    [AutoId]         BIGINT   IDENTITY (1, 1) NOT NULL,
    [ClassworkId]    BIGINT   NOT NULL,
    [AcademicId]     BIGINT   NOT NULL,
    [ViewByUserId]   BIGINT   NOT NULL,
    [ViewByDateTime] DATETIME NOT NULL
);


GO
PRINT N'Creating PK_tClassworkView...';


GO
ALTER TABLE [sAcademic].[tClassworkView]
    ADD CONSTRAINT [PK_tClassworkView] 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 [sBiometric].[tPunchCount]...';


GO
CREATE TABLE [sBiometric].[tPunchCount] (
    [SourceId] BIGINT   NULL,
    [Attn_dt]  DATETIME NULL,
    [InCnt]    INT      NULL,
    [OutCnt]   INT      NULL
);

 
GO
PRINT N'Creating [sAssessment].[fSubjectEmployeeGet]...';


GO
CREATE FUNCTION [sAssessment].[fSubjectEmployeeGet](@rDivisionId int,@rSubjectId int)
RETURNS [nvarchar](MAX) WITH EXECUTE AS CALLER
AS 
BEGIN

DECLARE @lEmployeeString  VARCHAR(MAX)

SELECT 
	@lEmployeeString = COALESCE(@lEmployeeString,'') + ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'')+ ',' 
	
	 
FROM 
	sHrm.tEmployeeMaster Emp 
	INNER JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.EmployeeId = Emp.Id  
WHERE 
	TSD.SubjectId = @rSubjectId AND TSD.DivisionId = @rDivisionId

RETURN @lEmployeeString

END
GO
PRINT N'Creating [sConfig].[fDisplayFieldAdmissionFormGet]...';


GO
CREATE FUNCTION [sConfig].[fDisplayFieldAdmissionFormGet](@rOrgId int)

RETURNS  @List TABLE (
		 IsBirth_Place bit,
		 IsFather_Name bit,
		 IsBirth_Taluka bit,
		 IsBirth_District bit,
		 IsBirth_State bit,
		 IsBirth_Country bit,
		 IsPrevious_School bit,
		 IsStudent_Photo bit,
		 IsACI_StreetOne bit,
		IsACI_StreetTwo bit,
		IsACI_StreetThree bit,
		IsACI_City bit,
		IsACI_State bit,
		IsACI_Country bit,
		IsACI_ZipCode bit,
		IsACI_ContactEmail bit,
		IsOtherDetails_Religion bit,
		IsOtherDetails_Family_Caste bit,
		IsOtherDetails_Nationality bit,
		IsOtherDetails_Mother_Tongue bit,
		IsOtherDetails_Aadhar_Number bit,
		IsOtherDetails_Other_Information bit,
		IsOtherDetails_Live_With bit,
		IsOtherDetails_Hostel_Required bit,

		IsTransportDetails_Transport_Required bit,
		IsTransportDetails_Qualification bit,
		IsTransportDetails_Occupation bit,
		IsTransportDetails_Email bit,
		IsTransportDetails_Yearly_Income bit,
		IsTransportDetails_Organization bit,
		IsTransportDetails_Designation bit,
		IsTransportDetails_OfficePhone bit,
		IsTransportDetails_Father_ExStudent bit,
		IsTransportDetails_Office_Address bit,
		IsTransportDetails_Photo bit,

		IsMotherInformation_Full_Name bit,
		IsMotherInformation_Mobile_No bit,
		IsMotherInformation_Qualification bit,
		IsMotherInformation_Occupation bit,
		IsMotherInformation_Email bit,
		IsMotherInformation_Yearly_Income bit,
		IsMotherInformation_Organization bit,
		IsMotherInformation_Designation bit,
		IsMotherInformation_OfficePhone bit,
		IsMotherInformation_Mother_ExStudent bit,
		IsMotherInformation_Office_Address bit,
		IsMotherInformation_Photo bit,
		IsMotherInformation_Class bit,
		IsMotherInformation_Academic_Year bit,
		IsMotherInformation_Institute_Name bit,
		IsMotherInformation_Institute_City bit,
		IsMotherInformation_Institute_Affiliaton bit,	
		IsMotherInformation_Medium_of_Study bit,

		IsReference_Detail bit,
		IsReference_Name bit,
		IsReference_Relation bit,
		IsReference_ContactNo bit,
		 OrgId smallint 
		 )  

WITH EXECUTE AS CALLER
AS 
BEGIN

    DECLARE @rIsBirth_Place bit 
	DECLARE @rIsFather_Name bit 
    DECLARE @rIsBirth_Taluka bit
    DECLARE @rIsBirth_District bit 
    DECLARE @rIsBirth_State bit
    DECLARE @rIsBirth_Country bit
    DECLARE @rIsPrevious_School bit
    DECLARE @rIsStudent_Photo bit
    
	DECLARE @rIsACI_StreetOne bit
	DECLARE @rIsACI_StreetTwo bit
	DECLARE @rIsACI_StreetThree bit
	DECLARE @rIsACI_City bit
	DECLARE @rIsACI_State bit
	DECLARE @rIsACI_Country bit
	DECLARE @rIsACI_ZipCode bit
	DECLARE @rIsACI_ContactEmail bit
	DECLARE @rIsOtherDetails_Religion bit
	DECLARE @rIsOtherDetails_Family_Caste bit
	DECLARE @rIsOtherDetails_Nationality bit
	DECLARE @rIsOtherDetails_Mother_Tongue bit
	DECLARE @rIsOtherDetails_Aadhar_Number bit
	DECLARE @rIsOtherDetails_Other_Information bit
	DECLARE @rIsOtherDetails_Live_With bit
	DECLARE @rIsOtherDetails_Hostel_Required bit

	DECLARE @rIsTransportDetails_Transport_Required bit
	DECLARE @rIsTransportDetails_Qualification bit
	DECLARE @rIsTransportDetails_Occupation bit
	DECLARE @rIsTransportDetails_Email bit
	DECLARE @rIsTransportDetails_Yearly_Income bit
	DECLARE @rIsTransportDetails_Organization bit
	DECLARE @rIsTransportDetails_Designation bit
	DECLARE @rIsTransportDetails_OfficePhone bit
	DECLARE @rIsTransportDetails_Father_ExStudent bit
	DECLARE @rIsTransportDetails_Office_Address bit
	DECLARE @rIsTransportDetails_Photo bit

	DECLARE @rIsMotherInformation_Full_Name bit
	DECLARE @rIsMotherInformation_Mobile_No bit
	DECLARE @rIsMotherInformation_Qualification bit
	DECLARE @rIsMotherInformation_Occupation bit
	DECLARE @rIsMotherInformation_Email bit
	DECLARE @rIsMotherInformation_Yearly_Income bit
	DECLARE @rIsMotherInformation_Organization bit
	DECLARE @rIsMotherInformation_Designation bit
	DECLARE @rIsMotherInformation_OfficePhone bit
	DECLARE @rIsMotherInformation_Mother_ExStudent bit
	DECLARE @rIsMotherInformation_Office_Address bit
	DECLARE @rIsMotherInformation_Photo bit
	DECLARE @rIsMotherInformation_Class bit
	DECLARE @rIsMotherInformation_Academic_Year bit
	DECLARE @rIsMotherInformation_Institute_Name bit
	DECLARE @rIsMotherInformation_Institute_City bit
	DECLARE @rIsMotherInformation_Institute_Affiliaton bit
	DECLARE @rIsMotherInformation_Medium_of_Study bit

	DECLARE @rIsReference_Detail bit
	DECLARE @rIsReference_Name bit
	DECLARE @rIsReference_Relation bit
	DECLARE @rIsReference_ContactNo bit
	
	
	SELECT @rIsBirth_Place=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 301
	SELECT @rIsFather_Name=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 302
	SELECT @rIsBirth_Taluka =DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 303
	SELECT @rIsBirth_District=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 304
	SELECT @rIsBirth_State=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 305
	SELECT @rIsBirth_Country=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 306
	SELECT @rIsPrevious_School=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 307
	SELECT @rIsStudent_Photo=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 308
	
	SELECT @rIsACI_StreetOne=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 309
	SELECT @rIsACI_StreetTwo=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 310
	SELECT @rIsACI_StreetThree=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 311
	SELECT @rIsACI_City=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 312
	SELECT @rIsACI_State=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 313
	SELECT @rIsACI_Country=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 314
	SELECT @rIsACI_ZipCode=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 315
	SELECT @rIsACI_ContactEmail=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 316
	
	SELECT @rIsOtherDetails_Religion=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 317
	SELECT @rIsOtherDetails_Family_Caste=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 318
	SELECT @rIsOtherDetails_Nationality=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 319
	SELECT @rIsOtherDetails_Mother_Tongue=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 320
	SELECT @rIsOtherDetails_Aadhar_Number=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 321
	SELECT @rIsOtherDetails_Other_Information=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 322
	SELECT @rIsOtherDetails_Live_With=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 323
	SELECT @rIsOtherDetails_Hostel_Required=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 324
	
	
	SELECT @rIsTransportDetails_Transport_Required=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 325
	SELECT @rIsTransportDetails_Qualification=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 326
	SELECT @rIsTransportDetails_Occupation=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 327
	SELECT @rIsTransportDetails_Email=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 328
	SELECT @rIsTransportDetails_Yearly_Income=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 329
	SELECT @rIsTransportDetails_Organization=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 330
	SELECT @rIsTransportDetails_Designation=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 331 
	SELECT @rIsTransportDetails_OfficePhone=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 332 
	SELECT @rIsTransportDetails_Father_ExStudent=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 333 
	SELECT @rIsTransportDetails_Office_Address=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 334 
	SELECT @rIsTransportDetails_Photo=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId =335  
	
	SELECT @rIsMotherInformation_Full_Name=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 336
	SELECT @rIsMotherInformation_Mobile_No=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 337
	SELECT @rIsMotherInformation_Qualification=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 338
	SELECT @rIsMotherInformation_Occupation=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 339
	SELECT @rIsMotherInformation_Email=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 340
	SELECT @rIsMotherInformation_Yearly_Income=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 341
	SELECT @rIsMotherInformation_Organization=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 342
	SELECT @rIsMotherInformation_Designation=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 343
	SELECT @rIsMotherInformation_OfficePhone=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 344
	SELECT @rIsMotherInformation_Mother_ExStudent=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 345
	SELECT @rIsMotherInformation_Office_Address=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 346
	SELECT @rIsMotherInformation_Photo=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 347
	SELECT @rIsMotherInformation_Class=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 348
	SELECT @rIsMotherInformation_Academic_Year=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 349
	SELECT @rIsMotherInformation_Institute_Name=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 350
	SELECT @rIsMotherInformation_Institute_City=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 351
	SELECT @rIsMotherInformation_Institute_Affiliaton=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 352 
	SELECT @rIsMotherInformation_Medium_of_Study=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 353
	
	
	SELECT @rIsReference_Detail=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 354
	SELECT @rIsReference_Name=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 355
	SELECT @rIsReference_Relation=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 356
	SELECT @rIsReference_ContactNo=DisplayFieldId FROM sConfig.tDisplayFieldOrg WHERE orgId = @rOrgId and DisplayFieldId = 357
	

	
	INSERT INTO @List 
	SELECT 
   (CASE WHEN @rIsBirth_Place Is Null THEN  0 ELSE 1 END) AS IsBirth_Place ,
   (CASE WHEN @rIsFather_Name Is Null THEN 0 ELSE 1 END)AS IsFather_Name,
   (CASE WHEN @rIsBirth_Taluka Is Null THEN 0 ELSE 1 END)AS IsBirth_Taluka,
   (CASE WHEN @rIsBirth_State Is Null THEN 0  ELSE 1 END)AS IsBirth_State,
   (CASE WHEN @rIsBirth_Country Is Null THEN 0  ELSE 1 END)AS IsBirth_Country,
   (CASE WHEN @rIsBirth_State Is Null THEN 0  ELSE 1 END)AS IsBirth_State,
   (CASE WHEN @rIsPrevious_School Is Null THEN 0  ELSE 1 END)AS IsPrevious_School,
   (CASE WHEN @rIsStudent_Photo Is Null THEN 0  ELSE 1 END)AS IsStudent_Photo,
   
   (CASE WHEN @rIsACI_StreetOne Is Null THEN 0  ELSE 1 END)AS IsACI_StreetOne ,
   (CASE WHEN @rIsACI_StreetTwo Is Null THEN 0  ELSE 1 END)AS IsACI_StreetTwo ,
   (CASE WHEN @rIsACI_StreetThree Is Null THEN 0  ELSE 1 END)AS IsACI_StreetThree ,
   (CASE WHEN @rIsACI_City Is Null THEN 0  ELSE 1 END)AS IsACI_City ,
   (CASE WHEN @rIsACI_State  Is Null THEN 0  ELSE 1 END)AS IsACI_State ,
   (CASE WHEN @rIsACI_Country  Is Null THEN 0  ELSE 1 END)AS IsACI_Country ,
   (CASE WHEN @rIsACI_ZipCode  Is Null THEN 0  ELSE 1 END)AS IsACI_ZipCode ,
   (CASE WHEN @rIsACI_ContactEmail  Is Null THEN 0  ELSE 1 END)AS IsACI_ContactEmail ,
   
   (CASE WHEN @rIsOtherDetails_Religion  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Religion ,
   (CASE WHEN @rIsOtherDetails_Family_Caste  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Family_Caste ,
   (CASE WHEN @rIsOtherDetails_Nationality  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Nationality ,
   (CASE WHEN @rIsOtherDetails_Mother_Tongue  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Mother_Tongue ,
   (CASE WHEN @rIsOtherDetails_Aadhar_Number  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Aadhar_Number ,
   (CASE WHEN @rIsOtherDetails_Other_Information  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Other_Information ,
   (CASE WHEN @rIsOtherDetails_Live_With  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Live_With ,
   (CASE WHEN @rIsOtherDetails_Hostel_Required  Is Null THEN 0  ELSE 1 END)AS IsOtherDetails_Hostel_Required ,
   
   (CASE WHEN @rIsTransportDetails_Transport_Required  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Transport_Required ,
   (CASE WHEN @rIsTransportDetails_Qualification  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Qualification ,
   (CASE WHEN @rIsTransportDetails_Occupation  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Occupation ,
   (CASE WHEN @rIsTransportDetails_Email  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Email ,
   (CASE WHEN @rIsTransportDetails_Yearly_Income  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Yearly_Income ,
   (CASE WHEN @rIsTransportDetails_Organization  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Organization ,
   (CASE WHEN @rIsTransportDetails_Designation  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Designation ,
   (CASE WHEN @rIsTransportDetails_OfficePhone  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_OfficePhone ,
   (CASE WHEN @rIsTransportDetails_Father_ExStudent  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Father_ExStudent ,
   (CASE WHEN @rIsTransportDetails_Office_Address  Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Office_Address ,
   (CASE WHEN @rIsTransportDetails_Photo Is Null THEN 0  ELSE 1 END)AS IsTransportDetails_Photo  ,
   
   (CASE WHEN @rIsMotherInformation_Full_Name  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Full_Name ,
   (CASE WHEN @rIsMotherInformation_Mobile_No  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Mobile_No ,
   (CASE WHEN @rIsMotherInformation_Qualification  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Qualification ,
   (CASE WHEN @rIsMotherInformation_Occupation  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Occupation ,
   (CASE WHEN @rIsMotherInformation_Email  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Email ,
   (CASE WHEN @rIsMotherInformation_Yearly_Income  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Yearly_Income ,
   (CASE WHEN @rIsMotherInformation_Organization  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Organization ,
   (CASE WHEN @rIsMotherInformation_Designation  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Designation ,
   (CASE WHEN @rIsMotherInformation_OfficePhone  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_OfficePhone ,
   (CASE WHEN @rIsMotherInformation_Mother_ExStudent  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Mother_ExStudent ,
   (CASE WHEN @rIsMotherInformation_Office_Address  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Office_Address ,
   (CASE WHEN @rIsMotherInformation_Photo  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Photo ,
   (CASE WHEN @rIsMotherInformation_Class  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Class ,
   (CASE WHEN @rIsMotherInformation_Academic_Year  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Academic_Year ,
   (CASE WHEN @rIsMotherInformation_Institute_Name  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Institute_Name ,
   (CASE WHEN @rIsMotherInformation_Institute_City  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Institute_City ,
   (CASE WHEN @rIsMotherInformation_Institute_Affiliaton  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Institute_Affiliaton ,
   (CASE WHEN @rIsMotherInformation_Medium_of_Study  Is Null THEN 0  ELSE 1 END)AS IsMotherInformation_Medium_of_Study ,
   
   (CASE WHEN @rIsReference_Detail  Is Null THEN 0  ELSE 1 END)AS IsReference_Detail ,
   (CASE WHEN @rIsReference_Name  Is Null THEN 0  ELSE 1 END)AS IsReference_Name ,
   (CASE WHEN @rIsReference_Relation  Is Null THEN 0  ELSE 1 END)AS IsReference_Relation ,
   (CASE WHEN @rIsReference_ContactNo  Is Null THEN 0  ELSE 1 END)AS IsReference_ContactNo ,
   
   @rOrgId AS OrgId		  
    
   RETURN  
   
END
GO
PRINT N'Altering [sStudent].[vStudentCommunication]...';


GO

 
 
ALTER VIEW [sStudent].[vStudentCommunication]  
  
AS  
  
SELECT 
	  A.Id AS AcademicId,	  
	  A.ClassId,
	  A.DivisionId,
	  A.RollNo,
	  A.OrgId,
	  A.BatchId,
	  SM.Id AS StudentId,
	  SM.Code,
	  SM.Number,
	  SM.FirstName,
	  SM.LastName,
	  [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
	  CM.DepartmentId,
	  SM.StatusId,
	  CM.DisplayTitle AS ClassName,
	  DM.DisplayTitle AS DivisionName,
	  STM.Title AS StatusName,
	  ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
	  ISNULL(SC.ParentEmail,'') AS ParentEmail,
	  ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
	  ISNULL(SC.StudentEmail,'') AS StudentEmail,
	  SO.DateOfBirth,
	  CM.OrderIndex AS ClassOrderIndex,
	  DM.OrderIndex AS DivisionOrderIndex,
	  ISNULL(BM.IsActive,0) AS IsActiveBatch,
	  BM.OrgGroupBatchId,
	   ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
	   ISNULL(SF.FatherMail,'') AS FatherMail,
	   ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
	   ISNULL(SF.MotherMail,'') AS MotherMail,
	  OM.OrgGroupId,
	  ISNULL(SM.SUId,'') AS SUId,
	  --SM.AdmissionCategoryId
	  ISNULL(A.AdmissionCategoryId,0) AS AdmissionCategoryId,
	  ISNULL(IsInContext,0) AS IsInContext,
	  ISNULL(IsBlockAttendanceAlert,0) AS IsBlockAttendanceAlert,
	  ISNULL(IsBlockAllAlert,0) AS IsBlockAllAlert
  FROM 
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM
		ON A.StudentId=SM.Id	
	INNER JOIN sSetup.tClassMaster CM
		ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM
		ON DM.Id=A.DivisionId
	INNER JOIN sStudent.tStatusMaster STM
		ON STM.Id=SM.StatusId	 
	LEFT JOIN sStudent.tStudentCommunication SC
		ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentFamily SF
		ON SF.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO
		ON SO.StudentId=A.StudentId
	INNER JOIN sSetup.tOrganizationMaster OM
	    ON SM.OrgId = OM.Id	
	INNER JOIN sSetup.tBatchMaster BM 
		ON BM.Id = A.BatchId
GO

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


GO
ALTER PROCEDURE [sAcademic].[pClassworkGet]

	 @rId bigint=0,	 
	 @rSubjectId int=0,
	 @rClassId int=0,
	 @rEmployeeId bigint=0,
	 @rDivisionid int=0,
	 @rFromDate datetime='',
     @rToDate datetime='',
     @rOrgId int=0,
     --@rBatchId int
     @rOrgGroupBatchId int=0,
    @rUserId bigint =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	if(@rId = 0)
		BEGIN
			SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
	order by 
			AC.HomeWorkEndDate DESC
		END 
	ELSE
		BEGIN
		SELECT 
			AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ISNULL(ClassworkStatusId,1) AS ClassworkStatusId,
			ISNULL(HomeWorkStatusId,1) AS HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			ISNULL(AC.HomeWorkEndDate,'') AS HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title AS Batch,
		    ISNULL(vTSD.SubjectName,'') as SubjectName,
		    ISNULL(EM.FirstName + ' ' + EM.LastName,'') AS TeacherName,
		    ISNULL(vTSD.ClassTitle,'') AS ClassName,
		    ISNULL(vTSD.DivisionTitle,'') AS DivisionName,
		    BM.OrgId,
		    OM.DisplayTitle AS Organization,
		    REPLACE(CONVERT(VARCHAR(20), AC.ClassWorkDate, 103),'/','') +'_'+ CONVERT(nvarchar(10),AC.DivisionId) +'_'+CONVERT(nvarchar(10),AC.SubjectId) AS UniqueId
	FROM 
			sAcademic.tClasswork AC
			INNER JOIN sAcademic.vTeacherSubjectDivision vTSD ON vTSD.SubjectId = AC.SubjectId AND vTSD.DivisionId = AC.DivisionId AND vTSD.ClassId=AC.ClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = vTSD.OrgId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId = OGM.Id
			INNER JOIN sHrm.tEmployeeMaster EM ON  AC.EmployeeId = EM.Id AND vTSD.EmployeeId = AC.EmployeeId
			INNER JOIN sHrm.tEmployeeJobdetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tBatchMaster BM On BM.Id= AC.BatchId AND BM.OrgGroupBatchId = OGBM.Id
			INNER JOIN sSecurity.tUserOrganization U ON U.OrgId = OM.Id 
	WHERE 
	        --((AC.BatchId = @rBatchId) OR (@rBatchId = 0))
			((AC.Id = @rId) OR (@rId = 0))
			AND ((AC.EmployeeId= @rEmployeeId) OR (@rEmployeeId = 0))
			AND	((AC.ClassId = @rClassId) OR (@rClassId = 0))
			AND	((vTSD.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((AC.SubjectId =@rSubjectId) OR (@rSubjectId=0))
			AND ((AC.DivisionId =@rDivisionId) OR (@rDivisionId=0))
			AND (AC.ClassWorkDate>=@rFromDate OR ISNULL(@rFromDate,'')='')
			AND (AC.ClassWorkDate<=@rToDate OR ISNULL(@rToDate,'')='')
			AND (OGBM.Id = @rOrgGroupBatchId) 
			AND ((U.UserId = @rUserId)OR(@rUserId=0))
			GROUP BY AC.Id,
			AC.EmployeeId,
			AC.ClassId,
			AC.DivisionId,
			AC.SubjectId,
			AC.ClassWorkDate,
			AC.Classwork,
			AC.Homework,
			ClassworkStatusId,
			HomeWorkStatusId,
			--AC.HomeWorkEndDate,
			AC.HomeWorkEndDate,
			AC.CreatedDateTime,
			AC.BatchId,
			BM.Title,
		  vTSD.SubjectName,
		    EM.FirstName,  EM.LastName,
		    vTSD.ClassTitle,
		   vTSD.DivisionTitle,
		    BM.OrgId,
		    OM.DisplayTitle,
		     AC.ClassWorkDate, AC.DivisionId,AC.SubjectId
	order by 
			AC.HomeWorkEndDate DESC
		END
	
END
GO
PRINT N'Altering [sAdmission].[pAdmissionAndInquiryConsolidateDashBoardGet]...';


GO
ALTER PROCEDURE [sAdmission].[pAdmissionAndInquiryConsolidateDashBoardGet]
                              
    @rTypeId int, -- 1-Admission, 2-Inquiry 
    @rType nvarchar(200), -- OrgGroup, Organization
    @rOrgGroupId int=0,
    @rOrgId int=0,
    @rCommonOrgGroupBatchId int=0,
	@rInquiryStatusId int=0,
	@rClassId int =0,
	@rSyncDate int =0,
	@rInquiryMainStatus int =0
	 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
	INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
	SELECT 
		OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
	FROM
		sSetup.tOrganizationMaster OM
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
	WHERE 
		((OM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
		AND BM.IsObsolete = 0 AND COGBM.Id=@rCommonOrgGroupBatchId
	GROUP BY
		OM.Id
		
	DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
	INSERT INTO @lTempBatchId (OrgId , BatchId)
	SELECT 
		BM.OrgId AS OrgId,
		BM.Id AS BatchId
	FROM 
		sSetup.tBatchMaster BM
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
	WHERE
		BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id=@rCommonOrgGroupBatchId

	-- For Admission
	IF(@rTypeId=1) 
	BEGIN
		IF(@rType='OrgGroup')
		BEGIN

			IF(@rSyncDate =1)
				BEGIN
				DELETE  sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
						IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))
							BEGIN
							IF(@rOrgGroupId !=0)
								INSERT INTO sAdmission.tTempAdmissionFormCount
								SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()
								FROM sSetup.tOrgGroupMaster OGM			
								INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId 
								INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id
								LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId
								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	
								LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId
								WHERE 
								OGM.Id<>1 AND
								COGBM.Id=@rCommonOrgGroupBatchId AND
								--BM.IsActive = 1
								BM.Id = TB.BatchId
								GROUP BY OGM.Id,OGM.Title
								SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
							END
						ELSE
							BEGIN
								INSERT INTO sAdmission.tTempAdmissionFormCount
								SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()
								FROM sSetup.tOrgGroupMaster OGM			
								INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId 
								INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id
								LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId
								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	
								LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId
								WHERE 
								OGM.Id<>1 AND
								COGBM.Id=@rCommonOrgGroupBatchId AND
								--BM.IsActive = 1
								BM.Id = TB.BatchId
								GROUP BY OGM.Id,OGM.Title
								SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
							END
				
			END
			ELSE
				BEGIN
					IF  Exists(select 1 from sAdmission.tTempAdmissionFormCount   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102) AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId) 
					BEGIN
					SELECT * FROM sAdmission.tTempAdmissionFormCount   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					return
					END
					ELSE
					BEGIN
					DELETE  sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					IF EXISTS (SELECT 1 FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))
							BEGIN
							IF(@rOrgGroupId !=0)
						
								INSERT INTO sAdmission.tTempAdmissionFormCount
								SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()
								FROM sSetup.tOrgGroupMaster OGM			
								INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId 
								INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id
								LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId
								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	
								LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId
								WHERE 
								OGM.Id<>1 AND
								COGBM.Id=@rCommonOrgGroupBatchId AND
								--BM.IsActive = 1
								BM.Id = TB.BatchId
								GROUP BY OGM.Id,OGM.Title
								SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
							END
						ELSE
							BEGIN
							
								INSERT INTO sAdmission.tTempAdmissionFormCount
								SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()
								FROM sSetup.tOrgGroupMaster OGM			
								INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId 
								INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id
								LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId
								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	
								LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId
								WHERE 
								OGM.Id<>1 AND
								COGBM.Id=@rCommonOrgGroupBatchId AND
								--BM.IsActive = 1
								BM.Id = TB.BatchId
								GROUP BY OGM.Id,OGM.Title
								SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
							END
					
					
					--INSERT INTO sAdmission.tTempAdmissionFormCount
					--SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AF.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()
					--FROM sSetup.tOrgGroupMaster OGM			
					--INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId 
					--INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id
					--LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId
					--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	
			
					--LEFT JOIN sAdmission.tAdmissionForm AF ON BM.Id = AF.BatchId
					--WHERE 
					--OGM.Id<>1 AND
					--COGBM.Id=@rCommonOrgGroupBatchId AND
					----BM.IsActive = 1
					--BM.Id = TB.BatchId
					--GROUP BY OGM.Id,OGM.Title
					--SELECT * FROM sAdmission.tTempAdmissionFormCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					END
				END
		
		END
		IF(@rType='Organization')
		BEGIN
			SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(COUNT(AF.Id),0) AS AdmissionCount 
			FROM sAdmission.tAdmissionForm AF 
			LEFT JOIN  sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			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	
			
			
			LEFT JOIN @lTempBatchId TB ON TB.OrgId = OM.Id and BM.Id = TB.BatchId
			WHERE --BM.IsActive = 1 
			OM.OrgGroupId = @rOrgGroupId 	
			AND BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId 
			
			GROUP BY OM.Id,OM.Title	
		END
		IF(@rType='Status')
		BEGIN
			SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount ,0 AS InquiryMainStatusId
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			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 @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId AND OM.Id = @rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId 
			GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title
		END
		IF(@rType='StatusOrgGroupWise')
		BEGIN
			SELECT ISNULL(ASM.Id,0) AS InquiryStatusId,ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization, ISNULL(ASM.Title,'Pending') AS StatusName ,ISNULL(COUNT(AF.Id),0) AS StatusCount ,0 AS InquiryMainStatusId
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			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 @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id
			
			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			GROUP BY OM.Id,OM.Title,ASM.Id,ASM.Title
		END
			ELSE IF(@rType='StatusClassWise')
		BEGIN
		
			SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(AF.Id),0) AS StatusCount ,CM.OrderIndex 
			FROM sAdmission.tAdmissionForm AF 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			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 @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

			LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
			LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
			WHERE --BM.IsActive = 1 
			BM.Id = TB.BatchId
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISNULL(ASM.Id,0)=@rInquiryStatusId
			AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
		END
	ELSE IF(@rType='StatusStudentList')
		BEGIN
	SELECT AF.FormNo As InquiryId, AF.FirstName+' '+AF.MiddleName +' '+ AF.LastName AS StudentName,AF.ContactNo AS ContactNo 
FROM sAdmission.tAdmissionForm AF 
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AF.ForClassId
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
	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 @lTempBatchId TB ON TB.BatchId = BM.Id
	INNER JOIN sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id

	LEFT JOIN sAdmission.tAdmissionFormSelected AFS ON AF.Id = AFS.AdmissionFormId
	LEFT JOIN sAdmission.tAdmissionStatusMaster ASM ON ASM.Id = AFS.AdmissionStatusId
	WHERE --BM.IsActive = 1 
	BM.Id = TB.BatchId
	AND OM.OrgGroupId = @rOrgGroupId 
	AND COGBM.Id=@rCommonOrgGroupBatchId
	AND ISNULL(ASM.Id,0)=@rInquiryStatusId
	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
	AND((CM.Id = @rClassId)OR(@rClassId=0))
	GROUP BY AF.FirstName,AF.MiddleName,AF.LastName,AF.ContactNo,AF.FormNo
			END
	END
	
	-- For Inquiry
	IF(@rTypeId=2)
	BEGIN
		IF(@rType='OrgGroup')
		BEGIN
			IF(@rSyncDate =1)
				BEGIN
					DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId
					INSERT INTO sAdmission.tTempAdmissionInquiryCount
						SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()
					FROM 
					sSetup.tOrgGroupMaster OGM
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId 
			
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId
					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	
			
					LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId
					--sAdmission.tAdmissionInquiry AI 
					--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
					--INNER JOIN sSetup.tOrgGroupMaster OGM  ON OGM.Id = OM.OrgGroupId 
					WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId 
					--BM.IsActive = 1
					GROUP BY OGM.Id,OGM.Title
					SELECT OrgGroupTitle AS OrgGroup,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId
				END
			ELSE
				BEGIN
					IF  Exists(select 1 from sAdmission.tTempAdmissionInquiryCount   where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId)
						BEGIN
							SELECT  OrgGroupTitle AS OrgGroup,* FROM sAdmission.tTempAdmissionInquiryCount   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId
							return
						END
					ELSE
						BEGIN
					DELETE  sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId
					INSERT INTO sAdmission.tTempAdmissionInquiryCount
						SELECT ISNULL(OGM.Id,0) AS OrgGroupId,OGM.Title AS OrgGroupTitle,ISNULL(COUNT(AI.Id),0) AS AdmissionCount,@rCommonOrgGroupBatchId,GetDate()
					FROM 
					sSetup.tOrgGroupMaster OGM
					INNER JOIN sSetup.tOrganizationMaster OM ON OGM.Id = OM.OrgGroupId 
			
					INNER JOIN @lTempBatchId TB ON TB.OrgId = OM.Id
					LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = TB.BatchId
					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	
			
					LEFT JOIN sAdmission.tAdmissionInquiry AI ON BM.Id = AI.ForBatchId
					--sAdmission.tAdmissionInquiry AI 
					--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
					--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
					--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
					--INNER JOIN sSetup.tOrgGroupMaster OGM  ON OGM.Id = OM.OrgGroupId 
					WHERE OGM.Id<>1 and BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId 
					--BM.IsActive = 1
					GROUP BY OGM.Id,OGM.Title
					SELECT OrgGroupTitle AS OrgGroup,* FROM sAdmission.tTempAdmissionInquiryCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId
					END
				END	
		END
		IF(@rType='Organization')
		BEGIN
			SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(COUNT(AI.Id),0) AS AdmissionCount 
			FROM sAdmission.tAdmissionInquiry AI 
			LEFT JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			
			--sAdmission.tAdmissionForm AF 
			--LEFT JOIN  sSetup.tOrganizationMaster OM ON AF.OrgId = OM.Id 	
			--LEFT JOIN sSetup.tBatchMaster BM ON BM.Id = AF.BatchId
			--LEFT JOIN @lTempBatchId TB ON TB.OrgId = OM.Id and BM.Id = TB.BatchId
			WHERE BM.Id = TB.BatchId
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId AND COGBM.Id=@rCommonOrgGroupBatchId
			GROUP BY OM.Id,OM.Title
		END
		IF(@rType='Status')
		BEGIN
			-- Inquiry Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			ISNULL(COUNT(ISM.Id),0) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =11
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			-- Admission Form Given
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 11
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =21
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			-- Admission Form Submitted
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 21
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =31
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			-- Appeared For Entrance Exam
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 31
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =41
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			-- Rejected Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 41
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =51
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			-- Came for Interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71

			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =61 
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			-- Not Came for interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 61

			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =71 
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			-- Fees Paid

			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=91

			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =91

 
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			--Confirmed Admission


			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 91 

			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
 
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			--Refunded Fees
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 101

			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =111
 
			--BM.IsActive = 1 
			AND OM.Id = @rOrgId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
		END
		
		IF(@rType='StatusOrgGroupWise')
		BEGIN
		
			-- Inquiry Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			ISNULL(COUNT(ISM.Id),0) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			 
			UNION ALL
			
			-- Admission Form Given
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 11
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			) AS StatusCount,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =21
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			-- Admission Form Submitted
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 21
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =31
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			-- Appeared For Entrance Exam
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 31
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =41
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			-- Rejected Form
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 41
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =51
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			-- Came for Interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =61 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			-- Not Came for interaction
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 61

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =71 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			-- Fees Paid

			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=91

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			) AS StatusCount ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =91

 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			--Confirmed Admission


			SELECT
			ISM.Id AS InquiryStatusId, 
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 91 

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =101
 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			UNION ALL
			
			--Refunded Fees
			SELECT 
			ISM.Id AS InquiryStatusId,
			ISNULL(OM.Id,0) AS OrgId,
			OM.Title AS Organization,
			ISNULL(ISM.Title,'') AS StatusName,
			(
			SELECT 
			ISNULL(COUNT(ISM.Id),0) AS StatusCount 
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId > 101

			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			) AS StatusCount  ,
			ISM.InquiryMainStatusId AS InquiryMainStatusId
			FROM sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			AND ISM.InquiryMainStatusId =111
 
			--BM.IsActive = 1 
			AND OM.OrgGroupId = @rOrgGroupId
			GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title,ISM.InquiryMainStatusId
			
			--SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(ISM.Title,'') AS StatusName,ISNULL(COUNT(ISM.Id),0) AS StatusCount
			--FROM sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--WHERE BM.Id = TB.BatchId
			----BM.IsActive = 1 
			--AND OM.OrgGroupId = @rOrgGroupId  AND COGBM.Id=@rCommonOrgGroupBatchId
			--GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title
		END

		IF(@rType='StatusClassWise')
			BEGIN
				DECLARE @lInquiryMainStatus nvarchar(500)='' 
				IF(@rInquiryMainStatus=11)
				SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId =11'
				ELSE IF(@rInquiryMainStatus=21)
				SET  @lInquiryMainStatus = 'AND ISM.InquiryMainStatusId > 11'
				ELSE IF(@rInquiryMainStatus=31)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 21'
				ELSE IF(@rInquiryMainStatus=41)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 31'
				ELSE IF(@rInquiryMainStatus=51)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 41'
				ELSE IF(@rInquiryMainStatus=61)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71'
				ELSE IF(@rInquiryMainStatus=71)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 61'
				ELSE IF(@rInquiryMainStatus=91)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=91'
				ELSE IF(@rInquiryMainStatus=101)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 91'
				ELSE IF(@rInquiryMainStatus=111)
				SET  @lInquiryMainStatus ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLString nvarchar(max)=''

				SET @lSQLString = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
	INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
	SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
	FROM
		sSetup.tOrganizationMaster OM
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
	WHERE 
		((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
		AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
	GROUP BY
		OM.Id
		
	DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
	INSERT INTO @lTempBatchId (OrgId , BatchId)
	SELECT 
		BM.OrgId AS OrgId,
		BM.Id AS BatchId
	FROM 
		sSetup.tBatchMaster BM
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
	WHERE
		BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
		
		
		SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(ISM.Id),0) AS StatusCount,CM.OrderIndex FROM 
			sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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	
			
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
			'+CONVERT(nvarchar(500),@lInquiryMainStatus)+'
			AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
			AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex'

			--print @lSQLString

				execute(@lSQLString)

			END
		--BEGIN
		
		--	-- Inquiry Form
		--	SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,ISNULL(COUNT(ISM.Id),0) AS StatusCount,CM.OrderIndex FROM 
		--	sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
			
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId =11
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) 
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex
			
			
		--	UNION ALL
			
		--	-- Admission Form Given
		--	SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,T.StatusCount,CM.OrderIndex FROM 
		--	sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	INNER JOIN (
		--	SELECT 
		--	ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId 
		--	FROM sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId > 11
		--	--BM.IsActive = 1 
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY AI.ForClassId
		--	) T ON T.ForClassId = AI.ForClassId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId =21
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex,T.StatusCount
			
		--	UNION ALL
		--	-- Admission Form Submitted
		--	SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,T.StatusCount,CM.OrderIndex FROM 
		--	sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	INNER JOIN 
		--	(
		--	SELECT 
		--	ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
		--	FROM sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId > 21
		--	--BM.IsActive = 1 
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY AI.ForClassId) T ON T.ForClassId = AI.ForClassId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId =31
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex,T.StatusCount
		
			
		--	UNION ALL
		--	-- Appeared For Entrance Exam
		--	SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,T.StatusCount,
		--	CM.OrderIndex FROM 
		--	sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
			
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	INNER JOIN 
		--	(
		--	SELECT 
		--	ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
		--	FROM sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId > 31
		--	--BM.IsActive = 1 
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY AI.ForClassId)T ON T.ForClassId = AI.ForClassId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId =41
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex,T.StatusCount
		
			
		--	UNION ALL
			
		--	-- Rejected Form
		--	SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,T.StatusCount,
		--	CM.OrderIndex FROM 
		--	sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	INNER JOIN (
		--	SELECT 
		--	ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
		--	FROM sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId > 41
		--	--BM.IsActive = 1 
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY AI.ForClassId	)T ON T.ForClassId = AI.ForClassId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId =51
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex,T.StatusCount
		
			
		--	UNION ALL
			
		--	-- Came for Interaction
		--	SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,T.StatusCount,
		--	CM.OrderIndex FROM 
		--	sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	INNER JOIN 
		--	(
		--	SELECT 
		--	ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
		--	FROM sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71

		--	--BM.IsActive = 1 
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY AI.ForClassId)T ON T.ForClassId = AI.ForClassId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId =61 
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex,T.StatusCount
		
			
		--	UNION ALL
			
		--	-- Not Came for interaction
		--	SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,T.StatusCount,
		--	CM.OrderIndex FROM 
		--	sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	INNER JOIN 
		--	(
		--	SELECT 
		--	ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
		--	FROM sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId > 61
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY AI.ForClassId) T ON T.ForClassId = AI.ForClassId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId =71 
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex,T.StatusCount
		
		--	UNION ALL
			
		--	-- Fees Paid

		--	SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,T.StatusCount,
		--	CM.OrderIndex FROM 
		--	sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	INNER JOIN 
		--	(
		--	SELECT 
		--	ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
		--	FROM sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=91

		--	--BM.IsActive = 1 
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY AI.ForClassId)T ON T.ForClassId = AI.ForClassId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId =91
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex,T.StatusCount
		
			
		--	UNION ALL
			
		--	--Confirmed Admission


		--	SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,T.StatusCount,
		--	CM.OrderIndex FROM 
		--	sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
			
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	INNER JOIN 
		--	(
		--	SELECT 
		--	ISNULL(COUNT(ISM.Id),0) AS StatusCount ,AI.ForClassId
		--	FROM sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId > 91 
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY AI.ForClassId) T ON T.ForClassId = AI.ForClassId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId =101
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex,T.StatusCount
		
		--	UNION ALL
			
		--	--Refunded Fees
		--	SELECT CM.Id AS ClassId,CM.DisplayTitle AS ClassName,T.StatusCount,
		--	CM.OrderIndex FROM 
		--	sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	INNER JOIN 
		--	(
		--	SELECT 
		--	ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
		--	FROM sAdmission.tAdmissionInquiry AI 
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
		--	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	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	
		--	LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		--	LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId > 101
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY AI.ForClassId) T ON T.ForClassId = AI.ForClassId
		--	WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
		--	AND ISM.InquiryMainStatusId =111
		--	AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--	AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
		--	AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
		--	GROUP BY CM.Id,CM.DisplayTitle,CM.OrderIndex,T.StatusCount
		
			
		--	--SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(ISM.Title,'') AS StatusName,ISNULL(COUNT(ISM.Id),0) AS StatusCount
		--	--FROM sAdmission.tAdmissionInquiry AI 
		--	--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
		--	--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	
			
		--	--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
		--	--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		
		--	--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
		--	--WHERE BM.Id = TB.BatchId
		--	----BM.IsActive = 1 
		--	--AND OM.OrgGroupId = @rOrgGroupId  AND COGBM.Id=@rCommonOrgGroupBatchId
		--	--GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title
		--END

		ELSE IF(@rType='StatusStudentList')
			BEGIN


			DECLARE @lInquiryMainStatusStudent nvarchar(500)='' 
				IF(@rInquiryMainStatus=11)
				SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId =11'
				ELSE IF(@rInquiryMainStatus=21)
				SET  @lInquiryMainStatusStudent = 'AND ISM.InquiryMainStatusId > 11'
				ELSE IF(@rInquiryMainStatus=31)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 21'
				ELSE IF(@rInquiryMainStatus=41)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 31'
				ELSE IF(@rInquiryMainStatus=51)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 41'
				ELSE IF(@rInquiryMainStatus=61)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71'
				ELSE IF(@rInquiryMainStatus=71)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 61'
				ELSE IF(@rInquiryMainStatus=91)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=91'
				ELSE IF(@rInquiryMainStatus=101)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 91'
				ELSE IF(@rInquiryMainStatus=111)
				SET  @lInquiryMainStatusStudent ='AND ISM.InquiryMainStatusId > 101'


				DECLARE @lSQLStduentList nvarchar(max)=''

				SET @lSQLStduentList = 'DECLARE @lTempOrgBatchOrder TABLE( OrgId int, BatchOrderIndex int)
	INSERT INTO @lTempOrgBatchOrder ( OrgId,BatchOrderIndex )
	SELECT OM.Id AS OrgId, MAX(BM.OrderIndex) AS BatchOrderIndex
	FROM
		sSetup.tOrganizationMaster OM
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId = OM.Id
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
	WHERE 
		((OM.OrgGroupId='+CONVERT(nvarchar(20),@rOrgGroupId)+') OR ('+CONVERT(nvarchar(20),@rOrgGroupId)+' = 0))
		AND BM.IsObsolete = 0 AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
	GROUP BY
		OM.Id
		
	DECLARE @lTempBatchId TABLE(OrgId int, BatchId int)
	INSERT INTO @lTempBatchId (OrgId , BatchId)
	SELECT 
		BM.OrgId AS OrgId,
		BM.Id AS BatchId
	FROM 
		sSetup.tBatchMaster BM
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=BM.OrgGroupBatchId
		INNER JOIN @lTempOrgBatchOrder BO ON BO.OrgId = BM.OrgId
	WHERE
		BO.BatchOrderIndex = BM.OrderIndex  AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
		
		
		SELECT AI.Number As InquiryId, AI.FirstName+ SPACE(1) +AI.MiddleName +SPACE(1) +AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
			sAdmission.tAdmissionInquiry AI 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			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
			
				
			LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			WHERE BM.Id = TB.BatchId AND COGBM.Id='+CONVERT(nvarchar(20),@rCommonOrgGroupBatchId)+'
			'+CONVERT(nvarchar(500),@lInquiryMainStatusStudent)+'
			AND ((OM.OrgGroupId = '+CONVERT(nvarchar(20),@rOrgGroupId)+' )OR('+CONVERT(nvarchar(20),@rOrgGroupId)+'=0)) 
			AND((ISM.Id = '+CONVERT(nvarchar(20),@rInquiryStatusId)+')OR('+CONVERT(nvarchar(20),@rInquiryStatusId)+'=0))
			AND((CM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+')OR('+CONVERT(nvarchar(20),@rOrgId)+'=0))
			AND((CM.Id ='+CONVERT(nvarchar(20),@rClassId)+' )OR('+CONVERT(nvarchar(20),@rClassId)+'=0))
			GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number'

			--print @lSQLStduentList

				execute(@lSQLStduentList)
		
			---- Inquiry Form
			--SELECT AI.Number As InquiryId, AI.FirstName+' '+AI.MiddleName +' '+ AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
			--sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--WHERE BM.Id = TB.BatchId AND ISM.InquiryMainStatusId =11
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--AND((CM.Id = @rClassId)OR(@rClassId=0))
			--GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number
			
			
			--UNION ALL
			
			---- Admission Form Given
			--SELECT AI.Number As InquiryId, AI.FirstName+' '+AI.MiddleName +' '+ AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
			--sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--INNER JOIN (
			--SELECT 
			--ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId 
			--FROM sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 11
			----BM.IsActive = 1 
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--GROUP BY AI.ForClassId
			--) T ON T.ForClassId = AI.ForClassId
			--WHERE BM.Id = TB.BatchId AND ISM.InquiryMainStatusId =21
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--AND((CM.Id = @rClassId)OR(@rClassId=0))
			--GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number
			
			--UNION ALL
			---- Admission Form Submitted
			--SELECT AI.Number As InquiryId, AI.FirstName+' '+AI.MiddleName +' '+ AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
			--sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--INNER JOIN 
			--(
			--SELECT 
			--ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
			--FROM sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 21
			----BM.IsActive = 1 
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--GROUP BY AI.ForClassId) T ON T.ForClassId = AI.ForClassId
			--WHERE BM.Id = TB.BatchId AND ISM.InquiryMainStatusId =31
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--AND((CM.Id = @rClassId)OR(@rClassId=0))
			--GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number
		
			
			--UNION ALL
			---- Appeared For Entrance Exam
			--SELECT AI.Number As InquiryId, AI.FirstName+' '+AI.MiddleName +' '+ AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
			--sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--INNER JOIN 
			--(
			--SELECT 
			--ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
			--FROM sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 31
			----BM.IsActive = 1 
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--GROUP BY AI.ForClassId)T ON T.ForClassId = AI.ForClassId
			--WHERE BM.Id = TB.BatchId AND ISM.InquiryMainStatusId =41
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--AND((CM.Id = @rClassId)OR(@rClassId=0))
			--GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number

		
			
			--UNION ALL
			
			---- Rejected Form
			--SELECT AI.Number As InquiryId, AI.FirstName+' '+AI.MiddleName +' '+ AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
			--sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--INNER JOIN (
			--SELECT 
			--ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
			--FROM sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 41
			----BM.IsActive = 1 
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--GROUP BY AI.ForClassId	)T ON T.ForClassId = AI.ForClassId
			--WHERE BM.Id = TB.BatchId AND ISM.InquiryMainStatusId =51
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--AND((CM.Id = @rClassId)OR(@rClassId=0))
			--GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number
		
			
			--UNION ALL
			
			---- Came for Interaction
			--SELECT AI.Number As InquiryId, AI.FirstName+' '+AI.MiddleName +' '+ AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
			--sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--INNER JOIN 
			--(
			--SELECT 
			--ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
			--FROM sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 51 AND ISM.InquiryMainStatusId !=71

			----BM.IsActive = 1 
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--GROUP BY AI.ForClassId)T ON T.ForClassId = AI.ForClassId
			--WHERE BM.Id = TB.BatchId AND ISM.InquiryMainStatusId =61 
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--AND((CM.Id = @rClassId)OR(@rClassId=0))
			--GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number
		
			
			--UNION ALL
			
			---- Not Came for interaction
			--SELECT AI.Number As InquiryId, AI.FirstName+' '+AI.MiddleName +' '+ AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM
			--sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--INNER JOIN 
			--(
			--SELECT 
			--ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
			--FROM sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 61
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--GROUP BY AI.ForClassId) T ON T.ForClassId = AI.ForClassId
			--WHERE BM.Id = TB.BatchId AND ISM.InquiryMainStatusId =71 
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--AND((CM.Id = @rClassId)OR(@rClassId=0))
			--GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number
		
			--UNION ALL
			
			---- Fees Paid

			--SELECT AI.Number As InquiryId, AI.FirstName+' '+AI.MiddleName +' '+ AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
			--sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--INNER JOIN 
			--(
			--SELECT 
			--ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
			--FROM sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 81 AND ISM.InquiryMainStatusId !=91

			----BM.IsActive = 1 
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--GROUP BY AI.ForClassId)T ON T.ForClassId = AI.ForClassId
			--WHERE BM.Id = TB.BatchId AND ISM.InquiryMainStatusId =91
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--AND((CM.Id = @rClassId)OR(@rClassId=0))
			--GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number
		
			
			--UNION ALL
			
			----Confirmed Admission


			--SELECT AI.Number As InquiryId, AI.FirstName+' '+AI.MiddleName +' '+ AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
			--sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--INNER JOIN 
			--(
			--SELECT 
			--ISNULL(COUNT(ISM.Id),0) AS StatusCount ,AI.ForClassId
			--FROM sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 91 
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--GROUP BY AI.ForClassId) T ON T.ForClassId = AI.ForClassId
			--WHERE BM.Id = TB.BatchId AND ISM.InquiryMainStatusId =101
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--AND((CM.Id = @rClassId)OR(@rClassId=0))
			--GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number
		
			--UNION ALL
			
			----Refunded Fees
			--SELECT AI.Number As InquiryId, AI.FirstName+' '+AI.MiddleName +' '+ AI.LastName AS StudentName,AI.ContactNo AS ContactNo FROM 
			--sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId 
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--INNER JOIN 
			--(
			--SELECT 
			--ISNULL(COUNT(ISM.Id),0) AS StatusCount,AI.ForClassId
			--FROM sAdmission.tAdmissionInquiry AI 
			--INNER JOIN sSetup.tClassMaster CM ON CM.Id = AI.ForClassId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			--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	
			--LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			--INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
			--LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			--WHERE BM.Id = TB.BatchId AND COGBM.Id=@rCommonOrgGroupBatchId
			--AND ISM.InquiryMainStatusId > 101
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--GROUP BY AI.ForClassId) T ON T.ForClassId = AI.ForClassId
			--WHERE BM.Id = TB.BatchId AND ISM.InquiryMainStatusId =111
			--AND ((OM.OrgGroupId = @rOrgGroupId )OR(@rOrgGroupId=0)) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			--AND((ISM.Id = @rInquiryStatusId)OR(@rInquiryStatusId=0))
			--AND((CM.OrgId = @rOrgId)OR(@rOrgId=0))
			--AND((CM.Id = @rClassId)OR(@rClassId=0))
			--GROUP BY AI.FirstName,AI.MiddleName,AI.LastName,AI.ContactNo,AI.Number
		
			
			----SELECT ISNULL(OM.Id,0) AS OrgId,OM.Title AS Organization,ISNULL(ISM.Title,'') AS StatusName,ISNULL(COUNT(ISM.Id),0) AS StatusCount
			----FROM sAdmission.tAdmissionInquiry AI 
			----INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForBatchId
			----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	
			
			----LEFT JOIN @lTempBatchId TB ON TB.BatchId = BM.Id
			----INNER JOIN sSetup.tOrganizationMaster OM ON AI.OrgId = OM.Id
		
			----LEFT JOIN sAdmission.tInquiryStatusMaster ISM ON ISM.Id = AI.InquiryStatusId
			----WHERE BM.Id = TB.BatchId
			------BM.IsActive = 1 
			----AND OM.OrgGroupId = @rOrgGroupId  AND COGBM.Id=@rCommonOrgGroupBatchId
			----GROUP BY OM.Id,OM.Title,ISM.Id,ISM.Title
		END

	END
END
GO
PRINT N'Altering [sAdmission].[pAdmissionFormOnlineGet]...';


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


GO

 
ALTER PROCEDURE [sAlert].[pAllBirthdayWishListGet]
	 	 
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rStrStudentId nvarchar(max),
	 @rStrCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rStudentId bigint,
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rStatusId int,
	 @rDateOfBirth int,
	 @rDepartmentId int,
	 @rDayOfBirth int=0,
	 @rTemp int=0,
	 @rIsStudent bit=0,
	 @rIsEmployee bit=0,
	 @rMother bit=0,
	 @rFather bit=0,
	 @rReletive bit=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
	Select 
			
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SC.ParentContactNo AS MobileNo,			 
			'Student' AS CategoryName,
			'' AS PersonName,
			SO.DateOfBirth,
			MONTH(SO.DateOfBirth),
			ISNULL(SI.StudentPhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
		    CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
	From 
	
	sStudent.tAcademic A
	INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
	LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
	LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--sStudent.vStudentAllDetail SC
		
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			AND ((MONTH(SO.DateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND ((DAY(SO.DateOfBirth) = @rDayOfBirth) OR (@rDayOfBirth = 0 ))
			AND (SM.StatusId=1)
			AND (@rIsStudent=1)
			AND SO.DateOfBirth!=''
	 	
			
UNION ALL

Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SF.FatherContactNo AS MobileNo,			 
			'Father' AS CategoryName,
			SF.FatherName AS PersonName,
			SF.FatherDateOfBirth AS DateOfBirth,
			MONTH(SF.FatherDateOfBirth),
			SI.FatherPhoto AS Photo,
			 CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
	From 
			--sStudent.vStudentAllDetail SC
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			--AND (DAY(SF.FatherDateOfBirth) = DAY(@rDateOfBirth))
			AND  (@rDayOfBirth = 0)
			AND ((MONTH(SF.FatherDateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND (SM.StatusId=1)		
			AND(@rFather=1)
			AND SF.FatherDateOfBirth != ''
	
	UNION ALL

	Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,			
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SF.MotherContactNo AS MobileNo,			 
			'Mother' AS CategoryName,
			SF.MotherName AS PersonName,
			SF.MotherDateOfBirth AS DateOfBirth,
			MONTH(SF.MotherDateOfBirth),
			ISNULL(SI.MotherPhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
	From 
			--sStudent.vStudentAllDetail SC
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			--AND (DAY(SF.MotherDateOfBirth) = DAY(@rDateOfBirth))
			AND  (@rDayOfBirth = 0)
			AND  ((MONTH(SF.MotherDateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND (SM.StatusId=1)		
			AND(@rMother=1)
			AND SF.MotherDateOfBirth != ''	
			
	UNION ALL

	Select 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			
			A.Id AS AcademicId,
			SM.Code,
			SM.FirstName + ' ' + SM.MiddleName + ' ' + SM.LastName AS Name,
			A.RollNo,
			SF.RelativeContactNo AS MobileNo,			 
			--SF.RelationshipName AS CategoryName,
			'Relative' AS CategoryName,
			SF.RelativeName AS PersonName,
			SF.RelativeDateOfBirth AS DateOfBirth,
			MONTH(SF.RelativeDateOfBirth),
			ISNULL(SI.RelativePhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
			CM.DisplayTitle+' '+DM.DisplayTitle AS ClassName
			
	From 
			--sStudent.vStudentAllDetail SC
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sStudent.tStudentFamily SF ON SC.StudentId = SF.StudentId
	WHERE
			((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (A.OrgId=@rOrgId)
			AND (A.BatchId=@rBatchId)
			--AND (DAY(SF.RelativeDateOfBirth) = DAY(@rDateOfBirth))
			AND  (@rDayOfBirth = 0)
			AND ((MONTH(SF.RelativeDateOfBirth) = @rDateOfBirth) OR (@rDateOfBirth=0))
			AND (SM.StatusId=1)	
			AND(@rReletive=1)
			AND SF.RelativeDateOfBirth != ''	
	
	UNION ALL
		
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS AcademicId,
			EM.Code,
			EM.FirstName + ' ' + EM.MiddleName + ' ' + EM.LastName AS Name,
	        '' AS RollNo,
	        EC.MobileNumber AS MobileNo,
	        'Employee' AS CategoryName,
	        '' AS PersonName,
			EPD.DateOfBirth,
			MONTH(EPD.DateOfBirth) ,
			ISNULL(EI.EmployeePhoto,CONVERT(VARBINARY(MAX), 0)) AS Photo,
			ISNULL(ODM.Title,'') AS ClassName
	FROM 
			--[sHrm].[vExtEmployeeMaster] EM	
			sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EM.Id = EPD.EmployeeId	
			LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.Id = EC.EmployeeId 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId 
			LEFT JOIN sHrm.tEmployeeImages EI ON EM.Id=EI.EmployeeId
			LEFT JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 	
	WHERE  	    
			(EM.OrgId = @rOrgId)
			AND ((MONTH(EPD.DateOfBirth) = @rDateOfBirth) or (@rDateOfBirth=0) )
			AND ((DAY(EPD.DateOfBirth) = @rDayOfBirth) OR (@rDayOfBirth = 0 ))
			AND (@rIsEmployee=1)
			AND (EM.StatusId=7)	
			AND EPD.DateOfBirth!=''
		

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
 )
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))
	
	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
	)
	SET @sql='insert into #TEMPExam SELECT AcademicId 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 tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	
	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].[pMarkEntryRankUpdate]...';


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryRankUpdate]
	 
	 @rExamId int,
	 @rDivisionId int,
	 @rBatchId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
 		
--Get Siddhi Krupa Configuration Value
DECLARE @lConfigValue bit, @lRankConfigValueToSet0 bit, @lSetRankLastConfig bit, @lOrgId smallint,@lMaxRank int
DECLARE @lSiddhiKrupaApplicable bit
DECLARE @lIsSkipRankConfigValue bit=0
	 
SELECT @lSiddhiKrupaApplicable = ISNULL(IsApplySiddhiKrupa,0) From sAssessment.tExamMaster Where Id = @rExamId

SELECT @lOrgId = OM.Id From sSetup.tBatchMaster BM
				 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId
				 Where BM.Id = @rBatchId
SELECT @lConfigValue = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationSetup CS
					   LEFT JOIN sConfig.tConfigurationMaster CM ON CM.Id = CS.ConfigurationId	
					   WHERE CS.ConfigurationId = 278 AND SourceId = @lOrgId AND SourceTypeId = 1016
SELECT @lRankConfigValueToSet0 = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM
							     LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId
							     WHERE CS.ConfigurationId = 280 AND SourceTypeId = 1016
SELECT @lSetRankLastConfig = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM 
						     LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId	
						     WHERE CS.ConfigurationId = 281 AND SourceTypeId = 1016	
						     
						     
SELECT @lIsSkipRankConfigValue = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM 
						     LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId	
						     WHERE CS.ConfigurationId = 315 AND SourceTypeId = 1016							     					     
--End Here


--    ,ROW_NUMBER() OVER (ORDER BY TotalObtain) AS "Row Number"    -- Row number
--    ,RANK() OVER (ORDER BY TotalObtain) AS Rank                  -- skip next number
--    ,DENSE_RANK() OVER (ORDER BY TotalObtain) AS "Dense Rank"    -- continue next number 
--    ,NTILE(4) OVER (ORDER BY TotalObtain) AS Quartile            -- make number of rank group    


Update R Set R.RankNumber = 0 From sAssessment.tResult R 
Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId  
 AND R.ExamId=@rExamId
 AND A.DivisionId = @rDivisionId 
 AND A.BatchId = @rBatchId

 
IF(@lIsSkipRankConfigValue=0)
BEGIN
	Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
	INNER JOIN
	(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
	--(Select ROW_NUMBER() OVER(ORDER BY TotalObtain Desc, RS.AcademicId Asc) AS RankNumber,
	--(Select RANK() OVER(ORDER BY TotalObtain Desc, RS.AcademicId Asc) AS RankNumber,
	AcademicId 
	from sAssessment.tResult RS
	INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
	AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
	AND ResultStatus='PASS' ) A
	ON A.AcademicId = R.AcademicId 
	WHERE R.ExamId = @rExamId
END
ELSE
BEGIN
   Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
	INNER JOIN
	(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
	--(Select ROW_NUMBER() OVER(ORDER BY TotalObtain Desc, RS.AcademicId Asc) AS RankNumber,
	--(Select RANK() OVER(ORDER BY TotalObtain Desc, RS.AcademicId Asc) AS RankNumber,
	AcademicId 
	from sAssessment.tResult RS
	INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
	AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
	AND ResultStatus='PASS' ) A
	ON A.AcademicId = R.AcademicId 
	WHERE R.ExamId = @rExamId
   
END
	
If @lConfigValue = 1 AND @lSiddhiKrupaApplicable = 1
BEGIN
      IF(@lIsSkipRankConfigValue=0)
       BEGIN
		Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R		
		INNER JOIN
		(Select DENSE_RANK() OVER ( ORDER BY ResultStatus,Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus in ('PASS','PROMOTED') ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId 
		AND R.Id Not in (Select ResultId from sAssessment.tResultDetail RD where RD.ResultId=R.Id and RD.KrupaMark > 0)
		-- If krupa Mark obtain then Rank set 0
	  END
	  ELSE
	  BEGIN
	     Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R		
		 INNER JOIN
		(Select RANK() OVER ( ORDER BY ResultStatus,Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus in ('PASS','PROMOTED') ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId 
		AND R.Id Not in (Select ResultId from sAssessment.tResultDetail RD where RD.ResultId=R.Id and RD.KrupaMark > 0)
		-- If krupa Mark obtain then Rank set 0	  
	  END
	  
		
		IF  @lSetRankLastConfig = 1 -- Set Rank of Student Whose Siddhi/GraceMark >0 after Normal Pass Student
									-- Assessment.IsMoveSiddhiRankToLast
		BEGIN
		
			Update R Set R.RankNumber = 0 From sAssessment.tResult R 
			Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId  
			AND R.ExamId=@rExamId
			AND A.DivisionId = @rDivisionId 
			AND A.BatchId = @rBatchId
		
		IF(@lIsSkipRankConfigValue=0)
		BEGIN
		
			Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND RS.Id Not IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			AND ResultStatus in ('PASS','PROMOTED')) A ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId --AND R.Percentage > 0
			AND R.Id Not IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
		END
		ELSE
		BEGIN
		    Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
			INNER JOIN
			(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND RS.Id Not IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			AND ResultStatus in ('PASS','PROMOTED')) A ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId --AND R.Percentage > 0
			AND R.Id Not IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)		     
		END	
			
			SELECT @lMaxRank = Max(RankNumber) 
			FROM sAssessment.tResult R 
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = EM.ClassId
			WHERE EM.Id = @rExamId  AND DM.Id = @rDivisionId AND EM.BatchId= @rBatchId AND R.Percentage > 0
			
		IF(@lIsSkipRankConfigValue=0)
		  BEGIN				
			Update R Set R.RankNumber=@lMaxRank + A.RankNumber From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND RS.Id IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			AND ResultStatus in ('PASS','PROMOTED')) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId --AND R.Percentage > 0
			AND R.Id IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
		 END
	    ELSE
	       BEGIN
	          Update R Set R.RankNumber=@lMaxRank + A.RankNumber From sAssessment.tResult R
			  INNER JOIN
			  (Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			   from sAssessment.tResult RS
			   INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			   AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			   AND RS.Id IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			   AND ResultStatus in ('PASS','PROMOTED')) A
			   ON A.AcademicId = R.AcademicId 
			   WHERE R.ExamId = @rExamId --AND R.Percentage > 0
			   AND R.Id IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)	       	       	       
	       END
	    	 
		 	
		END		
	
	 IF @lRankConfigValueToSet0 = 1  -- Set Rank 0 to Those whose Siddhi/GraceMark > 0
										-- Assessment.tIsSetSiddhiAppliedStudentRank0
		BEGIN
		
		IF(@lIsSkipRankConfigValue=0)
		 BEGIN		
			Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			
			Update R Set R.RankNumber=0
			From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
		  END
		  
	     ELSE
		  
		  BEGIN
		     Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
			
			Update R Set R.RankNumber=0
			From sAssessment.tResult R
			INNER JOIN
			(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id IN (Select DISTINCT ResultId from sAssessment.tResultDetail Where GraceMark > 0)
		  
		  END
		  			
		END
END   
    
SELECT 1 AS Result
 
END
GO
PRINT N'Altering [sAssessment].[pResultSheetStandardMultiExamGet]...';


GO
ALTER PROCEDURE [sAssessment].[pResultSheetStandardMultiExamGet]	 	 	
	 @rExamId int,	
	 @rAcademicId bigint=0	 
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
	(
	    SRNO INT IDENTITY(1,1) PRIMARY KEY, 
		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(500),
		Remark2 nvarchar(500),
		Remark3 nvarchar(500),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		
		
		
		IsResultStatus bit,
		
		ResultRemark nvarchar(200),
	
		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), 
		
		
		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),
		
		
--		ResultDetailId int,
		ResultDetailId1 bigint,
		ResultDetailId2 bigint,
		ResultDetailId3 bigint,
		ResultDetailId4 bigint,
		ResultDetailId5 bigint,
		ResultDetailId6 bigint,
		ResultDetailId7 bigint,
		ResultDetailId8 bigint,
		ResultDetailId9 bigint,
		ResultDetailId10 bigint,
		ResultDetailId11 bigint,
		ResultDetailId12 bigint,
		
		
	
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance 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),
		
		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),
		
		
		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
	)	
	 --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,
	
	IsResultStatus,
	
	ResultRemark,
	
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	
	
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	
	ExamCode,
	
	
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	
	SubjectGroupId,
	--SubjectGroupTitle,
	--SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	KrupaMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	
    IsPresent,
    GradeTitle,
	
	AchievementsTerm1,
	AchievementsTerm2,
	GeneralRemarkTerm1,
	GeneralRemarkTerm2,
	ResultRemark1Term1,
	ResultRemark2Term1,
	ResultRemark1Term2,
	ResultRemark2Term2,
	SR_HeightTerm1,
	SR_WeightTerm1,
	SR_HeightTerm2,
	SR_WeightTerm2,
	SR_PresentDaysTerm1,
	SR_PresentDaysTerm2,
	SR_TotalDaysTerm1,
	SR_TotalDaysTerm2	
	)
	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.IsResultStatus,		
		ISNULL(R.ResultRemark,'') AS ResultRemark,		
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
	
	    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,
		
		
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		
		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,
		
		IsPresent,
		GradeTitle ,
		
		
		'' 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	
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.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id	
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId	
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId	
	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.Id=@rAcademicId)OR (@rAcademicId=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 
	
	--If no any combine exam exist in current exam then insert current exam in combineExam for final level
	IF NOT EXISTS(select 1 FROM sAssessment.tExamCombine WHERE ExamId  = @rExamId)
	BEGIN
	  INSERT INTO #tempcombineExam (ExamID) 
	  SELECT C.Id From sAssessment.tExamMaster C WHERE C.Id  = @rExamId
	END
	
	
	-- 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
	--print @lCount
	--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,	
					 --ExamDetailId' + convert(nvarchar(15),@lCount)+'=RD.ExamDetailId,
					  ResultDetailId' + convert(nvarchar(15),@lCount)+'=RD.Id,
					 				
					 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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND  EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
				--print @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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND 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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND 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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND 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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND 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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND 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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND 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 R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END		
	
	SELECT T.*
	FROM #TempAllExam T  where 
	T.ExamId=@rExamId AND 
	AcademicId= @rAcademicId
	
	
	--Declare @Count AS Integer
    --SET @Count=(SELECT  count(ClassSubjectID) FROM #TempAllExam T)
    DECLARE @lCounter INT
    SET @lCounter = 1
    DECLARE @lMAXID INT=0
    
    SELECT @lMAXID = COUNT(*) FROM #TempAllExam
    Declare @FinalHtml nvarchar(max)=''
	Declare @tdHtml nvarchar(max)
	Declare @trHtml nvarchar(max)
	Declare @HeaderHtml nvarchar(max)
	Declare @HeaderCounter int=0
	Declare @thHtml nvarchar(max)
	
	WHILE (@lCounter <= @lMAXID)
	BEGIN 
	     Declare @ClassSubject nvarchar(max)
	     Declare @ResultDetailId1 nvarchar(max)
	     Declare @ResultDetailId2 nvarchar(max)
	     Declare @ResultDetailId3 nvarchar(max)
	     Declare @ResultDetailId4 nvarchar(max)
	     Declare @ResultDetailId5 nvarchar(max)
	     Declare @ResultDetailId6 nvarchar(max)
	     Declare @ResultDetailId7 nvarchar(max)
	     Declare @ResultDetailId8 nvarchar(max)
	     Declare @ResultDetailId9 nvarchar(max)
	     Declare @ResultDetailId10 nvarchar(max)
	     Declare @ResultDetailId11 nvarchar(max)
	     Declare @ResultDetailId12 nvarchar(max)
	     
	     Declare @Obtain1 decimal(10,2)
	     Declare @Obtain2 decimal(10,2)
	     Declare @Obtain3 decimal(10,2)
	     Declare @Obtain4 decimal(10,2)
	     Declare @Obtain5 decimal(10,2)
	     Declare @Obtain6 decimal(10,2)
	     Declare @Obtain7 decimal(10,2)
	     Declare @Obtain8 decimal(10,2)
	     Declare @Obtain9 decimal(10,2)
	     Declare @Obtain10 decimal(10,2)
	     Declare @Obtain11 decimal(10,2)
	     Declare @Obtain12 decimal(10,2)
	     
	     
	     Declare @ExamMaximumMarks1 decimal(10,2)
	     Declare @ExamMaximumMarks2 decimal(10,2)
	     Declare @ExamMaximumMarks3 decimal(10,2)
	     Declare @ExamMaximumMarks4 decimal(10,2)
	     Declare @ExamMaximumMarks5 decimal(10,2)
	     Declare @ExamMaximumMarks6 decimal(10,2)
	     Declare @ExamMaximumMarks7 decimal(10,2)
	     Declare @ExamMaximumMarks8 decimal(10,2)
	     Declare @ExamMaximumMarks9 decimal(10,2)
	     Declare @ExamMaximumMarks10 decimal(10,2)
	     Declare @ExamMaximumMarks11 decimal(10,2)
	     Declare @ExamMaximumMarks12 decimal(10,2)
	     
	     
	     Declare @Exam1Name nvarchar(max)
	     Declare @Exam2Name nvarchar(max)
	     Declare @Exam3Name nvarchar(max)
	     Declare @Exam4Name nvarchar(max)
	     Declare @Exam5Name nvarchar(max)
	     Declare @Exam6Name nvarchar(max)
	     Declare @Exam7Name nvarchar(max)
	     Declare @Exam8Name nvarchar(max)
	     Declare @Exam9Name nvarchar(max)
	     Declare @Exam10Name nvarchar(max)
	     Declare @Exam11Name nvarchar(max)
	     Declare @Exam12Name nvarchar(max)
	     Declare @IsMarksInDecimal bit
	     
	     
	     SET @ClassSubject=(SELECT SubjectName from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId1=(SELECT ResultDetailId1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId2=(SELECT ResultDetailId2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId3=(SELECT ResultDetailId3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId4=(SELECT ResultDetailId4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId5=(SELECT ResultDetailId5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId6=(SELECT ResultDetailId6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId7=(SELECT ResultDetailId7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId8=(SELECT ResultDetailId8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId9=(SELECT ResultDetailId9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId10=(SELECT ResultDetailId10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId11=(SELECT ResultDetailId11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId12=(SELECT ResultDetailId12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     SET @Obtain1=(SELECT Obtain1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain2=(SELECT Obtain2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain3=(SELECT Obtain3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain4=(SELECT Obtain4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain5=(SELECT Obtain5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain6=(SELECT Obtain6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain7=(SELECT Obtain7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain8=(SELECT Obtain8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain9=(SELECT Obtain9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain10=(SELECT Obtain10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain11=(SELECT Obtain11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain12=(SELECT Obtain12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     
	     
	     SET @Exam1Name=(SELECT Exam1Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam2Name=(SELECT Exam2Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam3Name=(SELECT Exam3Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam4Name=(SELECT Exam4Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam5Name=(SELECT Exam5Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam6Name=(SELECT Exam6Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam7Name=(SELECT Exam7Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam8Name=(SELECT Exam8Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam9Name=(SELECT Exam9Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam10Name=(SELECT Exam10Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam11Name=(SELECT Exam11Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam12Name=(SELECT Exam12Name from #TempAllExam WHERE SRNO=@lCounter)
	     
	     SET @ExamMaximumMarks1=(SELECT MaximumMark1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks2=(SELECT MaximumMark2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks3=(SELECT MaximumMark3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks4=(SELECT MaximumMark4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks5=(SELECT MaximumMark5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks6=(SELECT MaximumMark6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks7=(SELECT MaximumMark7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks8=(SELECT MaximumMark8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks9=(SELECT MaximumMark9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks10=(SELECT MaximumMark10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks11=(SELECT MaximumMark11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks12=(SELECT MaximumMark12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     
	     SET @IsMarksInDecimal=(SELECT IsMarksInDecimal from #TempAllExam WHERE SRNO=@lCounter)
	     --print @IsMarksInDecimal
	  
	     IF(@HeaderCounter=0)
	     BEGIN
	      SET @thHtml='<th>Subjects</th>'
	      if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL)	    
	      SET @thHtml=@thHtml+'<th>'+@Exam1Name+'</th>';   
	      if(@Exam2Name<>'' OR @Exam2Name IS NOT NULL)	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam2Name+'</th>';  
	       if(@Exam3Name<>'' OR @Exam3Name IS NOT NULL)	    	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam3Name+'</th>';   
	       if(@Exam4Name<>'' OR @Exam4Name IS NOT NULL)	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam4Name+'</th>';  
	      if(@Exam5Name<>'' OR @Exam5Name IS NOT NULL)	  	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam5Name+'</th>';  
	       if(@Exam6Name<>'' OR @Exam6Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam6Name+'</th>';  
	        if(@Exam7Name<>'' OR @Exam7Name IS NOT NULL)	  	  	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam7Name+'</th>';  
	        if(@Exam8Name<>'' OR @Exam8Name IS NOT NULL)	  	  	    		    
	      SET @thHtml=@thHtml+'<th>'+@Exam8Name+'</th>';  
	       if(@Exam9Name<>'' OR @Exam9Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam9Name+'</th>';  
	          if(@Exam10Name<>'' OR @Exam10Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam10Name+'</th>'; 
	       if(@Exam11Name<>'' OR @Exam11Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th>'+@Exam11Name+'</th>';  
	      if(@Exam12Name<>'' OR @Exam12Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th>'+@Exam12Name+'</th>';  
	     END   
	     SET @HeaderCounter=@HeaderCounter+1;
	    
	     
	     SET @tdHtml='<td class=Sub width=200>'+@ClassSubject+'</td>';
	     
	     Declare @SetDecimalFunction nvarchar(max)
	    --print @IsMarksInDecimal
	     IF(@IsMarksInDecimal=1)
			 BEGIN
			  SET @SetDecimalFunction='onblur="javascript:return fnValidateDecimal(this,10,2)" onKeypress="javascript:return MaskDecimal(event,10,2)"';
		
			  
		 if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain1)+'</div><input  title=title  class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks1)+' value='+CONVERT(varchar(20),@Obtain1)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain2)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks2)+' value='+CONVERT(varchar(20),@Obtain2)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain3)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks3)+' value='+CONVERT(varchar(20),@Obtain3)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain4)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks4)+' value='+CONVERT(varchar(20),@Obtain4)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain5)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks5)+' value='+CONVERT(varchar(20),@Obtain5)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain6)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks6)+' value='+CONVERT(varchar(20),@Obtain6)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain7)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks7)+' value='+CONVERT(varchar(20),@Obtain7)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain8)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks8)+' value='+CONVERT(varchar(20),@Obtain8)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain9)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks9)+' value='+CONVERT(varchar(20),@Obtain9)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain10)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks10)+' value='+CONVERT(varchar(20),@Obtain10)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	     SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain11)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks11)+' value='+CONVERT(varchar(20),@Obtain11)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain12)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks12)+' value='+CONVERT(varchar(20),@Obtain12)+' '+@SetDecimalFunction+' MaxLength="100"/></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
			  
			  
			  
			 END
	     ELSE
			 BEGIN
			   
			  SET @SetDecimalFunction='onblur="javascript:return fnValidateDecimal(this,10,0)" onKeypress="javascript:return MaskDecimal(event,10,0)"';
			  
			  
		if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain1 AS int))+'</div><input title=title class=numbersOnly masterTooltip Title="Hello" type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks1)+' value='+CONVERT(varchar(20),CAST(@Obtain1 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain2 AS int))+'</div><input class=numbersOnly type=text   ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks2)+' value='+CONVERT(varchar(20),CAST(@Obtain2 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain3 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks3)+' value='+CONVERT(varchar(20),CAST(@Obtain3 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain4 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks4)+' value='+CONVERT(varchar(20),CAST(@Obtain4 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain5 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks5)+' value='+CONVERT(varchar(20),CAST(@Obtain5 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain6 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks6)+' value='+CONVERT(varchar(20),CAST(@Obtain6 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain7 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks7)+' value='+CONVERT(varchar(20),CAST(@Obtain7 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain8 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks8)+' value='+CONVERT(varchar(20),CAST(@Obtain8 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain9 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks9)+' value='+CONVERT(varchar(20),CAST(@Obtain9 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain10 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks10)+' value='+CONVERT(varchar(20),CAST(@Obtain10 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	     SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain11 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks11)+' value='+CONVERT(varchar(20),CAST(@Obtain11 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain12 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks12)+' value='+CONVERT(varchar(20),CAST(@Obtain12 AS int))+' '+@SetDecimalFunction+' MaxLength="100"/></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
			  
			  
			 END
	     
	    SET @trHtml= '<tr>'+@tdHtml+'</tr>';
	    SET @FinalHtml=@FinalHtml+@trHtml;
        
	     SET @lCounter = @lCounter + 1
	END
	 --print @thHtml
	select '<table id="ExamDataTbl" class="table table-striped table-bordered table-hover" style=position:relative><tr class="sub_exam_width">'+@thHtml+'</tr>'+@FinalHtml+'</table>' AS Html; 
	--if(@FinalHtml IS NOT NULL and @FinalHtml <> '')	    
 --   select '<table  id="ExamDataTbl" class="table table-striped table-bordered table-hover" ><tr>'+@thHtml+'</tr>'+@FinalHtml+'</table>' AS Html; 
 --   ELSE
 --   select '<table id="ExamDataTbl" class="table table-striped table-bordered table-hover"><tr>No record found.</tr></table>' AS Html; 
			
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

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


GO
 
ALTER PROCEDURE [sAssessment].[pRptExamAdmitcard]
	  
	  @rBatchId int,
	  @rClassId int,
	  @rDivisionId int,
	 -- @rExamId int=0,
	  @rExamSubGroupId int=0,
	  @rCode nvarchar(20),
	  @rFromRollNo int,
	  @rToRollNo int,
	  @rDepartmentId int,
	  @rSubjectId int=0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 	
	SELECT 		
	       	ESGM.Title AS ExamName,
	       	ISNULL(ED.DisplayOrder,0) as DisplayOrder,
	        ISNULL(ED.ExamDate,sCommon.fGetDate()) as ExamDate,
	        ISNULL(ED.ExamTime,'') as ExamTime,
	        V.SubjectName AS SubjectName,
	        CM.DisplayTitle+' / '+DM.DisplayTitle AS ClassDivision,
	         CM.DisplayTitle AS ClassName,
	         CM.Id As ClassId,
	         DM.Id AS DiVisionId,
	        V.ClassSubjectId AS ClassSubjectId,
	        SA.Name,
	        SA.RollNo,
	        SA.Code,
	        SF.FatherName,
	        So.DateOfBirth,
	        GM.Title AS Gender,
	        EM.Remark1,
	        EM.Remark2,
	        EM.Remark3,
	        SA.AcademicId,
	        SI.StudentPhoto,
	        SF.MotherName,
	        SR. ExamCenter,
	        SR.ExamSeatNo,
	        V.SubjectCode AS SubjectCode,
	         
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN
			OI.CertificateHeaderA4 
			ELSE NULL END)AS  MarksheetHeaderA4 ,
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			EM.IsOnPrePrinted ,
	        --EM.Id As ExamId,
			EM.IsDisplayPhoto,
			SR.ExamBlock
			FROM
			sStudent.vStudentAcademic SA 
			INNER JOIN sSetup.tClassMaster CM ON SA.ClassId=CM.Id 
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CM.Id AND SA.DivisionId=DM.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.Id  ANd Em.BatchId=SA.BatchId 
			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.ExamId=EM.Id  
			LEFT JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  
			LEFT JOIN sAssessment.tOptionalSubject OS on OS.AcademicId=SA.AcademicId and OS.ClassSubjectId=V.ClassSubjectId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SA.StudentId  
			LEFT JOIN sStudent.tStudentOther SO ON So.StudentId=SA.StudentId  
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=So.GenderId   
			LEFT JOIN  sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId=EM.Id AND SR.AcademicId=SA.AcademicId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	WHERE 
			SA.BatchId = @rBatchId 
		 AND (SA.ClassId=@rClassId OR @rClassId=0) 
		 AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
		 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		 AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))	
	     AND ((SA.Code=@rCode) OR (@rCode=''))
	     AND (SA.DepartmentId=@rDepartmentId OR @rDepartmentId=0) 
	     AND (V.SubjectId=@rSubjectId OR @rSubjectId=0) 
	    AND ((V.IsOptional = 1 AND  isnull(OS.AcademicId,0) <> 0) OR (V.IsOptional = 0))
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,
		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,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rIsDetail bit=0,
	 @rIsShowWithDetail bit=0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId 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(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,
		--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(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,
		
	)	
	 --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
	
	)
	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,
		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
	   		
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 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)))
    ) 
	    
	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 [sAttendance].[pAttenanceRegisterGet]...';


GO
 
ALTER PROCEDURE [sAttendance].[pAttenanceRegisterGet]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rAttendanceTypeId smallint,
	 @rOrgId int,
	 @rForMonth smallint,
	 @rForYear smallint,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int = 0,
	 @rStudentCode nvarchar(20)='',
	 @rDepartmentId int = 0,
	 @rAcademicId bigint = 0,
	 @PageIndex int=0,
	 @rStatus int=0,
	 @rFromStudentId bigint = 0,
	 @rToStudentId bigint = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

--Select * from sAttendance.tTempAttendance

DECLARE @lFirstDate Date
	DECLARE @lResult nvarchar(max)
	DECLARE @li int 
	SET @li=1
	SET @lFirstDate = CONVERT(DATE,(CONVERT(NVARCHAR(4),@rForYear)+'/'+CONVERT(NVARCHAR(2),@rForMonth)+'/01'))	
	
	
DECLARE @lOrgId  int
--DECLARE @lSchoolRemark1  nvarchar(500)
--DECLARE @lSchoolRemark2  nvarchar(500)
--DECLARE @lSchoolRemark3  nvarchar(500)
DECLARE @lSchoolRequiredSignature  nvarchar(500)

SELECT  @lOrgId=RG.OrgId,
--@lSchoolRemark1 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark1,'')  ELSE RG.SchoolRemark1 END,
--@lSchoolRemark2= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark2,'')  ELSE RG.SchoolRemark2 END,
--@lSchoolRemark3 = CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRemark3,'')  ELSE RG.SchoolRemark3 END,
@lSchoolRequiredSignature= CASE  WHEN RG.OrgId IS NULL  THEN ISNULL(RGM.DefaultRequiredSignature,'')  ELSE RG.SchoolRequiredSignature END 
 
FROM sCommon.tReportRemarkGroupMaster RGM LEFT JOIN sCommon.tReportRemarkGroupOrg RG ON RGM.Id = RG.ReportRemarkGroupId AND RG.OrgId = @rOrgId AND RG.ReportRemarkGroupId=1 where RGM.Id=1
 
-- select @lSchoolRequiredSignature as sig
 	Declare @Days int 
 	select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
BEGIN 
	 CREATE Table #AttendanceRegistertempTable
(
	TID int identity(1,1),
	ClassDivisionTitle Nvarchar(500),
	Code nvarchar(500),
	RollNo int,
	AcademicId bigint,
	Name nvarchar(500),
	AttendanceTypeId int,
	ForYear int,
	ForMonth int,
	ForMonthInWord nvarchar(500),
	ClassId int,
	DivisionId int,
	ClassName nvarchar(500),
	DivisionName nvarchar(500),
	IsPresent bit,
	DayPart int,
	LeftDate date,
	ClassOrderIndex int,
	DivisionOrderIndex int,
	FooterSignature nvarchar(500),
	StatusId int,
	AttendanceDate date,
	AttendanceTagId int ,
	EmployeeName nvarchar(500),
	DateOfBirth date,
	Religion nvarchar(500),
	MotherName nvarchar(500),
	FamilyCast nvarchar(100)
)
Insert INTO #AttendanceRegistertempTable
(	
	ClassDivisionTitle,
	Code ,
	RollNo,
	AcademicId,
	Name,
	AttendanceTypeId,
	ForYear,
	ForMonth,
	ForMonthInWord,
	ClassId,
	DivisionId,
	ClassName,
	DivisionName,
	IsPresent,
	DayPart,
	LeftDate,
	ClassOrderIndex,
	DivisionOrderIndex,
	FooterSignature,
	StatusId,
	AttendanceDate,
	AttendanceTagId,
	EmployeeName,
	DateOfBirth,
	Religion,
	MotherName,
	FamilyCast
)
Select	    
	ISNULL(SA.ClassName + '-' + SA.DivisionName,'') AS ClassDivisionTitle,
	SA.Code,
	SA.RollNo,
	SA.AcademicId,
	SA.Name,
	SR.AttendanceTypeId ,
	YEAR(SR.AttendanceDate) AS ForYear,
	MONTH(SR.AttendanceDate) AS ForMonth,
	DATENAME(month, SR.AttendanceDate) AS ForMonthInWord,
	SA.ClassId,
	SA.DivisionId,
	SA.ClassName,Sa.DivisionName,
  
	--(CASE SR.IsPresent WHEN 1 THEN 'P' 
	--	WHEN 0 THEN 'A'
	--ELSE  ' ' END )AS  IsPresent,		
	SR.IsPresent,
	 day(SR.AttendanceDate) AS DayPart,
	 
	 A.LeftDate,
	 CM.OrderIndex AS ClassOrderIndex,
	 DM.OrderIndex As DivisionOrderIndex,
	@lSchoolRequiredSignature AS FooterSignature,
	 SA.StatusId,
	 SR.AttendanceDate As AttendanceDate,
	 SR.AttendanceTagId,
	 EM.FirstName+' ' + EM.LastName AS EmployeeName,
	 SO.DateOfBirth,
	 RE.Title As Religion,
	 Sf.MotherName,
	 SO.FamilyCast
	 --,
	 --SR.IsPresent
	 
	 
    from
            sStudent.vStudentAcademic SA 
            INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
            INNER JOIN sStudent.tStudentAdmission A ON SA.StudentId = A.StudentId
            INNER JOIN sSetup.tClassMaster CM ON CM.Id = SA.ClassId
            INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = CM.OrgId
            INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SA.DivisionId
            LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = DM.InchargeEmployeeId
            INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
			LEFT JOIN  sStudent.tStudentFamily SF ON Sf.StudentId=Sa.StudentID
            LEFT JOIN sCommon.tReligionMaster RE On RE.Id=SO.ReligionId
            
             WHERE  
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	         AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	          AND ((SA.BatchId=@rBatchId) OR (@rBatchId= 0))
	          AND ((YEAR(SR.AttendanceDate)=@rForYear) OR (@rForYear= 0))
	          AND ((MONTH(SR.AttendanceDate)=@rForMonth) OR (@rForMonth= 0))
	           AND ((SA.ClassId=@rClassId) OR (@rClassId= 0))
	           AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	           AND ((SA.AcademicId=@rAcademicId) OR (@rAcademicId=0))	           
				AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
	           AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	           AND ((SA.StatusId=@rStatus)OR (@rStatus=0))
	           --AND ((SA.Code = @rFromStudentId) OR (@rFromStudentId=0))
	           --AND ((SA.Code = @rToStudentId) OR (@rToStudentId=0))
	           
				
CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li<=@Days
BEGIN
INSERT INTO #TempDaysTempTable
(
	DayPart ,
   Value
)

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffGet](@rForYear,@rForMonth,@li,@rBatchId,@rClassId,@rDivisionId,'',@rOrgId) 
SET @li = @li + 1
END

 

SELECT  
			@lFirstDate AS LastDate,
			LeftDate,
            @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			PivotTable.AcademicId,
			ClassDivisionTitle,isnull(Code,'') as Code,isnull(RollNo,0) as RollNo,
			isnull(Name,'') as Name,isnull(AttendanceTypeId,0) as AttendanceTypeId,ForYear,
			ForMonth,ClassId,ClassName,DivisionId,
			DivisionName,
			ForMonthInWord,
			(ISNULL(TC.TCount,0) - ISNULL(AC.ACount,0)) AS PresentCount,
			ISNULL(ABU.AUCount,0) AS AbsentUpto,
			ISNULL(TC.TCount,0) AS AttendanceCount,
		    ISNULL(AC.ACount,0) As  AbsentCount,
		    ISNULL(PC.PCount,0) As  PresentUpto,	    
		    
		    ClassOrderIndex,
		    DivisionOrderIndex,
		    FooterSignature,
			(ISNULL(TotalPresent,0) + ISNULL(TC.TCount,0)) AS TotalPresent,
			 
			  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,1 ,@rBatchId ,@rClassId,@rDivisionId , isnull([1],''),@rOrgId )  AS P1,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,2 ,@rBatchId ,@rClassId,@rDivisionId , isnull([2],''),@rOrgId )  AS P2,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,3 ,@rBatchId ,@rClassId,@rDivisionId , isnull([3],''),@rOrgId )  AS P3,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,4 ,@rBatchId ,@rClassId,@rDivisionId , isnull([4],''),@rOrgId )  AS P4,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,5 ,@rBatchId ,@rClassId,@rDivisionId , isnull([5],''),@rOrgId )  AS P5,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,6 ,@rBatchId ,@rClassId,@rDivisionId , isnull([6],''),@rOrgId ) AS P6,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,7 ,@rBatchId ,@rClassId,@rDivisionId , isnull([7],''),@rOrgId ) AS P7,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,8 ,@rBatchId ,@rClassId,@rDivisionId , isnull([8],''),@rOrgId ) AS P8,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,9 ,@rBatchId ,@rClassId,@rDivisionId , isnull([9],''),@rOrgId ) AS P9,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,10 ,@rBatchId ,@rClassId,@rDivisionId , isnull([10],''),@rOrgId ) AS P10,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,11 ,@rBatchId ,@rClassId,@rDivisionId , isnull([11],''),@rOrgId ) AS P11,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,12 ,@rBatchId ,@rClassId,@rDivisionId , isnull([12],''),@rOrgId ) AS P12,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,13 ,@rBatchId ,@rClassId,@rDivisionId , isnull([13],''),@rOrgId ) AS P13,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,14 ,@rBatchId ,@rClassId,@rDivisionId , isnull([14],''),@rOrgId ) AS P14,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,15 ,@rBatchId ,@rClassId,@rDivisionId , isnull([15],''),@rOrgId ) AS P15,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,16 ,@rBatchId ,@rClassId,@rDivisionId , isnull([16],''),@rOrgId ) AS P16,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,17 ,@rBatchId ,@rClassId,@rDivisionId , isnull([17],''),@rOrgId ) AS P17,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,18 ,@rBatchId ,@rClassId,@rDivisionId , isnull([18],''),@rOrgId ) AS P18,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,19 ,@rBatchId ,@rClassId,@rDivisionId , isnull([19],''),@rOrgId ) AS P19,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,20 ,@rBatchId ,@rClassId,@rDivisionId , isnull([20],''),@rOrgId ) AS P20,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,21 ,@rBatchId ,@rClassId,@rDivisionId , isnull([21],''),@rOrgId ) AS P21,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,22 ,@rBatchId ,@rClassId,@rDivisionId , isnull([22],''),@rOrgId ) AS P22,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,23 ,@rBatchId ,@rClassId,@rDivisionId , isnull([23],''),@rOrgId ) AS P23,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,24 ,@rBatchId ,@rClassId,@rDivisionId , isnull([24],''),@rOrgId ) AS P24,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,25 ,@rBatchId ,@rClassId,@rDivisionId , isnull([25],''),@rOrgId ) AS P25,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,26 ,@rBatchId ,@rClassId,@rDivisionId , isnull([26],''),@rOrgId ) AS P26,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,27 ,@rBatchId ,@rClassId,@rDivisionId , isnull([27],''),@rOrgId ) AS P27,
			[sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,28 ,@rBatchId ,@rClassId,@rDivisionId , isnull([28],''),@rOrgId ) AS P28,
			CASE WHEN @Days>=29 THEN  [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,29 ,@rBatchId,@rClassId ,@rDivisionId , isnull([29],''),@rOrgId ) end AS P29,
			CASE WHEN @Days>=30 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,30 ,@rBatchId ,@rClassId,@rDivisionId , isnull([30],''),@rOrgId ) end AS P30,
			CASE WHEN @Days>=31 THEN [sAttendance].[fWeekHOffGet](@rForYear ,@rForMonth ,31 ,@rBatchId ,@rClassId,@rDivisionId , isnull([31],''),@rOrgId )  end AS P31,
			
	 	--	 isnull([1],'') AS P1,
			--isnull([2],'') AS P2,
			--isnull([3],'') AS P3,
			--isnull([4],'') AS P4,
			--isnull([5],'') AS P5,
			--isnull([6],'') AS P6,
			--isnull([7],'') AS P7,
			--isnull([8],'') AS P8,
			--isnull([9],'') AS P9,
			--isnull([10],'') AS P10,
			--isnull([11],'') AS P11,
			--isnull([12],'') AS P12,
			--isnull([13],'') AS P13,
			--isnull([14],'') AS P14,
			--isnull([15],'') AS P15,
			--isnull([16],'') AS P16,
			--isnull([17],'') AS P17,
			--isnull([18],'') AS P18,
			--isnull([19],'') AS P19,
			--isnull([20],'') AS P20,
			--isnull([21],'') AS P21,
			--isnull([22],'') AS P22,
			--isnull([23],'') AS P23,
			--isnull([24],'') AS P24,
			--isnull([25],'') AS P25,
			--isnull([26],'') AS P26,
			--isnull([27],'') AS P27,
			--isnull([28],'') AS P28,
			--isnull([29],'') AS P29,
			--isnull([30],'') AS P30,
			--isnull([31],'') AS P31, 
			 EmployeeName ,
 
             sCommon.fGetDaysInMonth ( @rForMonth,@rForYear) AS DaysInMonth,
              DateOfBirth,Religion,MotherName,FamilyCast
--,
--AttendanceTagId

 
FROM
(
	Select --TID, 
		ISNULL(ClassName + '-' + DivisionName,'') AS ClassDivisionTitle,
		Code,
		RollNo,
		AcademicId,
		Name,
		AttendanceTypeId ,
		YEAR(ST.AttendanceDate) AS ForYear,
		MONTH(ST.AttendanceDate) AS ForMonth,
		DATENAME(month, ST.AttendanceDate) AS ForMonthInWord,
		ClassId,
		DivisionId,
		ClassName,
		DivisionName,
		(
			CASE  WHEN IsPresent = 1 AND ST.AttendanceTagId = 1 THEN 'LC' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 2 THEN 'EL' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 3 THEN 'N' 
				  WHEN IsPresent = 1 AND ST.AttendanceTagId = 4 THEN 'G' 
			      WHEN IsPresent = 1  THEN 'P' 
				  WHEN IsPresent = 0 THEN 'A'
				  ELSE  DT.Value END 
		)AS  IsPresent,		
		day(ST.AttendanceDate) AS DayPart,
		LeftDate
		,
		ClassOrderIndex,
		DivisionOrderIndex,
		FooterSignature,EmployeeName,
		DateOfBirth,Religion,MotherName,FamilyCast
      -- DO NOT ADD ANY FIELD HERE WITHOUT PERMISSION OF RAJENDRA
	 FROM 
		#AttendanceRegistertempTable ST 
		INNER JOIN #TempDaysTempTable DT ON DT.DayPart = ST.DayPart
	 WHERE
		((LeftDate >= @lFirstDate) OR ISNULL(LeftDate,'') = '')
) AS SourceTable 
 
	           
	        
PIVOT
(	
MIN(IsPresent)
FOR DayPart IN ([0], [1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS PivotTable
	LEFT JOIN
	(
		Select  AcademicId AS AcademicId, COUNT(1) AS TCount 
		   FROM  
				#AttendanceRegistertempTable
		    
			GROUP BY  AcademicId
    ) TC ON TC.AcademicId = PivotTable.AcademicId
    
	LEFT JOIN
	(
		Select AcademicId AS AcademicId, COUNT(1) AS ACount 
		   FROM  #AttendanceRegistertempTable
		    WHERE   IsPresent = 0	 		
            
			GROUP BY  AcademicId
    ) AC ON AC.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS PCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 1	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	        AND ((SA.Id<=@rFromStudentId) OR (@rFromStudentId=0))
	        AND ((SA.Id>=@rToStudentId) OR (@rToStudentId=0))

			GROUP BY A.Id
    ) PC ON PC.AcademicId = PivotTable.AcademicId
		LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS AUCount  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			 SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
			AND SR.IsPresent = 0	    		
            --AND (SA.StatusId = 1)
	        AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	        AND ((SA.Id<=@rFromStudentId) OR (@rFromStudentId=0))
	        AND ((SA.Id>=@rToStudentId) OR (@rToStudentId=0))

			GROUP BY A.Id
    ) ABU ON ABU.AcademicId = PivotTable.AcademicId
	LEFT JOIN
	(SELECT A.Id AS AcademicId, COUNT(1) AS TotalPresent  FROM sAttendance.tStudentRegister SR 
			INNER JOIN sStudent.tAcademic A ON SR.AcademicId = A.Id 
		   INNER JOIN sStudent.tStudentMaster SA ON A.StudentId = SA.Id
		   INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
			WHERE  
			SR.AttendanceDate < (convert(date,CONVERT(nvarchar(10), @rForYear)+ '/' +  CONVERT(nvarchar(10), @rForMonth) + '/' + '01' ))
	        AND
	        ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId= 0))
	        AND ((SA.OrgId=@rOrgId) OR (@rOrgId= 0))
	        AND ((A.BatchId=@rBatchId) OR (@rBatchId= 0))	          
	        AND ((A.ClassId=@rClassId) OR (@rClassId= 0))
	        AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
	        AND ((A.Id=@rAcademicId) OR (@rAcademicId=0))	           
			AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))				
	        AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId= 0))
	        AND ((SA.Id<=@rFromStudentId) OR (@rFromStudentId=0))
	        AND ((SA.Id>=@rToStudentId) OR (@rToStudentId=0))

			GROUP BY A.Id
    ) AA ON AA.AcademicId = PivotTable.AcademicId
 
    ORDER BY RollNo;
 

select * from #TempDaysTempTable
 				
drop table #AttendanceRegistertempTable	  
drop table #TempDaysTempTable
	
	
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
	
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))
			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) )
			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))
			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

--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 
         
     WHERE OGMT.Id=@rOrgGroupId
   
    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
			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
				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
				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
				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
				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))<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
			   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
				   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	
				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
				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
			   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
				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
				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(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 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 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
			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
		 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
		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
				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
			 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].[pStudentRegisterGet]...';


GO
 
ALTER PROCEDURE [sAttendance].[pStudentRegisterGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rAttendanceDate date,
		 @rSubjectId int,
		 @rSubjectBatchId int,
		 @rRepeatCount tinyint,
	 	 @rBatchId int,
	 	 @rOrgId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
IF @rSubjectBatchId=0
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId,
			ISNULL(SO.GenderId,0) AS GenderId,
			ISNULL(GM.Title,'') AS Gender
  FROM 
            sStudent.vStudentAcademic SA 
            LEFT JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId
            LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
			LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
			LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
	  AND (SA.StatusId NOT IN (2,3))
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId 
			
  FROM 
            sStudent.vStudentAcademic SA 
            INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
	  AND (SA.StatusId NOT IN(2,3))
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
ELSE
BEGIN
	IF @rRepeatCount=0
	BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId 
			
  FROM 
            sStudent.vStudentAcademic SA
             INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND (ISNULL(SR.SubjectId,0)=@rSubjectId)
			AND (ISNULL(SR.RepeatCount,0)=@rRepeatCount)
		INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			AND SBS.BatchId=@rBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
	  AND (SA.StatusId NOT IN(2,3))
      AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
  ELSE
  BEGIN
	SELECT 
			SA.AcademicId,
			ISNULL(SA.RollNo,0) as RollNo,
			SA.Name,
			SA.Code,
			ISNULL(SR.IsPresent,'true') as IsPresent,
			ISNULL(SR.AbsentReasonId,0) as AbsentReasonId,
			case when SR.CreatedUserId IS NULL then 'false' else 'true' end as IsDeleted,
			SR.RepeatCount,
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			ISNULL(SR.AttendanceTagId,0) AS AttendanceTagId
			
  FROM 
            sStudent.vStudentAcademic SA 
             INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId
        LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
			AND (SR.AttendanceTypeId=@rAttendanceTypeId)
			AND (SR.AttendanceDate=@rAttendanceDate)
			AND ((ISNULL(SR.SubjectId,0)=@rSubjectId) OR (@rSubjectId=0))
			AND ((ISNULL(SR.RepeatCount,0)=@rRepeatCount) OR (@rRepeatCount=0))
		INNER JOIN sAttendance.tSubjectBatchStudent SBS ON SBS.AcademicId=SA.AcademicId 
			AND SBS.BatchId=@rBatchId AND SBS.SubjectBatchId=@rSubjectBatchId
		LEFT JOIN sHrm.vExtEmployeeMaster EM ON EM.EmployeeId=SA.InchargeEmployeeId
  WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
	  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
      AND (SA.OrgId = @rOrgId)
      AND (SA.BatchId = @rBatchID)
	  AND (SA.StatusId NOT IN(2,3))
       AND (AD.LeftDate > @rAttendanceDate OR ISNULL(AD.LeftDate,'')= '')
      AND (AD.AdmissionDate <= @rAttendanceDate)
      ORDER BY RollNo
  END
END
END
GO
PRINT N'Altering [sBiometric].[pBiometricReportDataDateWise]...';


GO
 ALTER PROCEDURE [sBiometric].[pBiometricReportDataDateWise]
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rFromDate Date,
	 @rToDate Date,
	 @rOrgId int,
	 @rOrganizationDepartmentId int=0,
	 @rEmployeeTypeId int =0,
	 @rEmployeeId bigint = 0,
	 @rForYear int=0,
	 @rForMonth int=0,
	 @rIsFirstIn bit=0,
	 @rIsLastOut bit=0,
	 @rIsOT bit=0,
	 @rIsLateBy	bit=0,
	 @rIsEarlyBy bit=0,
	 @rIsDuration  bit=0,
	 @rGradeId nvarchar(200) = '0'
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

DECLARE @TableEmployee TABLE (Id int Identity,EmployeeID BigINT, OrganizationDepartmentId int, EmployeeTypeId Int)
INSERT INTO @TableEmployee
SELECT EM.Id AS EmployeeId,ED.OrganizationDepartmentId,ED.EmployeeTypeId from shrm.tEmployeeMaster EM 
INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = EM.Id 
Where (ED.OrganizationDepartmentId =@rOrganizationDepartmentId Or @rOrganizationDepartmentId= 0 )
AND (ED.EmployeeTypeId = @rEmployeeTypeId OR @rEmployeeTypeId = 0 )
AND  EM.ORgId = @rOrgId AND EM.STatusId = 7



DECLARE @lCount int
DECLARE @lCount1 int
Declare @lQuery nvarchar(Max)
DECLARE @strQuery nvarchar(Max)
DECLARE @lDate date
DECLARE @lDay as nvarchar(3)
DECLARE @lBatchID int
DECLARE @lEmployeeId bigint
DECLARE @lEmpCount int
DECLARE @lEmpDepartmentID int

DECLARE @TempDate TABLE(Id int identity,Idate date)
insert into @TempDate
SELECT  TOP (DATEDIFF(DAY, @rFromDate, @rToDate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @rFromDate)
FROM    sys.all_objects a CROSS JOIN sys.all_objects b;

CREATE TABLE #TempMonthTrans (Id int Identity,EmployeeId bigint,Attn_Date DateTime,DayNumber nvarchar(8),PresentStatus nvarchar(25),
		FirstIn nvarchar(20),LastOut nvarchar(20),OverTime nvarchar(20),LateBy nvarchar(20),Duration nvarchar(20),EarlyBy nvarchar(20))

truncate table #TempMonthTrans

SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1

Select @lCount = Max(Id) from @TempDate
Select @lEmpCount = Max(Id) from @TableEmployee
While (@lEmpCount > 0)
	BEGIN
		SELECT @lEmployeeId = EmployeeId,@lEmpDepartmentID = OrganizationDepartmentId  From @TableEmployee Where Id = @lEmpCount	
	set @lCount1 = 1
	while (@lCount1 <= @lCount)
	begin			
		Select @lDate = Idate from @TempDate Where Id = @lCount1
		Select @lDay  = RIGHT('00' + CAST(DATEPART(dd,@lDate) AS varchar(2)), 2)

		DECLARE @weekoffstatus nvarchar(20)

		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@rEmployeeId , @rForYear ,@rForMonth ,@rDay ,@rBatchId ,@rDepartmentId ,@rOrgId , @rBiometricStatus )
		SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(@lDate)  ,Month(@lDate), @lDay, @lBatchId,@lEmpDepartmentID,@rOrgId,'')

		--SET @weekoffstatus = [sHrm].[fWeekHOffGetBio](@lEmployeeId,Year(''' + convert(nvarchar(15),@lDate) + convert(nvarchar(15),@lEmployeeId) + ', Year(''' + convert(nvarchar(15),@lDate) + '''),Month(''' + convert(nvarchar(15),@lDate) + '''),' + @lDay + ',' + convert(nvarchar(15),@lBatchId) + ',ED.OrganizationDepartmentId,' + convert(nvarchar(15),@rOrgId) + ')


		set @lQuery =  ' INSERT INTO #TempMonthTrans
						SELECT  ' + convert(nvarchar(15),@lEmployeeId) + ',''' + convert(nvarchar(15),@lDate) + ''',
						substring(DATENAME( dw, ''' + convert(nvarchar(15),@lDate) + '''),1,3) AS DN1,
						CAse 
						When ''' +@weekoffstatus +''' in (''H'') AND D'+ convert(nvarchar(15),@lDay) +' <> ''A'' then D'+convert(nvarchar(15),@lDay) +'
						When ''' +@weekoffstatus +''' Not in (''-'',''XX'') 
						Then ''' +@weekoffstatus +''' 
						Else D'+convert(nvarchar(15),@lDay)+' End D'+convert(nvarchar(15),@lDay)+',D'+convert(nvarchar(15),@lDay)+'_IN,D'+convert(nvarchar(15),@lDay)+'_OUT,D'+convert(nvarchar(15),@lDay)+'_O,D'+convert(nvarchar(15),@lDay)+'_L,D'+convert(nvarchar(15),@lDay)+'_T,D'+convert(nvarchar(15),@lDay)+'_E 
						FROM sBiometric.tMonthTrans T1 
						INNER JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = T1.EmployeeId AND (ED.OrganizationDepartmentId ='''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+''' Or '''+CONVERT(nvarchar(15),@rOrganizationDepartmentId)+'''= 0 )
						WHERE T1.EmployeeId =' + convert(nvarchar(15),@lEmployeeId) + ' AND ATTN_DT = cast(rtrim(YEAR(''' + convert(nvarchar(15),@lDate) + ''') *10000+ Month(''' + convert(nvarchar(15),@lDate) + ''') *100+ 01) as datetime) '				
						
		Execute(@lQuery )
		set @lCount1 = @lCount1 + 1
	end
		SET @lEmpCount = @lEmpCount - 1			
	END
	
	SET @strQuery = 'select  Day(T.Attn_Date), T.*,isnull(A.TotAbsent,0) AS TotAbsent,isnull(TotPresent,0) AS TotPresent,A1.TotWeekOff,
	isnull(TotHalfDay,0) AS TotHalfDay,Isnull(TotHoliday,0) AS TotHoliday,isnull(CLLeave,0) AS CLLeave,Isnull(LV.LeaveCode,'''') as LeaveCode1,isnull(LV1.LeaveCode1,'''') AS LeaveCode,
	Emp.Code AS EmpCode,Emp.FirstName +'' '' + Emp.MiddleName +'' ''+ Emp.LastName  AS EmpName,isnull(TotEarly,0) AS TotEarly,
	DM.Displaytitle DeptName,
	' + convert(nvarchar(10),@rIsFirstIn) + ' AS IsFirstIn,
	' + convert(nvarchar(10),@rIsLastOut) + ' AS IsLastOut,
	' +  convert(nvarchar(10),@rIsOT) + ' AS IsOT,
	' +  convert(nvarchar(10),@rIsLateBy) + '	AS IsLateBy,
	' +  convert(nvarchar(10),@rIsEarlyBy) + ' AS IsEarlyBy,
	' +  convert(nvarchar(10),@rIsDuration) + '  AS IsDuration
	from #TempMonthTrans T
	INNER JOIN sHRM.tEmployeeMaster Emp on Emp.Id = T.EmployeeId
	LEFT JOIN sHRM.tEmployeeJobDetail ED ON ED.EmployeeId = Emp.Id 
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = ED.OrganizationDepartmentId
	LEFT JOIN sHRM.tEmployeeDesignationMaster EDM ON EDM.Id = ED.EmployeeDesignationId 
	LEFT Join (Select COUNT(*) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN (''P'',''PW'',''PHW'') group by EmployeeId,PresentStatus) A4 ON A4.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotEarly,EmployeeId from #TempMonthTrans Where PresentStatus IN (''E'') group by EmployeeId,PresentStatus) A6 ON A6.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like ''A'' group by EmployeeId,PresentStatus) A ON A.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus Like ''W'' group by EmployeeId,PresentStatus) A1 ON A1.EmployeeId = T.employeeID
	LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like ''HD'' group by EmployeeId,PresentStatus) A3 ON A3.EmployeeId = T.employeeID
    LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like ''H'' group by EmployeeId,PresentStatus) A5 ON A5.EmployeeId = T.employeeID		
	
	LEFT Join (Select sum(NoOfLeave) AS CLLeave,EmployeeId,LT.Code as LeaveCode from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId 
	Where FromDate>=''' + Convert(nvarchar(12),@rFromDate) + ''' AND FromDate<=''' + Convert(nvarchar(12),@rToDate) + ''' GRoup By EmployeeId,LT.Code ) AS LV ON LV.EmployeeId = T.EmployeeId

	LEFT Join (select   distinct  EmployeeId,
    ISNULL( stuff((
        select Distinct '','' + LT.Code + '':'' + Convert(nvarchar(10),Sum(NoOfLeave)) 
        from shrm.tLeave L inner join shrm.tLeaveTypeMaster LT ON LT.Id=L.LeaveTypeId
        where  (FromDate >= ''' + Convert(nvarchar(12),@rFromDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rFromDate) + ''','''')='''')) 
        AND (ToDate <= ''' + Convert(nvarchar(12),@rToDate) + ''' OR (ISNULL(''' + Convert(nvarchar(12),@rToDate) + ''','''')='''') )
        AND L.EmployeeId = L1.EmployeeId AND L.StatusId= 550
        group by LT.Code
        for xml path('''')
    ),1,1,''''),'''') as LeaveCode1
	from shrm.tLeave L1 
	inner join shrm.tLeaveTypeMaster LT ON LT.Id=L1.LeaveTypeId AND L1.StatusId=550
	group by EmployeeId,LT.Code) AS LV1 ON LV1.EmployeeId = T.EmployeeId 
	WHERE  (len((''' + @rGRadeId + '''))= 1 AND EmployeeGradeId > 0 ) Or
   (len((''' + @rGRadeId + ''')) > 1 AND EmployeeGradeId in(' + convert(nvarchar(100),@rGRadeId) + ')) Order By T.EmployeeId,T.Attn_Date' 
	--WHERE 1=1 and (ED.EmployeeGradeId in (' + convert(nvarchar(100),@rGRadeId) + ') OR (' + convert(nvarchar(100),@rGRadeId) + ') = 0) )' 
	
	execute (@strQuery)
	
	
	

	
	DROP TABLE #TempMonthTrans
	--select  
	--@rBuilder1 as Builder1,
	--@rBuilder2 as Builder2,
	--'' as Attn_Date,
	--'' as EmployeeId,
	--'' as Attn_Date,
	--'' as DayNumber ,
	--'' as PresentStatus ,
	--'' as FirstIn,
	--'' as LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as TotPresent,
	--'' as TotWeekOff,
	--'' as TotHalfDay,
	--'' as TotHoliday,
	--'' AS TotEarly,
	--'' as CLLeave,
	--'' as LeaveCode,
	--'' as EmpCode,
	--'' as EmpName,
	--'' as DeptName,
	--'' as TotAbsent,
	--'' as IsFirstIn,
	--'' as IsLastOut,
	--'' as IsOT,
	--'' as IsLateBy,
	--'' as IsEarlyBy,
	--'' as IsDuration
END
GO
PRINT N'Altering [sBiometric].[pMonthlyPresenceSummaryGet]...';


GO
ALTER PROCEDURE [sBiometric].[pMonthlyPresenceSummaryGet]    
  @rCode nvarchar(20)='',  
  @rForYear int,  
  @rForMonth int,  
  @rOrgId int,
  @rStatusId int = 0,
  @rOrganizationDepartmentId int=0  
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
  
BEGIN   
  
 DECLARE @rFromDate date  
 DECLARE @rToDate date  
   
 SET @rFromDate = CONVERT(date,CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01')  
 SET @rToDate = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rFromDate) + 1, 0))  
   
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 PresentStatus nvarchar(5),  
 LateBy decimal(10,2),  
 Duration decimal(10,2),  
 EarlyBy nvarchar(10),  
 Attn_dt date,  
 FirstIn nvarchar(10)  
 )  
   
 INSERT INTO #TempMonthTrans  
   
 SELECT EmployeeId,D01,Replace(D01_L,':','.'),Replace(D01_T,':','.'),D01_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 1) as datetime),D01_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D02,Replace(D02_L,':','.'),Replace(D02_T,':','.'),D02_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 2) as datetime),D02_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D03,Replace(D03_L,':','.'),Replace(D03_T,':','.'),D03_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 3) as datetime),D03_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D04,Replace(D04_L,':','.'),Replace(D04_T,':','.'),D04_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 4) as datetime),D04_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D05,Replace(D05_L,':','.'),Replace(D05_T,':','.'),D05_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 5) as datetime),D05_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D06,Replace(D06_L,':','.'),Replace(D06_T,':','.'),D06_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 6) as datetime),D06_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D07,Replace(D07_L,':','.'),Replace(D07_T,':','.'),D07_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 7) as datetime),D07_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D08,Replace(D08_L,':','.'),Replace(D08_T,':','.'),D08_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 8) as datetime),D08_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D09,Replace(D09_L,':','.'),Replace(D09_T,':','.'),D09_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 9) as datetime),D09_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D10,Replace(D10_L,':','.'),Replace(D10_T,':','.'),D10_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),D10_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D11,Replace(D11_L,':','.'),Replace(D11_T,':','.'),D11_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),D11_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D12,Replace(D12_L,':','.'),Replace(D12_T,':','.'),D12_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),D12_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D13,Replace(D13_L,':','.'),Replace(D13_T,':','.'),D13_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),D13_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D14,Replace(D14_L,':','.'),Replace(D14_T,':','.'),D14_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),D14_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D15,Replace(D15_L,':','.'),Replace(D15_T,':','.'),D15_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),D15_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D16,Replace(D16_L,':','.'),Replace(D16_T,':','.'),D16_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),D16_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D17,Replace(D17_L,':','.'),Replace(D17_T,':','.'),D17_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),D17_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D18,Replace(D18_L,':','.'),Replace(D18_T,':','.'),D18_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),D18_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D19,Replace(D19_L,':','.'),Replace(D19_T,':','.'),D19_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),D19_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D20,Replace(D20_L,':','.'),Replace(D20_T,':','.'),D20_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),D20_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D21,Replace(D21_L,':','.'),Replace(D21_T,':','.'),D21_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),D21_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D22,Replace(D22_L,':','.'),Replace(D22_T,':','.'),D22_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),D22_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D23,Replace(D23_L,':','.'),Replace(D23_T,':','.'),D23_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),D23_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D24,Replace(D24_L,':','.'),Replace(D24_T,':','.'),D24_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),D24_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D25,Replace(D25_L,':','.'),Replace(D25_T,':','.'),D25_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),D25_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D26,Replace(D26_L,':','.'),Replace(D26_T,':','.'),D26_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),D26_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D27,Replace(D27_L,':','.'),Replace(D27_T,':','.'),D27_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),D27_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 UNION ALL  
 SELECT EmployeeId,D28,Replace(D28_L,':','.'),Replace(D28_T,':','.'),D28_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),D28_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
  
 IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2))   
 BEGIN  
  INSERT INTO #TempMonthTrans  
  SELECT EmployeeId,D29,Replace(D29_L,':','.'),Replace(D29_T,':','.'),D29_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29_IN FROM sBiometric.tMonthTrans WHERE 1=1   
  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 END  
   
 IF Month(@rFromDate) <> 2  
 BEGIN  
 INSERT INTO #TempMonthTrans  
 SELECT EmployeeId,D30,Replace(D30_L,':','.'),Replace(D30_T,':','.'),D30_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 END  
   
 IF Month(@rFromDate) NOT IN (2,4,6,9,11)  
 BEGIN  
 INSERT INTO #TempMonthTrans  
 SELECT EmployeeId,D31,Replace(D31_L,':','.'),Replace(D31_T,':','.'),D31_E,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31_IN FROM sBiometric.tMonthTrans WHERE 1=1   
 AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  
 END  
   
  --select * from #TempMonthTrans Where EmployeeID = 9901000000065
   
 DECLARE @lAttendanceDate AS nvarchar(20)  
 SET @lAttendanceDate = CONVERT(nvarchar(10), @rForYear) + '-' + CONVERT(nvarchar(10), @rForMonth) + '-' + '01'  
  
 DECLARE @lOrgGroupId int=0  
 SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId  
    
 DECLARE @lItemValue nvarchar(20) = ''  
 SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END  
 FROM sConfig.tConfigurationMaster CM  
 LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId  
 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 204  
  
 DECLARE @lItemValue1 nvarchar(20) = ''  
 SELECT @lItemValue1 = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END  
 FROM sConfig.tConfigurationMaster CM  
 LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId  
 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 227   
  
  --select * from #TempMonthTrans  
  --return

          
     --select convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1)),Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4))-0.05
  

 SELECT  
      
	ROW_NUMBER() OVER (ORDER BY EM.Code ASC) AS SrNo,  
	EM.Code,  
	EM.FirstName + ' ' + EM.Lastname AS Name,       

	DATEDIFF(dd, @rFromDate, @rToDate)+1 as WorkingDay,


	case When (Tot_Abs - Isnull(A1.LateStatus,0)*.5 - isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0))> 0 then
	Tot_Abs - Isnull(A1.LateStatus,0)*.5 - isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0)
	else 0 end    AS NoPunch, --     

	Isnull(LWP.NoOfLeave,0) AS CL,  
	Isnull(LWP1.NoofLeave,0) AS LWPLeave,

	Case When (Tot_Abs -Isnull(A1.LateStatus,0)*.5- isnull(A4.AbsentStatusApr,0)  - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0) - isnull(LWP.NoofLeave,0) - isnull(A3.LateStatusApr,0) * 0.5) >0 then
	Tot_Abs - isnull(A4.AbsentStatusApr,0) - Isnull(A1.LateStatus,0)*.5 - isnull(A5.HDStatusApr,0) * 0.5  - isnull(LHApproved.LHCount,0) - isnull(LWP.NoofLeave,0) -- isnull(A3.LateStatusApr,0) * 0.5
	else 0 end 	AS LeaveNotApply,

	Isnull(Comp.Compoff,0) AS CompOff,   

	ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans  
	UNPIVOT  
	(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT  
	WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS DinnerAllowance,  

	Count_Late - ISNULL(LateValidCount.LateValid,0) - ISNULL(LateCountAprooved.LateAprooved,0) AS Late,  

	Isnull(Late1030Count.Late1030Count,0)   - ISNULL(LateValid1030Count.LateValid1030Count,0) - isnull(Late1030CountAprooved.Late1030CountAprooved,0) AS Grt1030Cnt,


	sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_OT) + sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':'))) AS Tot_OT,   



	Isnull(Valid_Cnt.Vstatuscount,0) AS Valid_Cnt,  
	sBiometric.fcalcHour(ISNULL(InvalidHrs.InvalidHrs,0))  AS InvalidHrs,     
	sBiometric.fcalcHour(sBiometric.fcalcMINI(Tot_OT) + sBiometric.fcalcMINI(replace(ISNULL(LHApproved.LHHrs,0.0),'.',':')) - ISNULL(InvalidHrs.InvalidHrs,0)) AS Tot_OT_IVH,   

	CASE When (convert(decimal(5,2),(Isnull(Valid_Cnt.Vstatuscount,0) + Isnull(InValid_Cnt.Vstatuscount,0) + ISNULL(LateStatusApr,0) + ISNULL(ELValidApproveCount,0)))) >  0
	Then
	Convert(decimal(5,2),     convert(decimal(5,2),(Isnull(MT.Tot_PL,0)+Isnull(MT.Tot_ML,0)))
	/(convert(decimal(5,2),(Isnull(Valid_Cnt.Vstatuscount,0) + Isnull(InValid_Cnt.Vstatuscount,0) + ISNULL(LateStatusApr,0) + ISNULL(ELValidApproveCount,0))))  
	) else 0 end AS MonthlyPunchAvg, --INModeCount,  
	ISNULL(PunchCnt.PunchCnt,0) AS Gt8PunchCnt,  
	ISNULL(EC.CompanyEmail,'')+','+ISNULL(vEM.CompanyEmail,'') AS CompanyEmail  

 FROM   
  sBiometric.tMonthTrans MT  
  right JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt = @lAttendanceDate  
  LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id  
  LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id    
  LEFT JOIN sHrm.vEmployeeCommonDetail vEM  ON  vEM.EmployeeId = EJD.EmployeeManagerId   
    
  LEFT Join  
  (  
   SELECT ISNULL(SUM(NoOfLeave),0) NoOfLeave,L.EmployeeId FROM sHrm.tLeaveTypeMaster Lt   
   inner join sHrm.tLeave L ON L.LeaveTypeId = LT.Id AND LT.IsLWP =  0  
   --inner jOIN #TempMonthTrans TT on L.EmployeeId = TT.EmployeeId   
   --AND TT.PresentStatus NOT IN ('W','PW')   
   WHERE 1=1  --StatusId=550 --AND TT.attn_dt = L.FromDate  
   AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)) 
   AND StatusID <> 551
   Group By L.EmployeeId  
  )LWP ON LWP.EmployeeId = EM.ID  
    LEFT Join  
  (  
   SELECT ISNULL(SUM(NoOfLeave),0) NoOfLeave,L.EmployeeId FROM sHrm.tLeaveTypeMaster Lt   
   inner join sHrm.tLeave L ON L.LeaveTypeId = LT.Id AND LT.IsLWP =  1  
   WHERE StatusId=550 --AND TT.attn_dt = L.FromDate  
   AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))  
   Group By L.EmployeeId  
  )LWP1 ON LWP1.EmployeeId = EM.ID  
    
  LEFT JOIN  -- early or first half day early   
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid  
      From sBiometric.tMonthTrans MT  
   leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.PresentStatus ='HD' AND TT.LateBy > '4.0')  
   Or (TT.LateBy > 0.30))      
   where MT.attn_dt = @lAttendanceDate  
   GRoup By TT.EmployeeId  
  )LateValidCount ON LateValidCount.EmployeeId = MT.EmployeeId  
    
  LEFT JOIN  -- Late Approve entry count Less then 30 min late  
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateAprooved  
      From sBiometric.tMonthTrans MT  
   INNER JOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.LateBy <= 0.30 AND TT.LateBy > 0   
   INNER JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TT.EmployeeId AND ELS.StatusId = 550   
   --and ELS.LateStatus='V'  
   AND CONVERT(DATE,ELS.LateDate) = TT.Attn_Dt  
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LateCountAprooved ON LateCountAprooved.EmployeeId = MT.EmployeeId  
      
  LEFT JOIN  -- early or first half day early   
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid,0 AS EarlyBy,  --  
    sum(sBiometric.fcalcMINI(Replace(Isnull(Tt.lATEbY,0.0),'.',':'))) AS LateBy  
       From  
   sBiometric.tMonthTrans MT  
   INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.PresentStatus ='HD' AND TT.LateBy > '4.0')  
   Or (TT.LateBy > 0.30)) AND TT.PresentStatus <> 'E' AND TT.PresentStatus <> 'PW'   --AND TT.Duration <9.15  
     
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LateValid ON LateValid.EmployeeId = MT.EmployeeId  
  LEFT JOIN  -- Duration <= 9.15  AND Late <= 30  
  ( Select TT.EmployeeID, 0  AS LateBy   --  SUM(sBiometric.fcalcMINI(Replace(Isnull(Tt.lATEbY,0.0),'.',':')))  
      From sBiometric.tMonthTrans MT  
   INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId    
   AND TT.LateBy <= 0.30    
   AND TT.Duration < 9.30 WHERE MT.attn_dt = @lAttendanceDate AND TT.PresentStatus <> 'LH'   
   GRoup By TT.EmployeeId  
  )ELLateValid ON ELLateValid.EmployeeId = MT.EmployeeId  
  LEFT JOIN  -- Late arrive and attain full day > 9.15  
  ( Select TT.EmployeeID, sum(sBiometric.fcalcMINI(isnull(Replace(TT.LateBy,'.',':'),'0:0'))) AS LateBy From  
   sBiometric.tMonthTrans MT  
   leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND (TT.PresentStatus ='HD' AND TT.LateBy <= 0.30   
   AND TT.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))  
   AND TT.Duration <= Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4)))     
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LateNotEL ON LateNotEL.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- Half Day Early  
  ( Select TT.EmployeeID, sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS EarlyBy From  
   sBiometric.tMonthTrans MT  
   inner jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId    
   AND (((TT.PresentStatus ='HD' AND convert(decimal(10,2),Replace(TT.Duration,':','.')) > 4.0 AND convert(decimal(10,2),Replace(TT.Duration,':','.')) < 6.30)) Or TT.PresentStatus  in ('E') )  
   AND TT.Attn_Dt Not in (Select Latedate from sBiometric.tEmployeeLateStatus Where StatusId <> 550 AND LateStatus='EL' AND EmployeeId=MT.EmployeeId )  
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LateValid1 ON LateValid1.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- Less Hour  
  ( Select TT.EmployeeID, Count(TT.EmployeeID) LHCount, sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS EarlyBy ,sum(isnull(TT.Duration,0)) AS LHHrs From  
   sBiometric.tMonthTrans MT  
   inner jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus ='LH'   
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )LH ON LH.EmployeeId = MT.EmployeeId  

  LEFT JOIN -- Less Hour Approved  
  (   
  Select MT.EmployeeID, Count(MT.EmployeeID) LHCount,sBiometric.fcalcHour(sum(sBiometric.fcalcMINI(Replace(ISNULL(TT.Duration,0),'.',':'))))  
  AS LHHrs  From  sBiometric.tMonthTrans MT  
   INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus ='LH'   
   where MT.attn_dt = @lAttendanceDate AND  TT.Attn_DT   
   IN (select LateDate from sBiometric.tEmployeeLateStatus Where StatusId = 550 AND LateStatus='LH' AND EmployeeId=MT.EmployeeId )  
   GRoup By MT.EmployeeId  
  )LHApproved ON LHApproved.EmployeeId = MT.EmployeeId  

  Left Join (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) as LHCount FROM sBiometric.tEmployeeLateStatus ELS1  
  WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) AND ELS1.StatusId = 550  AND ElS1.LateStatus = 'LH'  
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS1.EmployeeId  
  )LHCountApproved ON LHCountApproved.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- PW  
  ( Select TT.EmployeeID,sum(sBiometric.fcalcMINI(isnull(TT.EarlyBy,'0:0'))) AS PWHrs From  
   sBiometric.tMonthTrans MT  
   leFT jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND TT.PresentStatus like '%PW%'   
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )PW ON PW.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- Aproved EL Time  
  (  
  SELECT   
  sBiometric.fcalcHour(sum(case when TM.LateBy <=0.30 then sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))-TM.lateBy*100  
  else sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))end ))  
  AS EarlyHrs,ELS.EmployeeId   
  FROM sBiometric.tEmployeeLateStatus ELS   
  INNER JOIN #TempMonthTrans TM ON TM.EmployeeId = ELS.EmployeeId and TM.ATTN_DT = ELS.LateDate AND (TM.LateBy >.30 OR TM.EarlyBy <> '00:00' )  
  WHERE ELS.StatusId = 550 AND ELS.LateStatus <> 'HD' AND ELS.LateStatus <> 'LH' AND ELS.LateStatus <> 'V' AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)     AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS.EmployeeId  
  ) A ON A.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- Aproved EL Time  
  (  
  SELECT sum(sBiometric.fcalcMINI(Replace(ISNULL(ELS.EarlyHrs,0),'.',':'))) AS EarlyLateMin,ELS.EmployeeId ,COUNT(ELS.EmployeeId ) VstatusLatecount  
  FROM sBiometric.tEmployeeLateStatus ELS   
  INNER JOIN #TempMonthTrans TM ON TM.EmployeeId = ELS.EmployeeId and TM.ATTN_DT = ELS.LateDate   
  AND (TM.LateBy >.30 OR sBiometric.fcalcMINI(isnull(TM.EarlyBy,'0:0')) > 0  )  
  WHERE ELS.StatusId = 550 AND ELS.LateStatus = 'V' AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS.EmployeeId  
  ) V_Status ON V_Status.EMployeeId = MT.EMployeeId   
  LEFT JOIN  -- EL Approved Count  
  (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS LateStatusApr FROM sBiometric.tEmployeeLateStatus ELS1  
  LEFT JOIN sHRM.tLeave L on L.EmployeeId = ELS1.EmployeeId AND L.LeavePeriodId = 2   
  AND L.StatusId = 550   
  AND L.FromDate = ELS1.LateDate   
  WHERE ELS1.StatusId = 550 AND L.Id IS NULL and  (LateStatus = 'EL') AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)  
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS1.EmployeeId  
  )A3 ON A3.EMployeeId = MT.EMployeeId   
  LEFT JOIN  -- EL Approved Count  
  (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS ELValidApproveCount FROM sBiometric.tEmployeeLateStatus ELS1  
  INNER JOIN sHRM.tLeave L on L.EmployeeId = ELS1.EmployeeId AND L.LeavePeriodId = 1   
  AND L.StatusId = 550   
  AND L.FromDate = ELS1.LateDate   
  WHERE ELS1.StatusId = 550 AND L.Id IS NULL and  (LateStatus = 'V') AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)  
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS1.EmployeeId  
  )ELValidApproveCount ON ELValidApproveCount.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- EL Entry AND Approved  Absent Case  
  (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS AbsentStatusApr FROM sBiometric.tEmployeeLateStatus ELS1  
  INNER JOIN #TempMonthTrans TM ON TM.EmployeeId = ELS1.EmployeeId   
  AND ELS1.StatusId = 550  AND ELS1.LateDate = TM.Attn_dt  
  WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)  
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND ELS1.LateStatus IN ( 'A','E')  
  GROUP BY ELS1.EmployeeId  
  )A4 ON A4.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- EL Entry AND Approved  HD Case  
  (  
  SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS HDStatusApr FROM sBiometric.tEmployeeLateStatus ELS1  
  WHERE CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate) AND ELS1.StatusId = 550  AND (ElS1.LateStatus IN ('HD','EL','L'))  -- OR ElS1.LateStatus = 'EL' -- Additional
  AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  GROUP BY ELS1.EmployeeId  
  )A5 ON A5.EMployeeId = MT.EMployeeId  
  Left Join -- EL Case   
  (  
  SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS LateStatus FROM #TempMonthTrans TM  
  WHERE 1=1   
  AND TM.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))  
  AND TM.Duration < 9.30 --Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4)) ---0.05 
  AND TM.PresentStatus not like '%PW%' AND ( PresentStatus IN ('HD'))   --sBiometric.fcalcMINI(TM.FirstIn) < 720 AND
  AND TM.EmployeeID Not in (Select EmployeeId from sHrm.tLeave L Inner join sHRM.tLeaveTypeMaster LM ON LM.Id =L.LeaveTypeID Where FromDate=Tm.Attn_dt AND L.StatusID = 550 aND LM.ISLWP=0)
  AND TM.EmployeeID Not in (Select EmployeeId FRom sBiometric.tEmployeeLateStatus ELS Where ELS.LateDate=Tm.Attn_dt AND ELS.StatusId = 550)
  GROUP BY TM.EmployeeId  
  )A1 ON A1.EMployeeId = MT.EMployeeId   
  LEFT JOIN  
  (    
  SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS TotalLate FROM #TempMonthTrans TM  
  LEFT JOIN sHRM.tLeave L on L.EmployeeId = TM.EmployeeId AND L.LeavePeriodId = 2   
  AND L.StatusId = 550   
  AND L.FromDate = TM.Attn_dt   
  WHERE 1=1 AND L.Id IS NULL  AND sBiometric.fcalcMINI(TM.FirstIn) < 720  AND (TM.LateBy > 0.30 or TM.EarlyBy <> '00:00')  
  AND TM.Duration >= convert(decimal(10,2),SUBSTRING(@lItemValue1,1,CHARINDEX ( ';',@lItemValue1)-1))  
  AND TM.Duration <= Convert(decimal(10,2),SUBSTRING(@lItemValue1,CHARINDEX (';',@lItemValue1)+1,4)) 
  GROUP BY TM.EmployeeId  
  )A2 ON A2.EMployeeId = MT.EMployeeId   
  LEFT JOIN  
  (    
  SELECT TM.EmployeeId,COUNT(TM.EmployeeId) AS ELValidCount FROM #TempMonthTrans TM  
  INNER JOIN sHRM.tLeave L on L.EmployeeId = TM.EmployeeId AND L.LeavePeriodId = 1   
  AND L.StatusId = 550   
  AND L.FromDate = TM.Attn_dt   
  WHERE 1=1 AND L.Id IS NULL  AND  (TM.LateBy > 0.30 or TM.EarlyBy <> '00:00')  
  GROUP BY TM.EmployeeId  
  ) ELValidCount ON ELValidCount.EMployeeId = MT.EMployeeId   
  LEFT Join  
  (  
  select Sum(isnull(AddRequestBalance,0)) AS Compoff,LV.EmployeeId from shrm.tLeaveBalanceAddRequest LV  
  inner join sHrm.tLeaveTypeMaster LT ON LV.LeaveTypeId=LT.Id AND MainLeaveTypeId = 3 AND ReportDate >= CONVERT(DATE,@lAttendanceDate)  
  AND ReportDate <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND LV.StatusId = 550  
  GRoup by LV.EmployeeId  
  )Comp ON Comp.EmployeeId = MT.EMployeeId   
  LEFT JOIN  -- EL and Late   
  ( Select TT.EmployeeID,sum(sBiometric.fcalcMINI(Replace(Isnull(Tt.LateBy,0.0),'.',':'))) AS LateBy  
       From sBiometric.tMonthTrans MT         
   INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  and TT.LateBy > 0.30  
   --AND ((TT.PresentStatus ='HD' AND TT.Duration > '6.15')  
   AND (TT.PresentStatus IN ('EL','V','P')  
   OR (TT.PresentStatus ='HD' AND TT.LateBy < 2.30)  
   )  
   AND TT.LateBy > 0   
   LEFT JOIN sBiometric.tEmployeeLateStatus ELS1  ON TT.EmployeeId = ELS1.EmployeeId   
     
   AND ELS1.LateDate = TT.Attn_dt  
   and CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@lAttendanceDate)   
   AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
   where MT.attn_dt = @lAttendanceDate AND ISNULL(ELS1.StatusId,0) <> 550    
   GRoup By TT.EmployeeId  
  )LateEL ON LateEL.EmployeeId = MT.EmployeeId  
  LEFT JOIN -- Aproved EL Time  
  (  
  SELECT COUNT(TM.EmployeeId ) VstatusLatecount,EMployeeId  
  FROM #TempMonthTrans TM   
  WHERE (TM.LateBy >.30 OR sBiometric.fcalcMINI(isnull(TM.EarlyBy,'0:0')) > 0  ) AND TM.Duration >= 9.30   
  GROUP BY TM.EmployeeId  
  ) V_StatusApprove ON V_StatusApprove.EMployeeId = MT.EMployeeId AND MT.attn_dt = @lAttendanceDate    
   
     LEFT JOIN -- Valid Count  
  (  
  SELECT TM.EmployeeId ,COUNT(TM.EmployeeId ) Vstatuscount  
  FROM  #TempMonthTrans TM   
  WHERE CONVERT(DATE,TM.Attn_dt)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,TM.Attn_dt) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND TM.Duration >= 9.30   
  GROUP BY TM.EmployeeId  
  ) Valid_Cnt ON Valid_Cnt.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- InValid Count  
  (  
  SELECT TM.EmployeeId ,COUNT(TM.EmployeeId ) Vstatuscount  
  FROM  #TempMonthTrans TM   
  WHERE CONVERT(DATE,TM.Attn_dt)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,TM.Attn_dt) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND TM.Duration < 9.30 AND TM.PresentStatus Not in ('A','W','XX','H','WH','LH')  
  AND   
   ( TM.Attn_dt NOT IN   
   (SELECT FromDate FRom sHRM.tLeave L Where L.EmployeeId=TM.EmployeeId AND L.StatusId = 550  
   AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
   AND  
   TM.Attn_dt NOT IN   
   (SELECT LateDate FRom sBiometric.tEmployeeLateStatus ELS Where ELS.EmployeeId=TM.EmployeeId AND ELS.StatusId = 550  
    AND CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)   
   AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))))  
   )   
  GROUP BY TM.EmployeeId  
  ) InValid_Cnt ON InValid_Cnt.EMployeeId = MT.EMployeeId   
  LEFT JOIN -- WeekOff Holiday Count  
  (  
  SELECT TM.EmployeeId ,COUNT(TM.EmployeeId ) WeekHolidayCount  
  FROM  #TempMonthTrans TM   
  WHERE CONVERT(DATE,TM.Attn_dt)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,TM.Attn_dt) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND TM.PresentStatus in ('H','W','PW','PWH')  
  GROUP BY TM.EmployeeId  
  ) WeekHolidayCount ON WeekHolidayCount.EMployeeId = MT.EMployeeId  
    
  LEFT JOIN -- Invalid Hrs Count  
  (  
  SELECT TM.EmployeeId ,sum(570 - sBiometric.fcalcMINI(replace(TM.Duration,'.',':')))  AS  InvalidHrs  
  FROM  #TempMonthTrans TM     
  WHERE CONVERT(DATE,TM.Attn_dt)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,TM.Attn_dt) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND TM.Duration < 9.30 AND TM.Duration > 0 --AND TM.PresentStatus in ('HD') --('A','W','XX','H','WH','PW','LH')  
  AND   
  ( TM.Attn_dt NOT IN   
  (SELECT FromDate FRom sHRM.tLeave L Where L.EmployeeId=TM.EmployeeId AND L.StatusId = 550  
  AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0)))  
  AND  
  TM.Attn_dt NOT IN   
  (SELECT LateDate FRom sBiometric.tEmployeeLateStatus ELS Where ELS.EmployeeId=TM.EmployeeId AND ELS.StatusId = 550  
   AND CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@lAttendanceDate)   
  AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))))  
  )  
  AND TM.PresentStatus NOT IN ('A','H','PW','PWH')  
    
  GROUP BY TM.EmployeeId  
  ) InvalidHrs ON InvalidHrs.EMployeeId = MT.EMployeeId   
    
  LEft Join  
  (select distinct SourceId,COUNT(cnt) AS PunchCnt From (  
   select SourceId,Count(Attn_dt) AS cnt from sBiometric.tPunchCount Group by SourceId,Attn_dt having sum(Incnt+OutCnt)>8  
   AND month(Attn_dt)=@rForMonth AND YEAR(Attn_dt)=@rForYear   
   ) A   
   group by A.SourceId)PunchCnt ON  PunchCnt.SourceId = MT.EMployeeId
   
   
   LEFT JOIN  -- >10.30 Count  
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS Late1030Count  
      From sBiometric.tMonthTrans MT  
   INNER JOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId     
   where MT.attn_dt = @lAttendanceDate   AND sBiometric.fcalcMINI(TT.FirstIn) > 630
   GRoup By TT.EmployeeId  
  )Late1030Count ON Late1030Count.EmployeeId = MT.EmployeeId 
      
  LEFT JOIN  -- Late Approve entry count Less then 30 min late  
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS Late1030CountAprooved  
      From sBiometric.tMonthTrans MT  
   INNER JOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND sBiometric.fcalcMINI(TT.FirstIn) > 630
   INNER JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TT.EmployeeId AND ELS.StatusId = 550   
   AND CONVERT(DATE,ELS.LateDate) = TT.Attn_Dt  
   where MT.attn_dt = @lAttendanceDate   
   GRoup By TT.EmployeeId  
  )Late1030CountAprooved ON Late1030CountAprooved.EmployeeId = MT.EmployeeId  

  LEFT JOIN  -- early or first half day early   
  ( Select TT.EmployeeID, Count(ISNULL(TT.EmployeeId,0)) AS LateValid1030Count  
      From sBiometric.tMonthTrans MT  
	  INNER JOIN sHRM.tLeave L on L.EmployeeId = MT.EmployeeId AND L.StatusId = 550
      INNER jOIN #TempMonthTrans TT on MT.EmployeeId = TT.EmployeeId  AND ((TT.PresentStatus ='HD' AND TT.LateBy > '4.0')  
	   AND L.FromDate = TT.Attn_Dt
      AND FromDATE BETWEEN CONVERT(DATE,@lAttendanceDate) AND DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @lAttendanceDate) + 1, 0))
  )      
   where MT.attn_dt = @lAttendanceDate  
   GRoup By TT.EmployeeId  
  )LateValid1030Count ON LateValid1030Count.EmployeeId = MT.EmployeeId  
     

   WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '') and (isnull(EJD.dateofleaving,'') ='' or EJD.dateofleaving  > @lAttendanceDate)  
   AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
   AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0)) 
--   AND EM.Code not in (1101,1102,1106,1107)
   ORDER BY EM.Code  


 TRUNCATE TABLE #TempMonthTrans  
END  
--select * from #TempMonthTrans  
GO
PRINT N'Altering [sBiometric].[pTimeSheetListGet]...';


GO
ALTER PROCEDURE [sBiometric].[pTimeSheetListGet]
  @rEmployeeId bigint=0,  
  @rFromDate Date,  
  @rToDate Date,  
  @rStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rEmployeeName nvarchar(50) = '',
  @rStatusId int = 0,
  @rOrganizationDepartmentId int=0
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN   
  
 CREATE TABLE #TempMonthTrans  
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20)  
 )  
   
 INSERT INTO #TempMonthTrans  
   
 	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	UNION ALL

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

	IF  Month(@rFromDate) <> 2 or (((YEAR(@rFromDate) % 4 = 0 AND YEAR(@rFromDate) % 100 <> 0) OR YEAR(@rFromDate) % 400 = 0 And Month(@rFromDate)  =2)) 
	BEGIN
		INSERT INTO #TempMonthTrans
		SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 31) as datetime),D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E FROM sBiometric.tMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	END
	
	


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


GO
ALTER PROCEDURE [sBiometric].[pYearlyPresenceSUMmaryGet]
	 
	 @rCode nvarchar(20)='',
	 @rOrgId int,
	 @rFromDate date,
	 @rToDate date,
	 @rIsMonthly bit=0,
	 @rStatusId int = 0,
	 @rOrganizationDepartmentId int=0 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	 
	DECLARE @lOrgGroupId int=0
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
		
	DECLARE @lItemValue nvarchar(20) = ''
	SELECT @lItemValue = CASE WHEN CS.Id IS NOT NULL THEN ISNULL(CS.ItemValue,'') ELSE ISNULL(CM.ItemValue,'') END
	FROM sConfig.tConfigurationMaster CM
	LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId
	AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId WHERE CM.Id = 204


	IF(@rIsMonthly = 1)
	BEGIN
		SELECT
			ROW_NUMBER() OVER (ORDER BY Code ASC) AS SrNo,
			EM.Code,
			EM.FirstName + ' ' + EM.Lastname AS Name,
			CONVERT(nvarchar(20), DATENAME(MONTH,(MT.attn_dt))) +' - '+ CONVERT(nvarchar(10),YEAR(MT.attn_dt)) AS MonthYear,
			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS DinnerAllowance,

			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01, d02, d03, d04, d05, d06, d07, d08, d09, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19, d20, d21, d22, d23, d24, d25, d26, d27, d28, d29, d30, d31)) PT
			WHERE value LIKE 'PW' AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS CompOff,

			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) + ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),Replace(value,':','.'))) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT 
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0)) AS EarlyLeave,

			SUM(CONVERT(float,REPLACE(Tot_OT,':','.'))) AS Tot_OT,		

			CASE WHEN (SUM(CONVERT(decimal(10,2),REPLACE(Tot_OT,':','.'))) - CONVERT(decimal(10,2),REPLACE((
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.'))) > 0 Then 
			Convert(nvarchar(20),SUM(Convert(decimal(10,2),Replace(Tot_OT,':','.'))) - Convert(decimal(10,2),Replace((
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.')))
		
			ELSE

			'-' + Convert(nvarchar(10),Convert(decimal(10,2),Replace(
			(
			SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			Replace(value,':','.')
			)) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			),':','.')) - SUM(Convert(decimal(10,2),Replace(Tot_OT,':','.'))))
			END	AS Tot_OT_EL,
		
			CONVERT(nvarchar(20), DATENAME(MONTH,(MT.attn_dt))) +' - '+ CONVERT(nvarchar(10),YEAR(MT.attn_dt)) AS MonthYear,
			ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			UNPIVOT
			(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
			WHERE CONVERT(FLOAT,REPLACE(value,':','.')) > 09.15 AND CONVERT(FLOAT,REPLACE(value,':','.')) <= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS OT_DinnerAllowance
		FROM 
			sBiometric.tMonthTrans MT
			INNER JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt >= @rFromDate  AND MT.attn_dt <= @rToDate
			LEFT JOIN
			(
			SELECT SUM(ISNULL(ELS.EarlyHrs,0)) AS EarlyHrs,ELS.EmployeeId FROM sBiometric.tEmployeeLateStatus ELS 
			WHERE ELS.StatusId = 550 AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS.EmployeeId
			) A ON A.EMployeeId = MT.EMployeeId 
			LEFT JOIN
			(
			SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS LateStatus FROM sBiometric.tEmployeeLateStatus ELS1 
			WHERE ELS1.StatusId = 550 AND LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS1.EmployeeId
			) A1 ON A1.EMployeeId = MT.EMployeeId 
			LEFT JOIN
			(
			SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS TotalLate FROM sBiometric.tEmployeeLateStatus ELS1 
			WHERE LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS1.EmployeeId
			) A2 ON A2.EMployeeId = MT.EMployeeId 
	
		WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '')
		GROUP BY EM.Id,EM.Code,EM.FirstName,EM.Lastname,MT.attn_dt,A1.LateStatus
		ORDER BY EM.Code
	END

	ELSE

	BEGIN
		DECLARE @lYearlyPresence TABLE(Code nvarchar(20),Name nvarchar(100),DinnerAllowance decimal(8,2),CompOff decimal(8,2), EarlyLeave decimal(8,2),	Total_OT decimal(8,2),Total_OT_EL decimal(8,2),OT_DinnerAllowance decimal(8,2))

		--INSERT INTO @lYearlyPresence
		SELECT
			EM.Code,
			EM.FirstName + ' ' + EM.Lastname AS Name,
			--ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			--UNPIVOT
			--(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
			--WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS DinnerAllowance,
			0  AS DinnerAllowance,
			--ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			--UNPIVOT
			--(value FOR col IN (d01, d02, d03, d04, d05, d06, d07, d08, d09, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19, d20, d21, d22, d23, d24, d25, d26, d27, d28, d29, d30, d31)) PT
			--WHERE value LIKE 'PW' AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS CompOff,
			0  AS CompOff,
			0 as EarlyLeave,
			--SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) + ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),Replace(value,':','.'))) FROM sBiometric.tMonthTrans
			--UNPIVOT
			--(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT 
			--WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0)) AS EarlyLeave,

			----SUM(CONVERT(float,REPLACE(Tot_OT,':','.'))) AS Tot_OT,		
			0 AS Tot_OT,
			0 as Tot_OT_EL,
			
			--CASE WHEN (SUM(CONVERT(decimal(10,2),REPLACE(Tot_OT,':','.'))) - CONVERT(decimal(10,2),REPLACE((
			--SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			--ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			--Replace(value,':','.')
			--)) FROM sBiometric.tMonthTrans
			--UNPIVOT
			--(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			--WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			--),':','.'))) > 0 Then 
			--Convert(nvarchar(20),SUM(Convert(decimal(10,2),Replace(Tot_OT,':','.'))) - Convert(decimal(10,2),Replace((
			--SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			--ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			--Replace(value,':','.')
			--)) FROM sBiometric.tMonthTrans
			--UNPIVOT
			--(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			--WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			--),':','.')))
		
			--ELSE

			--'-' + Convert(nvarchar(10),Convert(decimal(10,2),Replace(
			--(
			--SUM(CONVERT(FLOAT,REPLACE(Tot_Early,':','.'))) +
			--ISNULL((SELECT SUM(CONVERT(DECIMAL(10,2),
			--Replace(value,':','.')
			--)) FROM sBiometric.tMonthTrans
			--UNPIVOT
			--(value FOR col IN (d01_l, d02_l, d03_l, d04_l, d05_l, d06_l, d07_l, d08_l, d09_l, d10_l, d11_l, d12_l, d13_l, d14_l, d15_l, d16_l, d17_l, d18_l, d19_l, d20_l, d21_l, d22_l, d23_l, d24_l, d25_l, d26_l, d27_l, d28_l, d29_l, d30_l, d31_l)) PT
			--WHERE CONVERT(FLOAT,REPLACE(value,':','.')) >= CONVERT(FLOAT,REPLACE('00:30',':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) - SUM(ISNULL(A.EarlyHrs,0))
			--),':','.')) - SUM(Convert(decimal(10,2),Replace(Tot_OT,':','.'))))
			--END	AS Tot_OT_EL,
			0 AS OT_DinnerAllowance
			--ISNULL((SELECT COUNT(value) FROM sBiometric.tMonthTrans
			--UNPIVOT
			--(value FOR col IN (d01_t, d02_t, d03_t, d04_t, d05_t, d06_t, d07_t, d08_t, d09_t, d10_t, d11_t, d12_t, d13_t, d14_t, d15_t, d16_t, d17_t, d18_t, d19_t, d20_t, d21_t, d22_t, d23_t, d24_t, d25_t, d26_t, d27_t, d28_t, d29_t, d30_t, d31_t)) PT
			--WHERE CONVERT(FLOAT,REPLACE(value,':','.')) > 09.15  AND CONVERT(FLOAT,REPLACE(value,':','.')) <= CONVERT(FLOAT,REPLACE(@lItemValue,':','.')) AND attn_dt = MT.attn_dt AND EM.Id = PT.EmployeeId GROUP BY empcode),0) AS OT_DinnerAllowance
		FROM 
			sBiometric.tMonthTrans MT
			INNER JOIN sHrm.tEmployeeMaster EM ON MT.EMployeeId = EM.Id AND MT.attn_dt >= @rFromDate  AND MT.attn_dt <= @rToDate
			LEFT JOIN
			(
			SELECT SUM(ISNULL(ELS.EarlyHrs,0)) AS EarlyHrs,ELS.EmployeeId FROM sBiometric.tEmployeeLateStatus ELS 
			WHERE ELS.StatusId = 550 AND  CONVERT(DATE,ELS.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS.LateDate) <= CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS.EmployeeId
			) A ON A.EMployeeId = MT.EMployeeId 
			LEFT JOIN
			(
			SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS LateStatus FROM sBiometric.tEmployeeLateStatus ELS1 
			WHERE ELS1.StatusId = 550 AND LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS1.EmployeeId
			) A1 ON A1.EMployeeId = MT.EMployeeId 
			LEFT JOIN
			(
			SELECT ELS1.EmployeeId,COUNT(ELS1.LateStatus) AS TotalLate FROM sBiometric.tEmployeeLateStatus ELS1 
			WHERE LateStatus = 'EL' AND CONVERT(DATE,ELS1.LateDate)>= CONVERT(DATE,@rFromDate)
			AND CONVERT(DATE,ELS1.LateDate) <=CONVERT(DATE,DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @rToDate) + 1, 0)))
			GROUP BY ELS1.EmployeeId
			) A2 ON A2.EMployeeId = MT.EMployeeId 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
			INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
	
		WHERE (EM.Code = @rCode OR ISNULL(@rCode,'') = '')
		AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
		GROUP BY EM.Id,EM.Code,EM.FirstName,EM.Lastname,MT.attn_dt,A1.LateStatus
		ORDER BY EM.Code
	
		--SELECT ROW_NUMBER() OVER (ORDER BY Code ASC) AS SrNo, Code,Name, '' AS MonthYear,SUM(DinnerAllowance) AS DinnerAllowance,SUM(CompOff) AS CompOff,SUM(EarlyLeave) AS EarlyLeave,SUM(Total_OT) AS Tot_OT,SUM(Total_OT_EL) AS Tot_OT_EL,SUM(OT_DinnerAllowance) AS OT_DinnerAllowance FROM @lYearlyPresence GROUP BY Code,Name
	END
END
GO
PRINT N'Altering [sCommon].[pGeneralmasterGetCodeAndDescription]...';


GO
ALTER PROCEDURE [sCommon].[pGeneralmasterGetCodeAndDescription]
	  --@rOrgId		     Nvarchar(20),	
	  @rTableName		 Nvarchar(100),
	  @rIsStatic1To100	 bit,
	  @rCodeField		 Nvarchar(100) = '',
	  @rCode			 Nvarchar(100) = '',
	  @rRemarkField	     Nvarchar(100) = '',
	  @rVisibilityField nvarchar(100) = '',
	  @rVisibilityId    nvarchar(10) = '0'
	 
 
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--	DECLARE @lIsStatic int = 0

--IF ( @rTableName = 'sIp.tItemMainGroupMaster' or @rTableName = 'sIp.tStoreLocationMaster' or @rTableName = 'sHrm.tEmployeeJobTitleMaster' or @rTableName =  'sOrderEntry.tServiceItemTypeMaster')
--SET @lIsStatic = 1
--ELSE
--SET @lIsStatic = 0

	DECLARE @lSelectClause Nvarchar(2000)	 
     
  --   IF ( @rIsStatic1To100 = 1)
  --   BEGIN
  --      SET @lSelectClause =   'SELECT  ' + @rRemarkField + '  AS Result, ' + @rCodeField + ' AS ResultCode ' + ', Id, 0 AS StaticId, IsObsolete  FROM  ' + @rTableName + 
		--								' WHERE ' +  @rCodeField + ' LIKE '''+'%'+ @rCode +'%'+ '''  AND OrgId = ' + @rOrgId +  '' 
	 --END
	 --ELSE
	 BEGIN
        SET @lSelectClause =   'SELECT  ' + @rRemarkField + '  AS Result, ' + @rCodeField + ' AS ResultCode ' + ', Id, 0 As StaticId,  IsObsolete  FROM  ' + @rTableName + 
										' WHERE ' +  @rCodeField + ' = N''' + @rCode + ''' 
											AND     ((' + @rVisibilityField  + ' = ' + CAST(@rVisibilityId AS NVARCHAR(30)) + ') OR (' + CAST(@rVisibilityId AS NVARCHAR(30)) + ' = 0))' 
	 
	 END
				
	--SELECT @lSelectClause
	EXECUTE sp_executesql @lSelectClause
	



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


GO
 
 
ALTER PROCEDURE [sCommon].[pGeneralMasterWithValueAdd]
	@rTableName [nvarchar](100),
	@rCodeField [nvarchar](100),
	@rRemarkField [nvarchar](100),
	@rCode [nvarchar](50),
	@rRemark [nvarchar](100),
	@rIsObsolete [nvarchar](10),
	@rCreatedUserId [bigint],
	@rIsStatic1to100 [bit],
	@rOrgId int,
	@rVisibilityField nvarchar(100),
	@rVisibilityId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN

	--DECLARE @lSelectClause Nvarchar(2000)
	--DECLARE @lNextNumber BIGINT
	--EXECUTE @lNextNumber = sCommon.pTableRowIdGet @rTableName, 0, 1, 1
	DECLARE @lSelectClause Nvarchar(2000)
	DECLARE @lIsShow Nchar(1)
	DECLARE @lNextNumber BigInt
	DECLARE @lSchemaName Nvarchar(50)
	DECLARE @lTableName	Nvarchar(100)
	DECLARE @lSeed int
	
	SET @lSeed = (CASE WHEN @rIsStatic1to100 = 1 THEN 101 ELSE 1 END)
	EXECUTE  sCommon.pTableRowIdGet  @rOrgId,@rTableName, 0, @lSeed, 1,@outNextNumber = @lNextNumber output
	SET @lNextNumber = @lNextNumber
	SET @lIsShow = '0'
	SET @lSchemaName = SUBSTRING(@rTableName, 1, CHARINDEX('.', @rTableName, 1) - 1)
	SET @lTableName =  SUBSTRING(@rTableName, CHARINDEX('.', @rTableName, 1) + 1, LEN(@rTableName))
     
	--SELECT @lSchemaName, @lTableName
	
	SET @lSelectClause =     'IF EXISTS(SELECT ' + @rRemarkField + ' FROM ' + @rTableName + 
										' WHERE ' +  @rRemarkField + '	= ''' + @rRemark + ''' AND 
												' +  @rVisibilityField + '	= ' + CONVERT(NVARCHAR(20), @rVisibilityId) + ') 
     							BEGIN
									SELECT -102 AS Result
									RETURN
								END ' + 
							   'INSERT INTO ' + @rTableName 
								  + '(Id, ' + @rCodeField 
										   + ', ' + @rRemarkField 
										   + ', ' + ' UpdatedUserId ' 
										   + ', ' + ' UpdatedDateTime ' 
										   + ', ' + ' CreatedUserId ' 
										   + ', ' + ' CreatedDateTime ' 
                                           + ', ' + 'IsObsolete' +                                         
                                           --+' , ' +  'StoreLocationId' +
                                          ', ' + @rVisibilityField +
									      
									 ')
                               VALUES(' + CAST(@lNextNumber AS NVARCHAR(15)) + ', N''' + @rCode + ''', N''' 
							     		   + @rRemark +  ''', '''
                                           + CONVERT(NVARCHAR(25), @rCreatedUserId) + ''', ''' 
										   + CONVERT(NVARCHAR(30), sCommon.fGetDate()) + ''', '''
                                           + CONVERT(NVARCHAR(25), @rCreatedUserId) + ''', ''' 
										   + CONVERT(NVARCHAR(30), sCommon.fGetDate()) + ''', ''' + @rIsObsolete + ''','''										   
										   + CONVERT(NVARCHAR(20), @rVisibilityId) 
										 
								 + ''')
								 
								SELECT 1 AS Result'			
	
							 	
							 	
		--PRINT @lSelectClause
	EXECUTE sp_executesql @lSelectClause

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


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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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


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

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

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

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

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

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

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

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


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


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

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

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

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

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


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

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


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

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


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

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


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

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

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

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


GO
ALTER PROCEDURE [sCommunication].[pMyUpdateGet]
	 
@rOrgId int,	 
@rBatchId int,
@rOrgGroupBatchId int,
@rUserId bigint,
@rUserSourceId bigint,
@rUserSourceTypeId int,
@rSyncedAssignmentId bigint,
@rSyncedCircularId bigint,
@rSyncedPollId bigint,
@rSyncedQueryCommentId bigint,
@rSyncedNewsId bigint,
@rSyncedBlogId bigint,
@rSyncedBehaviourId bigint,
@rSyncedActivityId bigint,
@rSyncedResultId bigint,
@rSyncedAssignTaskId bigint,
@rSyncedPhotoCategoryId int,
@rVersionNumber nvarchar(30)=''

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	DECLARE @lAcademicId bigint,
	 @lScopeSourceId int,
	 @lScopeSourceTypeId int,
	 @lStudentId bigint,
	 @lClassId int,
	 @lDivisionId int,
	 @lOrgId int,
	 @lDepartmentId int,
	 @lAssignmentStatus bit=0,
	 @lCircularStatus bit=0,
	 @lPollStatus bit=0,
	 @lQueryStatus bit=0,
	 @lBlogStatus bit=0,
	 @lNewsStatus bit=0,
	 @lBehaviourStatus bit=0,
	 @lActivityStatus bit=0,
	 @lResultStatus bit=0,
	 @lAssignTaskStatus bit=0,
	 @lPhotoCategoryStatus bit=0,
	 @lIsActive bit=0,
	 @lIsOptimizeAppImageUpload bit=0

IF(	@rUserSourceTypeId = 2003)	
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 @lAcademicId = Id, @lScopeSourceId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rUserSourceId AND BatchId = @rBatchId
SET @lScopeSourceId = @lDivisionId
SET @lScopeSourceTypeId = 2005
END
ELSE
BEGIN
	SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId  FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD
			 ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId
--SELECT @lScopeSourceId = OrganizationDepartmentId FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId
SET @lScopeSourceId = @lDepartmentId
SET @lScopeSourceTypeId = 2004
END

 
IF EXISTS(SELECT 1 FROM sCommunication.tAssignmentScope ASO INNER JOIN  sCommunication.tAssignment A
	ON A.Id = ASO.AssignmentId
WHERE ASO.AssignmentId > @rSyncedAssignmentId AND ASO.SourceTypeId = @lScopeSourceTypeId AND ASO.SourceId = @lScopeSourceId AND A.BatchId=@rBatchId)
SET @lAssignmentStatus = 1


IF(	@rUserSourceTypeId = 2003)	
BEGIN

    IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS WHERE
      ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) 
      OR (CS.SourceTypeId = 2004 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)) D ON D.CircularId= C.Id
     	--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId
        WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
        AND C.AssigneeId IN (1,2) AND C.OrgGroupBatchId=@rOrgGroupBatchId) 
      SET @lCircularStatus = 1

END 
ELSE
BEGIN
	IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS
       WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId))
       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
       WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)
       AND C.AssigneeId IN (1,3) AND C.OrgGroupBatchId=@rOrgGroupBatchId) 
     SET @lCircularStatus = 1      	

END
--IF EXISTS(SELECT 1 FROM sCommunication.tCircularScope WHERE  CircularId > @rSyncedCircularId AND SourceTypeId = @lScopeSourceTypeId AND SourceId = @lScopeSourceId)
--SET @lCircularStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tPoll P INNER JOIN sCommunication.tPollMember PM ON P.Id=PM.PollId
	WHERE PM.PollId > @rSyncedPollId AND PM.SourceTypeId = @lScopeSourceTypeId AND PM.SourceId = @lScopeSourceId AND P.OrgGroupBatchId=@rOrgGroupBatchId)
SET @lPollStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tBlogScope BS INNER JOIN sCommunication.tBlog B
ON B.Id = BS.BlogId
WHERE B.IsPublish = 1 AND BS.BlogId > @rSyncedBlogId AND BS.SourceTypeId = 2021 AND BS.SourceId = @rOrgId AND B.OrgGroupBatchId = @rOrgGroupBatchId)
SET @lBlogStatus = 1

IF EXISTS(SELECT 1 FROM  sCommunication.tNews N INNER JOIN sCommunication.tNewsScope NS ON N.Id=NS.NewsId 
	  WHERE NS.NewsId > @rSyncedNewsId AND NS.SourceTypeId = 2021 AND NS.SourceId = @rOrgId AND N.OrgGroupBatchId = @rOrgGroupBatchId)
SET @lNewsStatus = 1

--IF EXISTS(SELECT 1 FROM sCommunication.tNewsScope WHERE NewsId > @rSyncedNewsId AND SourceTypeId = @rOrgId AND SourceId = 1016)
--SET @lNewsStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tUploadResult WHERE Id > @rSyncedResultId AND DivisionId = @lScopeSourceId AND BatchId=@rBatchId AND IsObsolete=0 )
SET @lResultStatus = 1

IF EXISTS(SELECT 1 FROM  
sCommunication.tPhotoCategoryMaster PCM
INNER JOIN sCommunication.tPhotoCategoryScope PCO 
ON PCM.Id=PCO.PhotoCategoryId WHERE PCM.Id > @rSyncedPhotoCategoryId AND LEFT(PCO.ScopeSourceId,4) = @rOrgId  AND PCM.IsObsolete=0 )
SET @lPhotoCategoryStatus = 1


IF EXISTS(SELECT 1 FROM sCommunication.tAssignTask WHERE  Id > @rSyncedAssignTaskId AND AssignedToSourceTypeId = @rUserSourceTypeId 
AND AssignedToSourceId = @rUserSourceId AND IsCompleted=0 AND IsClosed=0 AND OrgId=@rOrgId)
SET @lAssignTaskStatus = 1


IF EXISTS(SELECT 1 FROM  sActivity.tActivity A INNER JOIN sActivity.tActivityParticipant AP ON A.Id=AP.ActivityId
	WHERE AP.ActivityId > @rSyncedActivityId AND AP.SourceTypeId = @rUserSourceTypeId AND AP.SourceId = @rUserSourceId AND A.BatchId=@rBatchId)
SET @lActivityStatus = 1



IF EXISTS(SELECT 1 FROM sCommunication.tBehaviour WHERE Id > @rSyncedBehaviourId AND AcademicId = @lAcademicId )
SET @lBehaviourStatus = 1

IF EXISTS(SELECT 1 FROM sCommunication.tQuery Q INNER JOIN sCommunication.tQueryComment QC ON Q.Id=QC.QueryId
WHERE Q.CreatedUserId=@rUserId AND Q.IsUserView=0 AND QC.Id>@rSyncedQueryCommentId AND QC.CreatedUserId <> @rUserSourceId AND Q.OrgGroupBatchId=@rOrgGroupBatchId)
SET @lQueryStatus = 1
 
IF(@rUserSourceTypeId = 2003)
BEGIN 
	DECLARE @lStatusId1 smallint=0
 	SELECT @lStatusId1 = StatusId FROM sStudent.tStudentMaster SM WHERE Id = @rUserSourceId
	IF(@lStatusId1=1)
	BEGIN 
		SET @lIsActive = 1
	END	ELSE
	BEGIN
		SET @lIsActive = 0
	END
END
ELSE IF(@rUserSourceTypeId = 95)
BEGIN 
	DECLARE @lStatusId2 smallint=0
	SELECT @lStatusId2 = StatusId FROM sHrm.tEmployeeMaster EM WHERE Id = @rUserSourceId
	IF(@lStatusId2=7)
	BEGIN 
		SET @lIsActive = 1
	END	ELSE
	BEGIN
		SET @lIsActive = 0
	END
END

IF(@lIsActive=1)
BEGIN
	DECLARE @lIsObsolete bit=0
	SELECT @lIsObsolete=ISNULL(IsObsolete,0) FROM sSecurity.tUser WHERE Id = @rUserId

	IF(@lIsObsolete=0)
		SET @lIsActive = 1
	ELSE
		SET @lIsActive = 0
END

DECLARE @lOrgGroupId int=0
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id =@rOrgId
DECLARE @lOptimizeAppImageUpload nvarchar(50)
SELECT @lOptimizeAppImageUpload = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 247 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
IF (@lOptimizeAppImageUpload IS NULL) OR (@lOptimizeAppImageUpload = 'False')
	SET @lIsOptimizeAppImageUpload = 0
ELSE
	SET @lIsOptimizeAppImageUpload = 1	
	

DECLARE @lAlertRemark nvarchar(2000) = ''

	

IF(@rVersionNumber IS NULl OR @rVersionNumber='')
BEGIN
	DECLARE @lUserName nvarchar(100)=''
	DECLARE @lUserPassword nvarchar(100)=''
	DECLARE @lBatch nvarchar(100)=''
	SELECT @lBatch = Title  FROM sSetup.tBatchMaster WHERE Id = @rBatchId
	
	SELECT @lUserName=UserName,@lUserPassword=UserPassword FROM sSecurity.tTempUser WHERE UserId = @rUserId
	SET @lAlertRemark = 'Registration Number : '+LEFT(@rOrgGroupBatchId,4) +'
						 User Name : '+@lUserName+'
						 Password : '+@lUserPassword+'
						 Batch :' + @lBatch
END
ELSE 
BEGIN
	SELECT @lAlertRemark=AlertRemark FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @lOrgGroupId
END

DECLARE @lMobileAppModuleAutoSyncToken nvarchar(50)
SELECT @lMobileAppModuleAutoSyncToken = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 317 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId

CREATE TABLE #Module (
Id int,
Title nvarchar(2000),
IsNew bit )
INSERT INTO #Module VALUES (1,'IsActiveCheck',@lIsActive)
INSERT INTO #Module VALUES (2,'IsOptimizeAppImageUpload',@lIsOptimizeAppImageUpload)
INSERT INTO #Module VALUES (3,ISNULL(@lAlertRemark,''),1)
INSERT INTO #Module VALUES (4,ISNULL(@lMobileAppModuleAutoSyncToken,0),1)
INSERT INTO #Module VALUES (20085,'Circular',@lCircularStatus)
INSERT INTO #Module VALUES (20088,'Query',@lQueryStatus)
INSERT INTO #Module VALUES (20099,'Blog',@lBlogStatus)
INSERT INTO #Module VALUES (20104,'News',@lNewsStatus)
INSERT INTO #Module VALUES (20172,'AssignTask',@lAssignTaskStatus)
INSERT INTO #Module VALUES (20183,'Gallery',@lPhotoCategoryStatus)
INSERT INTO #Module VALUES (20204,'Poll',@lPollStatus)
INSERT INTO #Module VALUES (20093,'Assignment',@lAssignmentStatus)
INSERT INTO #Module VALUES (20209,'Activity',@lActivityStatus)
INSERT INTO #Module VALUES (20130,'Behaviour',@lBehaviourStatus)
INSERT INTO #Module VALUES (20180,'Result',@lResultStatus)
	
SELECT * FROM #Module
 
--SELECT @lAssignmentStatus AS Assignment,@lCircularStatus AS Circular,@lPollStatus AS Poll,@lQueryStatus AS Query,
--@lBlogStatus AS Blog,@lNewsStatus AS News,@lBehaviourStatus AS Behaviour,
--@lActivityStatus AS Activity,@lResultStatus AS Result,@lAssignTaskStatus AS AssignTask,@lPhotoCategoryStatus AS Gallery

END
GO
PRINT N'Altering [sConfig].[pDisplayFieldOrgAdd]...';


GO
ALTER PROCEDURE [sConfig].[pDisplayFieldOrgAdd]
	@rDisplayFieldOrgDetailXml [nvarchar](max),
	@rOrgId smallint,
	@rFieldSource nvarchar(100)
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rDisplayFieldOrgDetailXml
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION 
	 BEGIN	

	 Delete D FROM sConfig.tDisplayFieldOrg D  INNER  JOIN [sConfig].[tDisplayFieldMaster] DF
     ON DF.id=D.DisplayFieldId and FieldSource=@rFieldSource
				 WHERE OrgId=@rOrgId 
			
	 --DELETE FROM sConfig.tDisplayFieldOrg
		--		 WHERE OrgId=@rOrgId 
	 
	 INSERT INTO sConfig.tDisplayFieldOrg
		(
			DisplayFieldId,
			OrgId,
			IsFieldMandatory
			
			)
		SELECT
		
			DisplayFieldId,
			OrgId,
			IsFieldMandatory 
		FROM OPENXML (@loDoc, '/Table/DisplayFieldOrgDetail', 1)
		WITH ( 
				DisplayFieldId smallint,
				OrgId smallint,
				IsFieldMandatory bit
			  ) 
		
        SELECT 1 AS Result
	 END	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sConfig].[pDisplayFieldOrgListGet]...';


GO
ALTER PROCEDURE [sConfig].[pDisplayFieldOrgListGet]
          
           @rOrgId smallint,
           @rFieldSource  nvarchar(100)
 
AS
SET NOCOUNT ON

BEGIN

SELECT 
     
	   ISNULL(DM.Id,0) AS DisplayFieldId
	  ,ISNULL(DM.Name,'') AS Name
	 -- ,ISNULL(DM.FieldSource,'') AS FieldSource 
   ,(CASE WHEN DO.DisplayFieldId Is Null THEN 'False'  ELSE 'True' END) AS Selected 
    ,(CASE WHEN DO.IsFieldMandatory Is Null THEN 'False' WHEN DO.IsFieldMandatory = 1 THEN 'True' ELSE 'False' END) AS IsMandatory 
      
 
FROM sConfig.tDisplayFieldMaster DM
      LEFT JOIN sConfig.tDisplayFieldOrg DO ON DM.Id=DO.DisplayFieldId
	  AND DO.OrgId=@rOrgId
WHERE (DM.FieldSource=@rFieldSource) 
--	  ORDER by selected desc
END
GO
PRINT N'Altering [sErp].[pLeadFollowup_Get]...';


GO
 
ALTER PROCEDURE [sErp].[pLeadFollowup_Get]
	
	
	 @rId bigint = 0,
	 @rFromDate date='',
	 @rToDate date='',
	 @rOrgId Smallint=0,	
	 @rLeadId int=0,
	 @rEmployeeId bigint=0,
	 @rFollowupTypeId Smallint=0,
	 @rLeadStatusId smallint=0,
	 @rManagerFlag smallint =0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	SELECT 
	ISNULL(LF.Id,'') AS Id,
	LF.LeadId,
	ISNULL(LF.FollowupDate,'') AS  FollowupDate,
	ISNULL(LF.FollowupRemark,'') AS FollowupRemark,
	ISNULL(LF.FollowupEmployeeId,0) AS FollowupEmployeeId,
	ISNULL(LM.Title,'') AS Lead,
	ISNULl( LM.StateId,0) AS StateId,
	ISNULL(LF.FollowupNextDate,'0001/01/01') AS NextFollowupDate,
	LM.OrgId,
	OM.DisplayTitle AS OrgName,
	EM.FirstName +' '+ MiddleName +' '+ LastName AS EmployeeName,
	ISNULL(LM.ContactPerson,'') AS ContactPerson,
	ISNULL(LM.ContactMobileNo,'')AS ContactMobileNo,
	ISNULL(LM.MobileNo,'') AS MobileNo,
	LM.ContactEmail,
	ISNULL(LF.LeadStatusId,0) AS LeadStatusId,
	LSM.Title,
	ISNULL(LF.IsPhysical,'False') AS IsPhysical,
	ISNULL(LF.LatitudeAxis,'') AS LatitudeAxis,
	ISNULL(LF.LongitudeAxis,'')AS LongitudeAxis,
	ISNULL(FTM.Title,'') AS FollowupType,
	ISNULL(LF.FollowupTypeId,0) AS FollowupTypeId,
	LF.CreatedDateTime,
	ISNULL(LM.CityName,'') AS CityName,
	ISNULL(LF.FollowupLocation,'') AS FollowupLocation,
	ISNULL(LF.NonEffective,0) AS NonEffective,
	ISNULL(LF.WithManagerEmployeeId,0)As WithManagerEmployeeId

  FROM 
	sErp.tLeadMaster LM
    INNER JOIN  sErp.tLeadFollowup LF ON LM.Id=LF.LeadId  AND ((LM.OrgId=@rOrgId) OR (@rOrgId=0))
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=LM.OrgId
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=LF.FollowupEmployeeId
	INNER JOIN sErp.tLeadStatusMaster LSM ON LSM.Id = LF.LeadStatusId
	INNER JOIN sErp.tFollowupTypeMaster FTM ON FTM.Id = LF.FollowupTypeId
  WHERE  
     ((LF.Id = @rId) OR (@rId = 0))
      AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	  AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))	
	  AND ((LM.Id = @rLeadId) OR (@rLeadId = 0))
	  AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	  AND((LF.FollowupTypeId = @rFollowupTypeId)OR(@rFollowupTypeId=0))
	  AND((LF.LeadStatusId = @rLeadStatusId)OR(@rLeadStatusId=0))	
	  AND ((ISNULL(LF.WithManagerEmployeeId,0) > 100 AND @rManagerFlag = 1) OR (@rManagerFlag in (0,2) ))
	  AND ((LF.WithManagerEmployeeId <> LM.LeadOwnerEmployeeId AND @rManagerFlag = 2 AND ISNULL(LF.WithManagerEmployeeId,0) > 100) OR (@rManagerFlag in (0,1)))
	 -- AND  ((( (ISNULL(LF.WithManagerEmployeeId,0) > 100) OR (LF.WithManagerEmployeeId <> LM.LeadOwnerEmployeeId AND ISNULL(LF.WithManagerEmployeeId,0) > 100 ) ) AND (@rManagerFlag = 0)) OR  (@rManagerFlag in (1,2)) )
	  Order by LF.FollowupDate desc
END
GO
PRINT N'Altering [sErp].[pLeadFollowupAdd]...';


GO
 
 
ALTER PROCEDURE [sErp].[pLeadFollowupAdd]
		@rId	bigint,	
		@rLeadId int,
		@rFollowupDate	date,
		@rFollowupRemark	nvarchar(max),
		@rFollowupEmployeeId bigint,							
		@rCreatedUserId	bigint,
		@rOrgId smallint,
		@statusId int,
		@rNextFollowupDate date='',
		@rIsPhysical bit=0,
		@rLatitudeAxis nvarchar(20)='',
		@rLongitudeAxis nvarchar(20)='',
		@rFollowupType smallint=0,
		@rFollowupLocation nvarchar(20)='',
		@rNonEffective tinyint = 0,
		@rWithManagerEmployeeId bigint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN



	DECLARE @lFollowId BIGINT 
	IF Exists(select Id from sErp.tLeadFollowup where LeadId = @rLeadId AND FollowupTypeId=@rFollowupType  AND CONVERT(date,FollowupDate) =  CONVERT(date,getdate(),102))
				BEGIN
				SELECT @lFollowId = Id from sErp.tLeadFollowup where LeadId = @rLeadId  AND FollowupTypeId=@rFollowupType  AND CONVERT(date,FollowupDate) =  CONVERT(date,getdate(),102)
				IF Exists(select 1  from sErp.tLeadFollowup where LeadId = @rLeadId  AND FollowupTypeId=@rFollowupType  AND CONVERT(date,FollowupDate) =  CONVERT(date,getdate(),102) AND (LatitudeAxis IS NOT NULL OR LongitudeAxis IS NOT NULL ))
					BEGIN
						UPDATE  sErp.tLeadFollowup
						SET
						LeadId=@rLeadId,
						FollowupDate=@rFollowupDate,
						FollowupRemark=@rFollowupRemark,
						FollowupEmployeeId=@rFollowupEmployeeId,
						IsPhysical = @rIsPhysical,
						LatitudeAxis = @rLatitudeAxis,
						LongitudeAxis = @rLongitudeAxis,
						FollowupNextDate=@rNextFollowupDate,
						LeadStatusId = @statusId,
						FollowupTypeId=@rFollowupType,
						FollowupLocation=@rFollowupLocation,
						NonEffective=@rNonEffective, 
						WithManagerEmployeeId = @rWithManagerEmployeeId
						WHERE Id = @lFollowId 	   	
						
							UPDATE  sErp.tLeadMaster
							SET LeadStatusId = @statusId,
							NextFollowupDate=@rNextFollowupDate
							WHERE Id = @rLeadId 

						SELECT @lFollowId AS Result    
						SELECT 11 AS Operation  
						return
					END 
				ELSE 
					BEGIN
						UPDATE  sErp.tLeadFollowup
						SET
						LeadId=@rLeadId,
						FollowupDate=@rFollowupDate,
						FollowupRemark=@rFollowupRemark,
						FollowupEmployeeId=@rFollowupEmployeeId,
						IsPhysical = @rIsPhysical,
						--LatitudeAxis = @rLatitudeAxis,
						--LongitudeAxis = @rLongitudeAxis,
						FollowupNextDate=@rNextFollowupDate,
						LeadStatusId = @statusId,
						FollowupTypeId=@rFollowupType,
						NonEffective=@rNonEffective,
						WithManagerEmployeeId = @rWithManagerEmployeeId
						WHERE Id = @lFollowId 	   	



							UPDATE  sErp.tLeadMaster
							SET LeadStatusId = @statusId,
							NextFollowupDate=@rNextFollowupDate
							WHERE Id = @rLeadId 

						SELECT @lFollowId AS Result    
						SELECT 11 AS Operation  
						return
					END
					
				END
			ELSE
			BEGIN
				IF(@rId = 0)	
					BEGIN
						DECLARE @lNextNumber BIGINT 
						EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sErp.tLeadFollowup', 0, 1, 1,@outNextNumber = @lNextNumber output
						INSERT INTO sErp.tLeadFollowup
						(Id,LeadId,FollowupDate,FollowupRemark,FollowupEmployeeId,CreatedUserId,CreatedDateTime,IsPhysical,LatitudeAxis,LongitudeAxis,FollowupNextDate,LeadStatusId,FollowupTypeId,FollowupLocation,NonEffective,WithManagerEmployeeId)
						VALUES
						(@lNextNumber,@rLeadId,@rFollowupDate,@rFollowupRemark,@rFollowupEmployeeId,@rCreatedUserId,sCommon.fGetDate(),@rIsPhysical,@rLatitudeAxis,@rLongitudeAxis,@rNextFollowupDate,@statusId,@rFollowupType,	@rFollowupLocation,@rNonEffective, @rWithManagerEmployeeId)
						UPDATE sErp.tLeadMaster
						SET LeadStatusId = @statusId,
						NextFollowupDate = @rNextFollowupDate
						WHERE ID =@rLeadId
						SELECT @lNextNumber AS Result    
						SELECT 1 AS Operation     
					END	 
					ELSE
						BEGIN
							SET @lNextNumber = @rId
							UPDATE  sErp.tLeadFollowup
							SET
								LeadId=@rLeadId,
								FollowupDate=@rFollowupDate,
								FollowupRemark=@rFollowupRemark,
								FollowupEmployeeId=@rFollowupEmployeeId,
								IsPhysical = @rIsPhysical,
								LatitudeAxis = @rLatitudeAxis,
								LongitudeAxis = @rLongitudeAxis,
								FollowupNextDate=@rNextFollowupDate,
								LeadStatusId = @statusId,
								FollowupTypeId=@rFollowupType,
								FollowupLocation=@rFollowupLocation,
								NonEffective=@rNonEffective,
								WithManagerEmployeeId=@rWithManagerEmployeeId
							WHERE Id = @rId 	   

							UPDATE  sErp.tLeadMaster
							SET LeadStatusId = @statusId,
							NextFollowupDate=@rNextFollowupDate
							WHERE Id = @rLeadId 	  

							SELECT @rId AS Result 
							SELECT 11 AS Operation
						END  
					END
	
END
GO
PRINT N'Altering [sErp].[pPluginLogAdd]...';


GO
 
ALTER PROCEDURE [sErp].[pPluginLogAdd]    
	@rOrgGroupID int, 
	@rPlugin int,
	@rStatusRemark nvarchar(200) = 'Active',
	@rCreatedUserId bigint,
	@rPlugInStatusId tinyint,
	@rPluginDate DateTime

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
   
	BEGIN TRY
 	BEGIN TRANSACTION
	 
		BEGIN	
		IF NOT EXISTS(SELECT * FROM sErp.tCustomerPlugInLog WHERE PlugInId = @rPlugin AND LogDate = @rPluginDate AND PlugInStatusId = @rPluginStatusId)		
		INSERT INTO sErp.tCustomerPlugInLog
			(
			
			OrgGroupId,
			PlugInId,
			LogDate,
			StatusRemark,
			CreatedUserId,
			CreatedDateTime,
			PlugInStatusId
			)
			VALUES
			(
			
			@rOrgGroupID ,
			@rPlugin ,
			@rPluginDate,
			@rStatusRemark,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rPluginStatusId
			)
		
		
		SELECT 1 AS RESULT
		END

		COMMIT TRANSACTION
	 
		END TRY
		
		BEGIN CATCH
		ROLLBACK TRANSACTION 
				 SELECT -1 AS RESULT
		END CATCH			
	 
END
GO
PRINT N'Altering [sErp].[pWorkStatusGet]...';


GO
 
 
 
ALTER PROCEDURE   [sErp].[pWorkStatusGet]

	@rEmployeeId bigint =0, 
	@rFromDate DATETIME='',
	@rToDate DATETIME='',
	@rOrgId smallint=0
	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

------------- For Visit Type ---------------------------
		
	DECLARE @lTypeTotal table(
		FollowupTypeId int,
		FollowupCount int
		)
	DECLARE @lTypeEffective table(
		FollowupTypeId int,
		FollowupCount int
		)
	DECLARE @lTypeSchool table(
		FollowupTypeId int,
		FollowupCount int
		)
		DECLARE @lTypeNewSchool table(
		FollowupTypeId int,
		FollowupCount int
		)
		
		INSERT INTO @lTypeTotal		
		SELECT  LF.FollowupTypeId, ISNULL(count(LF.Id),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
		Group By FollowupTypeId
		 
		 
		INSERT INTO @lTypeEffective
				SELECT  LF.FollowupTypeId, ISNULL(count(LF.Id),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     AND NonEffective = 1
		Group By FollowupTypeId
		
				
 		INSERT INTO @lTypeSchool
		SELECT  LF.FollowupTypeId, ISNULL(count(Distinct LF.LeadId),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     AND NonEffective = 1
		Group By FollowupTypeId
	
	
INSERT INTO @lTypeNewSchool

SELECT LF.FollowupTypeId,ISNULL(Count(LF.LeadId),0) FROM sErp.tLeadFollowup LF INNER JOIN
(

	SELECT LF.LeadId FROM sErp.tLeadFollowup LF
	INNER JOIN
	(
	
	SELECT DISTINCT LF.LeadId
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		 (( LF.FollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))	  
		  AND (( LF.FollowupDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     ) L ON LF.LeadId = L.LeadId 
	     WHERE 
		 (( LF.FollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))	  
		  AND (( LF.FollowupDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	     GROUP BY LF.LeadId Having count(LF.LeadId) = 1
	     )
	       A ON LF.LeadId = A.LeadId
	  WHERE 
		 (( LF.FollowupDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))	  
		  AND (( LF.FollowupDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))  
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))     
	       GROUP BY LF.FollowupTypeId
	
	 	
 SELECT Id AS FollowupTypeId, Title AS FollowupType,
 ISNULL(TT.FollowupCount,0) AS TypeTotal,
 ISNULL(TE.FollowupCount,0) AS TypeEffective,
 ISNULL(TS.FollowupCount,0) AS TypeSchool,
 ISNULL(TN.FollowupCount,0) AS TypenewSchool
 FROM sErp.tFollowupTypeMaster FTM
 LEFT JOIN @lTypeTotal TT ON  FTM.Id = 	TT.FollowupTypeId
 LEFT JOIN @lTypeEffective TE ON FTM.Id = 	TE.FollowupTypeId
 LEFT JOIN @lTypeSchool TS ON FTM.Id = 	TS.FollowupTypeId
 LEFT JOIN @lTypeNewSchool TN ON FTM.Id = 	TN.FollowupTypeId
 
 ------------- For Lead Status ---------------------------

	DECLARE @lStatusTotal table(
		LeadStatusId int,
		FollowupCount int
		)
		
	--DECLARE @lStatusDistinct table(
	--	LeadStatusId int,
	--	FollowupCount int
	--	)
		
	DECLARE @lStatusSchool table(
		LeadStatusId int,
		FollowupCount int
		)

		INSERT INTO @lStatusTotal		
		SELECT  LF.LeadStatusId, ISNULL(count(LF.Id),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
		Group By LeadStatusId



		INSERT INTO @lStatusSchool		
		SELECT  LF.LeadStatusId, ISNULL(count( DISTINCT  LF.LeadId),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
		Group By LeadStatusId

		--INSERT INTO @lStatusSchool
		
		--SELECT  LM.LeadStatusId, ISNULL(count(LM.Id),0) FROM
		--(	
	
		--SELECT DISTINCT LF.LeadId
		--FROM		
		--sErp.tLeadFollowup LF
		--WHERE 
		--(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 --   AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	 --    AND((LF.FollowupEmployeeId = @rEmployeeId)OR(@rEmployeeId=0))
	 --    ) A INNER JOIN sErp.tLeadMaster LM on A.LeadId = LM.Id
	 --    Group By LM.LeadStatusId
	     


SELECT * FROM
(	
 SELECT Id AS LeadStatusId, Title AS LeadStatusType,
 ISNULL(TT.FollowupCount,0) AS StatusTotal, 
 ISNULL(TS.FollowupCount,0) AS StatusSchool
 
 FROM sErp.tLeadStatusMaster FTM
 LEFT JOIN @lStatusTotal TT ON  FTM.Id = 	TT.LeadStatusId  
 LEFT JOIN @lStatusSchool TS ON FTM.Id = 	TS.LeadStatusId
 ) A WHERE A.StatusTotal > 0
  

------------- For Leave ---------------------------
	    
	 SELECT  L.FromDate AS LeaveFromDate, L.ToDate AS LeaveToDate ,LPM.Title AS LeaveType
	 
	 FROM sHrm.tLeave L INNER JOIN sHrm.tLeavePeriodMaster LPM
	 ON L.LeavePeriodId = LPM.Id
	 WHERE
	 (( L.FromDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( L.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	    AND((L.EmployeeId = @rEmployeeId)OR(@rEmployeeId=0))

------------- For Manager ---------------------------

	CREATE TABLE #TempEmployeeId
	(
		EmployeeId bigint
	);
	
 
			WITH EmployeeCTE AS
			(
			 SELECT
			 EJD.EmployeeID
			 FROM sHrm.tEmployeeJobDetail EJD
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = EJD.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =EJD.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 WHERE ((EmployeeManagerId = @rEmployeeId) OR (@rEmployeeId = 0)) AND ((EM.OrgId = @rOrgId) OR (@rOrgId = 0))
			 AND EM.StatusId = 7
			-- AND EM.FirstName like '%'+@rEmpName+'%'
			 	
			 UNION ALL

			 SELECT
			  E.EmployeeID
			 FROM sHrm.tEmployeeJobDetail E
			 JOIN EmployeeCTE x ON x.EmployeeID = E.EmployeeManagerId
			 INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = E.EmployeeId
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id =E.OrgGroupDepartmentId AND (OGDM.Code = '01' OR OGDM.Code = '04')
			 AND EM.StatusId = 7
			) 
			INSERT INTO #TempEmployeeId(EmployeeId) SELECT E.EmployeeID FROM EmployeeCTE E	    
		INSERT INTO #TempEmployeeId(EmployeeId) SELECT @rEmployeeId
		
 
	    SELECT
	    EM.Id AS EmployeeId,
	    EM.FirstName + ' ' + EM.LastName AS EmployeeName,
	    EM.Code AS EmployeeCode,
	   (SELECT  ISNULL(count(Id),0) 
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		EM.Id = LF.FollowupEmployeeId
		AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	     AND LF.WithManagerEmployeeId > 100
	    AND LF.FollowupTypeId = 1		 
	     ) AS PhysicalWithManager,
	     
	    (SELECT  ISNULL(count(Id),0)
		FROM		
		sErp.tLeadFollowup LF
		WHERE 
		EM.Id = LF.FollowupEmployeeId
		AND(( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	    AND LF.WithManagerEmployeeId > 100
	    AND LF.FollowupTypeId = 2		 
	     ) AS CallWithManager,	     
	     
	 --  	(SELECT  ISNULL(count(Id),0)
		--FROM		
		--sErp.tLeadFollowup LF
		--WHERE 
		--EM.Id = LF.FollowupEmployeeId
		--AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 --   AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	 --   AND LF.WithManagerEmployeeId IS NOT NULL
	 --   AND LF.FollowupTypeId = 3		 
	 --    ) AS MailWithManager,
	     
	   	(SELECT  ISNULL(count(LF.Id),0) 
		FROM		
		sErp.tLeadFollowup LF INNER JOIN sErp.tLeadMaster LM
		ON LF.LeadId = LM.Id
		WHERE 
		EM.Id = LM.LeadOwnerEmployeeId
		AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	    AND LF.FollowupEmployeeId <> LM.LeadOwnerEmployeeId AND LF.FollowupEmployeeId > 100
	    AND LF.FollowupTypeId = 1		 
	     ) AS PhysicalManager ,
	     
	    (SELECT  ISNULL(count(LF.Id),0) 
		FROM		
		sErp.tLeadFollowup LF INNER JOIN sErp.tLeadMaster LM
		ON LF.LeadId = LM.Id
		WHERE 
		EM.Id = LM.LeadOwnerEmployeeId
		AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	    AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	    AND LF.FollowupEmployeeId <> LM.LeadOwnerEmployeeId AND LF.FollowupEmployeeId > 100
	    AND LF.FollowupTypeId = 2		 
	     ) AS CallManager 
	     --,
	     
	 --   (SELECT  ISNULL(count(LF.Id),0) 
		--FROM		
		--sErp.tLeadFollowup LF INNER JOIN sErp.tLeadMaster LM
		--ON LF.LeadId = LM.Id
		--WHERE 
		--EM.Id = LM.LeadOwnerEmployeeId
		--AND (( LF.FollowupDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 --   AND (( LF.FollowupDate<= @rToDate) OR (ISNULL(@rToDate,'')=''))
	 --   AND LF.FollowupEmployeeId <> LM.LeadOwnerEmployeeId
	 --   AND LF.FollowupTypeId = 3		 
	 --    ) AS MailManager	     
	    FROM
	    sHrm.tEmployeeMaster EM INNER JOIN #TempEmployeeId TE ON EM.Id = TE.EmployeeId
	   

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


GO
ALTER PROCEDURE [sFee].[pFeeConsolidateDashBoardGet]
		
	@rType nvarchar(100)='',
	@rCount int =0 ,
	@rDivisionId int  =0,
	@rClassId int  =0,
	@rOrgId int  =0,
	@rOrgGroupId int=0,
	@rOrgGroupBatchId int  =0,
	@rCollectionGroupId int =0,
	@rReceiptBookId int =0,
	@rDays int=0,
	@rCommonOrgGroupBatchId int=0,
	@rFromDate varchar(10)='',
	@rToDate varchar(10)='',
	@rMonth int =0,
	@rSyncDate int =0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

IF(@rType ='FeeStatusOrganization')
	BEGIN 
	IF(@rSyncDate =1)
		BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			CREATE TABLE #tempFeeSetupDetailsSync (
	FeeId int,
	Id int,
	IsOptional bit,
	IsVariable bit,
	Amount decimal(12,2),
	StartDate date,
	EndDate date,
	BatchId int,
	ReceiptBookId int,
	AcademicId bigint,
	FeeName nvarchar(200),
	FeeHeadId int
	)
				INSERT INTO #tempFeeSetupDetailsSync
				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
				FROM 
					sFee.tFeeSetup FS1
					INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 	    
					INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId		
				WHERE 
					((FS1.IsOptional=0))
					--AND (BM.IsActive =1)  
					And COGBM.Id=@rCommonOrgGroupBatchId 
					And O.IsObsolete = 0
					--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
					--AND (StartDate>='2017-01-01' AND EndDate<='2019-01-31')
					 
					
				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.Id AS AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM 
					sFee.tFeeSetup FS1
					INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
					INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
					AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					((FS1.IsOptional=1))
					--AND (BM.IsActive =1) 
					And COGBM.Id=@rCommonOrgGroupBatchId 
					And O.IsObsolete = 0
					--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
					--AND (StartDate>='2017-01-01' AND EndDate<='2019-01-31')	
				CREATE TABLE #tempFeeReceiptSync (
				PaidAmount decimal(12,2),
				FeeSetupId int,
				SourceId bigint
				)
				INSERT INTO #tempFeeReceiptSync
				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
					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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
				    
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) AND  COGBM.Id=@rCommonOrgGroupBatchId 
					And O.IsObsolete = 0
					--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
					--AND (StartDate>='2017-01-01' AND EndDate<='2019-01-31')
				GROUP BY FeeSetupId,R.SourceId	
				CREATE TABLE #tempOrganizationSync(
				PaidAmount DECIMAL(12,2),
				PendingAmount DECIMAL(12,2),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
				INSERT INTO #tempOrganizationSync
				SELECT 
						SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.tAcademic SA
						INNER JOIN #tempFeeSetupDetailsSync FS ON FS.AcademicId=SA.Id
						LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
						LEFT JOIN #tempFeeReceiptSync R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
						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.tOrganizationMaster OM ON OM.ID = SA.OrgId
						--INNER JOIN sSetup.tBatchMaster BM ON BM.ID = SA.BatchId 
						--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
						INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
						
						WHERE	
						--(BM.IsActive =1) 
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  And O.IsObsolete = 0
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
						--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
						GROUP BY  o.Id,o.Title
						IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))
							BEGIN
							IF(@rOrgGroupId !=0)
								INSERT INTO sFee.tTempOrgGroupFeeStatus
								SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
								ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
								SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
							END
						ELSE
							BEGIN
							INSERT INTO sFee.tTempOrgGroupFeeStatus
								SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
								ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganizationSync T
								SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
							END
				
			
				DROP TABLE #tempFeeSetupDetailsSync
				DROP TABLE #tempFeeReceiptSync
				DROP TABLE #tempOrganizationSync			
		END
	ELSE
		BEGIN
			IF  Exists(select 1 from sFee.tTempOrgGroupFeeStatus where CONVERT(date,UpdatedDateTime) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId)
			BEGIN
	
				SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN
			DELETE  sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			CREATE TABLE #tempFeeSetupDetails (
			FeeId int,
			Id int,
			IsOptional bit,
			IsVariable bit,
			Amount decimal(12,2),
			StartDate date,
			EndDate date,
			BatchId int,
			ReceiptBookId int,
			AcademicId bigint,
			FeeName nvarchar(200),
			FeeHeadId int
			)
				INSERT INTO #tempFeeSetupDetails
				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
				FROM 
					sFee.tFeeSetup FS1
					INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 	    
					INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId		
				WHERE 
					((FS1.IsOptional=0))
					--AND (BM.IsActive =1)  
					And COGBM.Id=@rCommonOrgGroupBatchId 
					And O.IsObsolete = 0
					--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
					--AND (StartDate>='2017-01-01' AND EndDate<='2019-01-31')
					 
					
				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.Id AS AcademicId,
					FM.Title AS FeeName,
					FM.FeeHeadId
				FROM 
					sFee.tFeeSetup FS1
					INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
					INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
					AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
					((FS1.IsOptional=1))
					--AND (BM.IsActive =1) 
					And COGBM.Id=@rCommonOrgGroupBatchId 
					And O.IsObsolete = 0
					--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
					--AND (StartDate>='2017-01-01' AND EndDate<='2019-01-31')	
				CREATE TABLE #tempFeeReceipt (
				PaidAmount decimal(12,2),
				FeeSetupId int,
				SourceId bigint
				)
				INSERT INTO #tempFeeReceipt
				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
					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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
				    
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) AND  COGBM.Id=@rCommonOrgGroupBatchId 
					And O.IsObsolete = 0
					--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
					--AND (StartDate>='2017-01-01' AND EndDate<='2019-01-31')
				GROUP BY FeeSetupId,R.SourceId	
				CREATE TABLE #tempOrganization (
				PaidAmount DECIMAL(12,2),
				PendingAmount DECIMAL(12,2),
				OrgGroupName nvarchar(200),
				OrgGroupId int
				)
				INSERT INTO #tempOrganization
				SELECT 
						SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
						O.Title AS OrgGroupName,
						O.Id AS OrgGroupId
					FROM 
						sStudent.tAcademic SA
						INNER JOIN #tempFeeSetupDetails FS ON FS.AcademicId=SA.Id
						LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
						LEFT JOIN #tempFeeReceipt R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
						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.tOrganizationMaster OM ON OM.ID = SA.OrgId
						--INNER JOIN sSetup.tBatchMaster BM ON BM.ID = SA.BatchId 
						--INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId
						INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
						INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId
						
						WHERE	
						--(BM.IsActive =1) 
						  COGBM.Id=@rCommonOrgGroupBatchId 
						  And O.IsObsolete = 0
						  AND ((O.Id = @rOrgGroupId )OR(@rOrgGroupId=0))
						--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
						GROUP BY  o.Id,o.Title
						
						--select *from #tempOrganization
						IF EXISTS (SELECT 1 FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)))
							BEGIN
							IF(@rOrgGroupId !=0)
								INSERT INTO sFee.tTempOrgGroupFeeStatus
								SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
								ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization  T
								SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
							END
						ELSE
							BEGIN
							INSERT INTO sFee.tTempOrgGroupFeeStatus
								SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
								ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization  T
								SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
							END 
					
				--	INSERT INTO sFee.tTempOrgGroupFeeStatus
				--SELECT @rCommonOrgGroupBatchId,T.OrgGroupName,T.OrgGroupId,ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
				--ISNULL(ISNULL(T.PaidAmount,0) + ISNULL(T.PendingAmount,0),0) AS TotalAmount,GETDATE() from #tempOrganization T
				--SELECT * FROM sFee.tTempOrgGroupFeeStatus WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			
				DROP TABLE #tempFeeSetupDetails
				DROP TABLE #tempFeeReceipt
				DROP TABLE #tempOrganization
			END
		END
		
	
	END
ELSE IF(@rType = 'FeeStatusPaid&UnpaidDetilsClassWise')
	BEGIN 
		CREATE TABLE #tempPaidDetailsClassWise(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(30),
	ClassId int,
	ClassName nvarchar(50),
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2)
)
CREATE TABLE #tempFSClassWise(
    Id int,
    Amount DECIMAL(12,2),
	AcademicId BIGINT
)
INSERT INTO #tempFSClassWise
SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		SA1.Id AS AcademicId
	FROM 
		sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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 sFee.tFeeMaster FM ON FM.Id=FS1.FeeId		
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA1.OrgId		
		
	WHERE 
		(FS1.IsOptional=0) 
		AND  ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		AND((OM.OrgGroupId) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
		--AND(BM.IsActive =1) 
UNION ALL				
SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		SA1.Id As 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON OM.Id = SA1.OrgId
		
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND COGBM.Id=1 
	WHERE
		(FS1.IsOptional=1)
		AND ((OM.OrgGroupId) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
		--AND(BM.IsActive =1)


CREATE TABLE #tempRClassWise(    
    PaidAmount DECIMAL(12,2),
	FeeSetupId int,
	SourceId BIGINT
)
INSERT INTO #tempRClassWise
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
	    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.tOrganizationMaster OM ON OM.Id = SA1.OrgId
		
	WHERE		
		(R.SourceTypeId = 2001)
		AND (OM.OrgGroupId = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND(BM.IsActive =1) 
		AND((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate 
		
	GROUP BY FeeSetupId,R.SourceId 

INSERT INTO #tempPaidDetailsClassWise
SELECT 
		 ISNULL(SA.AcademicId,0) AS AcademicId,
		 ISNULL(SA.OrgId,0) AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 ISNULL(SA.ClassId,0)AS ClassId,
		 ISNULL(SA.ClassName,'') AS ClassName,
		 SUM(ISNULL(TR.PaidAmount,0)) AS PaidAmount,
		 SUM(ISNULL(TFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TR.PaidAmount,0.00))AS PendingAmount
		
	FROM 		
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempFSClassWise TFS ON TFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempRClassWise TR ON TR.FeeSetupId = TFS.Id AND SA.AcademicId = TR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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			
		
	WHERE
		(LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
		AND((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
	GROUP by SA.OrgId,SA.ClassName,SA.ClassId,SA.OrganizationName,SA.AcademicId
	--HAVING SUM(ISNULL(TR.PaidAmount,0)) > 0 
	--AND SUM(ISNULL(TFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TR.PaidAmount,0.00)) >0
	IF(@rCount = 1)
		BEGIN
			SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount,COUNT(T.PaidAmount)AS StudentCount
			FROM #tempPaidDetailsClassWise T
			WHERE T.PaidAmount > 0
			GROUP BY T.OrgGroupId,T.ClassName,T.ClassId,T.OrgGroupName
			HAVING ISNULL(SUM(T.PaidAmount),0) > 0
			ORDER BY T.ClassId
			
		END
	IF(@rCount = 2)
		BEGIN
			SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS UnPaidAmount,COUNT(T.PendingAmount)AS StudentCount
			FROM #tempPaidDetailsClassWise T
				WHERE T.PendingAmount > 0
			GROUP BY T.OrgGroupId,T.ClassName,T.ClassId,T.OrgGroupName
			HAVING ISNULL(SUM(T.PendingAmount),0) > 0
			ORDER BY T.ClassId
		END
		DROP TABLE #tempPaidDetailsClassWise
	DROP TABLE #tempFSClassWise
	DROP TABLE #tempRClassWise
	END
ELSE IF(@rType ='FeeStatusPaid&UnpaidDetils')
BEGIN 
CREATE TABLE #tempPaidDetails(
	SourceId bigint,
	OrgGroupId int,
	ClassName nvarchar(50),
	DivisionId int,
	DivisionName nvarchar(50),
	Code nvarchar(20),
	Name nvarchar(200),
	ParentContactNo nvarchar(50),
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2),
	ClassOrderIndex int,
	DivisionOrder int,
	RollNo int
)
CREATE TABLE #tempFS(
    Id int,
    Amount DECIMAL(12,2),
	AcademicId BIGINT
)
INSERT INTO #tempFS
SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		SA1.Id AS AcademicId
	FROM 
		sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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 sFee.tFeeMaster FM ON FM.Id=FS1.FeeId		
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA1.OrgId		
		
	WHERE 
		(FS1.IsOptional=0) AND  COGBM.Id=@rCommonOrgGroupBatchId 
		AND((OM.OrgGroupId) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
		--AND(BM.IsActive =1) 
UNION ALL				
SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		SA1.Id As 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON OM.Id = SA1.OrgId
		
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND COGBM.Id=@rCommonOrgGroupBatchId 
	WHERE
		(FS1.IsOptional=1)
		AND ((OM.OrgGroupId) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
		--AND(BM.IsActive =1)


CREATE TABLE #tempR(    
    PaidAmount DECIMAL(12,2),
	FeeSetupId int,
	SourceId BIGINT
)
INSERT INTO #tempR
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
	    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.tOrganizationMaster OM ON OM.Id = SA1.OrgId
		
	WHERE		
		(R.SourceTypeId = 2001)
		AND (OM.OrgGroupId = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		And O.IsObsolete = 0
		--AND(BM.IsActive =1) 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate 
		
	GROUP BY FeeSetupId,R.SourceId 

INSERT INTO #tempPaidDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		ISNULL(O.Id,0) AS OrgGroupId,
		ISNULL(SA.ClassName,'') AS ClassName,
		ISNULL(SA.DivisionId,0) AS DivisionId,
		ISNULL(SA.DivisionName,'') AS DivisionName,
		ISNULL(SA.Code,'') As Code,
		ISNULL(SA.Name,'') AS Name,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		SUM(ISNULL(TR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TR.PaidAmount,0.00))AS PendingAmount,
		 SA.ClassOrderIndex,  
		 SA.DivisionOrder,
		 SA.RollNo 
	FROM 		
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempFS TFS ON TFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempR TR ON TR.FeeSetupId = TFS.Id AND SA.AcademicId = TR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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			
		
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND((SA.ClassId = @rClassId)OR(@rClassId=0))
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
	And O.IsObsolete = 0
	GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.Code,SA.Name,SC.ParentContactNo,SA.ClassOrderIndex,SA.DivisionOrder,SA.RollNo,SA.DivisionId,SA.AcademicId
	--HAVING SUM(ISNULL(TR.PaidAmount,0)) > 0 
	--AND SUM(ISNULL(TFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TR.PaidAmount,0.00)) >0

	IF(@rCount = 1)
		BEGIN
			SELECT T.SourceId, T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
				T.ParentContactNo AS ParentContactNo,T.PaidAmount AS PaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
			FROM #tempPaidDetails T
			WHERE T.PaidAmount > 0
			--WHERE PendingAmount  = 0
			GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PaidAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
			HAVING T.PaidAmount > 0
			ORDER BY T.OrgGroupId,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
			
		END
	IF(@rCount = 2)
		BEGIN
			SELECT T.SourceId,T.OrgGroupId,T.ClassName+' - '+  T.DivisionName  AS ClassDivision,T.Code AS Code,T.Name AS Name,T.DivisionId,
				T.ParentContactNo AS ParentContactNo,T.PendingAmount AS UnPaidAmount,T.ClassOrderIndex,T.DivisionOrder,T.RollNo
			FROM #tempPaidDetails T
			WHERE T.PendingAmount > 0
			--WHERE PendingAmount  != 0
			GROUP BY T.OrgGroupId,T.ClassName,T.DivisionName,T.Name,T.ParentContactNo,T.PendingAmount,T.Code,T.ClassOrderIndex,T.DivisionOrder,T.RollNo,T.DivisionId,T.SourceId
			HAVING T.PendingAmount > 0
			ORDER BY T.PendingAmount DESC
		END
	
	DROP TABLE #tempPaidDetails
	DROP TABLE #tempFS
	DROP TABLE #tempR
	

END

ELSE IF(@rType ='FeeStatusTotalHeadwiseAmount')
BEGIN 
	IF(@rSyncDate =1)
		BEGIN
		DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			CREATE TABLE #tempTotalPaidDetailsSync (
	FeeHeadId bigint,
	FeeHeadName nvarchar(200),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	ReceiptBookId bigint,
	RecepitTitle nvarchar(100),
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2),
	OrderIndex int
	)
CREATE TABLE #tempHFSSync (
    Id INT,
    Amount DECIMAL(12,2),
    FeeHeadId INT,
    CollectionGroupId INT,
    ReceiptBookId INT,
    AcademicId BIGINT
    
)	
INSERT INTO #tempHFSSync	
SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		 INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	     INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	     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 sFee.tFeeMaster FM ON FM.Id=FS1.FeeId		 
		 INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	     
		 
	WHERE 
	     (FS1.IsOptional=0) --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
	     AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		 And O.IsObsolete = 0
	      
				--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
				--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
UNION ALL
				
SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	WHERE
				
		(FS1.IsOptional=1) --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
CREATE TABLE #tempHRSync (
    PaidAmount DECIMAL(12,2),
    FeeSetupId INT,
    SourceId BIGINT
 
)
INSERT INTO #tempHRSync	
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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	  
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId
INSERT INTO #tempTotalPaidDetailsSync
SELECT 
		ISNULL(FHM.Id,0) AS FeeHeadId,
		ISNULL(FHM.code,'') AS FeeHeadName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Id,'')  AS ReceiptBookId,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		SUM(ISNULL(THR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(THFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(THR.PaidAmount,0.00))AS PendingAmount,
		FHM.OrderIndex
	FROM 
		sStudent.tAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempHFSSync THFS ON THFS.AcademicId=SA.Id
		
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=THFS.Id AND FA.SourceId=SA.Id
		LEFT JOIN #tempHRSync THR ON THR.FeeSetupId = THFS.Id AND SA.Id = THR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)		
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId		
	    INNER JOIN sFee.tReceiptBookMaster RBM ON THFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON THFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=THFS.FeeHeadId	
	WHERE
	 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(BM.IsActive =1) --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
	And O.IsObsolete = 0
	GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

	INSERT INTO sFee.tTempTotalPaidDetails
	SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
				ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
				ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
				ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
				T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE() from #tempTotalPaidDetailsSync T
	GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
	ORDER BY T.OrderIndex
	SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))		

		--New Temp Table Create-------------
	CREATE TABLE #tempTotalStudentCountSync (
	AcademicId bigint,
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	EndDate date,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2)
	)
	
	--Test
	
   CREATE TABLE #tempHFSSync1(
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT
	)
	INSERT INTO #tempHFSSync1
	SELECT 
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.FeeHeadId,
			FS1.CollectionGroupId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 	        
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
			(FS1.IsOptional=0) --AND BM.IsActive=1
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
			And O.IsObsolete = 0
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			UNION ALL
				
	SELECT 
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.FeeHeadId,
			FS1.CollectionGroupId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId
		    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
		    AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
		   (FS1.IsOptional=1) --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
		    AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			And O.IsObsolete = 0

	CREATE TABLE #tempHRSync1(
	     PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT     
	)
	
	INSERT INTO #tempHRSync1 
	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
		    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
		WHERE		
			(R.SourceTypeId = 2001)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND (R.IsObsolete = 0) --AND BM.IsActive=1 
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
			And O.IsObsolete = 0
			--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
		GROUP BY FeeSetupId,R.SourceId
	INSERT INTO #tempTotalStudentCountSync
	SELECT 
			ISNULL(SA.Id,0) AS AcademicId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Code,'') AS CollectionGroup,
			ISNULL(RBM.Title,'')  AS ReceiptTitle,
			ISNULL(RBM.Id,0) As ReceiptBookId,
			(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
			INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
			WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			 ORDER BY ReceiptDate DESC) EndDate,
			SUM(ISNULL(HR1.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(HFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(HR1.PaidAmount,0.00))AS PendingAmount
	FROM 
		sStudent.tAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 
		INNER JOIN #tempHFSSync1 HFS1 ON HFS1.AcademicId=SA.Id
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=HFS1.Id AND FA.SourceId=SA.Id
		LEFT JOIN #tempHRSync1 HR1 ON HR1.FeeSetupId = HFS1.Id AND SA.Id = HR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		INNER JOIN sFee.tReceiptBookMaster RBM ON HFS1.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON HFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=HFS1.FeeHeadId	
	WHERE
	 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
	 And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(BM.IsActive =1) 
	AND COGBM.Id=@rCommonOrgGroupBatchId 
	GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
	INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,
			ISNULL(E.EndDate,'1900-01-01')AS EndDate,
			--E.EndDate AS EndDate,
			SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount,@rCommonOrgGroupBatchId,GETDATE() FROM (
			SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(T.CollectionGroup,'') As CollectionGroup,
				ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
				ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from #tempTotalStudentCountSync T
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCountSync --CollectionGroupId,CollectionGroup,
						WHERE PendingAmount  = 0
						GROUP BY CollectionGroupId,ReceiptBookId
					) A ON A.CollectionGroupId = T.CollectionGroupId
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCountSync
						WHERE PendingAmount !=0
						GROUP BY CollectionGroupId,ReceiptBookId
					)B ON B.CollectionGroupId = T.CollectionGroupId 
					GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
					)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
		 SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	


		-------------Create a New Temp Table For Pending date-----------------
	CREATE TABLE #tempPendingCountSync(
	AcademicId bigint,
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	EndDate date,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2)
	)
	CREATE TABLE #tempHFSSync2(
	     Id INT,
	     Amount DECIMAL(12,2),
	     FeeHeadId INT,
	     CollectionGroupId INT,
	     ReceiptBookId INT,
	     AcademicId BIGINT
	)
	INSERT INTO #tempHFSSync2
	SELECT 
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.FeeHeadId,
			FS1.CollectionGroupId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 			
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
			(FS1.IsOptional=0) --AND BM.IsActive=1 
			AND COGBM.Id=@rCommonOrgGroupBatchId 
			And O.IsObsolete = 0
			--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.FeeHeadId,
			FS1.CollectionGroupId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId
		    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
		    AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId --AND BM.IsActive=1
	WHERE
				
		    (FS1.IsOptional=1) AND COGBM.Id=@rCommonOrgGroupBatchId 
			And O.IsObsolete = 0
			--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	CREATE TABLE #tempHRSync2(
	       PaidAmount DECIMAL(12,2),
	       FeeSetupId INT,
	       SourceId BIGINT
	       
	)
	INSERT INTO #tempHRSync2
	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
		    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
	    WHERE		
			(R.SourceTypeId = 2001)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND (R.IsObsolete = 0) --AND BM.IsActive=1 
			AND COGBM.Id=@rCommonOrgGroupBatchId 
			And O.IsObsolete = 0
			--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
			--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
			GROUP BY FeeSetupId,R.SourceId
	
	
	INSERT INTO #tempPendingCountSync
	SELECT 
			ISNULL(SA.Id,0) AS AcademicId,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Code,'') AS CollectionGroup,
			ISNULL(RBM.Title,'')  AS ReceiptTitle,
			ISNULL(RBM.Id,0) As ReceiptBookId,
				(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    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.tOrganizationMaster OM ON SA.OrgId = OM.Id 
			
			INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
			
	WHERE  
			(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			And O.IsObsolete = 0
	ORDER BY ReceiptDate DESC) EndDate,
			SUM(ISNULL(HR2.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(HFS2.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(HR2.PaidAmount,0.00))AS PendingAmount
	FROM 
		sStudent.tAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 
		INNER JOIN #tempHFSSync2 HFS2 ON HFS2.AcademicId=SA.Id
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=HFS2.Id AND FA.SourceId=SA.Id
		LEFT JOIN #tempHRSync2 HR2 ON HR2.FeeSetupId = HFS2.Id AND SA.Id = HR2.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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.tOrganizationMaster OM ON OM.Id = SA.OrgId
		
		--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		INNER JOIN sFee.tReceiptBookMaster RBM ON HFS2.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON HFS2.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=HFS2.FeeHeadId	
	WHERE
	 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
	 And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(BM.IsActive =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
	GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	INSERT INTO sFee.tTempPendingCount
	SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
	FROM   #tempPendingCountSync T
	WHERE PendingAmount !=0
	 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
	 GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup
	 SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	 
	 
	
	DROP TABLE #tempTotalPaidDetailsSync
	DROP TABLE #tempHFSSync
	DROP TABLE  #tempHRSync
	DROP TABLE #tempTotalStudentCountSync
	DROP TABLE #tempHFSSync1
	DROP TABLE #tempHRSync1
	DROP TABLE #tempPendingCountSync
	DROP TABLE #tempHFSSync2
	DROP TABLE #tempHRSync2
		END
	ELSE
		BEGIN
		IF  Exists(select 1 from sFee.tTempTotalPaidDetails where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0)) )
			BEGIN
	
				SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN

			DELETE  sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DELETE  sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
					CREATE TABLE #tempTotalPaidDetails (
				FeeHeadId bigint,
				FeeHeadName nvarchar(200),
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				ReceiptBookId bigint,
				RecepitTitle nvarchar(100),
				PaidAmount DECIMAL(12,2),
				PendingAmount DECIMAL(12,2),
				OrderIndex int
				)
			CREATE TABLE #tempHFS (
				Id INT,
				Amount DECIMAL(12,2),
				FeeHeadId INT,
				CollectionGroupId INT,
				ReceiptBookId INT,
				AcademicId BIGINT
    
			)	
			INSERT INTO #tempHFS	
			SELECT 
					 FS1.Id,
					 ISNULL(FS1.Amount,0)AS Amount,
					 FM.FeeHeadId,
					 FS1.CollectionGroupId,
					 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					 SA1.Id AS AcademicId
				FROM sFee.tFeeSetup FS1
					 INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
					 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					 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 sFee.tFeeMaster FM ON FM.Id=FS1.FeeId		 
					 INNER JOIN  sSetup.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	     
		 
				WHERE 
					 (FS1.IsOptional=0) --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
					 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
	      And O.IsObsolete = 0
							--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
							--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
							--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
							--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
			UNION ALL
				
			SELECT 
					 FS1.Id,
					 ISNULL(FS1.Amount,0)AS Amount,
					 FM.FeeHeadId,
					 FS1.CollectionGroupId,
					 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					 SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
					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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
					AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
				
					(FS1.IsOptional=1) --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
					AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
					And O.IsObsolete = 0
			CREATE TABLE #tempHR (
				PaidAmount DECIMAL(12,2),
				FeeSetupId INT,
				SourceId BIGINT
 
			)
			INSERT INTO #tempHR	
			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
					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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	  
				WHERE		
					(R.SourceTypeId = 2001)
					--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
					AND (R.IsObsolete = 0) --AND BM.IsActive=1 
					AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
					And O.IsObsolete = 0
					--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
					--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
				GROUP BY FeeSetupId,R.SourceId
			INSERT INTO #tempTotalPaidDetails
			SELECT 
					ISNULL(FHM.Id,0) AS FeeHeadId,
					ISNULL(FHM.code,'') AS FeeHeadName,
					ISNULL(CGM.Id,0) AS CollectionGroupId,
					ISNULL(CGM.Code,'') AS CollectionGroup,
					ISNULL(RBM.Id,'')  AS ReceiptBookId,
					ISNULL(RBM.Title,'')  AS ReceiptTitle,
					SUM(ISNULL(THR.PaidAmount,0)) AS PaidAmount,
					SUM(ISNULL(THFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(THR.PaidAmount,0.00))AS PendingAmount,
					FHM.OrderIndex
				FROM 
					sStudent.tAcademic SA
					LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
					INNER JOIN #tempHFS THFS ON THFS.AcademicId=SA.Id
		
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=THFS.Id AND FA.SourceId=SA.Id
					LEFT JOIN #tempHR THR ON THR.FeeSetupId = THFS.Id AND SA.Id = THR.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					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.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)		
					--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId		
					INNER JOIN sFee.tReceiptBookMaster RBM ON THFS.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM ON THFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=THFS.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
				And O.IsObsolete = 0
				GROUP BY FHM.Id,FHM.code,CGM.Id,CGM.Code,RBM.Title,RBM.Id,FHM.OrderIndex

				INSERT INTO sFee.tTempTotalPaidDetails
				SELECT @rOrgGroupId,T.FeeHeadId,ISNULL(T.FeeHeadName,'') AS FeeHeadName,T.CollectionGroupId,
				ISNULL(T.CollectionGroup,'') As CollectionGroup,ISNULL(T.ReceiptBookId,0)AS ReceiptBookId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,
				ISNULL(T.PaidAmount,0) AS PaidAmount,ISNULL(T.PendingAmount,0) AS  PendingAmount,
				ISNULL(ISNULL(T.PaidAmount,0)+ISNULL(T.PendingAmount,0),0) AS TotalAmount,
				T.OrderIndex,@rCommonOrgGroupBatchId,GETDATE()from #tempTotalPaidDetails T
				GROUP BY T.PaidAmount,T.PendingAmount,T.CollectionGroup,T.FeeHeadName,T.FeeHeadId,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroupId,T.OrderIndex
				ORDER BY T.OrderIndex
			SELECT * FROM sFee.tTempTotalPaidDetails WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	

					--New Temp Table Create-------------
				CREATE TABLE #tempTotalStudentCount (
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,2),
				PendingAmount DECIMAL(12,2)
				)
	
				--Test
	
			   CREATE TABLE #tempHFS1(
				   Id INT,
				   Amount DECIMAL(12,2),
				   FeeHeadId INT,
				   CollectionGroupId INT,
				   ReceiptBookId INT,
				   AcademicId BIGINT
				)
				INSERT INTO #tempHFS1
				SELECT 
						FS1.Id,
						ISNULL(FS1.Amount,0)AS Amount,
						FM.FeeHeadId,
						FS1.CollectionGroupId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						SA1.Id AS AcademicId
				FROM sFee.tFeeSetup FS1
						INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
						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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 	        
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
						(FS1.IsOptional=0) --AND BM.IsActive=1
						AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
						And O.IsObsolete = 0
						--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
						--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
						--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
						--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
						--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
						UNION ALL
				
				SELECT 
						FS1.Id,
						ISNULL(FS1.Amount,0)AS Amount,
						FM.FeeHeadId,
						FS1.CollectionGroupId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
						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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
						AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				WHERE
				
					   (FS1.IsOptional=1) 
					   --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate
						AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
						And O.IsObsolete = 0

				CREATE TABLE #tempHR1(
					 PaidAmount DECIMAL(12,2),
					 FeeSetupId INT,
					 SourceId BIGINT     
				)
	
				INSERT INTO #tempHR1 
				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
						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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
					WHERE		
						(R.SourceTypeId = 2001)
						--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
						AND (R.IsObsolete = 0) --AND BM.IsActive=1 
						AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
						And O.IsObsolete = 0
						--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate
						--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
					GROUP BY FeeSetupId,R.SourceId
				INSERT INTO #tempTotalStudentCount
				SELECT 
						ISNULL(SA.Id,0) AS AcademicId,
						ISNULL(CGM.Id,0) AS CollectionGroupId,
						ISNULL(CGM.Code,'') AS CollectionGroup,
						ISNULL(RBM.Title,'')  AS ReceiptTitle,
						ISNULL(RBM.Id,0) As ReceiptBookId,
						(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
						INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
						INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
						WHERE  (LEFT(CGM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
						 ORDER BY ReceiptDate DESC) EndDate,
						SUM(ISNULL(HR1.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(HFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(HR1.PaidAmount,0.00))AS PendingAmount
				FROM 
					sStudent.tAcademic SA
					LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 
					INNER JOIN #tempHFS1 HFS1 ON HFS1.AcademicId=SA.Id
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=HFS1.Id AND FA.SourceId=SA.Id
					LEFT JOIN #tempHR1 HR1 ON HR1.FeeSetupId = HFS1.Id AND SA.Id = HR1.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					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.tOrganizationMaster OM ON OM.Id = SA.OrgId
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
					INNER JOIN sFee.tReceiptBookMaster RBM ON HFS1.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM ON HFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=HFS1.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				 And O.IsObsolete = 0
				-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND COGBM.Id=@rCommonOrgGroupBatchId 
				GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
	
			INSERT INTO sFee.tTempTotalStudentCount
			SELECT @rOrgGroupId,E.CollectionGroupId,E.CollectionGroup AS CollectionGroup,E.ReceiptBookId AS ReceiptId,E.ReceiptCollection AS ReceiptCollection,
			ISNULL(E.EndDate,'1900-01-01')AS EndDate,
			--E.EndDate AS EndDate,
			SUM(E.TotalStudentCount) AS TotalStudentCount,SUM(E.PaidStudentCount) AS PaidStudentCount,SUM(E.PendingStudentCount) AS PendingStudentCount,@rCommonOrgGroupBatchId,GETDATE() FROM (
			SELECT ISNULL(T.ReceiptBookId,0) AS ReceiptBookId,T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(T.CollectionGroup,'') As CollectionGroup,
				ISNULL(COUNT(T.AcademicId),0) AS TotalStudentCount,T.CollectionGroupId AS CollectionGroupId,
				ISNULL(A.PaidCount,0) AS PaidStudentCount,ISNULL(B.PendingCount,0) AS PendingStudentCount,CASE CONVERT(varchar(20),T.EndDate,103) WHEN '01/01/1900' THEN '' ELSE T.EndDate END  AS EndDate from #tempTotalStudentCount T
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PaidCount  FROM #tempTotalStudentCount --CollectionGroupId,CollectionGroup,
						WHERE PendingAmount  = 0
						GROUP BY CollectionGroupId,ReceiptBookId
					) A ON A.CollectionGroupId = T.CollectionGroupId
					LEFT JOIN 
					(
						SELECT CollectionGroupId,ReceiptBookId,ISNULL(COUNT(AcademicId),0) AS PendingCount  FROM #tempTotalStudentCount
						WHERE PendingAmount !=0
						GROUP BY CollectionGroupId,ReceiptBookId
					)B ON B.CollectionGroupId = T.CollectionGroupId 
					GROUP BY T.CollectionGroupId,T.CollectionGroup,T.RecepitTitle,T.ReceiptBookId,T.CollectionGroup,A.PaidCount,B.PendingCount,T.EndDate
					)E
					GROUP BY E.ReceiptBookId,E.ReceiptCollection,E.CollectionGroup,E.EndDate,E.CollectionGroupId
				 SELECT * FROM sFee.tTempTotalStudentCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))


					-------------Create a New Temp Table For Pending date-----------------
				CREATE TABLE #tempPendingCount(
				AcademicId bigint,
				CollectionGroupId bigint,
				CollectionGroup nvarchar(200),
				RecepitTitle nvarchar(100),
				ReceiptBookId bigint,
				EndDate date,
				PaidAmount DECIMAL(12,2),
				PendingAmount DECIMAL(12,2)
				)
				CREATE TABLE #tempHFS2(
					 Id INT,
					 Amount DECIMAL(12,2),
					 FeeHeadId INT,
					 CollectionGroupId INT,
					 ReceiptBookId INT,
					 AcademicId BIGINT
				)
				INSERT INTO #tempHFS2
				SELECT 
						FS1.Id,
						ISNULL(FS1.Amount,0)AS Amount,
						FM.FeeHeadId,
						FS1.CollectionGroupId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						SA1.Id AS AcademicId
				FROM sFee.tFeeSetup FS1
						INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
						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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 			
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				WHERE 
						(FS1.IsOptional=0) --AND BM.IsActive=1 
						AND COGBM.Id=@rCommonOrgGroupBatchId 
						And O.IsObsolete = 0
						--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
						--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
						--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
						--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
						--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				UNION ALL
				
				SELECT 
						FS1.Id,
						ISNULL(FS1.Amount,0)AS Amount,
						FM.FeeHeadId,
						FS1.CollectionGroupId,
						ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
						SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
						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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
						AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId --AND BM.IsActive=1
				WHERE
				
						(FS1.IsOptional=1) AND COGBM.Id=@rCommonOrgGroupBatchId	
						And O.IsObsolete = 0
				CREATE TABLE #tempHR2(
					   PaidAmount DECIMAL(12,2),
					   FeeSetupId INT,
					   SourceId BIGINT
	       
				)
				INSERT INTO #tempHR2
				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
						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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
					WHERE		
						(R.SourceTypeId = 2001)
						--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
						AND (R.IsObsolete = 0) --AND BM.IsActive=1 
						AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
						--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
						GROUP BY FeeSetupId,R.SourceId	
				INSERT INTO #tempPendingCount
				SELECT 
						ISNULL(SA.Id,0) AS AcademicId,
						ISNULL(CGM.Id,0) AS CollectionGroupId,
						ISNULL(CGM.Code,'') AS CollectionGroup,
						ISNULL(RBM.Title,'')  AS ReceiptTitle,
						ISNULL(RBM.Id,0) As ReceiptBookId,
							(SELECT TOP 1 ReceiptDate FROM sFee.tReceipt R 
						INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
						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.tOrganizationMaster OM ON SA.OrgId = OM.Id 
			
						INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.ReceiptBookId = R.ReceiptBookId
			
				WHERE  
						(LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
						AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
						And O.IsObsolete = 0
				ORDER BY ReceiptDate DESC) EndDate,
						SUM(ISNULL(HR2.PaidAmount,0)) AS PaidAmount,
						SUM(ISNULL(HFS2.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(HR2.PaidAmount,0.00))AS PendingAmount
				FROM 
					sStudent.tAcademic SA
					 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		 
					INNER JOIN #tempHFS2 HFS2 ON HFS2.AcademicId=SA.Id
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=HFS2.Id AND FA.SourceId=SA.Id
					LEFT JOIN #tempHR2 HR2 ON HR2.FeeSetupId = HFS2.Id AND SA.Id = HR2.SourceId
					INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
					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.tOrganizationMaster OM ON OM.Id = SA.OrgId
		
					--INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
					INNER JOIN sFee.tReceiptBookMaster RBM ON HFS2.ReceiptBookId=RBM.Id
					LEFT JOIN sFee.tCollectionGroupMaster CGM ON HFS2.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=HFS2.FeeHeadId	
				WHERE
				 (O.Id = @rOrgGroupId OR (@rOrgGroupId=0))	
				-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
				And O.IsObsolete = 0
				GROUP BY SA.Id,CGM.Id,CGM.Code,RBM.Title,RBM.Id,CGM.EndDate
		
		INSERT INTO sFee.tTempPendingCount
				SELECT @rOrgGroupId,ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,ISNULL(T.CollectionGroup,'') As CollectionGroup,T.ReceiptBookId AS ReceiptId,
				T.RecepitTitle +'-'+T.CollectionGroup AS ReceiptCollection,ISNULL(COUNT(T.AcademicId),0) AS LastPendingCount,@rCommonOrgGroupBatchId,GETDATE()
				FROM   #tempPendingCount T
				WHERE PendingAmount !=0
				 AND  CONVERT(DATE,T.EndDate) BETWEEN CONVERT(DATE,GETDATE()- @rDays) AND CONVERT(DATE,GETDATE())
				 GROUP BY T.CollectionGroupId,T.CollectionGroup,T.ReceiptBookId,T.RecepitTitle,T.CollectionGroup
		SELECT * FROM sFee.tTempPendingCount WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))	
	
				DROP TABLE #tempTotalPaidDetails
				DROP TABLE #tempHFS
				DROP TABLE  #tempHR
				DROP TABLE #tempTotalStudentCount
				DROP TABLE #tempHFS1
				DROP TABLE #tempHR1
				DROP TABLE #tempPendingCount
				DROP TABLE #tempHFS2
				DROP TABLE #tempHR2
			END

			

		END
	 
END

ELSE IF(@rType ='FeeStatusPaidSubPartAmount')
BEGIN 
	CREATE TABLE #tempPaidSubPart (
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	ClassId bigint,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2),
	ClassOrderIndex int,
	MonthName nvarchar(15)
	--,DivisionOrder int
	)
   
    CREATE TABLE #tempPFS (
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    
    INSERT INTO #tempPFS	
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
	   (FS1.IsOptional=0)
	   --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))


     CREATE TABLE #tempPR (
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPR	
     SELECT 
		  ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 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
		  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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		 
	WHERE		
		  (R.SourceTypeId = 2001)
		   AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		   AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		   AND COGBM.Id=@rCommonOrgGroupBatchId 
		   And O.IsObsolete = 0
		   --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
		   --AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
 

IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPart
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 --O.Id AS OrgGroupId,
		 --O.Title As OrgGroupName,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 --SA.DivisionId AS DivisionId,
		 --SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR.PaidAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex,
		TPR.ReceiptDate
		--,SA.DivisionOrder
		 
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN #tempPFS TPFS ON TPFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=TPFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPR TPR ON TPR.FeeSetupId = TPFS.Id AND SA.AcademicId = TPR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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 sFee.tReceiptBookMaster RBM ON TPFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON TPFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=TPFS.FeeHeadId	    	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
	And O.IsObsolete = 0
		GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,TPR.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,DATENAME(month,T.MonthName)MonthName from #tempPaidSubPart T
		WHERE T.PaidAmount > 0
		group by T.OrgGroupId,T.PaidAmount,T.ClassName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex,T.OrgGroupName,DATENAME(month,T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		ORDER BY T.ClassOrderIndex
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempPFS1 (
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    INSERT INTO #tempPFS1
    SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		 INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	     INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	     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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		 --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		 AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		 And O.IsObsolete = 0
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		 --AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		
	WHERE
				
		(FS1.IsOptional=1) AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
    
    CREATE TABLE #tempPR1(
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPR1
     SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		

	WHERE		
		(R.SourceTypeId = 2001)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		AND (R.IsObsolete = 0) 
		And O.IsObsolete = 0
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate  
   
	
	INSERT INTO #tempPaidSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 --O.Id AS OrgGroupId,
		 --O.Title As OrgGroupName,
		 SA.OrgId AS OrgGroupId,SA.OrganizationName As OrgGroupName,
		 SA.ClassId As ClassId,
		 SA.ClassName AS ClassName,
		 --SA.DivisionId AS DivisionId,
		 --SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR1.PaidAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex,TPR1.ReceiptDate
		--,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPFS1 TPFS1 ON TPFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TPFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPR1 TPR1 ON TPR1.FeeSetupId = TPFS1.Id AND SA.AcademicId = TPR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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 sFee.tReceiptBookMaster RBM 
			ON TPFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TPFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TPFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	And O.IsObsolete = 0
		GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.ClassId,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex,TPR1.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount,COUNT(T.AcademicId) As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex,DATENAME(month,T.MonthName)MonthName from #tempPaidSubPart T
		WHERE T.PaidAmount > 0
		group by T.OrgGroupId,T.ClassName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex,T.OrgGroupName,DATENAME(month,T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		ORDER BY T.ClassOrderIndex
	END
	
	DROP TABLE #tempPaidSubPart
	DROP TABLE #tempPFS
	DROP TABLE #tempPR
	DROP TABLE #tempPFS1
	DROP TABLE #tempPR1
	
END

ELSE IF(@rType ='FeeStatusPaidSubPartAmountMonthWise')
BEGIN 
	CREATE TABLE #tempPaidSubPartMonthWise (
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2),
	MonthName nvarchar(15),
	)
   
    CREATE TABLE #tempPFSMonthWise (
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    
    INSERT INTO #tempPFSMonthWise	
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
	   (FS1.IsOptional=0)
	   --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))


     CREATE TABLE #tempPRMonthWise (
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise	
     SELECT 
		  ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 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
		  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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		 
	WHERE		
		  (R.SourceTypeId = 2001)
		   AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		   AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		   AND COGBM.Id=@rCommonOrgGroupBatchId 
		   And O.IsObsolete = 0
		   --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
		   --AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
 

IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPaidSubPartMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR.PaidAmount,0.00))AS PendingAmount,
		TPR.ReceiptDate		 
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN #tempPFSMonthWise TPFS ON TPFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=TPFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise TPR ON TPR.FeeSetupId = TPFS.Id AND SA.AcademicId = TPR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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 sFee.tReceiptBookMaster RBM ON TPFS.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON TPFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
	    INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=TPFS.FeeHeadId	    	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.PaidAmount,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempPFSMonthWise1 (
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT  
    )
    INSERT INTO #tempPFSMonthWise1
    SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		 SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		 INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	     INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	     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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		 INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		 --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		 AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		 And O.IsObsolete = 0
		 --AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		 --AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		 FS1.Id,
		 ISNULL(FS1.Amount,0)AS Amount,
		 FM.FeeHeadId,
		 FS1.CollectionGroupId,
		 ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		
	WHERE
				
		(FS1.IsOptional=1) AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
    
    CREATE TABLE #tempPRMonthWise1(
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT,
		  ReceiptDate DATE
     )
     INSERT INTO #tempPRMonthWise1
     SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId ,R.SourceId,R.ReceiptDate
	 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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
		

	WHERE		
		(R.SourceTypeId = 2001)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		AND (R.IsObsolete = 0) 
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate  
   
	
	INSERT INTO #tempPaidSubPartMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 O.Title As OrgGroupName,		
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TPR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TPFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TPR1.PaidAmount,0.00))AS PendingAmount,
		TPR1.ReceiptDate
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPFSMonthWise1 TPFS1 ON TPFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TPFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPRMonthWise1 TPR1 ON TPR1.FeeSetupId = TPFS1.Id AND SA.AcademicId = TPR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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 sFee.tReceiptBookMaster RBM 
			ON TPFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TPFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TPFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	And O.IsObsolete = 0
		GROUP by O.Id,O.Title,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,TPR1.ReceiptDate
	
	select T.OrgGroupId,T.OrgGroupName,ISNULL(SUM(T.PaidAmount),0) AS PaidAmount,COUNT(T.AcademicId) As StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,DATENAME(month,T.MonthName)MonthName,DATEPART(M, T.MonthName) AS Month from #tempPaidSubPartMonthWise T
		group by T.OrgGroupId,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName,DATENAME(month,T.MonthName),DATEPART(M, T.MonthName)
		HAVING ISNULL(SUM(T.PaidAmount),0) > 0
		--ORDER BY DATEPART(MONTH, T.MonthName)
	END
	
	DROP TABLE #tempPaidSubPartMonthWise
	DROP TABLE #tempPFSMonthWise
	DROP TABLE #tempPRMonthWise
	DROP TABLE #tempPFSMonthWise1
	DROP TABLE #tempPRMonthWise1
	
END

ELSE IF(@rType ='FeeStatusPendingSubPartAmount')
BEGIN 
CREATE TABLE #tempPendingSubPart(
	AcademicId bigint,
	OrgGroupId int,
	OrgGroupName nvarchar(50),
	ClassId bigint ,
	ClassName nvarchar(50),
	--DivisionId bigint,
	--DivisionName nvarchar(50),
	CollectionGroupId bigint,
	CollectionGroup nvarchar(200),
	RecepitTitle nvarchar(100),
	ReceiptBookId bigint,
	PaidAmount DECIMAL(12,2),
	PendingAmount DECIMAL(12,2),
	ClassOrderIndex int
	--,DivisionOrder int
	)

   CREATE TABLE #tempSFS(
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT
    )
    INSERT INTO #tempSFS
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0)
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		And O.IsObsolete = 0
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId --AND BM.IsActive=1 --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
		
    WHERE
				
	   (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 

    
      CREATE TABLE #tempSR(
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT
     )
     INSERT INTO #tempSR
     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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    

	  WHERE		
		(R.SourceTypeId = 2001)
		 AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) --AND BM.IsActive=1 
		 AND COGBM.Id=@rCommonOrgGroupBatchId 
		 And O.IsObsolete = 0
		 --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		 AND (R.IsObsolete = 0) 
		 --AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	  GROUP BY FeeSetupId,R.SourceId 


IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempPendingSubPart
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 --O.Id AS OrgGroupId,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		-- O.Title AS OrgGroupName,
		 SA.ClassId  AS ClassId,
		 SA.ClassName AS ClassName,
		 --SA.DivisionId AS DivisionId,
		 --SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TSR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TSFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TSR.PaidAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex
		--,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA 
		INNER JOIN #tempSFS TSFS ON TSFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TSFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempSR TSR ON TSR.FeeSetupId = TSFS.Id AND SA.AcademicId = TSR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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 sFee.tReceiptBookMaster RBM 
			ON TSFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TSFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TSFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	And O.IsObsolete = 0
		GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName,SA.AcademicId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,COUNT(T.AcademicId)AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex from #tempPendingSubPart T
		WHERE T.PendingAmount >0
		group by T.OrgGroupId,T.OrgGroupName,T.PaidAmount,T.ClassName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex
		--HAVING ISNULL(SUM(T.PendingAmount),0) > 0
		ORDER BY T.ClassOrderIndex
		
    DROP TABLE #tempPendingSubPart
	DROP TABLE #tempSFS
	DROP TABLE #tempSR
		
		
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempSFS1(
       Id INT,
       Amount DECIMAL(12,2),
       FeeHeadId INT,
       CollectionGroupId INT,
       ReceiptBookId INT,
       AcademicId BIGINT
    )
	INSERT INTO #tempSFS1
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0)
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0)) 
		And O.IsObsolete = 0
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	 
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	WHERE
				
		(FS1.IsOptional=1)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		And O.IsObsolete = 0
		 --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			
	CREATE TABLE #tempSR1(
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT
     )
	INSERT INTO #tempSR1
    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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    

	WHERE		
		(R.SourceTypeId = 2001)
		AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 	
		 
	
	INSERT INTO #tempPendingSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 --O.Id AS OrgGroupId,
		 --O.Title As OrgGroupName,
		 SA.OrgId AS OrgGroupId,
		 SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 --SA.DivisionId AS DivisionId,
		 --SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TSR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TSFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TSR1.PaidAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex  
		--,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempSFS1 TSFS1 ON TSFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TSFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempSR1 TSR1 ON TSR1.FeeSetupId = TSFS1.Id AND SA.AcademicId = TSR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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.tOrgGroupMaster O ON O.Id = LEFT(SA.OrgGroupBatchId,4)
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TSFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TSFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TSFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	And O.IsObsolete = 0 
		GROUP by SA.OrgId,SA.OrganizationName,SA.ClassName,SA.AcademicId,SA.ClassId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex
	
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount, COUNT(T.AcademicId) AS studentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.ClassOrderIndex from #tempPendingSubPart T
		WHERE T.PendingAmount >0
		GROUP BY T.OrgGroupId,T.ClassName,T.OrgGroupName,T.ClassId,T.CollectionGroupId,T.ReceiptBookId,T.ClassOrderIndex
		--HAVING ISNULL(SUM(T.PendingAmount),0) > 0
		ORDER BY T.ClassOrderIndex	
		
    DROP TABLE #tempSFS1
	DROP TABLE #tempSR1
		
	END
	
	
	
	
		
	END
  ELSE IF(@rType ='FeeStatusPendingSubPartDetails')
BEGIN 
CREATE TABLE #tempPendingSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2),
RollNo int
)

CREATE TABLE #tempPendingDFS(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempPendingDFS
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And O.IsObsolete = 0
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempPendingDR(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT
)
INSERT INTO #tempPendingDR
	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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPendingSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPendingDFS TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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	
		
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPendingDR TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And O.IsObsolete = 0
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempPendingDFS1(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempPendingDFS1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempPendingDR1(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT
)
INSERT INTO #tempPendingDR1
	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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 
	
	
	
	insert into #tempPendingSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempPendingDFS1 TDFS1 ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempPendingDR1 TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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 sFee.tReceiptBookMaster RBM 
			ON TDFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,ISNULL(SUM(T.PendingAmount),0) AS PendingAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPendingSubPartDetails T
		WHERE T.PendingAmount >0
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
		
		DROP TABLE #tempPendingDFS1
	DROP TABLE #tempPendingDR1
	END
	
	DROP TABLE #tempPendingSubPartDetails
	DROP TABLE #tempPendingDFS
	DROP TABLE #tempPendingDR
	
	
	
END	
	
ELSE IF(@rType ='FeeStatusTotalSubPartAmount')
BEGIN 
CREATE TABLE #tempTotalSubPart (
AcademicId bigint,
OrgGroupId int,
OrgGroupName nvarchar(50),
ClassId bigint,
ClassName nvarchar(50),
--DivisionId bigint,
--DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2),
ClassOrderIndex int
--,DivisionOrder int
)


CREATE TABLE #tempAFS(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT 

)
INSERT INTO #tempAFS
    SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id AS 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	  
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1 
		AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
		(FS1.IsOptional=1)
		And O.IsObsolete = 0
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 


CREATE TABLE #tempAR(
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT
     )
    INSERT INTO #tempAR
		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
		    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
		WHERE		
			(R.SourceTypeId = 2001)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND (R.IsObsolete = 0) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
			And O.IsObsolete = 0
			--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate  
			--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
		GROUP BY FeeSetupId,R.SourceId  
     


IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempTotalSubPart
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		-- O.Id AS OrgGroupId,
		SA.OrgId AS OrgGroupId,
		SA.OrganizationName AS OrgGroupName,
		 --O.Title AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 --SA.DivisionId AS DivisionId,
		 --SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TAR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TAFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TAR.PaidAmount,0.00))AS PendingAmount,
	SA.ClassOrderIndex
	--SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN #tempAFS TAFS ON TAFS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TAFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempAR TAR ON TAR.FeeSetupId = TAFS.Id AND SA.AcademicId = TAR.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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 sFee.tReceiptBookMaster RBM 
			ON TAFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TAFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TAFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1) 
	AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))  
		GROUP by SA.OrgId,SA.OrganizationName, SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex--,SA.DivisionOrder
	
	select T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from #tempTotalSubPart T
		--WHERE T.PaidAmount > 0  AND T.PendingAmount > 0
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount+PendingAmount) AS PaidCount  from @ltempTotalSubPart 
		--	--WHERE PendingAmount  != 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		
		
		DROP TABLE #tempAFS
		DROP TABLE #tempAR
		
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempAFS1(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

    )

    INSERT INTO #tempAFS1
		SELECT 
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.FeeHeadId,
			FS1.CollectionGroupId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id As AcademicId
		FROM sFee.tFeeSetup FS1
		    INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
		    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		WHERE 
			(FS1.IsOptional=0) AND   COGBM.Id=@rCommonOrgGroupBatchId 
			And O.IsObsolete = 0
			--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate   
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
			--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		UNION ALL
				
		SELECT 
			FS1.Id,
			ISNULL(FS1.Amount,0)AS Amount,
			FM.FeeHeadId,
			FS1.CollectionGroupId,
			ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
			SA1.Id As 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.tAcademic SA1 ON SA1.Id=FO.SourceId
		    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
		    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
		    AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		WHERE
				
		    (FS1.IsOptional=1)  AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
    
	CREATE TABLE #tempAR1(
         PaidAmount DECIMAL(12,2),
	     FeeSetupId INT,
	     SourceId BIGINT
     )
     INSERT INTO #tempAR1		 
		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
		    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
			
	    WHERE		
			(R.SourceTypeId = 2001)
			--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND (R.IsObsolete = 0) AND   COGBM.Id=@rCommonOrgGroupBatchId 
			And O.IsObsolete = 0
			--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate    
			--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
		GROUP BY FeeSetupId,R.SourceId
		
		
		
	
	INSERT INTO #tempTotalSubPart
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 SA.OrgId AS OrgGroupId,
		  SA.OrganizationName AS OrgGroupName,
		 SA.ClassId AS ClassId,
		 SA.ClassName AS ClassName,
		 --SA.DivisionId AS DivisionId,
		 --SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TAR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TAFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TAR1.PaidAmount,0.00))AS PendingAmount,
		SA.ClassOrderIndex--,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempAFS1 TAFS1 ON TAFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TAFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempAR1 TAR1 ON TAR1.FeeSetupId = TAFS1.Id AND SA.AcademicId = TAR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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 sFee.tReceiptBookMaster RBM ON TAFS1.ReceiptBookId=RBM.Id
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON TAFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
		INNER JOIN sFee.tFeeHeadMaster FHM 	ON FHM.Id=TAFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	AND  ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
	And O.IsObsolete = 0
		GROUP by SA.OrgId,SA.OrganizationName,SA.ClassId,SA.ClassName--,SA.DivisionName
		,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.ClassOrderIndex--,SA.DivisionOrder

		 
	SELECT T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount, COUNT(T.AcademicId) AS StudentCount,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId from #tempTotalSubPart T
		--WHERE T.PaidAmount > 0  AND T.PendingAmount > 0
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount+PendingAmount) AS PaidCount  from @ltempTotalSubPart T
		--	--WHERE PendingAmount  != 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		GROUP BY T.OrgGroupId,T.OrgGroupName,T.ClassId,T.ClassName,T.CollectionGroupId,T.ReceiptBookId,T.OrgGroupName--,T.ClassOrderIndex,T.DivisionOrder
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		--ORDER BY T.ClassOrderIndex,T.DivisionOrder
		
		DROP TABLE #tempAFS1
	    DROP TABLE #tempAR1
		
	END
	
	DROP TABLE #tempTotalSubPart
	
		
	
  END	
  ELSE IF(@rType ='FeeStatusTotalSubPartDetails')
BEGIN 
CREATE TABLE #tempTotalSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2),
RollNo int
)

CREATE TABLE #tempTotalDFS(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempTotalDFS
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And O.IsObsolete = 0
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempTotalDR(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT
)
INSERT INTO #tempTotalDR
	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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempTotalSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempTotalDFS TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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	
		
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempTotalDR TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempTotalSubPartDetails T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempTotalDFS1(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempTotalDFS1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0

		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempTotalDR1(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT
)
INSERT INTO #tempTotalDR1
	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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 
	
	
	
	insert into #tempTotalSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempTotalDFS1 TDFS1 ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempTotalDR1 TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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 sFee.tReceiptBookMaster RBM 
			ON TDFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And O.IsObsolete = 0
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) AS TotalAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempTotalSubPartDetails T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(PaidAmount,0)+ISNULL(PendingAmount,0)) > 0
		ORDER BY T.RollNo
		
		DROP TABLE #tempTotalDFS1
	DROP TABLE #tempTotalDR1
	END
	
	DROP TABLE #tempTotalSubPartDetails
	DROP TABLE #tempTotalDFS
	DROP TABLE #tempTotalDR
	
	 
	
END
  
ELSE IF(@rType ='FeeStatusPaidSubPartDetails')
BEGIN 
CREATE TABLE #tempPaidSubPartDetails(
SourceId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2),
RollNo int
)

CREATE TABLE #tempDFS(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempDFS
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And O.IsObsolete = 0
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempDR(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT
)
INSERT INTO #tempDR
	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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetails
SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFS TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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	
		
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDR TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
	 And O.IsObsolete = 0
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetails T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempDFS1(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempDFS1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempDR1(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT
)
INSERT INTO #tempDR1
	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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId 
	
	
	
	insert into #tempPaidSubPartDetails
		SELECT 
		ISNULL(SA.AcademicId,0) AS SourceId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFS1 TDFS1 ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDR1 TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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 sFee.tReceiptBookMaster RBM 
			ON TDFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	And O.IsObsolete = 0
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.SourceId,T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetails T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName,T.SourceId
		--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
		
		DROP TABLE #tempDFS1
	DROP TABLE #tempDR1
	END
	
	DROP TABLE #tempPaidSubPartDetails
	DROP TABLE #tempDFS
	DROP TABLE #tempDR
	
	
	
END

ELSE IF(@rType ='FeeStatusPaidSubPartDetailsMonthWise')
BEGIN 
CREATE TABLE #tempPaidSubPartDetailsMonthWise(
AcademicId bigint,
OrgGroupId int,
Code nvarchar(20),
Name nvarchar(200),
ParentContactNo nvarchar(50),
ClassName nvarchar(50),
DivisionId bigint,
DivisionName nvarchar(50),
CollectionGroupId bigint,
CollectionGroup nvarchar(200),
RecepitTitle nvarchar(100),
ReceiptBookId bigint,
PaidAmount DECIMAL(12,2),
PendingAmount DECIMAL(12,2),
RollNo int
)

CREATE TABLE #tempDFSMonthWise(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT

)

INSERT INTO #tempDFSMonthWise
	 SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId 
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) --AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
    WHERE
				
	   (FS1.IsOptional=1) --AND BM.IsActive=1 
	   AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And O.IsObsolete = 0
	   --AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
	    --AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
	    --AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0)) 
		


CREATE TABLE #tempDRMonthWise(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId
		,R.ReceiptDate
	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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
	WHERE		
		(R.SourceTypeId = 2001) 
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate     
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate



IF(@rCollectionGroupId = 0)
	BEGIN
	insert into #tempPaidSubPartDetailsMonthWise
SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		
	FROM 
		sStudent.vStudentAcademic SA
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise TDFS ON TDFS.AcademicId=SA.AcademicId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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	
		
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR ON TDR.FeeSetupId = TDFS.Id AND SA.AcademicId = TDR.SourceId
		
		   INNER JOIN sFee.tReceiptBookMaster RBM 
			ON TDFS.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId-- AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND  ISNULL(CGM.Id,0)=0
	AND((DATEPART(M, TDR.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	And O.IsObsolete = 0
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo
	
	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code AS Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
	END 
	ELSE 
	BEGIN
	
	CREATE TABLE #tempDFSMonthWise1(
     Id INT,
     Amount DECIMAL(12,2),
     FeeHeadId INT,
     CollectionGroupId INT,
     ReceiptBookId INT,
     AcademicId BIGINT  

    )
    
    INSERT INTO #tempDFSMonthWise1
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As AcademicId
	FROM sFee.tFeeSetup FS1
		INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	    
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
	WHERE 
		(FS1.IsOptional=0) 
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId 
		And O.IsObsolete = 0
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate    
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		--AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
	UNION ALL
				
	SELECT 
		FS1.Id,
		ISNULL(FS1.Amount,0)AS Amount,
		FM.FeeHeadId,
		FS1.CollectionGroupId,
		ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
		SA1.Id As 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.tAcademic SA1 ON SA1.Id=FO.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA1.BatchId
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
		AND FS1.BatchId = SA1.BatchId AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId 
		--AND BM.IsActive=1
		--AND FS1.StartDate>=@rFromDate AND FS1.EndDate<=@rToDate  
	WHERE
				
	    (FS1.IsOptional=1) AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))
		And O.IsObsolete = 0
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		--AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	
	
	
CREATE TABLE #tempDRMonthWise1(
       PaidAmount DECIMAL(12,2),
	   FeeSetupId INT,
	   SourceId BIGINT,
	   ReceiptDate DATE
)
INSERT INTO #tempDRMonthWise1
	SELECT 
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,
		RD.FeeSetupId,
		R.SourceId,
		R.ReceiptDate
	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
	    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.tOrganizationMaster OM ON SA1.OrgId = OM.Id 
	   
	WHERE		
		(R.SourceTypeId = 2001)
		--AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
		AND (R.IsObsolete = 0) 
		And O.IsObsolete = 0
		--AND BM.IsActive=1 
		AND COGBM.Id=@rCommonOrgGroupBatchId --AND FS.StartDate>=@rFromDate AND FS.EndDate<=@rToDate   
		--AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
	GROUP BY FeeSetupId,R.SourceId,R.ReceiptDate
	
	
	
	insert into #tempPaidSubPartDetailsMonthWise
		SELECT 
		ISNULL(SA.AcademicId,0) AS AcademicId,
		 O.Id AS OrgGroupId,
		 ISNULL(SA.Code,'') As Code,
		 ISNULL(SA.Name,'') AS Name,
		 ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		 SA.ClassName AS ClassName,
		 SA.DivisionId AS DivisionId,
		 SA.DivisionName AS DivisionName,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Code,'') AS CollectionGroup,
		ISNULL(RBM.Title,'')  AS ReceiptTitle,
		ISNULL(RBM.Id,0) As ReceiptBookId,
		SUM(ISNULL(TDR1.PaidAmount,0)) AS PaidAmount,
		SUM(ISNULL(TDFS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(TDR1.PaidAmount,0.00))AS PendingAmount,
		SA.RollNo
		--SA.ClassOrderIndex,SA.DivisionOrder
	FROM 
		sStudent.vStudentAcademic SA
		 LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		INNER JOIN #tempDFSMonthWise1 TDFS1 ON TDFS1.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=TDFS1.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN #tempDRMonthWise TDR1 ON TDR1.FeeSetupId = TDFS1.Id AND SA.AcademicId = TDR1.SourceId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
	    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 sFee.tReceiptBookMaster RBM 
			ON TDFS1.ReceiptBookId=RBM.Id
		   LEFT JOIN sFee.tCollectionGroupMaster CGM 
			ON TDFS1.CollectionGroupId=CGM.Id AND RBM.Id = CGM.ReceiptBookId --AND (CGM.OrgGroupBatchId = 0 OR(0=0))
			 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=TDFS1.FeeHeadId	
	WHERE
	 (LEFT(SA.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))	
	 AND ((RBM.Id = @rReceiptBookId) OR (@rReceiptBookId=0))
	AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
	AND((DATEPART(M, TDR1.ReceiptDate)  =@rMonth)OR(@rMonth=0))
	--AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
	-- ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
	--AND(SA.IsActiveBatch =1)
	And O.IsObsolete = 0
	 AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0)) 
		GROUP by O.Id,SA.ClassName,SA.DivisionName,SA.AcademicId,SA.DivisionId,CGM.Id,CGM.Code,RBM.Title,RBM.Id,SA.Name,SC.ParentContactNo,SA.Code,SA.RollNo--,SA.ClassOrderIndex,SA.DivisionOrder
	

	select T.Name AS Name,T.DivisionId,T.ClassName+'-'+ T.DivisionName AS ClassDivision,SUM(ISNULL(T.PaidAmount,0)) AS PaidAmount,T.ParentContactNo AS ParentContactNo,T.Code As Code,
		ISNULL(T.CollectionGroupId,0) AS CollectionGroupId,T.ReceiptBookId AS ReceiptBookId,T.RollNo from #tempPaidSubPartDetailsMonthWise T
		--LEFT JOIN 
		--(
		--	select OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId, SUM(PaidAmount) AS PaidCount  from @ltempPaidSubPartDetails 
		--	WHERE PendingAmount  = 0
		--	group by OrgGroupId,ClassId,CollectionGroupId,ReceiptBookId
		--) A ON A.OrgGroupId = T.OrgGroupId AND A.ClassId = T.ClassId AND A.CollectionGroupId = T.CollectionGroupId
		group by T.AcademicId,T.DivisionId,T.CollectionGroupId,T.ReceiptBookId,T.ParentContactNo,T.Name,T.Code,T.RollNo,T.ClassName,T.DivisionName
		--,T.ClassOrderIndex,T.DivisionOrder 
		HAVING SUM(ISNULL(T.PaidAmount,0)) > 0
		ORDER BY T.RollNo
		
		DROP TABLE #tempDFSMonthWise1
	DROP TABLE #tempDRMonthWise1
	END
	
	DROP TABLE #tempPaidSubPartDetailsMonthWise
	DROP TABLE #tempDFSMonthWise
	DROP TABLE #tempDRMonthWise
	
	
	
END

ELSE IF(@rType='ReceiptOrganization')
  BEGIN
	IF(@rSyncDate =1)
		BEGIN
				DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganizationSync(
				OrgGroupId int,
				OrgGroupName nvarchar(500),
				ReceiptId bigint,
				TotalReceiptAmount DECIMAL(12,2),
				IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganizationSync
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.TotalReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R
				INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				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.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId )
				And O.IsObsolete = 0 
				AND (R.ReceiptDate between @rFromDate and @rToDate)    
			
			INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganizationSync T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganizationSync WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				
				DROP TABLE #tempReceiptOrganizationSync
		END 
	ELSE
		BEGIN
			IF  Exists(select 1 from sFee.tTempReceiptOrganization where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND CONVERT(date,ReceiptDate) =@rFromDate AND CONVERT(date,ReceiptDate) =@rToDate )
			BEGIN
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
	ELSE
			BEGIN 
			DELETE  sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				CREATE TABLE #tempReceiptOrganization(
				OrgGroupId int,
				OrgGroupName nvarchar(500),
				ReceiptId bigint,
				TotalReceiptAmount DECIMAL(12,2),
				IsObsolete bit
				)
				INSERT INTO #tempReceiptOrganization
				SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,R.Id AS ReceiptCount,R.TotalReceiptAmount,R.IsObsolete
				FROM  sFee.tReceipt R
				INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId 
				INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
				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.tOrgGroupMaster OGM ON OGM.Id = LEFT(SA.OrgGroupBatchId,4)
				--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
				--INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=R.ReceiptBookId
				WHERE R.SourceTypeId = 2001
				AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
				AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				--AND(BM.IsActive =1) 
				AND (COGBM.Id=@rCommonOrgGroupBatchId ) 
				AND (R.ReceiptDate between @rFromDate and @rToDate)    
			
				INSERT INTO sFee.tTempReceiptOrganization
				SELECT  T.OrgGroupId,T.OrgGroupName,ISNULL(COUNT(ReceiptId),0) AS ReceiptCount,ISNULL(SUM(TotalReceiptAmount),0.00) AS ReceiptAmount ,
				ISNULL(a.CancelReceiptCount,0.00)AS CancelAmount,@rFromDate,@rCommonOrgGroupBatchId,GetDate() FROM #tempReceiptOrganization T  
				LEFT JOIN (
				SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrganization WHERE IsObsolete = 1
				GROUP BY OrgGroupId,OrgGroupName
				) A ON A.OrgGroupId=t.OrgGroupId
				WHERE IsObsolete = 0
				GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount
				ORDER BY OrgGroupId
				SELECT * FROM sFee.tTempReceiptOrganization WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		DROP TABLE #tempReceiptOrganization
			END
		END
  END
ELSE IF(@rType='ReceiptBookCollectionGroup')
  BEGIN
	CREATE TABLE #tempReceiptBookCollection (
	RecepitTitle nvarchar(200),
	CollectionTitle nvarchar(200),
	ReceiptCount int,
	ReceiptAmount DECIMAL(12,2),
	ReceiptId bigint,
	CollectionGroupId bigint,
	IsObsolete bit
)

INSERT INTO #tempReceiptBookCollection
 SELECT ISNULL(RBM.Title,'')  AS RecepitTitle ,ISNULL(CGM.Code,'') AS CollectionTitle,
			ISNULL(COUNT(DISTINCT R.Id),0) AS ReceiptCount,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount,
			ISNULL(RBM.Id,0) AS ReceiptId,ISNULL(CGM.Id,0) AS CollectionGroupId,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    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.tOrganizationMaster OM ON SA.OrgId = OM.Id 			
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId 
			AND FS.AdmissionCategoryId=SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id 
			AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			--AND (R.IsObsolete = 1) 
			--AND(BM.IsActive =1) 
			AND ((COGBM.Id=@rCommonOrgGroupBatchId)OR(@rCommonOrgGroupBatchId=0))AND R.ReceiptDate between @rFromDate and @rToDate 
			And O.IsObsolete = 0   
			GROUP BY RBM.Title,CGM.Code,RBM.Id,CGM.Id, R.ReceiptBookId,R.IsObsolete
			
			 
			SELECT  TRC.RecepitTitle +'-'+ TRC.CollectionTitle AS ReceictCollection,TRC.ReceiptId AS ReceiptId,TRC.CollectionGroupId AS CollectionGroupId,TRC.ReceiptCount,SUM(ReceiptAmount) AS ReceiptAmount ,
			ISNULL(A.CancelReceiptCount,0)AS CancelAmount FROM #tempReceiptBookCollection TRC 
			LEFT JOIN (
			SELECT ReceiptId,CollectionGroupId,SUM(ReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptBookCollection WHERE IsObsolete = 1
			GROUP BY ReceiptId,CollectionGroupId
			) A ON A.ReceiptId=TRC.ReceiptId AND A.CollectionGroupId=TRC.CollectionGroupId
			
			WHERE IsObsolete = 0
			GROUP BY TRC.RecepitTitle,TRC.CollectionTitle,A.ReceiptId,A.CancelReceiptCount,TRC.ReceiptId,TRC.CollectionGroupId,TRC.ReceiptCount 
		DROP TABLE #tempReceiptBookCollection
  END
ELSE IF(@rType='ReceiptBookCollectionGroupDetail')
  BEGIN
  CREATE TABLE #tempReceiptBookCollectionDetail(
  SourceId bigint,
Code nvarchar(200),
Name nvarchar(200),
ReceiptNumber bigint,
ReceiptAmount DECIMAL(12,2),
ReceiptId bigint,
IsObsolete bit
)
IF(@rCollectionGroupId = 0)
	BEGIN
	INSERT INTO #tempReceiptBookCollectionDetail
 SELECT ISNULL(SA.Id,0) AS SourceId,SM.Code AS Code,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) As Name,R.ReceiptNumber AS ReceiptNumber,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount,R.Id AS ReceiptId,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    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.tOrganizationMaster OM ON SA.OrgId = OM.Id
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId=SM.Id	
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId =  SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			AND  ISNULL(CGM.Id,0)=0
			--AND (R.IsObsolete = 0) 
			--AND(BM.IsActive =1) 
			And O.IsObsolete = 0
			AND COGBM.Id=@rCommonOrgGroupBatchId AND R.ReceiptDate between @rFromDate and @rToDate 
			GROUP BY SA.Id,SM.Code,R.ReceiptNumber,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId), R.ReceiptBookId,CGM.Id,R.Id,R.IsObsolete 
	END
ELSE
	BEGIN
	INSERT INTO #tempReceiptBookCollectionDetail
 SELECT ISNULL(SA.Id,0) AS SourceId,SM.Code AS Code,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) As Name,R.ReceiptNumber AS ReceiptNumber,ISNULL(SUM(RD.Amount),0) AS ReceiptAmount,R.Id AS ReceiptId,R.IsObsolete
		FROM  sFee.tReceipt R
			INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
			INNER JOIN sStudent.tAcademic SA ON SA.Id=R.SourceId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		    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.tOrganizationMaster OM ON SA.OrgId = OM.Id
			INNER JOIN sStudent.tStudentMaster SM ON SA.StudentId=SM.Id	
			INNER JOIN sFee.tFeeSetup FS ON FS.Id = RD.FeeSetupId AND FS.ClassId = SA.ClassId AND FS.AdmissionCategoryId =  SA.AdmissionCategoryId AND FS.ClassId = SA.ClassId
			INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FS.ReceiptBookId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FS.CollectionGroupId AND CGM.ReceiptBookId  = RBM.Id AND CGM.OrgGroupBatchId = BM.OrgGroupBatchId
		WHERE R.SourceTypeId = 2001
			AND (LEFT(BM.OrgGroupBatchId,4) = @rOrgGroupId OR (@rOrgGroupId=0))
			--AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId=0))
			AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND ((CGM.Id = @rCollectionGroupId) OR (@rCollectionGroupId=0))
			--AND (R.IsObsolete = 0) 
			--AND(BM.IsActive =1) 
			And O.IsObsolete = 0
			AND COGBM.Id=@rCommonOrgGroupBatchId AND R.ReceiptDate between @rFromDate and @rToDate     
			GROUP BY SA.Id,SM.Code,R.ReceiptNumber,[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId), R.ReceiptBookId,CGM.Id,R.Id,R.IsObsolete 
			--ORDER BY 
	END
  SELECT *  FROM #tempReceiptBookCollectionDetail ORDER BY ReceiptNumber
  
  DROP TABLE #tempReceiptBookCollectionDetail
  END
END
GO
PRINT N'Altering [sFee].[pFeePostingGet]...';


GO
 
ALTER PROCEDURE [sFee].[pFeePostingGet]
				
		   --@rClassId int,
           @rReceiptBookId int,
		   @rBatchId int,
		   @rOrgGroupId int,
		   @rReceiptDate date,
		   @rReceiptDateTo date,
		   @rChequePosting nvarchar(50)
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
	IF @rChequePosting = 'Single'
	BEGIN
			SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					SUM(RD.Amount) AS ReceiptAmount,
					'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,'' AS ChequeClearDate,0 AS PayTypeId	, 
					ISNULL(AYM.ISLocked,0) AS ISLocked,
					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 AND R.IsObsolete = 0
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
					--AND (FS.ClassId=@rClassId) 
						AND (FS.ReceiptBookId=@rReceiptBookId) 
						AND (R.OrgGroupBatchId=@rBatchId)
					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
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId			
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptNumber	
	 END
	 ELSE
		BEGIN		
		
			
		DECLARE @lConfigValue nvarchar(50)
		DECLARE @lIsAccountPostingBankNameWise bit=0

		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 244 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId

		IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
		SET @lIsAccountPostingBankNameWise = 0
		ELSE
		SET @lIsAccountPostingBankNameWise = 1	
		
		IF @lIsAccountPostingBankNameWise = 1	
			BEGIN
				  SELECT  
						R.ReceiptDate,
						AMast.Title AS AccountName,
						AYM.Title AS AccountingYearName,
						AM.CreditLedgerId,
						CLM.Title AS CreditLedgerName,
						AM.DebitLedgerId,
						DLM.Title AS DebitLedgerName,
						SUM(RD.Amount) AS ReceiptAmount,
						'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,'' AS ChequeClearDate,0 AS PayTypeId	,
						ISNULL(AYM.ISLocked,0) AS ISLocked,
						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 AND R.IsObsolete = 0
						INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
						--AND (FS.ClassId=@rClassId) 
							AND (FS.ReceiptBookId=@rReceiptBookId) 
							AND (R.OrgGroupBatchId=@rBatchId)
						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
					WHERE 
						AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1
						GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptNumber
						
					UNION ALL
					
SELECT  
						R.ReceiptDate,
						AMast.Title AS AccountName,
						AYM.Title AS AccountingYearName,
						AM.CreditLedgerId,
						CLM.Title AS CreditLedgerName,
						R.DepositedLedgerId AS DebitLedgerId, 
						DLM.Title AS DebitLedgerName,
						Sum(RD.Amount) AS ReceiptAmount,
						R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,2 AS PayTypeId,
						ISNULL(AYM.ISLocked,0) AS ISLocked,			
						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 AND R.IsObsolete = 0
						INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
							AND (FS.ReceiptBookId=@rReceiptBookId) 
							AND (R.OrgGroupBatchId=@rBatchId)
						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=R.DepositedLedgerId) AND DLM.AccountingYearId = AM.AccountingYearId
					WHERE  R.PayTypeId <> 1 AND	 AMast.OrgGroupId=@rOrgGroupId			
					Group By R.ReceiptDate,AMast.Title,AYM.Title,AM.CreditLedgerId,
						CLM.Title,R.DepositedLedgerId,DLM.Title,
						R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,AYM.IsLocked,R.ReceiptNumber
				END
		ELSE
		BEGIN				
				SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					SUM(RD.Amount) AS ReceiptAmount,
					'' AS ChequeNo,'' AS ChequeDate,'' AS BankName,'' AS ChequeClearDate,0 AS PayTypeId	,
					ISNULL(AYM.ISLocked,0) AS ISLocked,
					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 AND R.IsObsolete = 0
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
					--AND (FS.ClassId=@rClassId) 
						AND (FS.ReceiptBookId=@rReceiptBookId) 
						AND (R.OrgGroupBatchId=@rBatchId)
					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
				WHERE 
					AMast.OrgGroupId=@rOrgGroupId AND R.PayTypeId = 1
					GROUP BY R.ReceiptDate,AM.CreditLedgerId,	AM.DebitLedgerId,AMast.Title,AYM.Title,CLM.Title,DLM.Title,AYM.IsLocked,R.ReceiptNumber
					
				UNION ALL
				
				SELECT  
					R.ReceiptDate,
					AMast.Title AS AccountName,
					AYM.Title AS AccountingYearName,
					AM.CreditLedgerId,
					CLM.Title AS CreditLedgerName,
					AM.DebitLedgerId,
					DLM.Title AS DebitLedgerName,
					Sum(RD.Amount) AS ReceiptAmount,
					R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,2 AS PayTypeId,
					ISNULL(AYM.ISLocked,0) AS ISLocked,
					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 AND R.IsObsolete = 0
					INNER JOIN sFee.tFeeSetup FS ON FS.Id=AM.FeeSetupId 
						AND (FS.ReceiptBookId=@rReceiptBookId) 
						AND (R.OrgGroupBatchId=@rBatchId)
					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
				WHERE  R.PayTypeId <> 1 AND	 AMast.OrgGroupId=@rOrgGroupId			
				Group By R.ReceiptDate,AMast.Title,AYM.Title,AM.CreditLedgerId,
					CLM.Title,AM.DebitLedgerId,DLM.Title,
					R.ChequeNo,R.ChequeDate,R.BankName,R.ChequeClearDate,AYM.IsLocked,R.ReceiptNumber
			END
		END
END
GO
PRINT N'Altering [sFee].[pMyFeeGet]...';


GO
-- exec [sFee].[pMyFeeGet] 1201000000102,2001,120100001,0,'CollectionGroup'
ALTER PROCEDURE [sFee].[pMyFeeGet]  
    
  @rSourceId bigint ,  --1201000000102
  @rSourceTypeId int,  --2001
  @rBatchId int,  --120100001
  @rStudentId bigint =0,
  @rDisplay varchar(20)=''
    
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON    BEGIN    
 if (@rStudentId <> 0)  
 SELECT @rSourceId = Id, @rSourceTypeId = 2001 FROM sStudent.tAcademic WHERE StudentId = @rStudentId AND BatchId = @rBatchId  
  DECLARE @lClassId int  
  DECLARE @lAdmissionCategoryId int  
  SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId  
  
  -----------------------------------------------------------------------------------------------------------------------------------------

  create table #TempTable
  (id int identity(1,1),Feeid bigint,FeeName varchar(50),FeeSetupId bigint,isOptional tinyint,IsVariable tinyint,Amount decimal(12,2),
  StartDate Date,EndDate Date,FAAmount decimal(12,2),DiscountAmount decimal(12,2),AdditionalAmount decimal(12,2),PaidAmount decimal(12,2),PendingAmount decimal(12,2),
  NotApplicableAmount decimal(12,2),Remark Varchar(Max),OrderIndex int,ReceiptNumber int,ReceiptDate Date,ReceiptBookId bigint,CollectionGroupId Bigint,
  Col_StartDate Date,Col_EndDate Date,CollectionGroup varchar(200),FeeHeadid Bigint,FeeHead varchar(200),FeeDuration Varchar(100))


  Insert into #TempTable

SELECT   
   FM.Id AS FeeId,  
   FM.Title AS FeeName,  
   FS.Id AS FeeSetupId,  
   ISNULL(FS.IsOptional,0)AS IsOptional,  
   ISNULL(FS.IsVariable,0)AS IsVariable,  
   ISNULL(FS.Amount,0)AS Amount,  
   ISNULL(FS.StartDate,'1900-01-01')AS StartDate,  
   ISNULL(FS.EndDate,'1900-01-01')AS EndDate,  
   ISNULL(FA.VariableAmount,0.00)AS FAAmount,  
   ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,  
   ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,  
   ISNULL(R.PaidAmount,0) AS PaidAmount,  
   ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,  
   ISNULL(FA.NotApplicableAmount,0.00) AS NotApplicableAmount,  
   ISNULL(FA.Remark,'') AS Remark,  
   FM.OrderIndex,  
   0 AS ReceiptNumber,  
   '1900-01-01'AS ReceiptDate,  
   ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,  
   ISNULL(FS.CollectionGroupId,0) AS CollectionGroupId,
   ISNULL(CGM.StartDate,'') as Col_StartDate,
	ISNULL(CGM.EndDate,'') as Col_EndDate,
   ISNULL(CGM.Title,'') AS CollectionGroup,  
   FM.FeeHeadId,  
   FHM.Title AS FeeHead,  
   FS.FeeDuration  
  FROM   
   sFee.tFeeMaster FM  
  INNER JOIN   
  (  
   SELECT   
    FS1.FeeId,  
    FS1.Id,  
    ISNULL(FS1.IsOptional,0)AS IsOptional,  
    ISNULL(FS1.IsVariable,0)AS IsVariable,  
    ISNULL(FS1.Amount,0)AS Amount,  
    ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
    ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
    FS1.BatchId,  
    ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
    ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId,
    ISNULL(FS1.FeeDuration,'')  AS FeeDuration  
   FROM sFee.tFeeSetup FS1  
        
    WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0  
    AND FS1.BatchId = @rBatchId  
    UNION ALL  
      
   SELECT   
    FS1.FeeId,  
    FS1.Id,  
    ISNULL(FS1.IsOptional,0)AS IsOptional,  
    ISNULL(FS1.IsVariable,0)AS IsVariable,  
    ISNULL(FS1.Amount,0)AS Amount,  
    ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,  
    ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,  
    FS1.BatchId,  
    ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,  
    ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId , 
    ISNULL(FS1.FeeDuration,'') AS FeeDuration  
       
   FROM sFee.tFeeSetup FS1  
      
  INNER JOIN sFee.tFeeOptional FO  
   ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@rSourceId) AND(FO.SourceTypeId=@rSourceTypeId)  
   WHERE  
    FS1.BatchId = @rBatchId  
   AND FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1  
  ) FS ON FS.FeeId=FM.Id  
  INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId  
  LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId  
  LEFT JOIN sFee.tFeeAllocation FA  
   ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@rSourceId) AND(FA.SourceTypeId=@rSourceTypeId)  
  LEFT JOIN  
  (  
      SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId  
      FROM  
      sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id     
   WHERE        
    R.SourceId= @rSourceId  
   AND ((R.SourceTypeId = @rSourceTypeId) OR (@rSourceTypeId=0))  
   AND R.IsObsolete = 0   
   AND R.BatchId = @rBatchId  
    GROUP BY FeeSetupId  
  ) R ON R.FeeSetupId = FS.Id   
WHERE   
 FS.BatchId=@rBatchId  
ORDER BY FS.StartDate ASC,FM.OrderIndex ASC 
 
 --------------------------------------------------------------------------------------------
 -- Get Group Wise Data ---

 IF(@rDisplay = 'Fee Head')
 BEGIN
 Print @rDisplay + '1'
 
 Create Table #temp_head
 (id int identity(1,1),FeeHeadid Bigint,FeeHead varchar(200),Amount decimal(12,2),StartDate Date,EndDate Date,FAAmount decimal(12,2),
 DiscountAmount decimal(12,2),AdditionalAmount decimal(12,2),PaidAmount decimal(12,2),PendingAmount decimal(12,2),
 NotApplicableAmount decimal(12,2))

 Insert into #temp_head
 select FeeHeadid,FeeHead,sum(Amount) as Amount,min(StartDate) as StartDate,Max(EndDate) as EndDate,sum(FAAmount) as FAAmount,
 sum(DiscountAmount) as DiscountAmount,sum(AdditionalAmount) as AdditionalAmount,sum(PaidAmount) as PaidAmount,
 sum(PendingAmount) as PendingAmount,sum(NotApplicableAmount) as NotApplicableAmount--,Remark,ReceiptDate,ReceiptBookId,CollectionGroupID,CollectionGroup
 from #TempTable
 group by Feeheadid,FeeHead

 Declare @i int

 while(@i<= (Select Count(*) from #temp_head))
 BEGIN
 Update #temp_head set StartDate = (Select min(StartDate) from #tempTable A Where A.FeeHeadid = #temp_head.FeeHeadid) where id=@i
 Update #temp_head set EndDate = (Select Max(EndDate) from #tempTable A Where A.FeeHeadid = #temp_head.FeeHeadid) where id=@i
 PRINT 1
 END

 select FeeHeadid as Feeid,FeeHead as FeeName,PendingAmount,'' as IsVariable,
 '' as FeeSetupId,'' as Remark,'' as ReceiptNumber,'' as ReceiptDate,'' as CollectionGroupId,FeeHeadid,0 as IsOptional,
 (case when FAAmount>0 then FAAmount else Amount + AdditionalAmount - DiscountAmount - NotApplicableAmount End) as Amount ,
 StartDate,EndDate,FAAmount,DiscountAmount,AdditionalAmount,PaidAmount,PendingAmount,NotApplicableAmount,'' as FeeDuration from #temp_head
 
 END

 ELSE IF(@rDisplay = 'Collection Group')
 BEGIN

 select CollectionGroupID as Feeid,CollectionGroup as FeeName, sum(PendingAmount) as PendingAmount,CollectionGroupID as FeeHeadid,
 '' as IsVariable,'' as FeeSetupId,'' as Remark,'' as ReceiptNumber,'' as ReceiptDate,'' as CollectionGroupId,0 as IsOptional,
 (case when sum(FAAmount)>0 then sum(FAAmount) else sum(Amount) + sum(AdditionalAmount) - sum(DiscountAmount) - sum(NotApplicableAmount) End) as Amount ,
 Col_startDate as StartDate,Col_EndDate as EndDate,sum(FAAmount) as FAAmount,sum(DiscountAmount) as DiscountAmount,
 sum(AdditionalAmount) as AdditionalAmount,sum(PaidAmount) as PaidAmount,sum(PendingAmount) as PendingAmount,
 sum(NotApplicableAmount) as NotApplicableAmount,'' as FeeDuration from #TempTable
 group by CollectionGroupID,CollectionGroup,Col_startDate,Col_EndDate

 END

 ELSE
 BEGIN

 select CollectionGroupID as Feeid,FeeName,PendingAmount, 
 '' as IsVariable,'' as FeeSetupId,'' as Remark,'' as ReceiptNumber,'' as ReceiptDate,'' as CollectionGroupId,0 as IsOptional,
 CollectionGroupID as FeeHeadid,
 (case when FAAmount>0 then FAAmount else Amount + AdditionalAmount - DiscountAmount - NotApplicableAmount End) as Amount ,
 StartDate,EndDate,FAAmount,DiscountAmount, AdditionalAmount,PaidAmount,PendingAmount,NotApplicableAmount,'' as FeeDuration from #TempTable

 END

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


GO
ALTER PROC [sFee].[pRptDepositWisetransactionList] 
		
	 @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=''
   
      
AS
BEGIN

--select '' DepositDate,
--		0 as Amount,
--		0 AS Credit,
--		0 AS Debit,
--		0 As Balance,
--		'' as Code,
--		'' as StudentName,
--		0 as StudentId,
--convert(bigint,0) as StudentId,
--		'' as Class,
--		'' as SUId,
--		'' as GroupType,
--		0 as GroupID
 
	SELECT 
			
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Amount,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    'DepositeAdd' 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

			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			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,'')=''))
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			-ISnull (DAJ.Amount,0) As Amount,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    'DepositeAdjustment' As GroupType,
		    
		    VA.Name As StudentName, 
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     DAJ.CreatedDateTime,
		     VA.StudentId,
		     @rBuilder1 As builder1,
		     DAJ.AdjustmentNumber AS Number
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.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,DAJ.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((convert(date,DAJ.CreatedDateTime)<=@rToDate) OR (ISNULL(@rToDate,'')=''))
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			-ISnull (DR.RefundAmount,0) AS Amount,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    'DepositeRefund' 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
		     
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			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,'')=''))
	Order by CreatedDateTime
 
END
GO
PRINT N'Altering [sFee].[pRptFeeCircularGet]...';


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


WHERE 
		(FS.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((FS.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((FS.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((FS.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((FS.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((FS.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((FS.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((FS.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((FS.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((FS.Code=@rCode) OR (@rCode=''))
		AND ((FS.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
		AND ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0  
         AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     ) 
END
GO
PRINT N'Altering [sFee].[pRptFeePendingDetailListOtherGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeePendingDetailListOtherGet]
		@rReportId int=0,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rIsFilter bit=0,
		@rIsHeader bit=0,		
		@rCreatedUserName nvarchar(20) = '',
		@rIsReceiptBookGroup bit=0,
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = ''
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.FeeId,
		FS.FeeName,
		FS.FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	FS.ReceiptBookId
			 END) AS ReceiptBookId,	
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 'ALL'
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.Title,'')
			 END) AS ReceiptBookTitle,
		(CASE WHEN @rIsReceiptBookGroup = 0 THEN 0
			 WHEN @rIsReceiptBookGroup = 1 THEN	ISNULL(RBM.OrderIndex,0)
			 END) AS ReceiptOrderIndex,	 
		--FS.ReceiptBookId,
		--ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo
  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,
				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
				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
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    BM.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((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 ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				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,
				FM.OrderIndex AS FeeOrderIndex
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				
		) 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			
				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 ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND (R.ReceiptDate <= @rUptoDate)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((BM.Title = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				GROUP BY FeeSetupId,R.SourceId
				
				
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 LEFT JOIN sStudent.tStudentCommunication SC 
			ON SC.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.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND (SA.StatusId = @rStatusId OR @rStatusId=0)
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
			AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
			AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     )
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 	
			Order by SA.RollNo
 
END
GO
PRINT N'Altering [sFee].[pRptFeeSummaryOtherGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeSummaryOtherGet]
		@rReportId int,
		@rReceiptBookId int,
		@rAdmissionCategoryId int,
		@rClassId int,
		@rDivisionId int,
		@rUptoDate date,
		@rBatchId int,
		@rUserId bigint,
		@rBuilder1 nvarchar(max),
		@rBuilder2 nvarchar(max),
		@rIsDetail bit,
		@rOrgId int,
		@rOrgGroupBatchId int,
		@rIsExemption bit =0,
		@rStatusId int,
		@rCommonBatch nvarchar(100),
		@rDepartmentId int,
		@rFromRollNo int,
	    @rToRollNo int,
	    @rCode nvarchar(20),
	    @rIsFilter bit,
		@rIsHeader bit,
		@rCreatedUserName nvarchar(100)='',
		@rFeeHeadId nvarchar(max) = '',
		@rIsDisplayOrgGroup bit=0,
		@rExemptionTypeId int=0,
		@rFeeId nvarchar(max) = '',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '',
		@rIsReceiptBookGroup bit=0
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsDetail AS IsDetail,
		@rIsFilter As IsFilter,
		@rIsHeader As IsHeader, 
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		SA.DivisionOrder AS DivisionOrderIndex,
		SA.ClassOrderIndex AS ClassOrderIndex,
		SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
		FS.Id AS FeeSetupId,
		
		ISNULL(FS.IsVariable,0)AS IsVariable,
		ISNULL(FS.Amount,0)AS Amount,
		ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
		ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
		ISNULL(FA.VariableAmount,0.00)AS FAAmount,
		ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
		ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
		ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
		ISNULL(R.PaidAmount,0) AS PaidAmount,
		ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,
		FS.ReceiptBookId,
		FS.FeeName,
		SA.OrgId,
		O.DisplayTitle AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.DepartmentId,
		SA.DepartmentName,
		SA.ExemptionTypeId,
		ISNULL(ETM.Title,'') AS ExemptionType,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=0)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.FeeHeadId
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id 
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
		WHERE
					((FS1.ClassId=@rClassId) OR (@rClassId=0))
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND ((FS1.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA
			ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
					sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.ClassId=@rClassId OR @rClassId=0) 
				AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
			WHERE		
				(R.SourceTypeId = 2001)
				AND (R.IsObsolete = 0) 
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND (R.ReceiptDate <= @rUptoDate)
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					GROUP BY FeeSetupId,R.SourceId
		
		) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
		 INNER JOIN sSetup.tOrganizationMaster O ON
		 SA.OrgId = O.Id
		 INNER JOIN sFee.tReceiptBookMaster RBM 
			ON FS.ReceiptBookId=RBM.Id
		 INNER JOIN sFee.tFeeHeadMaster FHM 
			ON FHM.Id=FS.FeeHeadId	
		 LEFT JOIN sFee.tExemptionTypeMaster ETM
			ON ETM.Id = SA.ExemptionTypeId
		  LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
       LEFT JOIN
	(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
	((@rIsExemption = 0 AND  1 = 1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
    AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
    AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
    AND (SA.StatusId=@rStatusId OR @rStatusId=0)
	AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SA.Code=@rCode) OR (@rCode=''))
	AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
	AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
	AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
	AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
	AND (
				 (@rFilterId = 0) -- All
				 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
				 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
				 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
			     ) 	
    AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			     
			Order by SA.RollNo
END
GO
PRINT N'Altering [sFee].[pRptStudentDepositListGet]...';


GO
 

ALTER PROCEDURE [sFee].[pRptStudentDepositListGet]
          
          @rOrgGroupId smallint,
		   @rOrgId int,          
           @rDepositHeadId int=0,         
           @rFromDate date='',
           @rToDate date='',        
           --@rCode nvarchar(20)='',          
           @rStudentName nvarchar(100)='',
		  @rStudentCode nvarchar(100)='',
		  @rClassId int=0,
		  @rDivisionId int=0,
		  @rIsBasedOnSUId bit = 0,
		  @rDepartmentId int=0,
		  @rSUId nvarchar(20)='',
		  @rBatchId int=0,
		  @rBuilder1 nvarchar(max)='',
	      @rBuilder2 nvarchar(max)=''
	   
           
AS
SET NOCOUNT ON
 
BEGIN
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rDepositHeadId AS DepositHeadId,
		--DHM.Title AS DepositHeadName,
		(SELECT [sFee].[fDepositHeadNameGet](@rDepositHeadId)) AS DepositHeadName,
		ISNULL(SA.StudentId,0) as StudentId,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		ISNULL(D.TotalDeposit,0) AS Deposit,
		ISNULL(A.TotalAdjustment,0) AS Adjustment,
		ISNULL(R.TotalRefund,0) Refund,
		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
		
  FROM 		
		sStudent.vStudentAcademic SA
		--INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003
		--INNER JOIN sHostel.tRoomMaster RM ON  RM.Id=AR.RoomId 
	    --INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId 
		LEFT JOIN
		(SELECT SUM(ISNULL(DA.Amount,0)) AS TotalDeposit,DA.AcademicId,ISNull(DA.DepositHeadId,0) AS DepositHeadId,DA.DepositDate As DepositDate 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)D 
		ON D.AcademicId=SA.AcademicId
		LEFT JOIN 
		(SELECT SUM(ISNULL(AD.Amount,0)) AS TotalAdjustment,AD.AcademicId,ISNULL(AD.DepositHeadId,0) AS DepositHeadId,AD.AdjustmentDate As AdjustmentDate FROM sFee.tDepositAdjustment AD INNER JOIN sStudent.tAcademic A ON AD.AcademicId = A.Id  WHERE AD.DepositHeadId=@rDepositHeadId GROUP BY AD.AcademicId,DepositHeadId,AD.AdjustmentDate)A 
		ON A.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 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)R
		ON R.AcademicId=SA.AcademicId
		
    	--INNER JOIN  sFee.tDepositHeadMaster DHM ON DHM.Id = @rDepositHeadId
		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 (DHM.Id=@rDepositHeadId)
	
		--AND (SA.BatchId=@rBatchId OR @rBatchId=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 like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (SA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		--AND (AR.OrgGroupBatchId=@rOrgGroupBatchId)
		 
		
		AND (
		((D.DepositDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((D.DepositDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		OR
		((A.AdjustmentDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((A.AdjustmentDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		OR
		((R.RefundDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((R.RefundDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))

		) 


		
END
GO
PRINT N'Altering [sHrm].[pEmployeeAttendanceRegisterGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pEmployeeAttendanceRegisterGet]
	 	 
	 	 @rDepartmentId int=0,
	 	 @rAttendanceDate date='',
	 	 @rCode nvarchar(20)='',
	 	 @rBatchId int=0,
	 	 @rOrgId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
  BEGIN
	SELECT 
			EM.EmployeeId,
			EM.Code AS EmployeeCode,
			EM.EmployeeName,
			EM.DepartmentName,
			ISNULL(EAR.IsPresent,'true') as IsPresent,
			ISNULL(EAR.AbsentReasonId,0) as AbsentReasonId,
			CASE WHEN EAR.UpdatedUserId IS NULL THEN cast(0 as bit) ELSE cast(1 as bit) END AS IsDeleted,
			ISNULL(EAR.LeaveTypeId,0) AS LeaveTypeId,
			ISNULL(EAR.LeavePeriodId,0) AS LeavePeriodId
  FROM 
			sHrm.vExtEmployeeMaster EM
			LEFT JOIN sHrm.tEmployeeAttendanceRegister EAR ON EAR.EmployeeId=EM.EmployeeId
			 --AND (( convert(DATE,EAR.AttendanceDate,102) = @rAttendanceDate) OR (@rAttendanceDate='')) 	
			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 ((convert(DATE,EM.DateOfleaving,102) >= @rAttendanceDate) OR (@rAttendanceDate=''))
		   -- AND ((convert(DATE,EM.DateOfleaving,102) <= @rAttendanceDate) OR (@rAttendanceDate='')) 
		  AND ((EM.DateOfleaving >= @rAttendanceDate) OR ISNULL(EM.DateOfleaving,'') = '')
          AND ((EM.DateOfJoining <= @rAttendanceDate) OR ISNULL(EM.DateOfJoining,'') = '') 
		  AND (EM.StatusId = 7)
          ORDER BY EM.Code
  END
END
GO
PRINT N'Altering [sHrm].[pEmployeeAttendanceSummaryDashboard]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeAttendanceSummaryDashboard]
	@rType nvarchar(50)='',
	@rBatchId int=0,
	@rOrgGroupBatchId int=0,
	@rOrgId smallint=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 

	IF(@rType = 'EmployeePresentDetails')
		BEGIN
		    
		    SELECT 
		    (SELECT ISNULL(COUNT(EM.EmployeeId),0) AS AbsentCount FROM sHrm.vExtEmployeeMaster EM 
		           LEFT JOIN sHrm.tEmployeeAttendanceRegister EAT ON EAT.EmployeeId=EM.EmployeeId AND EAT.AttendanceDate =CONVERT(char(10), GetDate(),126) 
		               AND (EAT.BatchId = @rBatchId) 
		     WHERE ((EM.DateOfleaving >= CONVERT(char(10), GetDate(),126)) OR ISNULL(EM.DateOfleaving,'') = '')  AND (EM.OrgId = @rOrgId)) AS TotalCount,
		     
		     
		      (SELECT ISNULL(COUNT(EM.EmployeeId),0) AS AbsentCount FROM sHrm.vExtEmployeeMaster EM 
		           LEFT JOIN sHrm.tEmployeeAttendanceRegister EAT ON EAT.EmployeeId=EM.EmployeeId AND EAT.AttendanceDate =CONVERT(char(10), GetDate(),126) 
		               AND (EAT.BatchId = @rBatchId) 
		     WHERE ((EM.DateOfleaving >= CONVERT(char(10), GetDate(),126)) OR ISNULL(EM.DateOfleaving,'') = '')  AND (EM.OrgId = @rOrgId) AND EAT.IsPresent=1) AS PresentCount,
		     
		     
		       
		      (SELECT ISNULL(COUNT(EM.EmployeeId),0) AS AbsentCount FROM sHrm.vExtEmployeeMaster EM 
		           LEFT JOIN sHrm.tEmployeeAttendanceRegister EAT ON EAT.EmployeeId=EM.EmployeeId AND EAT.AttendanceDate =CONVERT(char(10), GetDate(),126) 
		               AND (EAT.BatchId = @rBatchId) 
		     WHERE ((EM.DateOfleaving >= CONVERT(char(10), GetDate(),126)) OR ISNULL(EM.DateOfleaving,'') = '')  AND (EM.OrgId = @rOrgId) AND EAT.IsPresent=0) AS AbsentCount,
		     
		      (SELECT ISNULL(COUNT(EM.EmployeeId),0) AS AbsentCount FROM sHrm.vExtEmployeeMaster EM 
		           LEFT JOIN sHrm.tEmployeeAttendanceRegister EAT ON EAT.EmployeeId=EM.EmployeeId AND EAT.AttendanceDate =CONVERT(char(10), GetDate(),126) 
		               AND (EAT.BatchId = @rBatchId) 
		     WHERE ((EM.DateOfleaving >= CONVERT(char(10), GetDate(),126)) OR ISNULL(EM.DateOfleaving,'') = '')  AND (EM.OrgId = @rOrgId) AND EAT.EmployeeId IS NULL) AS PendingAttendance
		         
		     
		    --(SELECT ISNULL(COUNT(EAT.EmployeeId),0) AS AbsentCount FROM sHrm.tEmployeeAttendanceRegister EAT  WHERE EAT.IsPresent=1 AND  EAT.AttendanceDate=CONVERT(char(10), GetDate(),126) AND EAT.BatchId= @rBatchId ) AS PresentCount,
		    --(SELECT ISNULL(COUNT(EAT.EmployeeId),0) AS AbsentCount FROM sHrm.tEmployeeAttendanceRegister EAT  WHERE EAT.IsPresent=0 AND EAT.AttendanceDate=CONVERT(char(10), GetDate(),126) AND EAT.BatchId= @rBatchId) AS AbsentCount,		    
         --(SELECT COUNT(Id) From sHrm.tEmployeeMaster EM WHERE ORGId=@rOrgId AND ID NOT IN (SELECT EmployeeId FROM sHrm.tEmployeeAttendanceRegister EAT WHERE EAT.AttendanceDate=CONVERT(char(10), GetDate(),126) AND EAT.BatchId= @rBatchId)) AS PendingAttendance
         
         
		    
		END
		
	 ELSE IF(@rType = 'EmployeeLeaveDetails')
	 
	  BEGIN
	  
	   SELECT 		
		--(SELECT ISNULL(SUM(NoOfLeave),0) AS ApprovedLeaves FROM sHrm.tLeave HL1 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL1.BatchId where HL1.StatusId=550 AND HL1.ToDate  >= DATEADD(day,-30, getdate()) AND HL1.FromDate  <= getdate() AND HL1.BatchId= @rBatchId AND BM.OrgGroupBatchId = 110100111) AS ApprovedLeaves,
		(SELECT ISNULL(SUM(NoOfLeave),0) AS PendingLeaves FROM sHrm.tLeave HL2 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL2.BatchId where HL2.StatusId=549 AND HL2.ToDate  >= DATEADD(day,-30, getdate()) AND HL2.FromDate  <= getdate() AND  BM.OrgGroupBatchId = @rOrgGroupBatchId ) AS PendingLeaves,
		(SELECT ISNULL(SUM(NoOfLeave),0) AS ApprovedLeaves FROM sHrm.tLeave HL1 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL1.BatchId where HL1.StatusId=550 AND HL1.ToDate  >= DATEADD(day,-30, getdate()) AND HL1.FromDate  <= getdate() AND BM.OrgGroupBatchId = @rOrgGroupBatchId) AS ApprovedLeaves,						
		(SELECT ISNULL(SUM(NoOfLeave),0) AS PendingLeaves FROM sHrm.tLeave HL3 INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL3.BatchId where HL3.StatusId=551 AND HL3.ToDate  >= DATEADD(day,-30, getdate()) AND HL3.FromDate  <= getdate() AND BM.OrgGroupBatchId = @rOrgGroupBatchId) AS RejectedLeaves
		
	  END
	  
	 ELSE IF(@rType = 'EmployeeCurrentYearLeaveDetails')
	 
	  BEGIN
	  
	   SELECT 	
	   (SELECT ISNULL(SUM(NoOfLeave),0) AS PendingLeaves 
	            FROM sHrm.tLeave HL2 
	               INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL2.BatchId 	               
				   INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = HL2.EmployeeId
				   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = HL2.EmployeeId 
	               where HL2.StatusId=549 AND HL2.FromDate  >= convert(date, DATEADD(yy, DATEDIFF(yy, 0,  DATEadd(day, -1,getdate())), 0), 103 ) AND HL2.ToDate  <= convert(date, DATEADD(yy, DATEDIFF(yy, 0, DATEDIFF(day, -1,getdate()))+1, -1), 103 ) AND  BM.OrgGroupBatchId = @rOrgGroupBatchId) AS PendingLeaves,	
		(SELECT ISNULL(SUM(NoOfLeave),0) AS ApprovedLeaves 
		      FROM sHrm.tLeave HL1 
		         INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL1.BatchId 
		         INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = HL1.EmployeeId
			     INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = HL1.EmployeeId 
		      where HL1.StatusId=550 AND HL1.FromDate  >= convert(date, DATEADD(yy, DATEDIFF(yy, 0,  DATEadd(day, -1,getdate())), 0), 103 ) AND HL1.ToDate  <= convert(date, DATEADD(yy, DATEDIFF(yy, 0, DATEDIFF(day, -1,getdate()))+1, -1), 103 ) AND   BM.OrgGroupBatchId = @rOrgGroupBatchId) AS ApprovedLeaves,		
		(SELECT ISNULL(SUM(NoOfLeave),0) AS PendingLeaves 
		      FROM sHrm.tLeave HL3 		         
		          INNER JOIN sSetup.tBatchMaster BM ON BM.Id = HL3.BatchId 
		          INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = HL3.EmployeeId
			      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = HL3.EmployeeId 
		          where HL3.StatusId=551 AND HL3.FromDate  >= convert(date, DATEADD(yy, DATEDIFF(yy, 0,  DATEadd(day, -1,getdate())), 0), 103 ) AND HL3.ToDate  <= convert(date, DATEADD(yy, DATEDIFF(yy, 0, DATEDIFF(day, -1,getdate()))+1, -1), 103 ) AND   BM.OrgGroupBatchId = @rOrgGroupBatchId) AS RejectedLeaves
	  
	  END   
	  
	  
	   ELSE IF(@rType = 'EmployeeMonthWiseAbsentPIChartDetails')
	   
	    BEGIN
	        Select M.Id,M.Title, ISNULL(COUNT(AttendanceDate),0) AS AbsentCount  From sCommon.tMonthMaster M
			 LEFT JOIN  sHrm.tEmployeeAttendanceRegister ER ON MONTH(ER.AttendanceDate) =M.Id AND BatchId=@rBatchId AND IsPresent=0
			 GROUP BY M.Id,M.Title
			 ORDER BY M.Id
 
	    END
	  	
	  ELSE IF(@rType = 'EmployeeMonthWiseLeavePIChartDetails')	
	  	
	  	BEGIN
	       
          Select M.Id,M.Title, ISNULL(SUM(NoOfLeave),0) AS LeaveCount  From sCommon.tMonthMaster M
			 LEFT JOIN  sHrm.tLeave HL ON MONTH(HL.FromDate) =M.Id AND BatchId=@rBatchId 
			 GROUP BY M.Id,M.Title
			 ORDER BY M.Id
 
	    END		
END
GO
PRINT N'Altering [sHrm].[pEmployeeCustomSearchGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeCustomSearchGet]
(
	@rPageIndex int = null,
	@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',
	@rLeftFromDate Date = '0001-01-01',
	@rLeftToDate Date = '9999-12-31',
	@rDropDownStatusId int
	
	
 )
AS
SET NOCOUNT ON
BEGIN
	DECLARE @Sql nvarchar(MAX)
	
	if @rDOBToDate = '9999-12-31'
	begin
		select @rDOBToDate = null
	end
	
	if @rLeftToDate = '9999-12-31'
	begin
		select @rLeftToDate = null
	end
	
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	
	SELECT * into sHrm.tTempEmployee1
	FROM sHrm.vEmployeeCustomSearch ECS
	WHERE ECS.OrgId = @rOrgId
	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
	AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
	AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))
	AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
	AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
	AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))
	AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
	AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='')
	AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='')
	AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='')
	AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='')
	AND (ISNULL(ECS.EmployeeGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupId,','))OR @rEmployeeGroupId='')
	AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='')
	AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='')
	AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='')
	AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='')
	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	
	
	
	SET @rOrderBy=Replace(@rOrderBy,'Code','Code')
	SET @sql='SELECT EmployeeId,Code AS Code,Name,EmployeeType,OrganizationDepartment AS OrganizationDepartment,
	StatusName FROM sHrm.tTempEmployee1 ORDER BY '+@rOrderBy
	exec(@Sql)
	
	create table #STUDENTTEMP
	(
		tid int identity(1,1),t_StudentId bigint
	)
	select @Sql = 'insert into #STUDENTTEMP
	SELECT EmployeeId FROM sHrm.tTempEmployee1 ORDER BY ' + @rOrderBy
	
	exec (@Sql)
	
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	declare @lTotalRecords int,@lPageSize int = 10,@lResult varchar(max) = '',@lPaging varchar(max) = ''
	
	select @lTotalRecords = COUNT(*) FROM #STUDENTTEMP
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex, @lTotalRecords, @lPageSize)
	
	select @lResult = @lResult + '<tr><td><a style="cursor:pointer;" onclick="SelectEmp(' + convert(varchar,EmployeeId) + ',''' + isnull(Code,'') + ''')">Select</a></td>
	<td>' + isnull(Code,'') + '</td><td>' + isnull(Name,'') + '</td><td>' + isnull(EmployeeType,'') + '</td>
	<td>' + isnull(StatusName,'') + '</td><td>' + isnull(OrganizationDepartment,'') + '</td></tr>'	
	from sHrm.tTempEmployee1,#STUDENTTEMP
	where t_StudentId = EmployeeId and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	order by tid
	
	select @lResult as EmpList,@lPaging as Paging,@lTotalRecords as TotalRecords
	
	DROP TABLE #STUDENTTEMP
	DROP Table sHrm.tTempEmployee1
END
GO
PRINT N'Altering [sHrm].[pEmployeeGenerateReport]...';


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

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

	SET @rColumnName=Replace(@rColumnName,',GR No',',Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
 
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	SET @rQualification = sCommon.fSearchStringGet(@rQualification)
	
		SELECT *into sHrm.tTempEmployee2
		FROM sHrm.vEmployeeCustomSearch ECS
		WHERE ECS.OrgId = @rOrgId 
		AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
		AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
		AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
		AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
		AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
		AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))
			
		AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
		AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
		AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 			
		AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
		--AND (ISNULL(ECS.EmployeeGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeGroupId,','))OR @rEmployeeGroupId='')
		AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
		AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
		AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
		AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
		AND ((ECS.DateOfleaving >= @rLeftFromDate) OR (ISNULL(@rLeftFromDate,'') = ''))			
		AND ((ECS.DateOfleaving <= @rLeftToDate) OR (ISNULL(@rLeftToDate,'') = ''))
		AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		
		--SELECT * FROM 
		--	sHrm.vEmployeeCustomSearch ECS
		--WHERE 
		--	ECS.OrgId = @rOrgId 
		--	AND ((ECS.Code Like @rCode + '%') OR (@rCode = ''))
		--	AND ((ECS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))	 			 
		
--	AND ((ECS.LastName Like @rLastName + '%')OR(@rLastName = ''))
		--	AND ((ISNULL(ECS.Qualification,'') Like @rQualification + '%')OR(@rQualification = ''))
		--	AND ((ECS.DateOfBirth >= @rDOBFromDate) OR (ISNULL(@rDOBFromDate,'') = ''))
		--	AND ((ECS.DateOfBirth <= @rDOBToDate) OR (ISNULL(@rDOBToDate,'') = ''))	
		--	AND ((ECS.DateOfJoining >= @rDOJFromDate) OR (ISNULL(@rDOJFromDate,'') = ''))
		--	AND ((ECS.DateOfJoining <= @rDOJToDate) OR (ISNULL(@rDOJToDate,'') = ''))	
			
		--	AND (ISNULL(ECS.OrganizationDepartmentId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrganizationDepartmentId,','))OR @rOrganizationDepartmentId='') 
			

		--	AND (ISNULL(ECS.StatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rStatusId,','))OR @rStatusId='') 
			
		--    AND (ISNULL(ECS.EmployeeTypeId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeTypeId,','))OR @rEmployeeTypeId='') 
			
		--    AND (ISNULL(ECS.EmployeeDesignationId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rEmployeeDesignationId,','))OR @rEmployeeDesignationId='') 
			
		--    AND (ISNULL(ECS.BloodGroupId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rBloodGroupId,','))OR @rBloodGroupId='') 
			   
		--    AND (ISNULL(ECS.ReligionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReligionId,','))OR @rReligionId='') 
			        
		--    AND (ISNULL(ECS.MaritalStatusId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rMaritalStatusId,','))OR @rMaritalStatusId='') 
			 
		--    AND (ISNULL(ECS.GenderId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGenderId,','))OR @rGenderId='') 
	
		--	AND ((ECS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
		
		SET @sql=
		'SELECT '+
		@rColumnName+' 
		FROM sHrm.tTempEmployee2 ORDER BY '+@rOrderBy
		--SELECT @sql
		exec(@Sql)
		
		DROP Table sHrm.tTempEmployee2
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sHrm].[pLeaveListingGet]...';


GO
 
ALTER PROCEDURE [sHrm].[pLeaveListingGet]  
(  
	@rOrgId int,  
    @rId bigint = 0,  
    @rEmployeeId  bigint,     
    @rFromDate date,  
    @rLeaveTypeId int,  
    @rTodate date,  
    @rOrgGroupBatchId int,  
    @rEmployeeCode nvarchar(100)='',  
    @rEmployeeName nvarchar(100)='',  
    @rStatusId int = 0,  
    @rOrgGroupId int,  
    @rIsSearchLeaveHierarchyWise int = 0,  
    @rDepartmentId int,
	@rUserId bigint = 0
 )  
AS  
SET NOCOUNT ON  
  
BEGIN  
      
    CREATE TABLE #TempEmployeeId  
    (  
  EmployeeId bigint  
    )  
      
    IF(@rIsSearchLeaveHierarchyWise = 1)  
 BEGIN  
  WITH EmployeeCTE AS  
   (  
    SELECT  
     EmployeeID  
    FROM sHrm.tEmployeeJobDetail  
    WHERE ((EmployeeManagerId = @rEmployeeId) OR (@rEmployeeId = 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  
    END  
      
      
    ELSE  
    BEGIN  
  INSERT INTO #TempEmployeeId(EmployeeId)  
  SELECT EmployeeId FROM sHrm.tEmployeeJobDetail EJD   
  WHERE ((EJD.EmployeeManagerId = @rEmployeeId) OR (@rEmployeeId = 0))  
      AND ((OrgId = @rOrgId) OR (@rOrgId = 0))  
    END  
      
  SELECT   
      L.[Id] AS LeaveId,  
      L.[EmployeeId],  
      L.[ReportDate],  
      L.[FromDate],  
      L.[ToDate],  
      L.[LeavePeriodId],  
      L.[LeaveTypeId],  
      L.[LeaveReason],  
      LPM.Title AS LeavePeriod,  
      LTM.Title AS LeaveType,  
      EM.EmployeeName,  
      EM.Code AS EmployeeCode,  
      L.NoOfLeave,  
      ISNULL(L.StatusId,0) AS StatusId,  
      ISNULL(SM.Title,'Pending') AS StatusName,  
      ISNULL(L.LeaveRemark,'') AS  LeaveRemark,  
      OM.DisplayTitle AS OrganizationName,  
      L.ActionByEmployeeId,  
      CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND L.StatusId = 549 THEN NULL  
      WHEN L.ActionByEmployeeId = 0 AND L.StatusId != 549 THEN US.DisplayTitle  
      ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
      OM.Id AS OrgId,  
      L.BatchId AS BatchId,  
      EM.DepartmentId AS DepartmentId,  
      EM.DepartmentName As DepartmentName  
  FROM   
      sHrm.tLeave L  
      INNER JOIN sSetup.tBatchMaster BM ON BM.Id = L.BatchId    
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
      INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId  
      INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId  
      INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId  
      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = L.EmployeeId  
      INNER JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
      INNER JOIN #TempEmployeeId EID ON EID.EmployeeId = L.EmployeeId  
      LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId  
      LEFT JOIN sSecurity.tUser US ON US.Id = L.UpdatedUserId    
	  INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017
  WHERE   
      (L.Id = @rId OR @rId = 0)  
      --AND (EJD.EmployeeManagerId = @rEmployeeId OR @rEmployeeId = 0)  
      AND ((L.FromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
      AND ((L.FromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
      AND (L.LeaveTypeId = @rLeaveTypeId OR @rLeaveTypeId = 0)        
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
      AND ((L.OrgId = @rOrgId) OR (@rOrgId = 0))  
      AND (EM.Code = @rEmployeeCode OR ISNULL(@rEmployeeCode,'') = '')  
      AND (EM.EmployeeName like @rEmployeeName+'%' OR ISNULL(@rEmployeeName,'') = '')  
      AND (L.StatusId = @rStatusId OR @rStatusId = 0) 
      AND ((EM.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))  
	  AND U.UserId = @rUserId     
  ORDER BY   
      L.FromDate DESC  
       
END
GO
PRINT N'Altering [sHrm].[pStaffAttendaceDashboardGet]...';


GO
ALTER PROCEDURE [sHrm].[pStaffAttendaceDashboardGet]
	 
	 @rTypeId smallint,
	 @rUptoDate date='',
	 @rOrgGroupId int=0,
	 @rOrgId int=0,
	 @rDepartmentId int=0,
	 @rCommonOrgGroupBatchId int=0,
	  @rSyncDate int =0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

if @rTypeId=1
BEGIN
	IF(@rSyncDate=1)
		BEGIN
			DELETE  sHrm.tTempStaffAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sHrm.tTempStaffAttendance
				SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
    0 As OrgId,'' As OrgTitle,
	    (SELECT 
        COUNT(EM.Id) 
     FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		           
	 WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 and EM.statusid=7) AS TotalCount,
 --PresentCount
    (SELECT 
        COUNT(ETRP.EmployeeId) 
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DME.OrgGroupId=OGM.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7
      ) AS PresentCount,
--AbsentCount
     (SELECT 
         COUNT(ETRP.EmployeeId) 
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
      WHERE DME.OrgGroupId=OGM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
            AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7
      ) As AbsentCount,
--LeaveCount
    (SELECT 
        COUNT(EM.Id)
     FROM sHrm.tLeave SHT
          INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.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 sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				
	 WHERE DME.OrgGroupId=OGM.Id  AND COGBM.Id=@rCommonOrgGroupBatchId   and EM.statusid=7
		  AND((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
	) As LeaveCount,
--AB10Count
	(SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,
             (OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.PresentContactNo) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)
		
		
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp) As 'AB10Count',
--AB3DaysCount
   (SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			  and EM.statusid=7
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3) as AB3DaysCount,
--Leave3DayCount    
 (SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
          d.ToDate=CONVERT(char(10), @rUptoDate,126)
		  and EM.statusid=7
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    )  As Leave3DayCount,
   
--HundredPerAttnCount		
   (SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.PresentContactNo) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp) As 'HundredPerAttnCount',
--PendingCount	  
	   (SELECT 
        COUNT(EM.Id) 
		 FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	 WHERE OGM.Id=OGMM.Id 
	 and EM.statusid=7 
	 
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   
	   @rUptoDate,
		  @rCommonOrgGroupBatchId,GetDate()	
	   
    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE OGM.Id<>1 AND COGBM.Id=@rCommonOrgGroupBatchId   AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
	And OGM.IsObsolete = 0
	SELECT * FROM sHrm.tTempStaffAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId
		END
	ELSE
		BEGIN
			  IF  Exists(select 1 from sHrm.tTempStaffAttendance    where CONVERT(date,UpdateDate) =  CONVERT(date,getdate(),102)   AND CommonOrgGroupBatchId=@rCommonOrgGroupBatchId AND EmployeeAttendanceDate=  CONVERT(date,@rUptoDate,102) )
			BEGIN
	
				SELECT * FROM sHrm.tTempStaffAttendance   WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
				return
			END
		ELSE
			BEGIN
			DELETE  sHrm.tTempStaffAttendance WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			INSERT INTO sHrm.tTempStaffAttendance
--TotalCount	
				SELECT     
    OGM.Id AS OrgGroupId,
    OGM.Title As OrgGroupTitle,
    0 As OrgId,'' As OrgTitle,
	    (SELECT 
        COUNT(EM.Id) 
     FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		  --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
          --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				    
		  --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		  --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID          
	 WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 and EM.statusid=7) AS TotalCount,
  --  (SELECT 
  --      COUNT(EM.Id) 
  --   FROM sHrm.tEmployeeMaster EM
		--  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		--  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--  --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --        --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
  --        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				    
		--  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		--  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID          
	 --WHERE OGM.Id=OGMM.Id --AND COGBM.Id=@rCommonOrgGroupBatchId 
	 --and EM.statusid=7) AS Total,

    (SELECT 
        COUNT(ETRP.EmployeeId) 
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DME.OrgGroupId=OGM.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId 
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
		   and EM.statusid=7
      ) AS PresentCount,

     (SELECT 
         COUNT(ETRP.EmployeeId) 
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		 INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		 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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	     LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
      WHERE DME.OrgGroupId=OGM.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId
            AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			 and EM.statusid=7
      ) As AbsentCount,
      
    (SELECT 
        COUNT(EM.Id)
     FROM sHrm.tLeave SHT
          INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.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 sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
				
	 WHERE DME.OrgGroupId=OGM.Id  AND COGBM.Id=@rCommonOrgGroupBatchId 
		  AND((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		  and EM.statusid=7
	) As LeaveCount,

	(SELECT 
	    COUNT(EmployeeId) 
	FROM(
         SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,
             (OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.PresentContactNo) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR						
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
		WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)
		
		
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	 ) AS Tmp) As 'AB10Count',

   (SELECT 
	   COUNT(EmployeeId) FROM(
	      SELECT 
	          ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		      d.EmployeeId,
		      AttendanceDate,
		      d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			  INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			  LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
         WHERE
              DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
              IsPresent IN(0) 
              AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			  and EM.statusid=7
         GROUP BY d.EmployeeId,AttendanceDate,IsPresent
         ) as sfsf
     WHERE rowno=3) as AB3DaysCount,
    
 (SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d
		 	 INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
             LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
           DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND
          d.ToDate=CONVERT(char(10), @rUptoDate,126) 
		  and EM.statusid=7
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
    )  As Leave3DayCount,
   
		
   (SELECT 
      COUNT(EmployeeId) FROM (
          SELECT    
             OGMEL.Id AS OrgGroupId,
             OGMEL.Title AS OrgGroupTitle,
             OMEL.Id AS OrgId,(OMEL.Title) AS OrgTitle,
             DME.Id,DME.Code AS DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.PresentContactNo) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) as PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(numeric(10,2),((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage												
		  FROM sHrm.tEmployeeAttendanceRegister EAR						
						INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
						INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID						
						INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
						LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID						
		  WHERE DME.OrgGroupId=OGM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)		
		  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	   ) AS Tmp) As 'HundredPerAttnCount',

	   (SELECT COUNT(EM.Id) 
		 FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		 WHERE OGM.Id=OGMM.Id 
		  and EM.statusid=7
		  and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
							WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   @rUptoDate,
		  @rCommonOrgGroupBatchId,GetDate()	
	   
    FROM sSetup.tOrgGroupMaster OGM
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGM.Id
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
    WHERE OGM.Id<>1 AND COGBM.Id=@rCommonOrgGroupBatchId  AND ((OGM.Id = @rOrgGroupId)OR(@rOrgGroupId=0))
	And OGM.IsObsolete = 0
	SELECT * FROM sHrm.tTempStaffAttendance  WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			END
		END
  END
  
ELSE IF @rTypeId=2  

BEGIN
  SELECT 
     OGMT.Id As OrgGroupId,
     OM.Id AS OrgId, 
     OM.DisplayTitle AS OrgTitle,
     OGMT.Title As OrgGroupTitle,
	 (SELECT 
         COUNT(EM.Id) 
      FROM sHrm.tEmployeeMaster EM
		 INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
         --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
         INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
       WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
       AND EM.statusid=7) As TotalCount,
   --  (SELECT 
   --      COUNT(EM.Id) 
   --   FROM sHrm.tEmployeeMaster EM
		 --INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		 --INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OMM.OrgGroupId
		 ----INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --      --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId  
   --      INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		 --INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		 --LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
   --    WHERE OM.Id=OMM.Id  --AND COGBM.Id=@rCommonOrgGroupBatchId 
   --    AND EM.statusid=7) As Total,
        
      (SELECT 
          COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
       WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=1  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS PresentCount,
        
      (SELECT 
           COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
		  INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		  INNER JOIN sSetup.tOrganizationMaster OMEM ON OMEM.Id = BME.OrgId
		  INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OMEM.OrgGroupId
		  INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=BME.OrgGroupBatchId
          INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		  INNER JOIN sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		  INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		  INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	      LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE EJD.OrgId=OM.Id and ETRP.IsPresent=0  and EM.statusid=7
          AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
        ) AS AbsentCount, 	

	   (SELECT 
	         COUNT(EM.Id)
        FROM sHrm.tLeave SHT
           INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.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 sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
		   INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		      
		   INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
	       LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID				
		 WHERE EJD.OrgId=OM.Id AND				
			  ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			   AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))  AND COGBM.Id=@rCommonOrgGroupBatchId		
			   and EM.statusid=7		
		) As LeaveCount,
		
   (SELECT 
	   COUNT(EmployeeId) FROM(
           SELECT    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,
              (OMEL.Title) As OrgTitle,
              DME.Id,DME.Code As DeptCode,
              (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  (EC.PresentContactNo) AS ContactNo,
			   COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
               CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
			FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID												
			WHERE EJD.OrgId=OM.Id AND 
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)  AND COGBM.Id=@rCommonOrgGroupBatchId
				and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)

	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	      ) AS Tmp) As 'AB10Count',
	
	(SELECT COUNT(EmployeeId) from(
	    SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
		FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
              AND COGBM.Id=@rCommonOrgGroupBatchId
			  and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) as T
        WHERE rowno=3) AS AB3DaysCount,
        
     (SELECT 
        COUNT(EmployeeId) FROM(
	       SELECT 
			d.EmployeeId,
			d.FromDate,
			d.ToDate
		  FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE EJD.OrgId=OM.Id AND d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId
		and EM.statusid=7
        ) AS Temp 
        WHERE (DATEDIFF(d, FromDate, ToDate)=2)
        )  AS Leave3DayCount,
      
    (SELECT 
        COUNT(EmployeeId) FROM  (
           SELECT    
             OGMEL.Id as OrgGroupId,
             OGMEL.Title As OrgGroupTitle,
             OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
             DME.Id,DME.Code As DeptCode,
             (EM.Id)EmployeeID,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			 (EC.PresentContactNo) AS ContactNo,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
              convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage

            FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				--INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		    WHERE EJD.OrgId=OM.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND 
                 EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				 and EM.statusid=7
			GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DME.Id,DME.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)
		
	        HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	     ) AS Tmp) As 'HundredPerAttnCount'
		 ,
	(SELECT  COUNT(EM.Id) 
		FROM sHrm.tEmployeeMaster EM
		  INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
		  INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	 WHERE OM.Id=OMM.Id 
	 and EM.statusid=7
	   and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))
       ) AS PendingCount,
	   getdate()AS UpdateDate
			
    FROM 
       sSetup.tOrgGroupMaster OGMT 
    INNER JOIN sSetup.tOrganizationMaster OM ON OGMT.Id=OM.OrgGroupId    
    INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OM.OrgGroupId
    INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    WHERE OGMT.Id=@rOrgGroupId AND COGBML.Id=@rCommonOrgGroupBatchId 
	And OGMT.IsObsolete = 0
      
  END
  
  
else if @rTypeId=3   
  BEGIN
--TotalCount
    (SELECT 
      (DME.Id) As DepartmentId,
        DME.Code As DepartmentCode,OGMM.Id AS OrgGroupId,
        OGMM.Title As OrgGroupTitle,0 As OrgId,'' As OrgTitle,
        COUNT(DME.Id) As TotalCount,
--PresentCount
	(SELECT 
            COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE DME.Id=DMER.Id 
			and ETRP.IsPresent=1 
			AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
	   ) AS PresentCount,
--AbsentCount			
	  (SELECT COUNT(ETRP.EmployeeId) 
            FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
	   WHERE DME.Id=DMER.Id and ETRP.IsPresent=0 
			AND ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
			and EM.statusid=7
		) AS AbsentCount,
--LeaveCount			
   (SELECT    
        COUNT(EM.Id)
    FROM sHrm.tLeave SHT
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.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 sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
	WHERE DME.Id=DMER.Id AND				
			((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		     AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))		
			 and EM.statusid=7		
	) AS LeaveCount,
				
--AB10%Count				
     (SELECT 
         COUNT(EmployeeId) 
      FROM (
         SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.PresentContactNo) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) As TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id) AS FLOAT))*100)) as Percentage		
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
		WHERE DME.Id=DMER.Id AND 
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
	    GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)
	    HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id) AS FLOAT))*100))<=90
	     ) AS Tmp) AS 'AB10Count',
	           
--AB3DaysCount	           
      (SELECT 
          COUNT(EmployeeId) FROM(
	         SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		     d.EmployeeId,
		     AttendanceDate,
		     d.IsPresent
	   FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	    WHERE
            DME.Id=DMER.Id  AND IsPresent IN(0) 
            AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
			and EM.statusid=7
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) as AB3DaysCount,
  --Leave3DayCount
   (SELECT COUNT(EmployeeId) FROM(
	   SELECT
			d.EmployeeId,d.FromDate,d.ToDate
	   FROM sHrm.tLeave d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND 
			 d.ToDate=CONVERT(char(10), @rUptoDate,126)   
			 and EM.statusid=7     
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)        
      )  AS Leave3DayCount,
        
--HundredPerAttnCount     
        
  (SELECT 
      COUNT(EmployeeId) FROM(
         SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,
            (OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.PresentContactNo) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage		
	      FROM sHrm.tEmployeeAttendanceRegister EAR			
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE DME.Id=DMER.Id AND 		
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
			and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)
	      HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	  ) AS Tmp) As 'HundredPerAttnCount',

--PendingCount


	  (	select COUNT(*) from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
	where    EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126)) AND DMER.Id = DME.Id AND DMER.OrgGroupId = OGMM.Id and EM.statusid=7) 
	AS PendingCount

	FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
        --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	WHERE OGMM.ID=@rOrgGroupId AND EM.statusid=7 --AND COGBML.Id=@rCommonOrgGroupBatchId AND 
	And OGMM.IsObsolete = 0
	GROUP BY DME.Id,DME.Code,OGMM.Id,OGMM.Title
	) 
					
  END
  
  
else if @rTypeId=4 
  BEGIN     
     SELECT (DME.Id) As DepartmentId,
         DME.Code As DepartmentCode,
         OGMM.Id AS OrgGroupId,OGMM.Title As OrgGroupTitle,
         OM.Id As OrgId,OM.DisplayTitle As OrgTitle,
         COUNT(DME.Id) As TotalCount, 
         (SELECT 
            COUNT(ETRP.EmployeeId) 
          FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE DME.Id=DMER.Id AND ETRP.IsPresent=1 AND COGBM.Id=@rCommonOrgGroupBatchId AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId  
			AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126)  and EM.statusid=7
           ) As PresentCount,
			
	  (SELECT 
	      COUNT(ETRP.EmployeeId) 
       FROM sHrm.tEmployeeAttendanceRegister ETRP         
			INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
			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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
       WHERE DME.Id=DMER.Id and ETRP.IsPresent=0 AND COGBM.Id=@rCommonOrgGroupBatchId  
	   and EM.statusid=7
	   AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId  
			AND ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
	  ) AS AbsentCount,
			
			
      (SELECT 
       COUNT(EM.Id)
      FROM sHrm.tLeave SHT
            INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.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 sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
	        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	       
	        INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
            LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID			
	  WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND  EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  				
			((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			 AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			 and EM.statusid=7
	  ) As LeaveCount,
				
				
     (SELECT 
         COUNT(EmployeeId) FROM  (
            SELECT    
                OGMEL.Id as OrgGroupId,
                OGMEL.Title AS OrgGroupTitle,
                OMEL.Id AS OrgId,(OMEL.Title) As OrgTitle,
                DMER.Id,DMER.Code AS DepartmentCode,
                (EM.Id)EmployeeID,
                (EM.FirstName+' '+EM.LastName) AS EmployeeName,
				(EC.PresentContactNo) AS ContactNo,
				COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(COUNT(EM.Id)AS FLOAT) AS TotalCount,
                CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) as Percentage

			 FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
			 WHERE DME.Id=DMER.Id AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
				and EM.statusid=7
			 GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)

	         HAVING CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100))<=90
	       ) AS Tmp) As 'AB10Count',
	           
	           
   (SELECT 
       COUNT(EmployeeId) FROM(
	      SELECT ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			    d.EmployeeId,
			    AttendanceDate,
			    d.IsPresent
		  FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId  AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND  
			IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, CONVERT(DATE, @rUptoDate, 126)) AND @rUptoDate    
			and EM.statusid=7           
        GROUP BY d.EmployeeId,AttendanceDate,IsPresent
        ) AS T
        WHERE rowno=3) AS AB3DaysCount,
        
  (SELECT 
      COUNT(EmployeeId) FROM(
	     SELECT 
		     d.EmployeeId,
		     d.FromDate,
		     d.ToDate
		 FROM sHrm.tLeave d		
 			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		  
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID		
        WHERE
			 DME.Id=DMER.Id AND COGBM.Id=@rCommonOrgGroupBatchId AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND 
			 d.ToDate=CONVERT(CHAR(10), @rUptoDate,126)     
			 and EM.statusid=7   
        ) AS Temp WHERE (DATEDIFF(d, FromDate, ToDate)=2)       
    )  AS Leave3DayCount,
        
        
    (SELECT 
       COUNT(EmployeeId) FROM  (
          SELECT    
            OGMEL.Id as OrgGroupId,
            OGMEL.Title As OrgGroupTitle,
            OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
            DMER.Id,DMER.Code As DepartmentCode,
            (EM.Id)EmployeeID,
            (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.PresentContactNo) AS ContactNo,
			COUNT(CASE WHEN IsPresent=1 THEN 1 END) AS PresentCount,CAST(Count(EM.Id)AS FLOAT) AS TotalCount,
            CONVERT(NUMERIC(10,2), ((COUNT(CAST((CASE WHEN IsPresent=1 THEN 1 END) AS FLOAT))/CAST(COUNT(EM.Id)AS FLOAT))*100)) AS Percentage
		FROM sHrm.tEmployeeAttendanceRegister EAR
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE DME.Id=DMER.Id AND EJD.OrgId=@rOrgId AND DMER.OrgGroupId=@rOrgGroupId AND
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			and EM.statusid=7
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)
	    HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
	) AS Tmp) As 'HundredPerAttnCount',
	 (	select COUNT(*) from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sSetup.tOrganizationMaster OMM ON OM.Id = EM.OrgID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
	where  OM.Id=OMM.Id and  EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126)) AND DMER.Id = DME.Id AND DMER.OrgGroupId=OGMM.Id and EM.statusid=7) 
	AS PendingCount
  
   FROM sHrm.tEmployeeMaster EM
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
	INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
	--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
     --INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBML ON COGBML.Id=OGBM.CommonOrgGroupBatchId
    INNER JOIN sHrm.tEmployeeJobDetail EJD1 ON EJD1.EmployeeId=EM.ID
    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD1.OrgGroupDepartmentId
	LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID              
  WHERE DME.OrgGroupId=@rOrgGroupId And EJD1.OrgId=@rOrgId and EM.statusid=7 --AND COGBML.Id=@rCommonOrgGroupBatchId 
  And OGMM.IsObsolete = 0
  GROUP BY DME.Id,DME.Code,OGMM.Id,OGMM.Title,OM.Id,OM.DisplayTitle
	 
END  
   
   
else if @rTypeId=5   

BEGIN
   (SELECT(DM.code) As Dept,
          (EM.Id) As EmployeeId,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
          (EC.PresentContactNo) AS ContactNo
    FROM sHrm.tEmployeeMaster EM
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
			INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
   --         INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
     WHERE DM.Id=@rDepartmentId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And OGMM.IsObsolete = 0
	  and EM.statusid=7
     )
END
   
ELSE IF @rTypeId=31
 BEGIN
     SELECT 
        (OGMM.id) AS OrgGroupId,(OGMM.Title) As OrgGroupTitle,
        (OM.id) OrgId,(OM.Title) OrgTitle,
        (DME.Code) As DepartmentCode,
		(EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
        (EC.PresentContactNo) AS ContactNo
     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	    
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID                    
	 WHERE DME.OrgGroupId=@rOrgGroupId --AND COGBM.Id=@rCommonOrgGroupBatchId 
	  And OGMM.IsObsolete = 0
	  and EM.statusid=7
	 AND DME.Id=@rDepartmentId--) As Total
       
 END   
 
ELSE IF @rTypeId=41 
 BEGIN
	SELECT 
	   (OGMM.id) As OrgGroupId,
	   (OGMM.Title) As OrgGroupTitle,
	   (OM.id) OrgId,(OM.Title) OrgTitle,
	   DME.Code As DepartmentCode,(EM.Id)EmployeeID,
	   (EM.Code)EmployeeCode,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
	   (EC.PresentContactNo) AS ContactNo
     FROM sHrm.tEmployeeMaster EM
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgID
		INNER JOIN sSetup.tOrgGroupMaster OGMM ON OGMM.Id = OM.OrgGroupId
		--INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.OrgGroupId=OGMM.Id
  --      INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
        INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID	   
	    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	WHERE 
		EJD.OrgId=@rOrgId --AND COGBM.Id=@rCommonOrgGroupBatchId 
		and EM.statusid=7	
		 And OGMM.IsObsolete = 0
		AND ((@rDepartmentId <>1 AND DME.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))   
 END   
 
ELSE IF @rTypeId=32   

BEGIN
    SELECT 
        (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,(EM.FirstName+' '+EM.LastName) AS EmployeeName,
        (EC.PresentContactNo) AS ContactNo
    FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	 WHERE DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId and  ETRP.IsPresent=1
	  And OGME.IsObsolete = 0
	  and EM.statusid=7
		  AND ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
		
END

else if @rTypeId=42  

BEGIN
    SELECT 
        (OGME.id) As OrgGroupId,
        (OGME.Title) As OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code As DepartmentCode,
        (EM.Id)EmployeeID,
		(EM.Code)EmployeeCode,
        (EM.FirstName+' '+EM.LastName) AS EmployeeName,
        (EC.PresentContactNo) AS ContactNo
     FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID		
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	 WHERE EJD.OrgId=@rOrgId
		and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		and  ETRP.IsPresent=1
		and EM.statusid=7
		And OGME.IsObsolete = 0
		and ETRP.AttendanceDate = CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
	
END


else if @rTypeId=33  
  BEGIN
     SELECT 
        (OGME.id) As OrgGroupId,
        (OGME.Title) As OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code As DepartmentCode,
		(EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
        (EC.PresentContactNo) AS ContactNo
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			
	where DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId and  ETRP.IsPresent=0  AND COGBM.Id=@rCommonOrgGroupBatchId 
	And OGME.IsObsolete = 0
	and EM.statusid=7
	    AND ETRP.AttendanceDate = CONVERT(CHAR(10),  @rUptoDate,126)
	
  END   
  
  ELSE IF @rTypeId=43   
  BEGIN
     SELECT 
       (OGME.id) As OrgGroupId,
       (OGME.Title) As OrgGroupTitle,
 (OME.id) OrgId,(OME.Title) OrgTitle,
       DMER.Code As DepartmentCode,
       (EM.Id)EmployeeID,
	   (EM.Code)EmployeeCode,
       (EM.FirstName+' '+EM.LastName) AS EmployeeName,
       (EC.PresentContactNo) AS ContactNo
      FROM sHrm.tEmployeeAttendanceRegister ETRP         
		INNER JOIN sSetup.tBatchMaster BME ON BME.Id = ETRP.BatchId -- AND BME.IsActive = 1
		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 sHrm.tEmployeeMaster EM ON ETRP.EmployeeId=EM.Id
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	  WHERE EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId 
		and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		and  ETRP.IsPresent=0 
		and EM.statusid=7
		And OGME.IsObsolete = 0
		and ETRP.AttendanceDate = CONVERT(char(10),  @rUptoDate,126)
	
  END 
   
 ELSE IF @rTypeId=34 
   
   BEGIN
      
       select (OGMEL.id) As OrgGroupId,
              (OGMEL.Title) As OrgGroupTitle,
              (OMEL.id) OrgId,(OMEL.Title) OrgTitle,
              DMER.Code As DepartmentCode,
              (EM.Id)EmployeeID,
			  (EM.Code)EmployeeCode,
              (EM.FirstName+' '+EM.LastName) AS EmployeeName,
              (EC.PresentContactNo) AS ContactNo
       FROM sHrm.tLeave SHT
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.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 sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE DMER.OrgGroupId=@rOrgGroupId AND DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId 
	   And OGMEL.IsObsolete = 0
	   and EM.statusid=7
	   AND			
				((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
   
   END
   
   
 ELSE IF @rTypeId=44    
   BEGIN
       SELECT (OGMEL.id) As OrgGroupId,
              (OGMEL.Title) As OrgGroupTitle,
              (OMEL.id) OrgId,(OMEL.Title) OrgTitle,
              DMER.Code As DepartmentCode,
			  (EM.Id)EmployeeID,
              (EM.Code)EmployeeCode,
			  (EM.FirstName+' '+EM.LastName) AS EmployeeName,
              (EC.PresentContactNo) AS ContactNo
       FROM sHrm.tLeave SHT
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = SHT.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 sHrm.tEmployeeMaster EM ON SHT.EmployeeId=EM.Id
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	   WHERE EJD.OrgId=@rOrgId	AND COGBM.Id=@rCommonOrgGroupBatchId 
	   And OGMEL.IsObsolete = 0
	   and EM.statusid=7
				AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And				
				 ((SHT.FromDate >= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			     AND ((SHT.FromDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
		
   END
   
 ELSE IF @rTypeId=35 
   
   BEGIN

    select * from (
          select    
              OGMEL.Id as OrgGroupId,
              OGMEL.Title As OrgGroupTitle,
              OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,--DMER.Id,DMER.Code As DeptCode,
              (EM.Id)EmployeeID,
			  (EM.Code)EmployeeCode,
			  (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			  (EC.PresentContactNo) AS ContactNo,DMER.Code As DepartmentCode,
			  count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
			  convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		  FROM sHrm.tEmployeeAttendanceRegister EAR
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
			
		  WHERE DMER.OrgGroupId=@rOrgGroupId  AND DMER.Id=@rDepartmentId 
		  And OGMEL.IsObsolete = 0
		  
		  AND COGBM.Id=@rCommonOrgGroupBatchId AND
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7
		  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,
				EM.Id,(EM.Code),(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo),DMER.Code
	       HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	   ) AS Tmp
      
   END
   
   
   else if @rTypeId=45 
   
   BEGIN
   
    SELECT * FROM (
          SELECT    
               OGMEL.Id as OrgGroupId,
               OGMEL.Title As OrgGroupTitle,
               OMEL.Id As OrgId,
               (OMEL.Title) As OrgTitle,
               (EM.Id)EmployeeID,
			   (EM.Code)EmployeeCode,
               (EM.FirstName+' '+EM.LastName) AS EmployeeName,
				(EC.PresentContactNo) AS ContactNo,DMER.Code As DepartmentCode,
				count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
                convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
		  FROM sHrm.tEmployeeAttendanceRegister EAR				
				INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
				INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID				
				INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
				LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		  WHERE EJD.OrgId=@rOrgId  AND COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
			    and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) AND
				EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
				and EM.statusid=7
				GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title
				,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo),DMER.Code 
	       HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))<=90
	    ) AS Tmp
      
   END
   
   
 ELSE IF @rTypeId=36
  
  BEGIN
    (SELECT Temp.OrgGroupId,
            Temp.OrgGroupTitle,
            Temp.OrgId,Temp.OrgTitle,
            (EMR.Id) As EmployeeId,
			EMR.Code As EmployeeCode,
            (EMR.FirstName+' '+EMR.LastName) AS EmployeeName			,
            (ECR.PresentContactNo) AS ContactNo,
			DepartmentCode
     FROM(select ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
		    d.EmployeeId,(EM.Code)EmployeeCode,
		    AttendanceDate,d.IsPresent,
		    OGMEL.Id As OrgGroupId,
		    OGMEL.Title As OrgGroupTitle,
		    OMEL.Id As OrgId,OMEL.Title As OrgTitle,
		    DMER.Code As DepartmentCode
          FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID	
        WHERE
            DMER.OrgGroupId=@rOrgGroupId And DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
			and EM.statusid=7
			AND 
            IsPresent IN(0) AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate       
        Group By d.EmployeeId,EM.Code,AttendanceDate,IsPresent,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Code 
        ) As Temp
            INNER JOIN sHrm.tEmployeeMaster EMR ON EMR.ID=Temp.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMR.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications ECR on EMR.ID=ECR.EmployeeID        
        where rowno=3
      ) 
       
  END
  
  
  
 ELSE IF @rTypeId=46 
 
  BEGIN
  (SELECT Temp.OrgGroupId,
          Temp.OrgGroupTitle,
          Temp.OrgId,Temp.OrgTitle,
          (EMR.Id) As EmployeeId,
		  EMR.Code As EmployeeCode,
          (EMR.FirstName+' '+EMR.LastName) AS EmployeeName,		
          (ECR.PresentContactNo) AS ContactNo,DepartmentCode
      FROM(
	      select 
	         ROW_NUMBER() OVER ( PARTITION BY d.EmployeeId ORDER BY MIN(AttendanceDate) DESC) as rowno,
			 d.EmployeeId,
			 EM.Code As EmployeeCode,
			 AttendanceDate,d.IsPresent,
			 OGMEL.Id As OrgGroupId,
			 OGMEL.Title As OrgGroupTitle,
			 OMEL.Id As OrgId,
			 OMEL.Title As OrgTitle,
			 DMER.Code As DepartmentCode
		   FROM sHrm.tEmployeeAttendanceRegister d
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
        WHERE
        EJD.OrgId=@rOrgId 
        AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And OGMEL.IsObsolete = 0
		and EM.statusid=7
		AND
        IsPresent IN(0) AND COGBM.Id=@rCommonOrgGroupBatchId 
        AND AttendanceDate between DATEADD(DAY, -2, convert(date, @rUptoDate, 126)) AND @rUptoDate
        Group By d.EmployeeId,EM.Code,AttendanceDate,IsPresent,OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Code 
        ) As Temp
		INNER JOIN sHrm.tEmployeeMaster EMR ON EMR.ID=Temp.EmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMR.ID
		INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		LEFT JOIN sHrm.tEmployeeCommunications ECR on EMR.ID=ECR.EmployeeID
      WHERE rowno=3
    ) 
    
  END

  ELSE IF @rTypeId=37
  
  BEGIN
     (SELECT * FROM(
	     SELECT
			d.FromDate,
			d.ToDate,
			OGMEL.Id As OrgGroupId,
			OGMEL.Title As OrgGroupTitle,
			OMEL.Id As OrgId,
			OMEL.Title As OrgTitle,
			EM.Code As EmployeeId,
			EM.ID As EmployeeCode,
			(EM.FirstName+' '+EM.LastName) AS EmployeeName						,
            (EC.PresentContactNo) AS ContactNo,
            DME.Code As DepartmentCode
		FROM sHrm.tLeave d
	 	    INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
		    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
		    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
		    LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE
			d.ToDate=CONVERT(char(10), @rUptoDate,126) AND COGBM.Id=@rCommonOrgGroupBatchId 
			and DME.OrgGroupId=@rOrgGroupId AND DME.Id=@rDepartmentId And OGMEL.IsObsolete = 0
			and EM.statusid=7
        ) as Temp where (DATEDIFF(d, FromDate, ToDate)=2)
      ) 
  END

  ELSE IF @rTypeId=47   
  
  BEGIN
  
     (SELECT * from(
	     SELECT
			d.FromDate,
			d.ToDate,
			OGMEL.Id As OrgGroupId,
			OGMEL.Title As OrgGroupTitle,
			OMEL.Id As OrgId,OMEL.Title As OrgTitle,
			EM.Code As EmployeeId,
			EM.Id As EmployeeCode,
			(EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.PresentContactNo) AS ContactNo,DME.Code As DepartmentCode
		  FROM sHrm.tLeave d
		 	    INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = d.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 sHrm.tEmployeeMaster EM ON EM.ID=d.EmployeeId
			    INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			    INNER JOIN sCommon.tOrgGroupDepartmentMaster DME ON DME.Id=EJD.OrgGroupDepartmentId
			    LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE
          d.ToDate=CONVERT(char(10), @rUptoDate,126)
		  and EM.statusid=7
          AND EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0
          AND ((@rDepartmentId <>1 AND DME.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) 
        ) AS Temp where (DATEDIFF(d, FromDate, ToDate)=2)        
      ) 
  
  
  END 
  
  
  else if @rTypeId=38
  
  BEGIN
      SELECT    
          OGMEL.Id as OrgGroupId,
          OGMEL.Title As OrgGroupTitle,
          OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
          DMER.Id,DMER.Code As DepartmentCode,
          (EM.Id)EmployeeID,
		  (EM.Code)EmployeeCode,
          (EM.FirstName+' '+EM.LastName) AS EmployeeName,
		  (EC.PresentContactNo) AS ContactNo,
		   count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
		   convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage
	  FROM sHrm.tEmployeeAttendanceRegister EAR		
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
	  WHERE DMER.OrgGroupId=@rOrgGroupId AND DMER.Id=@rDepartmentId And COGBM.Id=@rCommonOrgGroupBatchId And OGMEL.IsObsolete = 0 
	  and EM.statusid=7
	  AND		
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
	  GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)
	  HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
  
  END
  
  
  ELSE IF @rTypeId=48 
  
  BEGIN
      
      SELECT    
           OGMEL.Id as OrgGroupId,
           OGMEL.Title As OrgGroupTitle,
           OMEL.Id As OrgId,(OMEL.Title) As OrgTitle,
           DMER.Id,DMER.Code As DepartmentCode,
           (EM.Id)EmployeeID,
		   (EM.Code)EmployeeCode,
           (EM.FirstName+' '+EM.LastName) AS EmployeeName,
			(EC.PresentContactNo) AS ContactNo,
			count(case when IsPresent=1 then 1 end) as PresentCount,CAST(Count(EM.Id)AS float) As TotalCount,
            convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100)) as Percentage						
		FROM sHrm.tEmployeeAttendanceRegister EAR			
			INNER JOIN sSetup.tBatchMaster BMEL ON BMEL.Id = EAR.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 sHrm.tEmployeeMaster EM ON EM.ID=EAR.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID			
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		WHERE EJD.OrgId=@rOrgId AND COGBM.Id=@rCommonOrgGroupBatchId  And OGMEL.IsObsolete = 0
		and EM.statusid=7
			and ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1)) And
			EAR.AttendanceDate <= CONVERT(char(10), @rUptoDate,126)
		GROUP BY OGMEL.Id,OGMEL.Title,OMEL.Id,OMEL.Title,DMER.Id,DMER.Code,EM.Id,EM.Code,(EM.FirstName+' '+EM.LastName),(EC.PresentContactNo)
		HAVING convert(numeric(10,2), ((count(CAST((case when IsPresent=1 then 1 end) AS float))/CAST(Count(EM.Id)AS float))*100))=100
  END

  ELSE IF @rTypeId=39   

BEGIN
    SELECT 
       (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
        (EC.PresentContactNo) AS ContactNo
	 from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		
	where DMER.OrgGroupId=@rOrgGroupId and DMER.Id=@rDepartmentId And OGME.IsObsolete = 0
	and EM.statusid=7
	AND EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10), @rUptoDate,126))		
END

  ELSE IF @rTypeId=49   

BEGIN
    SELECT 
        (OGME.id) AS OrgGroupId,
        (OGME.Title) AS OrgGroupTitle,
        (OME.id) OrgId,
		(OME.Title) OrgTitle,
        DMER.Code AS DepartmentCode,
        (EM.Id)EmployeeID,
        (EM.Code)EmployeeCode,
		(EM.FirstName+' '+EM.LastName) AS EmployeeName,
        (EC.PresentContactNo) AS ContactNo
	 from  sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EM.ID
			INNER JOIN sCommon.tOrgGroupDepartmentMaster DMER ON DMER.Id=EJD.OrgGroupDepartmentId
			INNER JOIN sSetup.tOrganizationMaster OME ON OME.Id = EM.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OGME ON OGME.Id=OME.OrgGroupId
		LEFT JOIN sHrm.tEmployeeCommunications EC on EM.ID=EC.EmployeeID
		

		WHERE EJD.OrgId=@rOrgId
		AND ((@rDepartmentId <>1 AND DMER.Id=@rDepartmentId)OR(@rDepartmentId=1 AND 1=1))
		And OGME.IsObsolete = 0
		and EM.statusid=7
		AND   EM.Id not IN (select EmployeeId from sHrm.tEmployeeAttendanceRegister 
	WHERE AttendanceDate = CONVERT(char(10),@rUptoDate,126))		
		
END


END
GO
PRINT N'Altering [sLibrary].[pBookLogGet]...';


GO
ALTER PROCEDURE [sLibrary].[pBookLogGet]
	 @rBookLogId bigint,
	 @rResourceSourceId bigint,
	 @rStatusId smallint,
	 @rIscurrentStatus bit,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 	
DECLARE @lEmployeeString  VARCHAR(MAX);

	SELECT 
			BL.Id AS BookLogId,
			BL.ReaderSourceTypeId,
			BL.ReaderSourceId,
			SA.Code AS ReaderCode,
			SA.Name AS ReaderName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDept,
			SA.ClassId As SourceId,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			BL.Remark,
			BL.IsCurrentStatus,
			IS1.PenaltyPerDay,
			BL.OrgId,
			BL.BatchId,
			ISNULL(BL.ReturnDate,'') AS ReturnDate,
			SA.SUId,
			BM.Author,
			BM.Publisher,
			( SELECT  stuff((
        SELECT ', ' + cast(CM.Title AS VARCHAR(MAX))
        FROM sSetup.tClassmaster CM
        INNER JOIN sLibrary.tBooksForClass BFC1 ON CM.Id= BFC1.ClassId  
        WHERE BFC.BookId = BFC1.BookId
        GROUP BY CM.Title,BFC1.BookId   
        for xml path('')
    ),1,1,'')  FROM sLibrary.tBooksForClass BFC
 WHERE BFC.BookId =   BM.Id 
GROUP BY  BFC.BookId) AS AssignClassDivision 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=SA.ClassId AND IS1.SourceTypeId = 2005
	WHERE 
			((BL.ResourceSourceId=@rResourceSourceId) OR (@rResourceSourceId=0))
			AND ((BL.Id=@rBookLogId) OR (@rBookLogId=0))
			AND ((BL.IsCurrentStatus=@rIscurrentStatus) OR (@rIscurrentStatus=0))
			AND ((BL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
	
	UNION ALL
	
	SELECT 
			BL.Id AS BookLogId,
			BL.ReaderSourceTypeId,
			BL.ReaderSourceId,
			EM.Code AS ReaderCode,
			EM.FirstName+' '+EM.LastName AS ReaderName,
			ODM.Title as ClassDept,
			ODM.Id AS SourceId,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			BL.Remark,
			BL.IsCurrentStatus,
			IS1.PenaltyPerDay,
			BL.OrgId,
			BL.BatchId,
			ISNULL(BL.ReturnDate,'') AS ReturnDate,
			'' AS SUId,
			BM.Author,
			BM.Publisher,
			'' AS AssignClassDivision 	
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id = EJD.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster ODM ON ODM.Id = EJD.OrganizationDepartmentId
			INNER JOIN sLibrary.tIssueSetting IS1 ON IS1.SourceId=ODM.Id AND IS1.SourceTypeId = 2004
	WHERE 
			((BL.ResourceSourceId=@rResourceSourceId) OR (@rResourceSourceId=0))
			AND ((BL.Id=@rBookLogId) OR (@rBookLogId=0))
			AND ((BL.IsCurrentStatus=@rIscurrentStatus) OR (@rIscurrentStatus=0))
			AND ((BL.StatusId=@rStatusId) OR (@rStatusId=0))
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
END
GO
PRINT N'Altering [sLibrary].[pBookMasterGet]...';


GO
ALTER PROCEDURE [sLibrary].[pBookMasterGet]
	 
	 @rId bigint = 0,
	 @rCode nvarchar(200),
	 @rTitle nvarchar(100),
	 @rOrgId int,
	 @rPublisher nvarchar(200),
	 @rSupplier nvarchar(200),
	 @rAuthor nvarchar(200),
	 @rSubject nvarchar(200),
	 @rLanguage nvarchar(200),
	 @rLocation nvarchar(200),
	 @rEdition nvarchar(50),
	 @rPrice decimal=0,
	 @rCurrency nvarchar(100),
	 @rISBNNumber nvarchar(100),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rBookAgeGroupId int,
	 @rResourceTypeId int,
	 @rStatusId smallint,
	 @rCreatedUserId bigint,
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150),
	 @rShowWithPhotoId int=0,
	 @rBookGroup1Id int=0,
	 @rBookGroup2Id int=0,
	 @rAccession nvarchar(50)
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--DECLARE @lpaging
BEGIN 


	  --BEGIN
			--SET @rCode = sCommon.fSearchStringGet(@rCode)
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
			SET @rPublisher = sCommon.fSearchStringGet(@rPublisher)
			SET @rSupplier = sCommon.fSearchStringGet(@rSupplier)
			SET @rAuthor = sCommon.fSearchStringGet(@rAuthor)
			SET @rSubject = sCommon.fSearchStringGet(@rSubject)
			SET @rLanguage = sCommon.fSearchStringGet(@rLanguage)
			SET @rLocation = sCommon.fSearchStringGet(@rLocation)
			SET @rEdition = sCommon.fSearchStringGet(@rEdition)
			SET @rCurrency = sCommon.fSearchStringGet(@rCurrency)
			SET @rISBNNumber = sCommon.fSearchStringGet(@rISBNNumber)
			SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
			SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
			SET @rAccession = sCommon.fSearchStringGet(@rAccession)
		
	  --END
	 declare @quer varchar(max)=''
	declare @lId bigint = 0,@lCode nvarchar(200),@lTitle nvarchar(100),@lOrgId int,
	@lPublisher nvarchar(200),@lSupplier nvarchar(200),@lAuthor nvarchar(200),
	@lSubject nvarchar(200),@lLanguage nvarchar(200),@lLocation nvarchar(200),
	@lEdition nvarchar(50),@lPrice decimal=0,@lCurrency nvarchar(100),
	@lISBNNumber nvarchar(100),@lBookTag nvarchar(200),@lBookCustomTag nvarchar(200),
	@lBookAgeGroupId int,@lResourceTypeId int,@lStatusId smallint,@lCreatedUserId bigint,
	@lLibraryId int,@lBookDepartment nvarchar(150),@lBookGroup1Id int,@lBookGroup2Id int,@lAccession nvarchar(50)
	select @lId = isnull(@rId,0),@lCode = isnull(@rCode,''),@lTitle = isnull(@rTitle,''),
	@lOrgId = isnull(@rOrgId,0),@lPublisher = isnull(@rPublisher,''),@lSupplier = isnull(@rSupplier,''),
	@lAuthor = isnull(@rAuthor,''),@lSubject = isnull(@rSubject,''),
	@lLanguage = isnull(@rLanguage,''),@lLocation = isnull(@rLocation,''),
	@lEdition = isnull(@rEdition,''),@lPrice = isnull(@rPrice,0),@lCurrency = isnull(@rCurrency,''),
	@lISBNNumber = isnull(@rISBNNumber,''),@lBookTag = isnull(@rBookTag,''),
	@lBookCustomTag = isnull(@rBookCustomTag,''),@lBookAgeGroupId = isnull(@rBookAgeGroupId,0),
	@lResourceTypeId = isnull(@rResourceTypeId,0),@lStatusId = isnull(@rStatusId,0),@lCreatedUserId = isnull(@rCreatedUserId,0),
	@lLibraryId = isnull(@rLibraryId,0),@lBookDepartment = isnull(@rBookDepartment,''),
	@lBookGroup1Id = isnull(@rBookGroup1Id,0),@lBookGroup2Id = isnull(@rBookGroup2Id,0),@lAccession = ISNULL(@rAccession,'')

	 
	SELECT @quer='SELECT BM.Code,
	BM.Title,
	ISNULL(BM.Publisher,'''')AS Publisher,
	ISNULL(BM.Supplier,'''')AS Supplier,
	ISNULL(BM.Author,'''')AS Author,
	ISNULL(BM.BookSubject,'''') AS BookSubject,
	ISNULL(BM.BookLanguage,'''') AS BookLanguage,
	ISNULL(BM.Location,'''') AS Location,
	ISNULL(BM.Edition,'''')AS Edition,
	ISNULL(BM.ISBNNumber,'''') AS ISBNNumber,
	ISNULL(BM.Price,0) AS Price,
	ISNULL(BM.Currency,'''') AS Currency,
	ISNULL(BM.BookTag,'''')AS BookTag,
	ISNULL(BM.BookCustomTag,'''') AS BookCustomTag,
	ISNULL(BM.BookDepartment,'''') AS BookDepartment,
	ISNULL(BM.ClassNumber,'''') AS ClassNumber,
	ISNULL(BM.BookVolume,1) AS BookVolume,
	ISNULL(BM.NoOfCopies,1) AS NoOfCopies,
	SM.Title AS StatusName,
	BM.Id,
	ISNULL(AGM.Id,0)AS BookAgeGroupId,
	ISNULL(RTM.Id,0) AS ResourceTypeId,
	BM.CreatedUserId,
	BM.CreatedDateTime,
	ISNULL(BM.UpdatedUserId,0) AS UpdatedUserId,
	ISNULL(BM.UpdatedDateTime,'''') AS UpdatedDateTime,
	BM.LibraryId,
	SM.Id AS StatusId,
	BM.ClassificationNo,
	BM.AccessionNo,
	ISNUll(BM.NoOfPages,0) AS NoOfPages,
	 ISNULL(BM.PurchaseDate,''0001/01/01'') AS PurchaseDate,
    ISNUll(BM.BookRemark,'''') AS BookRemark,
    ISNULL(BM.BillNumber,'''') AS BillNumber,
    BM.YearOfPublication,
    ISNULL(BM.BookEntryDate,''0001/01/01'') AS BookEntryDate,
    CASE WHEN ' + convert(varchar,@rShowWithPhotoId) + '= 1 Then ISNULL(BM.BookImage, CONVERT(VARBINARY(MAX), 0)) ELSE BM.BookImage END AS BookPicture,
    ISNULL(BM.BookGroup1Id,0) AS BookGroup1Id,
    ISNULL(BM.BookGroup2Id,0) AS BookGroup2Id
 
	FROM 
         sLibrary.tBookMaster BM
         LEFT JOIN sLibrary.tBookAgeGroupMaster AGM ON BM.BookAgeGroupId=AGM.Id
         INNER JOIN sLibrary.tResourceTypeMaster RTM ON BM.ResourceTypeId=RTM.Id
         INNER JOIN sLibrary.tBookLog BL ON BL.ResourceSourceId = BM.Id AND IsCurrentStatus=1
         INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId 
         
         WHERE ((BM.Id = ' + convert(varchar,@lId) + ') OR (' + convert(varchar,@lId) + ' = 0))
	AND ((BM.Code = ''' + @lCode + ''') OR (''' + @lCode + ''' = ''''))
	AND ((BM.Title like ''' + @lTitle + ''') OR (''' + @lTitle + ''' = '''')) 
	AND ((BM.AccessionNo like ''' + @lAccession + ''') OR (''' + @lAccession + ''' = '''')) 
	AND ((BM.Publisher like ''' + @lPublisher + ''') OR (''' + @lPublisher + ''' = '''')) 
	AND ((BM.Supplier like ''' + @lSupplier + ''') OR (''' + @lSupplier + ''' = '''')) 
	AND ((BM.Author like ''' + @lAuthor + ''') OR (''' + @lAuthor + ''' = '''')) 
	AND ((BM.BookSubject like ''' + @lSubject + ''') OR (''' + @lSubject + ''' = ''''))  
	AND ((BM.BookLanguage like ''' + @lLanguage + ''') OR (''' + @lLanguage + ''' = ''''))  
	AND ((BM.Location like ''' + @lLocation + ''') OR (''' + @lLocation + ''' = ''''))  
	AND ((BM.Edition like ''' + @lEdition + ''') OR (''' + @lEdition + ''' = ''''))  
	AND ((BM.ISBNNumber like ''' + @lISBNNumber + ''') OR (''' + @lISBNNumber + ''' = ''''))  
	AND ((BM.BookTag like ''' + @lBookTag + ''') OR ( ''' + @lBookTag + ''' = ''''))
	AND ((BM.BookCustomTag like ''' + @lBookCustomTag + ''') OR (''' + @lBookCustomTag + ''' = ''''))
	AND ((BM.BookAgeGroupId = ' + convert(varchar,@lBookAgeGroupId) + ') OR(' + convert(varchar,@lBookAgeGroupId) + ' = 0))
	AND ((BM.ResourceTypeId = ' + convert(varchar,@lResourceTypeId) + ') OR (' + convert(varchar,@lResourceTypeId) + ' = 0))
	AND ((BM.BookGroup1Id = ' + convert(varchar,@lBookGroup1Id) + ') OR (' + convert(varchar,@lBookGroup1Id) + ' = 0))
	AND ((BM.BookGroup2Id = ' + convert(varchar,@lBookGroup2Id) + ') OR (' + convert(varchar,@lBookGroup2Id) + ' = 0))
	AND ((BM.Price = ' + convert(varchar,@lPrice) + ') OR (' + convert(varchar,@lPrice) + ' = 0))
	AND ((BM.Currency like ''' + @lCurrency + ''') OR (''' + @lCurrency  + ''' = ''''))
	AND ((BL.StatusId = ' + convert(varchar,@lStatusId) + ') OR (' + convert(varchar,@lStatusId) + '=0))
	AND ((BM.BookDepartment like ''' + @lBookDepartment + ''') OR (''' + @lBookDepartment + ''' = ''''))
	AND BM.LibraryId = ' + convert(varchar,@lLibraryId)
	print(@quer);
	exec (@quer)
	

  --FROM 
  --      sLibrary.tBookMaster BM
  --       LEFT JOIN sLibrary.tBookAgeGroupMaster AGM
  --       ON BM.BookAgeGroupId=AGM.Id
  --       INNER JOIN sLibrary.tResourceTypeMaster RTM
  --       ON BM.ResourceTypeId=RTM.Id
  --       INNER JOIN sLibrary.tBookLog BL
  --       ON BL.ResourceSourceId=BM.Id AND IsCurrentStatus=1
  --       INNER JOIN sCommon.tStatusMaster SM
  --       ON SM.Id=BL.StatusId 
        -- WHERE 
  
      --((BM.Id = @rId) OR (@rId = 0))
      --ANd ((BM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
      -- AND  ((BM.Title like @rTitle) OR (ISNULL(@rTitle,'') = '')) 
      --  AND  ((BM.Publisher like @rPublisher) OR (ISNULL(@rPublisher,'') = '')) 
      --   AND  ((BM.Supplier like @rSupplier) OR (ISNULL(@rSupplier,'') = '')) 
      --    AND  ((BM.Author like @rAuthor) OR (ISNULL(@rAuthor,'') = '')) 
      --     AND  ((BM.BookSubject like @rSubject) OR (ISNULL(@rSubject,'') = ''))  
      --      AND  ((BM.BookLanguage like @rLanguage) OR (ISNULL(@rLanguage,'') = ''))  
      --       AND  ((BM.Location like @rLocation) OR (ISNULL(@rLocation,'') = ''))  
      --        AND  ((BM.Edition like @rEdition) OR (ISNULL(@rEdition,'') = ''))  
      --         AND  ((BM.ISBNNumber like @rISBNNumber) OR (ISNULL(@rISBNNumber,'') = ''))  
      --          AND  ((BM.BookTag like @rBookTag) OR (ISNULL(@rBookTag,'') = ''))
      --           AND  ((BM.BookCustomTag like @rBookCustomTag) OR (ISNULL(@rBookCustomTag,'') = ''))
      --            AND  ((BM.BookAgeGroupId = @rBookAgeGroupId) OR(@rBookAgeGroupId=0))
      --             AND  ((BM.ResourceTypeId = @rResourceTypeId) OR (@rResourceTypeId=0))
      --              AND  ((BM.Price = @rPrice) OR (@rPrice=0))
      --               AND  ((BM.Currency like @rCurrency) OR (ISNULL(@rCurrency,'') = ''))
      --                AND  ((BL.StatusId = @rStatusId) OR (@rStatusId=0))
      --                ANd ((BM.BookDepartment like @rBookDepartment) OR (ISNULL(@rBookDepartment,'') = ''))
						--AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	  --AND BM.LibraryId = @rLibraryId
END
GO
PRINT N'Altering [sLibrary].[pRptBookListCirculationGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookListCirculationGet]

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

BEGIN 
		SELECT 
				Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount ,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2
	        
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND SA.BatchId = BL.BatchId
	WHERE 
			(BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			
	UNION

	SELECT 
				Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount ,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95

	WHERE 
			(BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			
			
	UNION 

	SELECT 
	Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
	WHERE (BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND (ISNULL(BL.ReaderSourceTypeId,0)=0 AND 0=0)
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			ORDER BY COUNT(BL.Id) desc


		
		--SELECT Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2 FROM sLibrary.tBookLog BL
		--	INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		--	--INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
		--WHERE (BL.LibraryId=@rLibraryId) AND ReaderSourceTypeId = 2003 AND BL.StatusId = 523 AND IsCurrentStatus =0
		--	AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		--	AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		 
		--	GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
		--	ORDER BY COUNT(BL.Id) desc

END
GO
PRINT N'Altering [sLibrary].[pRptBookListCirculationLowFrequencyGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookListCirculationLowFrequencyGet]

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

BEGIN 

	SELECT 
				Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount ,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2
	        
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND SA.BatchId = BL.BatchId
	WHERE 
			(BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			
	UNION

	SELECT 
				Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount ,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95

	WHERE 
			(BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			
			
	UNION 

	SELECT 
	Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,@rBuilder2 AS Builder2 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
	WHERE (BL.LibraryId=@rLibraryId)  AND BL.StatusId = 523 --AND IsCurrentStatus =0
			AND (ISNULL(BL.ReaderSourceTypeId,0)=0 AND 0=0)
			AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			AND (BL.ReaderSourceTypeId != 0)
			GROUP  by BM.Id,BM.Code,BM.Title--,BL.ReaderSourceId
			ORDER BY COUNT(BL.Id) 

		--SELECT Top(@rTopFrequency) BM.Id,BM.Code,BM.Title, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2 FROM sLibrary.tBookLog BL
		--	INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		--	INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
		--WHERE (BL.LibraryId=@rLibraryId) AND ReaderSourceTypeId = 2003 AND BL.StatusId = 523 AND IsCurrentStatus =0
		--	AND ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		--	AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		--	GROUP  by BM.Id,BM.Code,BM.Title
		--	ORDER BY COUNT(BL.Id) 

END
GO
PRINT N'Altering [sLibrary].[pRptBookListGet]...';


GO
 
ALTER PROCEDURE [sLibrary].[pRptBookListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rBookSupplier nvarchar(200),
	 @rBookPublisher nvarchar(200),
	 @rBookSubject nvarchar(200),
	 @rBookLanguage nvarchar(200),
	 @rBookTag nvarchar(200),
	 @rBookCustomTag nvarchar(200),
	 @rLibraryId int,
	 @rBookDepartment nvarchar(150)='',
	 @rIsDetail bit=0,
	 @rFromPurchaseDate date='',
	 @rToPurchaseDate date='',
	 @rBookGroup1Id int,
	 @rBookGroup2Id int,
	 --@rOrgGroupId int,
	 @rFromCode nvarchar(25) ='',
	 @rToCode nvarchar(25) ='',
	 @rSpecificCode nvarchar(max) =''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		
BEGIN 
	--DECLARE @rFromCodeInt INT, @rToCodeInt INT
	--DECLARE @BookConfig NVARCHAR, @rFromCodeString NVARCHAR, @rToCodeString NVARCHAR
	--SELECT @BookConfig = ItemValue From sConfig.tConfigurationSetup	WHERE ConfigurationId = 260 AND SourceId = @rOrgGroupId
	
	--SET @rFromCodeInt = Convert(Int,ISNULL(@rFromCode,0))
	--SET @rToCodeInt = Convert(Int,ISNULL(@rToCode,0))
	--SET @rFromCodeString = Convert(nvarchar,ISNULL(@rFromCode,''))
	--SET @rToCodeString = Convert(nvarchar,ISNULL(@rToCode,''))
	
	DECLARE @ListofBookCodes TABLE(Code nvarchar(25), ID INT IDENTITY(1,1));
		INSERT INTO @ListofBookCodes
	
	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
		

	BEGIN	  
		SET @rBookSupplier = sCommon.fSearchStringGet(@rBookSupplier)
		SET @rBookPublisher = sCommon.fSearchStringGet(@rBookPublisher)
		SET @rBookSubject = sCommon.fSearchStringGet(@rBookSubject)
		SET @rBookLanguage = sCommon.fSearchStringGet(@rBookLanguage)
		SET @rBookTag = sCommon.fSearchStringGet(@rBookTag)
		SET @rBookCustomTag = sCommon.fSearchStringGet(@rBookCustomTag)
		SET @rBookDepartment = sCommon.fSearchStringGet(@rBookDepartment)
    END

	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		BM.Code,
		BM.Title As BookTitle,
		BM.Publisher,BM.Supplier,
		BM.BookSubject,
		BM.Code AS BookCode,
		BM.BookLanguage,
		BM.BookCustomTag,
		BM.BookCustomTag,
		BM.Location,
		BM.ISBNNumber,
		LM.ReportOrgTitle,
        LM.SmallAddress1,
        LM.SmallAddress2,
        CASE WHEN BM.BookDepartment is null THEN 'Blank'
            WHEN BM.BookDepartment='' THEN 'Blank'  ELSE BM.BookDepartment END AS  BookDepartment,
        BM.NoOfCopies,
        @rIsDetail AS IsDetail,
        LM.Code AS LibraryCode,	       
         LM.Title AS LibraryTitle,
        BM.AccessionNo AS AccessionNo
	FROM 
		sLibrary.tBookMaster BM
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BM.LibraryId
	WHERE 
		BM.LibraryId=@rLibraryId
		AND ((BM.Supplier like @rBookSupplier) OR (@rBookSupplier=''))
		AND ((BM.Publisher like @rBookPublisher) OR (@rBookPublisher=''))
		AND ((BM.BookSubject like @rBookSubject) OR (@rBookSubject=''))
		AND ((BM.BookLanguage like @rBookLanguage) OR (@rBookLanguage=''))
		AND ((BM.BookTag like @rBookTag) OR (@rBookTag=''))
		AND ((BM.BookCustomTag like @rBookCustomTag) OR (@rBookCustomTag=''))
		AND ((BM.BookDepartment like @rBookDepartment) OR (@rBookDepartment=''))
		AND ((BM.PurchaseDate >= @rFromPurchaseDate) OR (ISNULL(@rFromPurchaseDate,'') = ''))
		AND ((BM.PurchaseDate <= @rToPurchaseDate) OR (ISNULL(@rToPurchaseDate,'') ='') OR (BM.PurchaseDate is null))
		AND ((BM.BookGroup1Id = @rBookGroup1Id) OR (@rBookGroup1Id=0))
		AND ((BM.BookGroup2Id = @rBookGroup2Id) OR (@rBookGroup2Id=0))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
		AND ((Convert(nvarchar(25),ISNULL(BM.Code,'')) <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
		
		AND ((BM.Code IN(SELECT Code FROM @ListofBookCodes)) OR (ISNULL(@rSpecificCode,'') = ''))
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code >= @rFromCodeString ELSE BM.Code > @rFromCodeInt END AS BM.Code
		--AND CASE WHEN @BookConfig = 'True' THEN BM.Code <= @rToCodeString ELSE BM.Code > @rToCodeInt END AS BM.Code	
	END
GO
PRINT N'Altering [sLibrary].[pRptBookListNotIssueGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookListNotIssueGet]
@rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rReaderSourceTypeId smallint=0,
	 --@rReaderSourceId bigint,
	 --@rOrgId smallint,	
	@rOrgGroupId int =0,
	 @rFromLogDate date='',
	 @rToLogDate date='',
	 @rLibraryId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

		 SELECT  @rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BM.Code AS Code,
			BM.Title AS Title FROM sLibrary.tBookMaster BM
LEFT JOIN
(SELECT DISTINCT ISNULL(BL.ResourceSourceId,0) AS BookId FROM  sLibrary.tBookLog BL 
	INNER JOIN sSetup.tOrganizationMaster OM ON BL.OrgId = OM.Id
	WHERE BL.LibraryId=@rLibraryId 
	--AND ISNULL(BL.ReaderSourceTypeId,0) =0 AND ISNULL(ReaderSourceId,0) = 0
	AND OM.OrgGroupId = @rOrgGroupId AND BL.StatusId = 523 AND ResourceSourceTypeId = 2009 
	--AND ((BL.LogDate>= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
	--		AND((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
			) B ON BM.Id = B.BookId
WHERE BookId IS NULL AND BM.LibraryId=@rLibraryId 


	--SELECT 
	     
	--        @rBuilder1 AS Builder1,
	--		@rBuilder2 AS Builder2,
	--		BM.Code AS Code,
	--		BM.Title AS Title
			
			
	--FROM sLibrary.tBookLog BL
	--	INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
	--		INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId
	----WHERE ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
	----	AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))		
	----	AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	----	AND BL.ReaderSourceTypeId IS NULL AND  BL.ReaderSourceId IS NULL
	----	AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
	----	AND (BL.LibraryId=@rLibraryId)
	--	WHERE BL.ResourceSourceId  IN (
	--		SELECT BM.Id FROM sLibrary.tBookLog  BL
	--		INNER JOIN   sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
	--		WHERE((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
	--		AND((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))	
	--		AND BL.LibraryId=@rLibraryId 
	--		AND BL.ReaderSourceTypeId IS NULL AND  BL.ReaderSourceId IS NULL)
	--		AND BL.ReaderSourceTypeId IS NULL AND  BL.ReaderSourceId IS NULL
END
GO
PRINT N'Altering [sLibrary].[pRptBookListNotReturnGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptBookListNotReturnGet]
	 
	       @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
           @rLibraryId int=0,
           @rSourceTypeId int=0,
           @rFromLogDate date='',
           @rToLogDate date='',
           @rOrgId smallint=0,
           @rBatchId int=0,
            @rFromDueDate date='',
	 @rToDueDate date=''
           
AS
SET NOCOUNT ON
BEGIN
SELECT   
	   @rBuilder1 AS Builder1,
	   @rBuilder2 AS Builder2,
	   BL.Id AS BookLogId,
	   BL.LibraryId,
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	'Employee'
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	'Student'
			 ELSE 'Other' END) AS TypeName,

		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.EmployeeName
			WHEN BL.ReaderSourceTypeId = 2003 THEN vSF.Name
			ELSE
			''
			END) AS Name,
			
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN Emp.DepartmentName
			WHEN BL.ReaderSourceTypeId = 2003 THEN (vSF.ClassName + ' - '+ vSF.DivisionName)
			ELSE '' END) AS ClassDepartmentName,	
		 
		(CASE WHEN BL.ReaderSourceTypeId = 95 THEN	Emp.Code
			 WHEN BL.ReaderSourceTypeId = 2003 THEN	vSF.Code
			 ELSE '' END) AS Code, 	
	   BL.ReaderSourceTypeId,
	   BL.ReaderSourceId,
	   BL.LogDate,
	   BL.DueDate,
	   BL.ReturnDate,
	   BM.Code AS BookCode,
	   BM.Title AS BookName,
	   OM.DisplayTitle AS OrganizationName,
	    LM.ReportOrgTitle,
	    LM.SmallAddress1,
	    LM.SmallAddress2
	   
  FROM  
		sLibrary.tBookLog BL
		INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 95 
		LEFT JOIN sStudent.vStudentLastAcademic vSF
			ON vSF.StudentId = BL.ReaderSourceId AND BL.ReaderSourceTypeId = 2003 
			AND (SELECT IsActive FROM sSetup.tBatchMaster WHERE Id=vSF.BatchId AND IsActive = 1) = 1	
		LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId			
 
  WHERE 
    BL.StatusId = 523 
	AND BL.LibraryId=@rLibraryId
	--AND (BL.LogDate>=@rFromLogDate OR ISNULL(@rFromLogDate,'')='')
	--AND (BL.LogDate<=@rToLogDate OR ISNULL(@rToLogDate,'')='')
	AND ((BL.DueDate >= @rFromDueDate) OR (ISNULL(@rFromDueDate,'') = ''))
	AND ((BL.DueDate <= @rToDueDate) OR (ISNULL(@rToDueDate,'') = ''))
	AND ((BL.ReaderSourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
	AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
	AND (ISNULL(BL.ReturnDate,'')='')
	
END
GO
PRINT N'Altering [sLibrary].[pRptLibraryRegularUserGet]...';


GO
ALTER PROCEDURE [sLibrary].[pRptLibraryRegularUserGet]

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

BEGIN 

	SELECT 
	    Top(@rTopFrequency) SA.StudentId,SA.Name,
		SA.RollNo,
		SA.Code,
		SA.ClassName,
		SA.DivisionName, COUNT(BL.Id)AS IssueCount,@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2 
			FROM sStudent.vStudentLastAcademic SA 
INNER JOIN sLibrary.tBookLog BL ON SA.StudentId=BL.ReaderSourceId
	WHERE ((BL.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
		AND ((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
		AND (BL.LibraryId=@rLibraryId) AND ReaderSourceTypeId = 2003  
		AND BL.StatusId = 523
		GROUP  by SA.StudentId,SA.Name,SA.RollNo,SA.Code,SA.ClassName,SA.DivisionName
ORDER BY COUNT(BL.Id) desc
		

END
GO
PRINT N'Altering [sLibrary].[pRptMonthlyNotIssuingBookStudentListGet]...';


GO

ALTER PROCEDURE [sLibrary].[pRptMonthlyNotIssuingBookStudentListGet]

	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rReaderSourceId bigint,
	 @rOrgGroupId int=0,
	 @rBatchId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromLogDate date='',
	 @rToLogDate date='',
	 @rLibraryId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT    
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		SA.Name,
		SA.RollNo,
		SA.Code,
		SA.ClassName,
		SA.DivisionName

	FROM sStudent.vStudentLastAcademic SA
INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId = OM.Id
 LEFT JOIN
(SELECT DISTINCT ISNULL(BL.ReaderSourceId,0) AS StudentId FROM  sLibrary.tBookLog BL 
	INNER JOIN sSetup.tOrganizationMaster OM ON BL.OrgId = OM.Id
	WHERE BL.LibraryId=@rLibraryId 
	AND OM.OrgGroupId = @rOrgGroupId AND BL.StatusId = 523 AND ReaderSourceTypeId = 2003 
	AND ((BL.LogDate>= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
			AND((BL.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))) B ON SA.StudentId= B.StudentId
WHERE B.StudentId IS NULL AND OM.OrgGroupId = @rOrgGroupId
	

END
GO
PRINT N'Altering [sSetup].[pDivisionInchargeAdd]...';


GO
 
ALTER  PROCEDURE [sSetup].[pDivisionInchargeAdd]
	 
 
	 @rDivisionId int,
	 @rEmployeeId bigint,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	if exists(select 1 from sSetup.tDivisionInchargeEmployee where divisionid=@rdivisionid   and batchid=@rBatchId)
	begin
		Update sSetup.tDivisionInchargeEmployee Set
			divisionid=@rdivisionid,
			employeeid= @remployeeid
		Where divisionid=@rdivisionid   and batchid=@rbatchid
		select 11 as result	
	end
	Else
	begin
	
	 INSERT Into sSetup.tDivisionInchargeEmployee
	 (
		DivisionId,
		EmployeeId,
		BatchId
	 )
	 values
	 (
		@rDivisionId,
		@rEmployeeId,
		@rBatchId
	 )
	 Select 1 as result
	 end
END
GO
PRINT N'Altering [sSetup].[pMastedDataModify]...';


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

EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF(@rSubCategoryField = 'InchargeEmployee') 	
		SET @rSubCategoryField = @rSubCategoryField + 'Id'	
	
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id int,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
	
	IF(@rCategoryId= 1)  
		BEGIN
		
		insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
						
		select *from ListofData				
		UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tOrganizationMaster ) 
		
		set @sql='INSERT INTO sSetup.tOrganizationMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tOrganizationMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tOrganizationMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    END
	    
	else IF(@rCategoryId= 2)     
	 
	 BEGIN
	 
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tClassMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tClassMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tClassMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tClassMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  END
	  
	  
	  else IF(@rCategoryId= 3)
	  BEGIN
	     
	     insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tDivisionMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tDivisionMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tDivisionMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tDivisionMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		--print @sql
		--return
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	    
	  
	  END    
	  
	  else IF(@rCategoryId= 4)
	  BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tSubjectMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tSubjectMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tSubjectMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tSubjectMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  
	  END 
	    
	 else IF(@rCategoryId= 5)
	 
	 BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tOrgGroupBatchMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tOrgGroupBatchMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tOrgGroupBatchMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tOrgGroupBatchMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	  
	  END 
	  
   else IF(@rCategoryId= 6)
	 BEGIN
	  
	   insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tBatchMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tBatchMaster 
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tBatchMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tBatchMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	  
	else IF(@rCategoryId= 7)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sSetup.tDepartmentMaster ) 
	    
	    set @sql='INSERT INTO sSetup.tDepartmentMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sSetup.tDepartmentMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sSetup.tDepartmentMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	  
	  
 else IF(@rCategoryId= 8)
	 BEGIN
	  insert into ListofData
		select E.Id,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),E.UpdatedUserId,0
		from
		(
				SELECT Id,SubCategory,UpdatedUserId FROM
				OPENXML (@loDoc, '/Masters/Masters', 2)
				WITH (
						Id BIGINT, 
						SubCategory nvarchar(150),
						UpdatedUserId bigint)	
						)E 	
	    UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT Id FROM sCommon.tOrgGroupDepartmentMaster ) 
	    
	    set @sql='INSERT INTO sCommon.tOrgGroupDepartmentMaster
					(Id,'+@rSubCategoryField+',CreatedUserId,CreatedDateTime)
					SELECT
						LD.Id,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=1'
					
		print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sCommon.tOrgGroupDepartmentMaster  set '+@rSubCategoryField+' = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sCommon.tOrgGroupDepartmentMaster SC 
					INNER JOIN ListofData LD ON SC.Id=LD.Id AND IsExist=0'
		
		Exec sp_executesql @sql
	
		
		Drop Table ListofData
			 SELECT 1 AS StatusCode
			
	  END 
	    
	 	
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering [sStudent].[pAddSiblingLink]...';


GO
 

ALTER PROCEDURE [sStudent].[pAddSiblingLink]	 
	    @rStudentId bigint,
	    @rLinkedStudentId bigint
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	 BEGIN TRANSACTION	

 BEGIN 
	IF EXISTS(SELECT LinkedStudentId FROM sStudent.tLinkSibling WHERE ((StudentId=@rStudentId) AND (LinkedStudentId = @rLinkedStudentId)))
	BEGIN
select -102 as Result
	END
	
Else
	BEGIN
	
 	INSERT INTO sStudent.tLinkSibling
    (
	   StudentId,
	   LinkedStudentId
	)
	VALUES
	(
        @rStudentId,  
		@rLinkedStudentId		 
	)
	INSERT INTO sStudent.tLinkSibling
	(
	    StudentId,
		LinkedStudentId
		
	)
	VALUES
	(
		 @rLinkedStudentId,		 
		 @rStudentId
	)
	SELECT 1 AS Result

	END
	    
	 END  	

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


GO

ALTER PROCEDURE [sStudent].[pImportStudent]
    
    @rOrgGroupId smallint,
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rOperation int = 1
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lCode nvarchar(20),
		@lNumber bigint,
		@lRegistrationNumber nvarchar(20),
		@lFirstName nvarchar(100),
		@lMiddleName nvarchar(100),
		@lLastName nvarchar(100),
		@lClassId int,
		@lClass nvarchar(100),
		@lDivisionId int,
		@lDivision nvarchar(100),
		@lRollNo int,
		@lAdmissionStandardId int,
		@lAdmissionStandard nvarchar(100),
		@lAdmissionDate date,
		@lPreviousSchool nvarchar(200),
		@lDOB date,
		@lGenderId int = 0,
		@lGender nvarchar(10),
		@lBloodGroupId int = 0,
		@lBloodGroup nvarchar(10),
		@lAdmissionCategoryId int,
		--@lAdmissionCategory nvarchar(100),
		@lReligionId int,
		@lReligion nvarchar(100),
		@lFamilyCast nvarchar(100),
		@lFamilySubCast nvarchar(100),
		@lCastCategoryId int = 0,
		@lCastCategory nvarchar(100),
		@lParentContactNo nvarchar(20),
		@lParentEmail nvarchar(50),
		@lStudentContactNo nvarchar(20),
		@lStudentEmail nvarchar(50),
		@lPresentStreetOne nvarchar(150),
		@lPresentStreetTwo nvarchar(150),
		@lPresentStreetThree nvarchar(150),
		@lPresentCity nvarchar(50),
		@lPresentZipCode nvarchar(20),
		@lPresentState nvarchar(50),
		@lPresentCountry nvarchar(50),
		@lPresentContactNo nvarchar(20),
		--@lEmergencyStreetOne nvarchar(50),
		--@lEmergencyStreetTwo nvarchar(50),
		--@lEmergencyStreetThree nvarchar(50),
		--@lEmergencyCountry nvarchar(50),
		--@lEmergencyState nvarchar(50),
		--@lEmergencyCity nvarchar(50),
		--@lEmergencyZipCode nvarchar(20),
		@lEmergencyContactNo nvarchar(20),
		@lBirthPlace nvarchar(150),
		@lBirthTaluka nvarchar(150),
		@lBirthDistrict nvarchar(150),
		@lBirthDateInWord nvarchar(150),
		@lHouseId int,
		@lHouse nvarchar(100),
		--@lMotherTongueId int,
		@lMotherTongue nvarchar(100),
		@lAdhaarNumber nvarchar(20),
		@lUIDNumber nvarchar(50),
		@lQuotaId int,
		@lQuota nvarchar(100),
		-- New Add
		@lSUId nvarchar(20),
		@lLeftStandardId int,
		@lLeftStandard nvarchar(100),
		@lLeftDate date,
		@lLCNumber nvarchar(20),
		@lLCDate date,
		@lLCReason nvarchar(200) ,
		@lLCProgress nvarchar(200) ,
        @lLCConduct nvarchar(200) ,
        @lLCRemark nvarchar(200),
        @lStatusId smallint,
        @lBirthState nvarchar(100),
        @lBirthCountry nvarchar(100)
		
			
DECLARE @EmployeeId bigint			
--DECLARE @OutClassId int
--DECLARE @OutDivisionId int
DECLARE @OutStudentId bigint 
--DECLARE @OutAdmissionStandardId int
--DECLARE @OutReligionId int
--DECLARE @OutAdmissionCategoryId int		
SET @lAdmissionCategoryId=sCommon.fGetIntIdForOrg(1,@rOrgGroupId)	

						
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		Code nvarchar(20),
		Number bigint,
		RegistrationNumber nvarchar(20),
		FirstName nvarchar(100),
		MiddleName nvarchar(100),
		LastName nvarchar(100),
		ClassId int null,
		Class nvarchar(100),
		DivisionId int null,
		Division nvarchar(100),
		RollNo int,
		AdmissionStandardId int,
		AdmissionStandard nvarchar(100),
		AdmissionDate date,
		PreviousSchool nvarchar(200),
		DOB date,
		GenderId int null,
		Gender nvarchar(10),
		BloodGroupId int null,
		BloodGroup nvarchar(10),
		ReligionId int,
		Religion nvarchar(100),
		--AdmissionCategoryId int,
		--AdmissionCategory nvarchar(100),
		FamilyCast nvarchar(100),
		FamilySubCast nvarchar(100),
		CastCategoryId int,
		CastCategory nvarchar(100),
		ParentContactNo nvarchar(20),
		ParentEmail nvarchar(50),
		StudentContactNo nvarchar(20),
		StudentEmail nvarchar(50),
		PresentStreetOne nvarchar(150),
		PresentStreetTwo nvarchar(150),
		PresentStreetThree nvarchar(150),
		PresentCity nvarchar(50),
		PresentZipCode nvarchar(20),
		PresentState nvarchar(50),
		PresentCountry nvarchar(50),
		PresentContactNo nvarchar(20),
		--EmergencyStreetOne nvarchar(50),
		--EmergencyStreetTwo nvarchar(50),
		--EmergencyStreetThree nvarchar(50),
		--EmergencyCountry nvarchar(50),
		--EmergencyState nvarchar(50),
		--EmergencyCity nvarchar(50),
		--EmergencyZipCode nvarchar(20),
		EmergencyContactNo nvarchar(20),
		BirthPlace nvarchar(150),
		BirthTaluka nvarchar(150),
		BirthDistrict nvarchar(150),
		BirthDateInWord nvarchar(150),
		CreatedUserId bigint,
		HouseId int,
		House nvarchar(100),
		MotherTongueId int,
		MotherTongue nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIDNumber nvarchar(50),
		QuotaId int,
		Quota nvarchar(100),
		SUId nvarchar(20),
		LeftStandardId int,
		LeftStandard nvarchar(100),
		LeftDate date,
		LCNumber nvarchar(20),
		LCDate date,
		LCReason nvarchar(200) ,
		LCProgress nvarchar(200) ,
        LCConduct nvarchar(200) ,
        LCRemark nvarchar(200),
        StatusId smallint,
        BirthState nvarchar(100),
        BirthCountry Nvarchar(100)
	)
		
	INSERT INTO #tTable
	(
		Code,
		Number,
		RegistrationNumber,
		FirstName,
		MiddleName,
		LastName,
		ClassId,
		Class,
		DivisionId,
		Division,
		RollNo,
		AdmissionStandardId,
		AdmissionStandard,
		AdmissionDate,
		PreviousSchool,
		DOB,
		GenderId,
		Gender,
		BloodGroupId,
		BloodGroup,
		ReligionId,
		Religion,
		--AdmissionCategoryId,
		--AdmissionCategory,
		FamilyCast,
		FamilySubCast,
		CastCategoryId,
		CastCategory,
		ParentContactNo,
		ParentEmail,
		StudentContactNo,
		StudentEmail,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		--EmergencyStreetOne,
		--EmergencyStreetTwo,
		--EmergencyStreetThree,
		--EmergencyCountry,
		--EmergencyState,
		--EmergencyCity,
		--EmergencyZipCode,
		EmergencyContactNo,
		BirthPlace,
		BirthTaluka,
		BirthDistrict,
		BirthDateInWord,
		CreatedUserId,
		HouseId,
		House,
		MotherTongueId,
		MotherTongue,
		AdhaarNumber,
		UIDNumber,
		QuotaId,
		Quota,
		SUId,
		LeftStandardId,
		LeftStandard,
		LeftDate,
		LCNumber,
		LCDate,
		LCReason,
		LCProgress,
        LCConduct,
        LCRemark,
        StatusId,
        BirthState,
        BirthCountry
	)
	SELECT
		Code,
		Number,
		RegistrationNumber,
		sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName,
		sSetup.fPortalXMLTagsReplaceReverse(MiddleName) AS MiddleName,
		sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(Class) AS Class,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(Division) AS Division,
		RollNo,
		0,
		AdmissionStandard,
		AdmissionDate,
		sSetup.fPortalXMLTagsReplaceReverse(PreviousSchool) AS PreviousSchool,
		DOB,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(Gender) AS Gender,
		0,
		BloodGroup,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion,
		--0,
		--AdmissionCategory,
		sSetup.fPortalXMLTagsReplaceReverse(FamilyCast) AS FamilyCast,
		sSetup.fPortalXMLTagsReplaceReverse(FamilySubCast) AS FamilySubCast,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory,
		ParentContactNo,
		ParentEmail,
		StudentContactNo,
		StudentEmail,
		sSetup.fPortalXMLTagsReplaceReverse(PresentStreetOne) AS PresentStreetOne,
		sSetup.fPortalXMLTagsReplaceReverse(PresentStreetTwo) AS PresentStreetTwo,
		sSetup.fPortalXMLTagsReplaceReverse(PresentStreetThree) AS PresentStreetThree,
		sSetup.fPortalXMLTagsReplaceReverse(PresentCity) AS PresentCity,
		PresentZipCode,
		sSetup.fPortalXMLTagsReplaceReverse(PresentState) AS PresentState,
		sSetup.fPortalXMLTagsReplaceReverse(PresentCountry) AS PresentCountry,
		PresentContactNo,
		--EmergencyStreetOne,
		--EmergencyStreetTwo,
		--EmergencyStreetThree,
		--EmergencyCountry,
		--EmergencyState,
		--EmergencyCity,
		--EmergencyZipCode,
		EmergencyContactNo,
		sSetup.fPortalXMLTagsReplaceReverse(BirthPlace) AS BirthPlace,
		sSetup.fPortalXMLTagsReplaceReverse(BirthTaluka) AS BirthTaluka,
		sSetup.fPortalXMLTagsReplaceReverse(BirthDistrict) AS BirthDistrict,
		sSetup.fPortalXMLTagsReplaceReverse(BirthDateInWord) AS BirthDateInWord,
		CreatedUserId,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(House) AS House,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(MotherTongue) AS MotherTongue,
		sSetup.fPortalXMLTagsReplaceReverse(AdhaarNumber) AS AdhaarNumber,
		UIDNumber,
		0,
		Quota,
		SUId,
		0,
		LeftStandard,
		LeftDate,
		LCNumber,
		LCDate,
		sSetup.fPortalXMLTagsReplaceReverse(LCReason) AS LCReason,
		LCProgress,
        LCConduct,
        sSetup.fPortalXMLTagsReplaceReverse(LCRemark) AS LCRemark,
        StatusId,
        sSetup.fPortalXMLTagsReplaceReverse(BirthState) AS BirthState,
        sSetup.fPortalXMLTagsReplaceReverse(BIrthCountry) AS BIrthCountry 
			
	FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
	WITH
	( 
		Code nvarchar(20) '@Code',
		Number bigint '@Number',
		RegistrationNumber nvarchar(20) '@RegistrationNumber',
		FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
		LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		RollNo int '@RollNo',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate date '@AdmissionDate',
		PreviousSchool nvarchar(200) '@PreviousSchool',
		DOB date '@DOB',
		Gender nvarchar(10) '@Gender',
		BloodGroup nvarchar(10) '@BloodGroup', 			
		Religion nvarchar(100) '@Religion',
		--AdmissionCategory nvarchar(100) '@AdmissionCategory',
		FamilyCast nvarchar(100) '@FamilyCast',
		FamilySubCast nvarchar(100) '@FamilySubCast',
		CastCategory nvarchar(100) '@CastCategory',
		ParentContactNo nvarchar(20) '@ParentContactNo',
		ParentEmail nvarchar(50) '@ParentEmail',
		StudentContactNo nvarchar(20) '@StudentContactNo',
		StudentEmail nvarchar(50) '@StudentEmail',
		PresentStreetOne nvarchar(150) '@PresentStreetOne',
		PresentStreetTwo nvarchar(150) '@PresentStreetTwo',
		PresentStreetThree nvarchar(150) '@PresentStreetThree',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		PresentState nvarchar(50) '@PresentState',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentContactNo nvarchar(20) '@PresentContactNo',
		--EmergencyStreetOne nvarchar(50) '@EmergencyStreetOne',
		--EmergencyStreetTwo nvarchar(50) '@EmergencyStreetTwo',
		--EmergencyStreetThree nvarchar(50) '@EmergencyStreetThree',
		--EmergencyCountry nvarchar(50) '@EmergencyCountry',
		--EmergencyState nvarchar(50) '@EmergencyState',
		--EmergencyCity nvarchar(50) '@EmergencyCity',
		--EmergencyZipCode nvarchar(20) '@EmergencyZipCode',
		EmergencyContactNo nvarchar(20) '@EmergencyContactNo',
		 
		BirthPlace nvarchar(150) '@BirthPlace',
		BirthTaluka nvarchar(150) '@BirthTaluka',
		BirthDistrict nvarchar(150) '@BirthDistrict',		
		BirthDateInWord nvarchar(150) '@BirthDateInWord',
		CreatedUserId bigint '@CreatedUserId',
		House nvarchar(100) '@House',
		MotherTongue nvarchar(100) '@MotherTongue',
		AdhaarNumber nvarchar(20) '@AdhaarNumber',
		UIDNumber nvarchar(50) '@UIDNumber',
		Quota nvarchar(20) '@Quota',
		SUId nvarchar(20) '@SUId',
		LeftStandard nvarchar(100) '@LeftStandard',
		LeftDate date '@LeftDate',
		LCNumber nvarchar(20) '@LCNumber',
		LCDate date '@LCDate',
		LCReason nvarchar(200) '@LCReason',
		LCProgress nvarchar(200) '@LCProgress',
        LCConduct nvarchar(200) '@LCConduct',
        LCRemark nvarchar(200) '@LCRemark',
        StatusId smallint '@StatusId',
        BirthState nvarchar(100) '@BirthState',
        BirthCountry nvarchar(100) '@BirthCountry'
	)
	
	--print 'check'
 
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 

BEGIN
		SET @lCode = ''
		SET @lNumber = null
		SET @lRegistrationNumber = null
		SET @lFirstName = ''
		SET @lMiddleName = ''
		SET @lLastName = ''
		SET @lClassId = null
		SET @lClass = ''
		SET @lDivisionId = null
		SET @lDivision = ''
		SET @lRollNo = null
		SET @lAdmissionStandardId = null
		SET @lAdmissionStandard = ''
		SET @lAdmissionDate  = ''
		SET @lPreviousSchool = ''
		SET @lDOB = ''
		SET @lGenderId = null
		SET @lGender = ''
		SET @lBloodGroupId = null
		SET @lBloodGroup = ''
		SET @lReligionId  = null
		SET @lReligion = ''
		--SET @lAdmissionCategoryId  = null
		--SET @lAdmissionCategory = ''
		SET @lFamilyCast = ''
		SET @lFamilySubCast = ''
		SET @lCastCategoryId  = null
		SET @lCastCategory = ''
		SET @lParentContactNo = ''
		SET @lParentEmail = ''
		SET @lStudentContactNo = ''
		SET @lStudentEmail = ''
		SET @lPresentStreetOne = ''
		SET @lPresentStreetTwo = ''
		SET @lPresentStreetThree = ''
		SET @lPresentCity = ''
		SET @lPresentZipCode = ''
		SET @lPresentState = ''
		SET @lPresentCountry = ''
		SET @lPresentContactNo = ''
		--SET @lEmergencyStreetOne = ''
		--SET @lEmergencyStreetTwo = ''
		--SET @lEmergencyStreetThree = ''
		--SET @lEmergencyCountry = ''
		--SET @lEmergencyState = ''
		--SET @lEmergencyCity = ''
		--SET @lEmergencyZipCode = ''
		SET @lEmergencyContactNo = ''
		SET @lBirthPlace = ''
		SET @lBirthTaluka = ''
		SET @lBirthDistrict = ''
		SET @lBirthDateInWord = ''
		--SET @OutClassId = null
		--SET @OutDivisionId = null
		SET @OutStudentId = null
		--SET @OutAdmissionStandardId = null
		--SET @OutReligionId = null,
		SET @lHouseId=NULL
		SET	@lHouse=''
		--SET @lMotherTongueId=NULL
		SET	@lMotherTongue=''
		SET	@lAdhaarNumber=''
		SET @lUIDNumber=''
		SET @lQuotaId = NULL
		SET	@lQuota =''
		SET	@lSUId =''
		SET	@lLeftStandardId=NULL
		SET	@lLeftStandard = ''
		SET	@lLeftDate = ''
		SET	@lLCNumber = ''
		SET	@lLCDate = ''
		SET	@lLCReason = ''
		SET	@lLCProgress = ''
        SET	@lLCConduct = ''
        SET	@lLCRemark = ''
        SET @lStatusId = NULL 
        Set @lBirthState ='' 
        Set @lBirthCountry =''
		
SELECT		
		@lCode = Code,
		@lNumber=Number,
		@lRegistrationNumber = RegistrationNumber,
		@lFirstName = FirstName,
		@lMiddleName = MiddleName,
		@lLastName = LastName,
		@lClass = Class,
		@lDivision = Division,
		@lRollNo = RollNo,
		@lAdmissionStandard = AdmissionStandard,
		@lAdmissionDate  = CASE WHEN AdmissionDate = '' THEN  NULL ELSE AdmissionDate END,
		@lPreviousSchool = PreviousSchool,
		@lReligion = Religion,
		--@lAdmissionCategory = AdmissionCategory,
		@lFamilyCast = FamilyCast,
		@lFamilySubCast = FamilySubCast,
		@lCastCategory = CastCategory,
		@lDOB = CASE WHEN DOB = '' THEN  NULL ELSE DOB END,
		@lGender = Gender,
		@lBloodGroup = BloodGroup,
		@lParentContactNo = ParentContactNo,
		@lParentEmail = ParentEmail,
		@lStudentContactNo = StudentContactNo,
		@lStudentEmail = StudentEmail,
		@lPresentStreetOne = PresentStreetOne,
		@lPresentStreetTwo = PresentStreetTwo,
		@lPresentStreetThree = PresentStreetThree,
		@lPresentCountry = PresentCountry,
		@lPresentState = PresentState,
		@lPresentCity = PresentCity,
		@lPresentZipCode = PresentZipCode,
		@lPresentContactNo = PresentContactNo,
		--@lEmergencyStreetOne = EmergencyStreetOne,
		--@lEmergencyStreetTwo = EmergencyStreetTwo,
		--@lEmergencyStreetThree = EmergencyStreetThree,
		--@lEmergencyCountry = EmergencyCountry,
		--@lEmergencyState = EmergencyState,
		--@lEmergencyCity = EmergencyCity,
		--@lEmergencyZipCode = EmergencyZipCode,
		@lEmergencyContactNo = EmergencyContactNo,		 
		@lBirthPlace = BirthPlace,
		@lBirthTaluka = BirthTaluka,
		@lBirthDistrict = BirthDistrict,
		@lBirthDateInWord = BirthDateInWord,
		@lHouse = House,
		@lMotherTongue = MotherTongue,
		@lAdhaarNumber = AdhaarNumber,
		@lUIDNumber = UIDNumber,
		@lSUId = SUId,
		@lLeftStandard = LeftStandard,
		@lLeftDate = CASE WHEN LeftDate = '' THEN  NULL ELSE LeftDate END,
		@lLCNumber = LCNumber,
		@lLCDate = CASE WHEN LCDate = '' THEN  NULL ELSE LCDate END,
		@lLCReason = LCReason,
		@lLCProgress = LCProgress,
        @lLCConduct = LCConduct,
        @lLCRemark = LCRemark,
        @lStatusId = StatusId,
        @lBirthState = BirthState,
        @lBirthCountry = BirthCountry
											 	 
FROM #tTable WHERE Id = @lCount  

	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lLeftStandardId  = ID FROM sSetup.tClassMaster WHERE Title = @lLeftStandard AND OrgId = @rOrgId
	SELECT	@lClassId  = ID FROM sSetup.tClassMaster WHERE Title = @lClass AND OrgId = @rOrgId
	SELECT	@lDivisionId  = ID FROM sSetup.tDivisionMaster WHERE Title = @lDivision AND ClassId=@lClassId AND OrgId = @rOrgId
	SELECT	@lBloodGroupId  = ID FROM sCommon.tBloodGroupMaster WHERE Title = @lBloodGroup
	SELECT	@lAdmissionStandardId  = ID FROM sSetup.tClassMaster WHERE Title = @lAdmissionStandard AND OrgId = @rOrgId
	SELECT	@lReligionId  = ID FROM sCommon.tReligionMaster WHERE Title = @lReligion AND OrgGroupId = @rOrgGroupId
	--SELECT	@lAdmissionCategoryId  = ID FROM tAdmissionCategoryMaster WHERE Title = @lAdmissionCategory AND OrgGroupId = @rOrgGroupId
	SELECT	@lCastCategoryId  = ID FROM sCommon.tCastCategoryMaster WHERE Title = @lCastCategory AND OrgGroupId = @rOrgGroupId	
	SELECT	@lHouseId  = ID FROM sActivity.tHouseMaster WHERE Title = @lHouse AND OrgId = @rOrgId
	SELECT	@lQuotaId  = ID FROM sCommon.tQuotaMaster WHERE Title = @lQuota AND OrgGroupId = @rOrgGroupId	
	--SELECT	@lMotherTongueId  = ID FROM sCommon.tMotherTongueMaster WHERE Title = @lMotherTongue
	
	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
	IF(@lBloodGroupId IS NULL)
		SET	@lBloodGroupId = 0
	IF(@lCastCategoryId IS NULL)
		SET	@lCastCategoryId = 0
	IF(@lHouseId IS NULL)
		SET	@lHouseId = 0
	IF(@lQuotaId IS NULL)
		SET	@lQuotaId = 0	
	--IF(@lMotherTongueId IS NULL)
	--	SET	@lMotherTongueId = 0		
		
--IF 	@lClassId IS NULL  AND @lClass != ''
--BEGIN
--	EXEC [sSetup].[pClassMasterAdd] 0,@lClass,@lClass,@lClass,@lClass,1,0,0,0,@rUserId,@rUserId,@rOrgId,@OutClassId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutClassId = @lClassId
--END

--IF 	@lAdmissionStandardId IS NULL  AND @lAdmissionStandard != ''
--BEGIN
--	EXEC [sSetup].[pClassMasterAdd] 0,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,1,0,0,0,@rUserId,@rUserId,@rOrgId,0,@OutAdmissionStandardId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutAdmissionStandardId = @lAdmissionStandardId
--END

--IF 	@lDivisionId IS NULL  AND @lDivision != ''
--BEGIN
--	SET @EmployeeId = sCommon.fGetBigIntIdForOrg(1,@rOrgId)
--	EXEC [sSetup].[pDivisionMasterAdd] 0,@lDivision,@lDivision,@lDivision,@lClassId,@EmployeeId,NULL,0,@rUserId,@rUserId,0,@rOrgId,@OutDivisionId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutDivisionId = @lDivisionId
--END

--IF 	@lReligionId IS NULL  AND @lReligion != ''
--BEGIN
--	EXEC [sCommon].[pReligionMasterAdd] 0,@lReligion,@lReligion,0,@rUserId,@rOrgId,@OutReligionId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutReligionId = @lReligionId
--END

--IF 	@lAdmissionCategoryId IS NULL  AND @lAdmissionCategory != ''
--BEGIN
--	EXEC [sStudent].[pAdmissionCategoryMasterAdd] 0,@lAdmissionCategory,@lAdmissionCategory,0,@rUserId,@rOrgId,@OutAdmissionCategoryId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutAdmissionCategoryId = @lAdmissionCategoryId
--END
 
BEGIN TRANSACTION

Declare @lStudCap int,@lOrgStudentCap int
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 
	COMMIT TRANSACTION			
	Return
END
print @lStatusId

IF(@lStatusId=1)
	EXEC sStudent.pStudentMasterAdd 0,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,1,502,@rUserId,@rUserId,@rOrgGroupBatchId,@OutStudentId OUTPUT ,@lSUId
ELSE
	EXEC sStudent.pStudentMasterAdd 0,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,3,502,@rUserId,@rUserId,@rOrgGroupBatchId,@OutStudentId OUTPUT,@lSUId

EXEC sStudent.pAcademicAdd 0,@OutStudentId,@lClassId,@lDivisionId,@lRollNo,@rOrgId,@rBatchId,@rUserId,@rUserId,@lAdmissionCategoryId

EXEC sStudent.pStudentCommunicationAdd @OutStudentId,@lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetThree,
			@lPresentCountry,@lPresentState,@lPresentCity,@lPresentZipCode,@lPresentContactNo,NULL,NULL,NULL,NULL,NULL,
			NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,@lEmergencyContactNo,@lParentContactNo,@lParentEmail,
			@lStudentContactNo,@lStudentEmail,@rUserId,@rUserId

EXEC sStudent.pStudentOtherAdd @OutStudentId,@lUIDNumber,@lDOB,@lGenderId,@lReligionId,@lBloodGroupId,@lBirthPlace,@lBirthTaluka,@lBirthDistrict,@lBirthDateInWord,
			@lFamilyCast,@lFamilySubCast,@lCastCategoryId,NULL,@lHouseId,NULL,NULL,'',@rUserId,@rUserId,'',@lAdhaarNumber,@lMotherTongue,@lQuotaId,@lBirthState,@lBirthCountry

IF(@lStatusId=1)		
	EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
			@lAdmissionStandardId,@lAdmissionDate,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
			NULL,NULL,NULL,NULL,NULL,@rBatchId,@rUserId,@rUserId,1
ELSE
	EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
			@lAdmissionStandardId,@lAdmissionDate,NULL,@lLeftStandardId,@lLeftDate,NULL,NULL,NULL,@lLCReason,@lLCProgress,@lLCConduct,NULL,
			@lLCNumber,@lLCDate,@lLCRemark,NULL,NULL,@rBatchId,@rUserId,@rUserId,0
			

		SET @lCount = @lCount - 1	
		COMMIT TRANSACTION			
END


	 SELECT 1
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Altering [sStudent].[pStudentCustomFieldDataModify]...';


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


EXEC sp_xml_preparedocument @loDoc OUTPUT,@rXML
BEGIN
	
	IF OBJECT_ID('ListofData') IS NOT NULL	
	BEGIN 
		DROP TABLE ListofData
	END	
	
	CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),CustomFieldId int,UpdatedUserId bigint,IsExist bit);
	
	insert into ListofData(Id,StudentId,SubCategory,CustomFieldId,UpdatedUserId,IsExist)
		select 0,E.StudentId,sSetup.fPortalXMLTagsReplaceReverse(E.SubCategory),@rCustomFieldId,E.UpdatedUserId,0
		from
		(
				SELECT StudentId,SubCategory,CustomFieldId,UpdatedUserId FROM
				OPENXML (@loDoc, '/Students/Students', 2)
				WITH (						
						StudentId BIGINT,
						--AutoId int,
						SubCategory nvarchar(150),
                        CustomFieldId int,
						UpdatedUserId bigint
						)	
						)E 	
		--UPDATE ListofData SET IsExist=1 WHERE (StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCustomFieldData) AND CustomFieldId NOT IN (SELECT StudentCustomFieldId FROM sStudent.tStudentCustomFieldData))
		UPDATE LD SET IsExist=1 
		   FROM sStudent.tStudentCustomFieldData SC
		      LEFT JOIN ListofData LD ON SC.StudentId=LD.StudentId 
		      AND  EXISTS (SELECT StudentCustomFieldId FROM sStudent.tStudentCustomFieldData WHERE StudentId=LD.StudentId AND StudentCustomFieldId = LD.CustomFieldId) 
		
		
		--SELECT *From ListofData --where StudentId=1101000003521
		
		set @sql='INSERT INTO sStudent.tStudentCustomFieldData
					(StudentId,StudentCustomFieldId,FieldData,CreatedUserId,CreatedDateTime)
					SELECT
						LD.StudentId,ISNULL('+@rCustomFieldId+',0),LD.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
					FROM
						ListofData LD WHERE LD.IsExist=0'
					
		--print @sql		
		Exec sp_executesql @sql
		set @sql='UPDATE sStudent.tStudentCustomFieldData set FieldData = LD.SubCategory,
					UpdatedUserId=LD.UpdatedUserId,
					UpdatedDateTime=sCommon.fGetDate()  
					from sStudent.tStudentCustomFieldData SC 
					INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND SC.StudentCustomFieldId=LD.CustomFieldId AND IsExist=1'
		print @sql
		Exec sp_executesql @sql
	
		Drop Table ListofData
			 SELECT 1 AS StatusCode
	   
END 
	--   COMMIT TRANSACTION
		
	--END TRY
	
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS Result
	--END CATCH
GO
PRINT N'Altering [sStudent].[pValidateImportStudent]...';


GO

ALTER PROCEDURE [sStudent].[pValidateImportStudent]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rOperation int=1
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lSUIdActivate nvarchar(50)=''
DECLARE @lIsActivateUniqueId bit = 0
DECLARE @lOrgGroupId int = 0
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
SELECT @lSUIdActivate = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 167 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	
IF (@lSUIdActivate = '') OR (@lSUIdActivate = 'False')
	SET @lIsActivateUniqueId = 0
ELSE
	SET @lIsActivateUniqueId = 1	

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),
        @lClass nvarchar(100),
        @lDivision nvarchar(100),        
        @lRegistrationNumber nvarchar(20),  
        @lAdmissionDate nvarchar(15),        
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ExistStudentCode nvarchar(max) = '',
        @1ExistStudentRegistrationNumber nvarchar(max) = '',
        @1ValidAdmissionDate nvarchar(max) = '',
        @1ValidDOB nvarchar(max) = '',
        @1DuplicateStudentCode nvarchar(max) = '',
        @1DuplicateStudentRegistrationNumber nvarchar(max) = '',
        @lSUId nvarchar(20),
        @1ExistStudentSUId nvarchar(max) = '',
        @1DuplicateStudentSUId nvarchar(max) = '',
        @lLeftDate nvarchar(15),
        @lLCDate nvarchar(15),
        @1ValidLeftDate nvarchar(max) = '',
        @1ValidLCDate nvarchar(max) = '',
        @lStatusId smallint,
        
        @lAdhaarNumber nvarchar(50),  
        @1DuplicateAdhaarNumber nvarchar(max) = '',
        
        @lUIDNumber nvarchar(50),  
        @1DuplicateUIDNumber nvarchar(max) = ''
        
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(50),
        RegistrationNumber nvarchar(20),
        FirstName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		Division nvarchar(100),
		AdmissionStandard nvarchar(100),
		AdmissionDate nvarchar(15),
        DOB nvarchar(15),
        Gender nvarchar(10),
        --AdmissionCategory nvarchar(100),
		Religion nvarchar(100),
		CastCategory nvarchar(100),
        SUId nvarchar(20),
        LeftDate nvarchar(15),
        LCDate nvarchar(15),
        LeftStandard nvarchar(100),
        StatusId smallint,
        AdhaarNumber varchar(100),
        UIDNumber varchar(100)
        --Id1 bigint NULL,
        --departmentId int NULL
 
  )
  INSERT INTO #tTable1
	(
	    Code,
	    RegistrationNumber, 
	    FirstName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    Religion,
	    CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber
    ) 
   SELECT
        Code,
	    RegistrationNumber, 
	    sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName,
	    sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion,
	    sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        Code nvarchar(50) '@Code',
        RegistrationNumber nvarchar(20) '@RegistrationNumber',
        FirstName nvarchar(100) '@FirstName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate nvarchar(15) '@AdmissionDate',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender',
		--AdmissionCategory nvarchar(100) '@AdmissionCategory',
		Religion nvarchar(100) '@Religion',
		CastCategory nvarchar(100) '@CastCategory',
		SUId nvarchar(20) '@SUId',
		LeftDate nvarchar(15) '@LeftDate',
		LCDate nvarchar(15) '@LCDate',
		LeftStandard nvarchar(100) '@LeftStandard',
		StatusId smallint '@StatusId',
		AdhaarNumber varchar(100) '@AdhaarNumber',
		UIDNumber varchar(100) '@UIDNumber'
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1

WHILE @lCount > 0 
  BEGIN
  
       SELECT         
         
         @lCode = Code, 
         @lRegistrationNumber = RegistrationNumber,
         @lAdmissionDate = AdmissionDate,
         @lDOB=DOB,
         @lSUId = SUId,
         @lLeftDate = LeftDate,
         @lLCDate = LCDate,
         @lStatusId = StatusId,
         @lAdhaarNumber = AdhaarNumber,
         @lUIDNumber = UIDNumber
        FROM #tTable1 WHERE Id = @lCount 
        
        
     
    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	       END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId))         
          BEGIN
  			    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	       END	         
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT))         
          BEGIN
          
                IF(ISNULL(@lAdhaarNumber,'')!='')
                BEGIN
  			        SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
  			    END
	       END	
	     
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT))         
          BEGIN
         
                IF(ISNULL(@lUIDNumber,'')!='')
                BEGIN
                
  			        SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
  			    END    
	       END	
	       
	       
	IF(ISDATE(@lAdmissionDate) = 0 AND @lAdmissionDate!='')
	BEGIN
		SET @1ValidAdmissionDate=@1ValidAdmissionDate + @lCode + '-' + @lAdmissionDate+','
	END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB + @lCode + '-' + @lDOB+','
	END
	
	IF(ISDATE(@lLeftDate) = 0 AND @lLeftDate!='')
	BEGIN
		SET @1ValidLeftDate=@1ValidLeftDate + @lCode + '-' + @lLeftDate+','
	END
	
	IF(ISDATE(@lLCDate) = 0 AND @lLCDate!='')
	BEGIN
		SET @1ValidLCDate=@1ValidLCDate + @lCode + '-' + @lLCDate+','
	END
	
     SET @lCount = @lCount - 1	
   END	
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
		BEGIN
			SELECT         
         
			 @lClass = Class, 
			 @lDivision = Division
     
			FROM #tTable1 WHERE Id = @lCount
			
			IF NOT EXISTS (SELECT 1 FROM sSetup.tDivisionMaster DM 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId 
						WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT AND DM.Title COLLATE DATABASE_DEFAULT =@lDivision COLLATE DATABASE_DEFAULT AND DM.OrgId=@rOrgId)	
			BEGIN
				
				SELECT 'Enter proper value for Division ' + @lClass + ' ' + @lDivision AS StudentCode
				RETURN
			END
			SET @lCount = @lCount - 1	
		END
   	
		IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'ID No Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number='')
		--BEGIN
		--	SELECT 'Number Should not be empty' AS StudentCode
		--END
		--ELSE IF EXISTS(SELECT 1 FROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'Surname Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Class Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Division IS NULL OR Division COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Division Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard IS NULL OR AdmissionStandard='')
		--BEGIN
		--	SELECT 'Admission Standard Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender='')
		BEGIN
			SELECT 'Gender Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionCategory IS NULL OR AdmissionCategory='')
		--BEGIN
		--	SELECT 'Admission Category Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionDate IS NULL OR AdmissionDate COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'Admission Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId))
		BEGIN
			SELECT 'Enter proper value for Class as per Institute Setup > Class Master' AS StudentCode
		END				
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard  COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND AdmissionStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId))
		BEGIN
			SELECT 'Enter proper value for Admission Class as per Admin Tool > Institute Setup > Class Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Religion COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Religion COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tReligionMaster WHERE OrgGroupId=@rOrgGroupId))
		BEGIN
			SELECT 'Enter proper value / Check spelling for Religion per Admin Tool > Master > Religion Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE CastCategory COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND CastCategory COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tCastCategoryMaster))
		BEGIN
			SELECT 'Enter proper value for Cast Category (OBC,SC,ST,GENERAL)' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1)
		BEGIN
			SELECT 'Left Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LCDate IS NULL OR LCDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1)
		BEGIN
			SELECT 'LC Date Should not be empty or check the date format' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE  LeftStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId) AND @lLeftDate!='')
		--BEGIN
		--	SELECT 'Enter proper value for Left Standard as per Institute Setup > Class Master' AS StudentCode
		--END	
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'LeftDate Should not be empty or check the date format' AS StudentCode
		--END
		ELSE
		BEGIN
		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
			
	    
			
		SELECT @1DuplicateStudentSUId=COALESCE(@1DuplicateStudentSUId ,'') + SUId + ',' FROM #tTable1 GROUP BY SUId HAVING ( COUNT(SUId) > 1 )	
			IF(@1DuplicateStudentSUId IS NOT NULL AND @1DuplicateStudentSUId != '' AND @lIsActivateUniqueId=1)
				BEGIN
				
					SET @1DuplicateStudentSUId = 'Duplicate SUId ' + @1DuplicateStudentSUId
					SELECT @1DuplicateStudentSUId AS StudentCode
				END
			ELSE IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
				  
					SET @1DuplicateStudentCode = 'Duplicate Code ' + @1DuplicateStudentCode
					
					SELECT @1DuplicateStudentCode AS StudentCode
				END
			ELSE			
				BEGIN
				SELECT @1DuplicateStudentRegistrationNumber=COALESCE(@1DuplicateStudentRegistrationNumber ,'') + CONVERT(VARCHAR(20),RegistrationNumber) + ',' FROM #tTable1 GROUP BY RegistrationNumber HAVING ( COUNT(RegistrationNumber) > 1 AND ISNULL(RegistrationNumber,'')!='')	
				IF(@1DuplicateStudentRegistrationNumber IS NOT NULL AND @1DuplicateStudentRegistrationNumber  COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
					SET @1DuplicateStudentRegistrationNumber = 'Duplicate Registration Number ' + @1DuplicateStudentRegistrationNumber
					SELECT @1DuplicateStudentRegistrationNumber AS StudentCode
				END
		
		ELSE IF (@1DuplicateAdhaarNumber IS NOT NULL AND @1DuplicateAdhaarNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
		  
			SET @1DuplicateAdhaarNumber = 'Exist Adhaar Number ' + @1DuplicateAdhaarNumber
			Select @1DuplicateAdhaarNumber AS StudentCode
		END
		
		
		ELSE IF (@1DuplicateUIDNumber IS NOT NULL AND @1DuplicateUIDNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1DuplicateUIDNumber = 'Exist UID Number ' + @1DuplicateUIDNumber
			Select @1DuplicateUIDNumber AS StudentCode
		END
		
				
		ELSE IF((@1ExistStudentSUId IS NULL OR @1ExistStudentSUId = '' OR @lIsActivateUniqueId=0) AND (@1ExistStudentCode IS NULL OR @1ExistStudentCode = '') AND (@1ExistStudentRegistrationNumber IS NULL OR @1ExistStudentRegistrationNumber = '')
		AND (@1ValidAdmissionDate IS NULL OR @1ValidAdmissionDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
		
			SELECT '' AS StudentCode
		END
		ELSE IF (@1ExistStudentSUId IS NOT NULL AND @1ExistStudentSUId != '' AND @lIsActivateUniqueId=1)
		BEGIN
			SET @1ExistStudentSUId = 'Exist SUId ' + @1ExistStudentSUId
			Select @1ExistStudentSUId AS StudentCode
		END
		
		
		
		
		ELSE IF (@1ExistStudentCode IS NOT NULL AND @1ExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentCode = 'Exist Code ' + @1ExistStudentCode
			Select @1ExistStudentCode AS StudentCode
		END
		ELSE IF (@1ExistStudentRegistrationNumber IS NOT NULL AND @1ExistStudentRegistrationNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentRegistrationNumber = 'Exist Registration Number ' + @1ExistStudentRegistrationNumber
			Select @1ExistStudentRegistrationNumber AS StudentCode
		END
		ELSE IF (@1ValidAdmissionDate IS NOT NULL AND @1ValidAdmissionDate != '')
		BEGIN
			SET @1ValidAdmissionDate = 'Wrong Admission Date ' + @1ValidAdmissionDate
			Select @1ValidAdmissionDate AS StudentCode
		END
		ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
		BEGIN
			SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
			Select @1ValidDOB AS StudentCode
		END
		ELSE IF (@1ValidLeftDate IS NOT NULL AND @1ValidLeftDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLeftDate = 'Wrong LeftDate ' + @1ValidLeftDate
			Select @1ValidLeftDate AS StudentCode
		END
		ELSE IF (@1ValidLCDate IS NOT NULL AND @1ValidLCDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLCDate = 'Wrong LCDate ' + @1ValidLCDate
			Select @1ValidLCDate AS StudentCode
		END
		END
		END
END
GO
PRINT N'Altering [sStudent].[pValidateStudentBulkDateUpdate]...';


GO
ALTER PROCEDURE [sStudent].[pValidateStudentBulkDateUpdate]

	@rOrgGroupId int,
    @rOrgId int,
    @rSubCategoryType varchar(100),
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),             
        @1ReturnCode int = 1,
        @1DuplicateCode nvarchar(400) = '' ,
        
        @lStudentId bigint,
        @lSubCategory nvarchar(max)
       
        
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        StudentId bigint,
        SubCategory nvarchar(100),
        Code nvarchar(100)
 
  )
  INSERT INTO #tTable1
	(
	    StudentId,
	    SubCategory,
	    Code
    ) 
   SELECT
      StudentId,
      SubCategory,
      Code
   
   FROM OPENXML (@intDoc, 'Students/Students', 1)
   With
   (
        StudentId bigint 'StudentId',
        SubCategory nvarchar(100) 'SubCategory',
        Code nvarchar(50) 'Code'
        
   )   
EXEC sp_xml_removedocument @intDoc


SELECT @lCount =  COUNT(Id) FROM #tTable1
 
WHILE @lCount > 0 
  BEGIN
     --SELECT @lCount
       SELECT         
        
         @lStudentId = StudentId,
         @lSubCategory = SubCategory
     
        FROM #tTable1 WHERE Id = @lCount 
        
        IF (@rSubCategoryType='AdhaarNumber')
        BEGIN
			IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lSubCategory COLLATE DATABASE_DEFAULT AND SO.StudentId <> @lStudentId AND SM.OrgId=@rOrgId))         
			  BEGIN
					IF(ISNULL(@lSubCategory,'')!='')
					BEGIN
	                    
  						SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ','
	  			        
  					END
			   END	
	     END  
	     
	   IF (@rSubCategoryType='UIDNumber')
        BEGIN
			IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lSubCategory COLLATE DATABASE_DEFAULT AND SO.StudentId <> @lStudentId AND SM.OrgId=@rOrgId))         
			  BEGIN
					IF(ISNULL(@lSubCategory,'')!='')
					BEGIN
	                    
  						SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ','
	  			        
  					END
			   END	
	     END 
	     
	      --   IF (@rSubCategoryType='AdmissionDate')
   --     BEGIN
			--IF Exists ((select * from sStudent.tStudentAdmission SA INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId 
			--INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
			--where 
			--SA.AdmissionDate = @lSubCategory 
			--AND SA.StudentId <> @lStudentId AND SM.OrgId=@rOrgId
			--AND SA.AdmissionDate=SO.DateOfBirth
			--AND SA.AdmissionDate<=SO.DateOfBirth))         
			--  BEGIN
			--		IF(ISNULL(@lSubCategory,'')!='')
			--		BEGIN
	                    
  	--					SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ','
	  			        
  	--				END
			--   END	
	  --   END 
	     
	     
	     
	      
	    --IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lSubCategory COLLATE DATABASE_DEFAULT))         
     --     BEGIN
     --           IF(ISNULL(@lSubCategory,'')!='')
     --           BEGIN
  			--        SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ',' 
  			       	        
  			--    END    
	    --   END
	       
	       
  SET @lCount = @lCount - 1		               
  END       
        
--select * from sStudent.tStudentOther SO where AdhaarNumber='8327'



--SELECT @lCount =  COUNT(Id) FROM #tTable1


 --SELECT @1DuplicateCode=COALESCE(@1DuplicateCode ,'') + SubCategory + ',' FROM #tTable1 GROUP BY SubCategory HAVING ( COUNT(SubCategory) > 1 )
 	
 --  IF(@1DuplicateCode IS NOT NULL AND @1DuplicateCode != '' )
	--			BEGIN
	--				--SET @1DuplicateCode = 'Duplicate '+@rSubCategoryType+' ' + @1DuplicateCode
	--				SELECT @1DuplicateCode AS StudentCode
	--				--Select right(@1DuplicateCode, len(@1DuplicateCode)-1) as StudentCode
	--			END
   
 SELECT @1DuplicateCode AS StudentCode 		
END
GO
PRINT N'Altering [sTally].[pCompanyMappingGet]...';


GO

ALTER PROCEDURE [sTally].[pCompanyMappingGet]

	 @rOrgGroupBatchId int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	Declare @lOrgGroupId Int
	Declare @lPostingTYpe nvarchar(100)

	SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrgGroupBatchMaster Where Id=@rOrgGroupBatchId

	SELECT @lPostingTYpe = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END  
	FROM sConfig.tConfigurationMaster C INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
	LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID=@lOrgGroupId
	WHERE  C.ItemKey = 'Tally.PostingType'

	if @lPostingTYpe = 'OrgMainGroupWise' 
	BEGIN
		SELECT OSM.Id AS ReceiptBookId,OSM.Title AS ReceiptBookName,CompanyName,CashLedgerName,BankLedgerName,IsNull(IsLocked,0) as IsLocked
		FROM 
		sSetup.tOrgSubGroupMaster OSM 
		LEFT JOIN sTally.tReceiptBookCompanyMapping RCM ON OSM.Id = RCM.REceiptBookId
		AND RCM.OrgGroupBatchId =@rOrgGroupBatchId	
	END
	ELSE
	BEGIN
		SELECT RB.Id AS ReceiptBookId,RB.Title AS ReceiptBookName,CompanyName,CashLedgerName,BankLedgerName,IsNull(IsLocked,0) as IsLocked  
		FROM sTally.tReceiptBookCompanyMapping RCM
		RIGHT JOIN sfee.tReceiptbookmaster RB ON RCM.ReceiptBookId = RB.Id
		AND RCM.OrgGroupBatchId =@rOrgGroupBatchId	
	END
END
GO
PRINT N'Altering [sTally].[pFeeLedgerMappingGet]...';


GO

ALTER PROCEDURE [sTally].[pFeeLedgerMappingGet]

	 @rOrgGroupBatchId int,
	 @rReceiptBookId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
Declare @lOrgGroupId Int
	Declare @lPostingTYpe nvarchar(100)
	
	SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrgGroupBatchMaster Where Id=@rOrgGroupBatchId

	SELECT @lPostingTYpe = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END  
	FROM sConfig.tConfigurationMaster C INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
	LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID=@lOrgGroupId
	WHERE  C.ItemKey = 'Tally.PostingType'
    	
	if @lPostingTYpe = 'OrgMainGroupWise' 
	BEGIN
		SELECT Distinct
			   OM.TITLE AS FeeName,
			   OM.Id AS FeeId,
			    FLM.LedgerName AS LedgerName,
			   RBC.CompanyName 
	    FROM sSetup.tORganizationMAster OM 
		INNER JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.Id = OM.OrgSubGRoupID
		INNER JOIN sTally.tReceiptBookCompanyMapping RBC ON RBC.ReceiptBookId = OSM.Id AND RBC.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sTally.tFeeLedgerMapping FLM ON FLM.FeeId= OM.Id
		--Where RBC.ReceiptBookId = @rReceiptBookId 
	END
	
	ELSE 
	
	BEGIN
		
		SELECT Distinct
			   FHM.TITLE AS FeeName,
			   FHM.Id AS FeeId,
			   FLM.LedgerName,
			   RBC.CompanyName 
	    FROM sFee.tFeeSetup FS
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FS.BatchId AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sTally.tReceiptBookCompanyMapping RBC ON RBC.ReceiptBookId = FS.ReceiptBookId AND RBC.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sTally.tFeeLedgerMapping FLM ON FLM.FeeId= FHM.Id
		Where FS.ReceiptBookId = @rReceiptBookId 
	END
END
GO
PRINT N'Altering [sTally].[pReceiptPostingGet]...';


GO
ALTER PROCEDURE [sTally].[pReceiptPostingGet]

	 @rOrgGroupBatchId int,
	 @rReceiptBookId int,
	 @rReceiptDate Date,
	 @rToReceiptDate Date
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
	DECLARE @lTallyPostingType nVarchar(100)
	DECLARE @lOrgGroupId INT
	
	SELECT @lOrgGroupId = OrgGroupId from sSetup.tOrgGroupBatchMaster Where Id=@rOrgGroupBatchId
	
	SELECT @lTallyPostingType = CASE WHEN CS.ItemValue IS NULL THEN C.ItemValue ELSE CS.ItemValue END 
		FROM sConfig.tConfigurationMaster C
        INNER JOIN sConfig.tConfigurationLevelMaster CM ON CM.Id = C.ConfigurationLevelId
        LEFT JOIN sConfig.tConfigurationSetup CS ON CS.ConfigurationId = C.Id AND CS.SOURCEID= @lOrgGroupId
        WHERE  C.ItemKey = 'Tally.PostingType'
        
		
        IF @lTallyPostingType = 'FeeHeadWise' 
        BEGIN
			   SELECT	ReceiptDate,
						ISNULL(FHM.Title,'') AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						'' as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FHM.Id AS FeeId,
						0 AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					WHERE	FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
				group by ReceiptDate,FHM.Title,PM.Title,FHM.Id,FR.PayTypeId
				Order By ReceiptDate Desc
			END				
       ELSE IF @lTallyPostingType = 'FeeHeadWiseCustom' 
        BEGIN
			   SELECT	ReceiptDate,
						FR.Id AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  as Narration,						
						FR.PayTypeId AS PayTypeId, 
						0 AS FeeId,
						FR.Id AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSetup.tOrganizationMaster OM ON  OM.Id=SM.OrgId
					INNER JOIN sSetup.tOrgSubGroupMaster OSM ON OSM.id=OM.OrgSubGroupId

					WHERE	OSM.Id = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
				group by ReceiptDate,PM.Title,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	

       ELSE IF @lTallyPostingType = 'OrgMainGroupWise' 
        BEGIN
			   SELECT	ReceiptDate,
						SM.AcademicId AS FeeName,
						PM.Title AS PayType,
						Sum(FRD.Amount) AS Amount,
						SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  as Narration,						
						FR.PayTypeId AS PayTypeId, 
						FR.Id AS FeeId,
						SM.AcademicId AS ReceiptId
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sStudent.vStudentAcademic SM ON SM.ACademicId = FR.SourceID AND SM.OrgGRoupBatchId = FR.OrgGRoupBatchId 
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sSEtup.tOrganizationMaster OM ON OM.OrgSubGRoupID =  @rReceiptBookId AND OM.ID = SM.OrgId					
					WHERE	FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate AND FR.ReceiptDate <= @rToReceiptDate
							AND FR.PayTypeID = 2
				group by ReceiptDate,PM.Title,SM.AcademicId ,FR.PayTypeId,FR.Id,SM.Name + '(' + ClassName + ':' + DivisionName + ') ' + ' # Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')
				Order By FR.Id,ReceiptDate Desc
			END	
	ELSE IF @lTallyPostingType = 'ReceiptWise' 
			BEGIN	
				SELECT	ReceiptDate,						
						ISNULL(SLM.LedgerName,'') AS FeeName,
						PM.Title AS PayType,						
						Sum(FRD.Amount) AS Amount,
						case When FR.PayTypeId = 1 then
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') 
						when FR.PayTypeId <> 1 then 
						'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName + '-->' +
						STUFF((SELECT ','  + convert(nvarchar(20),isnull(FRD1.Amount,'')) + '-' + isnull(FM1.Title ,'') 
						from sFee.tReceipt FR1  INNER JOIN sFee.tReceiptDetail FRD1 ON FR1.Id = FRD1.ReceiptId
						INNER JOIN sFee.tFeeSetup FS1 ON FS1.Id = FRD1.FeeSetupId 						
						INNER JOIN sFee.tFeeMaster FM1 ON FM1.Id = FS1.FeeId AND FRD.ReceiptId=FRD1.ReceiptId  FOR XML PATH('')),1,1,'') + '  Cheque No. :' + ISNULL(FR.ChequeNo,'') + ' BankName :' + ISNULL(FR.BankName,'')  ENd
						AS Narration,					
						FR.PayTypeId AS PayTypeId,									
						A.StudentId AS FeeId,
						FRD.ReceiptId					 
				FROM sFee.tReceipt FR 
					INNER JOIN sFee.tReceiptDetail FRD ON FR.Id = FRD.ReceiptId
					INNER JOIN sFee.tFeeSetup FS ON FS.Id = FRD.FeeSetupId
					INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
					INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
					INNER JOIN sFinanceCommon.tPayTypeMaster PM ON PM.Id = FR.PayTypeId
					INNER JOIN sStudent.vStudentAcademic A ON A.AcademicId = FR.SourceId AND A.OrgGRoupBatchId = FR.OrgGRoupBatchId
					LEFT JOIN sTally.tStudentLedgerMapping SLM ON SLM.StudentId = A.StudentId AND SLM.ReceiptBookid = FR.ReceiptBookId
					WHERE							
							FR.ReceiptBookId = @rReceiptBookId 
							AND FR.IsObsolete = 0 
							AND FR.OrgGroupBatchId = @rOrgGroupBatchId
							AND FR.ReceiptDate >= @rReceiptDate	And FR.ReceiptDate <= @rToReceiptDate					
				group by 
				ReceiptDate,PM.Title,
				SLM.LedgerName,FR.PayTypeId,A.StudentId,
				FRD.ReceiptId,Isnull(FR.ChequeNo,''),ISNull(FR.BankName,''),
				'Std-' + ClassName + ':' + DivisionName + ' RollNo :' + convert(nvarchar(20),RollNo) + ' ' + BatchName				
				Order By ReceiptDate desc	
			END			
			
END
GO
PRINT N'Altering [sTimetable].[pNoOfPeriodGet]...';


GO
ALTER PROCEDURE [sTimetable].[pNoOfPeriodGet] 
	 
	  @rBatchId int,
	  @rTimeTableSchemaId int 
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
	DECLARE @lOrgGroupBatchId int = 0		 
	SELECT @lOrgGroupBatchId = OrgGroupBatchId FROM sSetup.tBatchMaster WHERE Id = @rBatchId

BEGIN   
	SELECT 
	MAX(NoOfPeriod) AS NoOfPeriod,
	DayId,
	DM.Title AS DayName  
         
    from 
    sCommon.tDayMaster DM INNER JOIN
    sTimetable.tTimeSetup TS
    ON DM.Id = TS.DayId
    INNER JOIN sSetup.tBatchMaster BM ON BM.Id = TS.BatchId AND BM.OrgGroupBatchId = @lOrgGroupBatchId AND BM.Id=@rBatchId
    AND TS.TimeTableSchemaId=@rTimeTableSchemaId
 
    
    WHERE DayId  IN (1,2,3,4,5,6,7)
    Group By DayId,DM.Title
    
    order by DayId
		
END
GO
PRINT N'Creating [sAcademic].[pHomeworkViewAdd]...';


GO
 
CREATE PROCEDURE [sAcademic].[pHomeworkViewAdd]
	 
	@rAcademicId bigint,
	@rClassworkId bigint,
	@rViewByUserId bigint
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	 BEGIN TRANSACTION	
		 BEGIN
		 IF NOT EXISTS(SELECT ClassworkId,AcademicId,ViewByUserId FROM sAcademic.tClassworkView WHERE ClassworkId=@rClassworkId AND AcademicId=@rAcademicId AND ViewByUserId=@rViewByUserId)
		 INSERT INTO sAcademic.tClassworkView
		 (
			ClassworkId,
			AcademicId,
			ViewByUserId,
			ViewByDateTime
		 )
		 VALUES
		 (
			@rClassworkId,
			@rAcademicId,
			@rViewByUserId,
        	sCommon.fGetDate()
		 )
		SELECT 1 AS RESULT
        END  
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END
GO
PRINT N'Creating [sAcademic].[pHomeworkViewGet]...';


GO
CREATE PROCEDURE [sAcademic].[pHomeworkViewGet]
	 
	@rClassworkId bigint

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	 BEGIN TRANSACTION	
		 BEGIN
		 SELECT 
			 SM.Code,
			 SM.FirstName +' '+ SM.LastName as Name,
			 CV.ViewByDateTime
		 FROM
			 sAcademic.tClassworkView as CV
			 INNER JOIN sStudent.tAcademic SA on SA.Id = CV.AcademicId
			 INNER JOIN sStudent.tStudentMaster SM on SM.Id = SA.StudentId
		 WHERE
		 ClassworkId = @rClassworkId
		SELECT 1 AS RESULT
        END  
	COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END
GO
PRINT N'Creating [sAssessment].[pRptResultListAnalysisGet1]...';


GO

CREATE PROCEDURE [sAssessment].[pRptResultListAnalysisGet1]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 --@rOrgId smallint,
	 @rBatchId int=0,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
	 @rExamSubGroupId nvarchar(max)='',
	 @rCode nvarchar(20)='',
	 @rFromRollNo int=0,
	 @rToRollNo int=0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rAcademicId bigint=0,
	 @rGroupId int=0,
	 @rClass nvarchar(MAX)='',
	 @rSubject nvarchar(max)='',
	 @rStatusId int =0
	 
	 
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT  
	EM.ExamSubGroupId,
			R.ExamId,
			@rBuilder1 AS Builder1,
	 		A.RollNo,
	 		R.AcademicId,
			CM.DisplayTitle+'/'+DM.DisplayTitle AS Class,
			 DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
		 
			--CM.DisplayTitle AS Class,
			
			ED.ClassSubjectId AS ClassSubjectId,
			RD.Obtain AS SubjectObtain,
			Subj.Id AS SubjectId,
			 
			Subj.Code AS SubjectCode,
			
			Subj.Title AS SubjectName,
			BM.Title,
			BM.Id AS Batch,
			 Subj.OrderIndex AS SubjectOrderIndex,
			 BM.OrderIndex AS BatchOrderIndex,
			--CM.OrderIndex AS ClassOrderIndex ,
			RD.SubjectGrade,
			
			CASE WHEN @rGroupId=1 THEN DM.Id 
				WHEN @rGroupId=2 THEN CM.Id 
				WHEN @rGroupId =3 THEN Dept.Id 
				WHEn @rGroupId =4 THEN OM.Id END AS GroupId,
				
			CASE WHEN @rGroupId=1 THEN CM.DisplayTitle+'/'+DM.DisplayTitle
				WHEN @rGroupId=2 THEN CM.DisplayTitle
				WHEN @rGroupId=3 THEN Dept.Title 
				WHEN @rGroupId=4 THEN OM.Title END AS GroupName,
				
			CASE WHEN @rGroupId=1 THEN Dm.OrderIndex
				WHEN @rGroupId=2  THEN Cm.OrderIndex
				WHEN @rGroupId=3  THEN Dept.Id
				WHen @rGroupId=4 THen OM.OrderIndex  END AS OrderIndex,
				
			CASE WHEN @rGroupId=1 THEN 'Class/Division'
				WHEN @rGroupId=2  THEN 'Class'
				WHEN @rGroupId=3  THEN 'Department'
				WHen @rGroupId=4 THen  'Organization'  END AS GroupTitle,	
				
				Dept.Title AS DepartmentName,
				OM.Title AS OraganizationName
      
	FROM 
			
			sAssessment.tResultDetail RD 
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sStudent.tAcademic A ON R.AcademicId=A.Id
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId			
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster Subj ON Subj.Id=CS.SubjectId			
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId			
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = EM.BatchId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId=DM.Id
			INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
			inner join sStudent.tStudentMaster STM ON STM.Id = A.StudentId 
			
			 
	WHERE 
			
		 ((EM.batchId = @rBatchId  ) OR (@rBatchId=0))
	    AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		 
		--AND (( EM.ExamSubGroupId = @rExamSubGroupId )	OR (@rExamSubGroupId = 0))
		 AND (ISNULL(EM.ExamSubGroupId,0) IN( SELECT item FROM  sCommon.fnsplit(@rExamSubGroupId ,','))OR @rExamSubGroupId ='')
		AND ((A.Id =@rAcademicId) OR (@rAcademicId=0))
		 AND (ISNULL(EM.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
		AND (ISNULL(Subj.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
		and((STM.StatusId=@rStatusId) or (@rStatusId=0))
		 
END
GO
PRINT N'Creating [sAssessment].[pRptResultSheetStandardMultiExamGetwithResultDetailOther]...';


GO
 CREATE 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
	
	 --,@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(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,
		--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(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,
		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)))
    ) 
	    
	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'Creating [sStudent].[pImportStudent_New]...';


GO
 
CREATE PROCEDURE [sStudent].[pImportStudent_New]
    
    @rOrgGroupId smallint,
    @rOrgId smallint,
	@rXmldoc [nvarchar](max),
	@rUserId bigint,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rOperation int=0   --1 For Insert,2 For Update
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
BEGIN TRY

DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lCode nvarchar(20),
		@lNumber bigint,
		@lRegistrationNumber nvarchar(20),
		@lFirstName nvarchar(100),
		@lMiddleName nvarchar(100),
		@lLastName nvarchar(100),
		@lClassId int,
		@lClass nvarchar(100),
		@lDivisionId int,
		@lDivision nvarchar(100),
		@lRollNo int,
		@lAdmissionStandardId int,
		@lAdmissionStandard nvarchar(100),
		@lAdmissionDate date,
		@lPreviousSchool nvarchar(200),
		@lDOB date,
		@lGenderId int = 0,
		@lGender nvarchar(10),
		@lBloodGroupId int = 0,
		@lBloodGroup nvarchar(10),
		@lAdmissionCategoryId int,
		--@lAdmissionCategory nvarchar(100),
		@lReligionId int,
		@lReligion nvarchar(100),
		@lFamilyCast nvarchar(100),
		@lFamilySubCast nvarchar(100),
		@lCastCategoryId int = 0,
		@lCastCategory nvarchar(100),
		@lParentContactNo nvarchar(20),
		@lParentEmail nvarchar(50),
		@lStudentContactNo nvarchar(20),
		@lStudentEmail nvarchar(50),
		@lPresentStreetOne nvarchar(150),
		@lPresentStreetTwo nvarchar(150),
		@lPresentStreetThree nvarchar(150),
		@lPresentCity nvarchar(50),
		@lPresentZipCode nvarchar(20),
		@lPresentState nvarchar(50),
		@lPresentCountry nvarchar(50),
		@lPresentContactNo nvarchar(20),
		--@lEmergencyStreetOne nvarchar(50),
		--@lEmergencyStreetTwo nvarchar(50),
		--@lEmergencyStreetThree nvarchar(50),
		--@lEmergencyCountry nvarchar(50),
		--@lEmergencyState nvarchar(50),
		--@lEmergencyCity nvarchar(50),
		--@lEmergencyZipCode nvarchar(20),
		@lEmergencyContactNo nvarchar(20),
		@lBirthPlace nvarchar(150),
		@lBirthTaluka nvarchar(150),
		@lBirthDistrict nvarchar(150),
		@lBirthDateInWord nvarchar(150),
		@lHouseId int,
		@lHouse nvarchar(100),
		--@lMotherTongueId int,
		@lMotherTongue nvarchar(100),
		@lAdhaarNumber nvarchar(20),
		@lUIDNumber nvarchar(50),
		@lQuotaId int,
		@lQuota nvarchar(100),
		-- New Add
		@lSUId nvarchar(20),
		@lLeftStandardId int,
		@lLeftStandard nvarchar(100),
		@lLeftDate date,
		@lLCNumber nvarchar(20),
		@lLCDate date,
		@lLCReason nvarchar(200) ,
		@lLCProgress nvarchar(200) ,
        @lLCConduct nvarchar(200) ,
        @lLCRemark nvarchar(200),
        @lStatusId smallint,
        @lBirthState nvarchar(100),
        @lBirthCountry nvarchar(100),
		@lAcademicId bigint
		
			
DECLARE @EmployeeId bigint			
--DECLARE @OutClassId int
--DECLARE @OutDivisionId int
DECLARE @OutStudentId bigint 
--DECLARE @OutAdmissionStandardId int
--DECLARE @OutReligionId int
--DECLARE @OutAdmissionCategoryId int		
SET @lAdmissionCategoryId=sCommon.fGetIntIdForOrg(1,@rOrgGroupId)	
DECLARE @1StudentId BIGINT = 0
						
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
	
	CREATE TABLE #tTable  
	(
		Id bigint identity,	 
		Code nvarchar(20),
		Number bigint,
		RegistrationNumber nvarchar(20),
		FirstName nvarchar(100),
		MiddleName nvarchar(100),
		LastName nvarchar(100),
		ClassId int null,
		Class nvarchar(100),
		DivisionId int null,
		Division nvarchar(100),
		RollNo int,
		AdmissionStandardId int,
		AdmissionStandard nvarchar(100),
		AdmissionDate date,
		PreviousSchool nvarchar(200),
		DOB date,
		GenderId int null,
		Gender nvarchar(10),
		BloodGroupId int null,
		BloodGroup nvarchar(10),
		ReligionId int,
		Religion nvarchar(100),
		--AdmissionCategoryId int,
		--AdmissionCategory nvarchar(100),
		FamilyCast nvarchar(100),
		FamilySubCast nvarchar(100),
		CastCategoryId int,
		CastCategory nvarchar(100),
		ParentContactNo nvarchar(20),
		ParentEmail nvarchar(50),
		StudentContactNo nvarchar(20),
		StudentEmail nvarchar(50),
		PresentStreetOne nvarchar(150),
		PresentStreetTwo nvarchar(150),
		PresentStreetThree nvarchar(150),
		PresentCity nvarchar(50),
		PresentZipCode nvarchar(20),
		PresentState nvarchar(50),
		PresentCountry nvarchar(50),
		PresentContactNo nvarchar(20),
		--EmergencyStreetOne nvarchar(50),
		--EmergencyStreetTwo nvarchar(50),
		--EmergencyStreetThree nvarchar(50),
		--EmergencyCountry nvarchar(50),
		--EmergencyState nvarchar(50),
		--EmergencyCity nvarchar(50),
		--EmergencyZipCode nvarchar(20),
		EmergencyContactNo nvarchar(20),
		BirthPlace nvarchar(150),
		BirthTaluka nvarchar(150),
		BirthDistrict nvarchar(150),
		BirthDateInWord nvarchar(150),
		CreatedUserId bigint,
		HouseId int,
		House nvarchar(100),
		MotherTongueId int,
		MotherTongue nvarchar(100),
		AdhaarNumber nvarchar(20),
		UIDNumber nvarchar(50),
		QuotaId int,
		Quota nvarchar(100),
		SUId nvarchar(20),
		LeftStandardId int,
		LeftStandard nvarchar(100),
		LeftDate date,
		LCNumber nvarchar(20),
		LCDate date,
		LCReason nvarchar(200) ,
		LCProgress nvarchar(200) ,
        LCConduct nvarchar(200) ,
        LCRemark nvarchar(200),
        StatusId smallint,
        BirthState nvarchar(100),
        BirthCountry Nvarchar(100)
	)
		
	INSERT INTO #tTable
	(
		Code,
		Number,
		RegistrationNumber,
		FirstName,
		MiddleName,
		LastName,
		ClassId,
		Class,
		DivisionId,
		Division,
		RollNo,
		AdmissionStandardId,
		AdmissionStandard,
		AdmissionDate,
		PreviousSchool,
		DOB,
		GenderId,
		Gender,
		BloodGroupId,
		BloodGroup,
		ReligionId,
		Religion,
		--AdmissionCategoryId,
		--AdmissionCategory,
		FamilyCast,
		FamilySubCast,
		CastCategoryId,
		CastCategory,
		ParentContactNo,
		ParentEmail,
		StudentContactNo,
		StudentEmail,
		PresentStreetOne,
		PresentStreetTwo,
		PresentStreetThree,
		PresentCity,
		PresentZipCode,
		PresentState,
		PresentCountry,
		PresentContactNo,
		--EmergencyStreetOne,
		--EmergencyStreetTwo,
		--EmergencyStreetThree,
		--EmergencyCountry,
		--EmergencyState,
		--EmergencyCity,
		--EmergencyZipCode,
		EmergencyContactNo,
		BirthPlace,
		BirthTaluka,
		BirthDistrict,
		BirthDateInWord,
		CreatedUserId,
		HouseId,
		House,
		MotherTongueId,
		MotherTongue,
		AdhaarNumber,
		UIDNumber,
		QuotaId,
		Quota,
		SUId,
		LeftStandardId,
		LeftStandard,
		LeftDate,
		LCNumber,
		LCDate,
		LCReason,
		LCProgress,
        LCConduct,
        LCRemark,
        StatusId,
        BirthState,
        BirthCountry
	)
	SELECT
		Code,
		Number,
		RegistrationNumber,
		sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName,
		sSetup.fPortalXMLTagsReplaceReverse(MiddleName) AS MiddleName,
		sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(Class) AS Class,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(Division) AS Division,
		RollNo,
		0,
		AdmissionStandard,
		AdmissionDate,
		sSetup.fPortalXMLTagsReplaceReverse(PreviousSchool) AS PreviousSchool,
		DOB,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(Gender) AS Gender,
		0,
		BloodGroup,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion,
		--0,
		--AdmissionCategory,
		sSetup.fPortalXMLTagsReplaceReverse(FamilyCast) AS FamilyCast,
		sSetup.fPortalXMLTagsReplaceReverse(FamilySubCast) AS FamilySubCast,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory,
		ParentContactNo,
		ParentEmail,
		StudentContactNo,
		StudentEmail,
		sSetup.fPortalXMLTagsReplaceReverse(PresentStreetOne) AS PresentStreetOne,
		sSetup.fPortalXMLTagsReplaceReverse(PresentStreetTwo) AS PresentStreetTwo,
		sSetup.fPortalXMLTagsReplaceReverse(PresentStreetThree) AS PresentStreetThree,
		sSetup.fPortalXMLTagsReplaceReverse(PresentCity) AS PresentCity,
		PresentZipCode,
		sSetup.fPortalXMLTagsReplaceReverse(PresentState) AS PresentState,
		sSetup.fPortalXMLTagsReplaceReverse(PresentCountry) AS PresentCountry,
		PresentContactNo,
		--EmergencyStreetOne,
		--EmergencyStreetTwo,
		--EmergencyStreetThree,
		--EmergencyCountry,
		--EmergencyState,
		--EmergencyCity,
		--EmergencyZipCode,
		EmergencyContactNo,
		sSetup.fPortalXMLTagsReplaceReverse(BirthPlace) AS BirthPlace,
		sSetup.fPortalXMLTagsReplaceReverse(BirthTaluka) AS BirthTaluka,
		sSetup.fPortalXMLTagsReplaceReverse(BirthDistrict) AS BirthDistrict,
		sSetup.fPortalXMLTagsReplaceReverse(BirthDateInWord) AS BirthDateInWord,
		CreatedUserId,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(House) AS House,
		0,
		sSetup.fPortalXMLTagsReplaceReverse(MotherTongue) AS MotherTongue,
		sSetup.fPortalXMLTagsReplaceReverse(AdhaarNumber) AS AdhaarNumber,
		UIDNumber,
		0,
		Quota,
		SUId,
		0,
		LeftStandard,
		LeftDate,
		LCNumber,
		LCDate,
		sSetup.fPortalXMLTagsReplaceReverse(LCReason) AS LCReason,
		LCProgress,
        LCConduct,
        sSetup.fPortalXMLTagsReplaceReverse(LCRemark) AS LCRemark,
        StatusId,
        sSetup.fPortalXMLTagsReplaceReverse(BirthState) AS BirthState,
        sSetup.fPortalXMLTagsReplaceReverse(BIrthCountry) AS BIrthCountry 
			
	FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
	WITH
	( 
		Code nvarchar(20) '@Code',
		Number bigint '@Number',
		RegistrationNumber nvarchar(20) '@RegistrationNumber',
		FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
		LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		RollNo int '@RollNo',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate date '@AdmissionDate',
		PreviousSchool nvarchar(200) '@PreviousSchool',
		DOB date '@DOB',
		Gender nvarchar(10) '@Gender',
		BloodGroup nvarchar(10) '@BloodGroup', 			
		Religion nvarchar(100) '@Religion',
		--AdmissionCategory nvarchar(100) '@AdmissionCategory',
		FamilyCast nvarchar(100) '@FamilyCast',
		FamilySubCast nvarchar(100) '@FamilySubCast',
		CastCategory nvarchar(100) '@CastCategory',
		ParentContactNo nvarchar(20) '@ParentContactNo',
		ParentEmail nvarchar(50) '@ParentEmail',
		StudentContactNo nvarchar(20) '@StudentContactNo',
		StudentEmail nvarchar(50) '@StudentEmail',
		PresentStreetOne nvarchar(150) '@PresentStreetOne',
		PresentStreetTwo nvarchar(150) '@PresentStreetTwo',
		PresentStreetThree nvarchar(150) '@PresentStreetThree',
		PresentCity nvarchar(50) '@PresentCity',
		PresentZipCode nvarchar(20) '@PresentZipCode',
		PresentState nvarchar(50) '@PresentState',
		PresentCountry nvarchar(50) '@PresentCountry',
		PresentContactNo nvarchar(20) '@PresentContactNo',
		--EmergencyStreetOne nvarchar(50) '@EmergencyStreetOne',
		--EmergencyStreetTwo nvarchar(50) '@EmergencyStreetTwo',
		--EmergencyStreetThree nvarchar(50) '@EmergencyStreetThree',
		--EmergencyCountry nvarchar(50) '@EmergencyCountry',
		--EmergencyState nvarchar(50) '@EmergencyState',
		--EmergencyCity nvarchar(50) '@EmergencyCity',
		--EmergencyZipCode nvarchar(20) '@EmergencyZipCode',
		EmergencyContactNo nvarchar(20) '@EmergencyContactNo',
		 
		BirthPlace nvarchar(150) '@BirthPlace',
		BirthTaluka nvarchar(150) '@BirthTaluka',
		BirthDistrict nvarchar(150) '@BirthDistrict',		
		BirthDateInWord nvarchar(150) '@BirthDateInWord',
		CreatedUserId bigint '@CreatedUserId',
		House nvarchar(100) '@House',
		MotherTongue nvarchar(100) '@MotherTongue',
		AdhaarNumber nvarchar(20) '@AdhaarNumber',
		UIDNumber nvarchar(50) '@UIDNumber',
		Quota nvarchar(20) '@Quota',
		SUId nvarchar(20) '@SUId',
		LeftStandard nvarchar(100) '@LeftStandard',
		LeftDate date '@LeftDate',
		LCNumber nvarchar(20) '@LCNumber',
		LCDate date '@LCDate',
		LCReason nvarchar(200) '@LCReason',
		LCProgress nvarchar(200) '@LCProgress',
        LCConduct nvarchar(200) '@LCConduct',
        LCRemark nvarchar(200) '@LCRemark',
        StatusId smallint '@StatusId',
        BirthState nvarchar(100) '@BirthState',
        BirthCountry nvarchar(100) '@BirthCountry'
	)
	
	--print 'check'
 
EXEC sp_xml_removedocument @intDoc
			
SELECT @lCount =  COUNT(Id) FROM #tTable
WHILE @lCount > 0 

BEGIN
		SET @lCode = ''
		SET @lNumber = null
		SET @lRegistrationNumber = null
		SET @lFirstName = ''
		SET @lMiddleName = ''
		SET @lLastName = ''
		SET @lClassId = null
		SET @lClass = ''
		SET @lDivisionId = null
		SET @lDivision = ''
		SET @lRollNo = null
		SET @lAdmissionStandardId = null
		SET @lAdmissionStandard = ''
		SET @lAdmissionDate  = ''
		SET @lPreviousSchool = ''
		SET @lDOB = ''
		SET @lGenderId = null
		SET @lGender = ''
		SET @lBloodGroupId = null
		SET @lBloodGroup = ''
		SET @lReligionId  = null
		SET @lReligion = ''
		--SET @lAdmissionCategoryId  = null
		--SET @lAdmissionCategory = ''
		SET @lFamilyCast = ''
		SET @lFamilySubCast = ''
		SET @lCastCategoryId  = null
		SET @lCastCategory = ''
		SET @lParentContactNo = ''
		SET @lParentEmail = ''
		SET @lStudentContactNo = ''
		SET @lStudentEmail = ''
		SET @lPresentStreetOne = ''
		SET @lPresentStreetTwo = ''
		SET @lPresentStreetThree = ''
		SET @lPresentCity = ''
		SET @lPresentZipCode = ''
		SET @lPresentState = ''
		SET @lPresentCountry = ''
		SET @lPresentContactNo = ''
		--SET @lEmergencyStreetOne = ''
		--SET @lEmergencyStreetTwo = ''
		--SET @lEmergencyStreetThree = ''
		--SET @lEmergencyCountry = ''
		--SET @lEmergencyState = ''
		--SET @lEmergencyCity = ''
		--SET @lEmergencyZipCode = ''
		SET @lEmergencyContactNo = ''
		SET @lBirthPlace = ''
		SET @lBirthTaluka = ''
		SET @lBirthDistrict = ''
		SET @lBirthDateInWord = ''
		--SET @OutClassId = null
		--SET @OutDivisionId = null
		SET @OutStudentId = null
		--SET @OutAdmissionStandardId = null
		--SET @OutReligionId = null,
		SET @lHouseId=NULL
		SET	@lHouse=''
		--SET @lMotherTongueId=NULL
		SET	@lMotherTongue=''
		SET	@lAdhaarNumber=''
		SET @lUIDNumber=''
		SET @lQuotaId = NULL
		SET	@lQuota =''
		SET	@lSUId =''
		SET	@lLeftStandardId=NULL
		SET	@lLeftStandard = ''
		SET	@lLeftDate = ''
		SET	@lLCNumber = ''
		SET	@lLCDate = ''
		SET	@lLCReason = ''
		SET	@lLCProgress = ''
        SET	@lLCConduct = ''
        SET	@lLCRemark = ''
        SET @lStatusId = NULL 
        Set @lBirthState ='' 
        Set @lBirthCountry =''
		
SELECT		
		@lCode = Code,
		@lNumber=Number,
		@lRegistrationNumber = RegistrationNumber,
		@lFirstName = FirstName,
		@lMiddleName = MiddleName,
		@lLastName = LastName,
		@lClass = Class,
		@lDivision = Division,
		@lRollNo = RollNo,
		@lAdmissionStandard = AdmissionStandard,
		@lAdmissionDate  = CASE WHEN AdmissionDate = '' THEN  NULL ELSE AdmissionDate END,
		@lPreviousSchool = PreviousSchool,
		@lReligion = Religion,
		--@lAdmissionCategory = AdmissionCategory,
		@lFamilyCast = FamilyCast,
		@lFamilySubCast = FamilySubCast,
		@lCastCategory = CastCategory,
		@lDOB = CASE WHEN DOB = '' THEN  NULL ELSE DOB END,
		@lGender = Gender,
		@lBloodGroup = BloodGroup,
		@lParentContactNo = ParentContactNo,
		@lParentEmail = ParentEmail,
		@lStudentContactNo = StudentContactNo,
		@lStudentEmail = StudentEmail,
		@lPresentStreetOne = PresentStreetOne,
		@lPresentStreetTwo = PresentStreetTwo,
		@lPresentStreetThree = PresentStreetThree,
		@lPresentCountry = PresentCountry,
		@lPresentState = PresentState,
		@lPresentCity = PresentCity,
		@lPresentZipCode = PresentZipCode,
		@lPresentContactNo = PresentContactNo,
		--@lEmergencyStreetOne = EmergencyStreetOne,
		--@lEmergencyStreetTwo = EmergencyStreetTwo,
		--@lEmergencyStreetThree = EmergencyStreetThree,
		--@lEmergencyCountry = EmergencyCountry,
		--@lEmergencyState = EmergencyState,
		--@lEmergencyCity = EmergencyCity,
		--@lEmergencyZipCode = EmergencyZipCode,
		@lEmergencyContactNo = EmergencyContactNo,		 
		@lBirthPlace = BirthPlace,
		@lBirthTaluka = BirthTaluka,
		@lBirthDistrict = BirthDistrict,
		@lBirthDateInWord = BirthDateInWord,
		@lHouse = House,
		@lMotherTongue = MotherTongue,
		@lAdhaarNumber = AdhaarNumber,
		@lUIDNumber = UIDNumber,
		@lSUId = SUId,
		@lLeftStandard = LeftStandard,
		@lLeftDate = CASE WHEN LeftDate = '' THEN  NULL ELSE LeftDate END,
		@lLCNumber = LCNumber,
		@lLCDate = CASE WHEN LCDate = '' THEN  NULL ELSE LCDate END,
		@lLCReason = LCReason,
		@lLCProgress = LCProgress,
        @lLCConduct = LCConduct,
        @lLCRemark = LCRemark,
        @lStatusId = StatusId,
        @lBirthState = BirthState,
        @lBirthCountry = BirthCountry
											 	 
FROM #tTable WHERE Id = @lCount  

	SELECT	@lGenderId = ID FROM sCommon.tGenderMaster WHERE Title = @lGender
	SELECT	@lLeftStandardId  = ID FROM sSetup.tClassMaster WHERE Title = @lLeftStandard AND OrgId = @rOrgId
	SELECT	@lClassId  = ID FROM sSetup.tClassMaster WHERE Title = @lClass AND OrgId = @rOrgId
	SELECT	@lDivisionId  = ID FROM sSetup.tDivisionMaster WHERE Title = @lDivision AND ClassId=@lClassId AND OrgId = @rOrgId
	SELECT	@lBloodGroupId  = ID FROM sCommon.tBloodGroupMaster WHERE Title = @lBloodGroup
	SELECT	@lAdmissionStandardId  = ID FROM sSetup.tClassMaster WHERE Title = @lAdmissionStandard AND OrgId = @rOrgId
	SELECT	@lReligionId  = ID FROM sCommon.tReligionMaster WHERE Title = @lReligion AND OrgGroupId = @rOrgGroupId
	--SELECT	@lAdmissionCategoryId  = ID FROM tAdmissionCategoryMaster WHERE Title = @lAdmissionCategory AND OrgGroupId = @rOrgGroupId
	SELECT	@lCastCategoryId  = ID FROM sCommon.tCastCategoryMaster WHERE Title = @lCastCategory AND OrgGroupId = @rOrgGroupId	
	SELECT	@lHouseId  = ID FROM sActivity.tHouseMaster WHERE Title = @lHouse AND OrgId = @rOrgId
	SELECT	@lQuotaId  = ID FROM sCommon.tQuotaMaster WHERE Title = @lQuota AND OrgGroupId = @rOrgGroupId	
	--SELECT	@lMotherTongueId  = ID FROM sCommon.tMotherTongueMaster WHERE Title = @lMotherTongue
	
	
	
	IF(@lGenderId IS NULL)
		SET @lGenderId = 0
	IF(@lBloodGroupId IS NULL)
		SET	@lBloodGroupId = 0
	IF(@lCastCategoryId IS NULL)
		SET	@lCastCategoryId = 0
	IF(@lHouseId IS NULL)
		SET	@lHouseId = 0
	IF(@lQuotaId IS NULL)
		SET	@lQuotaId = 0	
	--IF(@lMotherTongueId IS NULL)
	--	SET	@lMotherTongueId = 0		
		
--IF 	@lClassId IS NULL  AND @lClass != ''
--BEGIN
--	EXEC [sSetup].[pClassMasterAdd] 0,@lClass,@lClass,@lClass,@lClass,1,0,0,0,@rUserId,@rUserId,@rOrgId,@OutClassId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutClassId = @lClassId
--END

--IF 	@lAdmissionStandardId IS NULL  AND @lAdmissionStandard != ''
--BEGIN
--	EXEC [sSetup].[pClassMasterAdd] 0,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,@lAdmissionStandard,1,0,0,0,@rUserId,@rUserId,@rOrgId,0,@OutAdmissionStandardId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutAdmissionStandardId = @lAdmissionStandardId
--END

--IF 	@lDivisionId IS NULL  AND @lDivision != ''
--BEGIN
--	SET @EmployeeId = sCommon.fGetBigIntIdForOrg(1,@rOrgId)
--	EXEC [sSetup].[pDivisionMasterAdd] 0,@lDivision,@lDivision,@lDivision,@lClassId,@EmployeeId,NULL,0,@rUserId,@rUserId,0,@rOrgId,@OutDivisionId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutDivisionId = @lDivisionId
--END

--IF 	@lReligionId IS NULL  AND @lReligion != ''
--BEGIN
--	EXEC [sCommon].[pReligionMasterAdd] 0,@lReligion,@lReligion,0,@rUserId,@rOrgId,@OutReligionId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutReligionId = @lReligionId
--END

--IF 	@lAdmissionCategoryId IS NULL  AND @lAdmissionCategory != ''
--BEGIN
--	EXEC [sStudent].[pAdmissionCategoryMasterAdd] 0,@lAdmissionCategory,@lAdmissionCategory,0,@rUserId,@rOrgId,@OutAdmissionCategoryId OUTPUT
-- END
--ELSE
--BEGIN
--SET @OutAdmissionCategoryId = @lAdmissionCategoryId
--END
 
BEGIN TRANSACTION

Declare @lStudCap int,@lOrgStudentCap int
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 
	COMMIT TRANSACTION			
	Return
END


IF(@rOperation=1 OR @rOperation =0)
BEGIN

	IF(@lStatusId=1)
		EXEC sStudent.pStudentMasterAdd 0,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,1,502,@rUserId,@rUserId,@rOrgGroupBatchId,@OutStudentId OUTPUT ,@lSUId
	ELSE
		EXEC sStudent.pStudentMasterAdd 0,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,3,502,@rUserId,@rUserId,@rOrgGroupBatchId,@OutStudentId OUTPUT,@lSUId

	EXEC sStudent.pAcademicAdd 0,@OutStudentId,@lClassId,@lDivisionId,@lRollNo,@rOrgId,@rBatchId,@rUserId,@rUserId,@lAdmissionCategoryId
	
	EXEC sStudent.pStudentCommunicationAdd @OutStudentId,@lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetThree,
				@lPresentCountry,@lPresentState,@lPresentCity,@lPresentZipCode,@lPresentContactNo,NULL,NULL,NULL,NULL,NULL,
				NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,@lEmergencyContactNo,@lParentContactNo,@lParentEmail,
				@lStudentContactNo,@lStudentEmail,@rUserId,@rUserId

	EXEC sStudent.pStudentOtherAdd @OutStudentId,@lUIDNumber,@lDOB,@lGenderId,@lReligionId,@lBloodGroupId,@lBirthPlace,@lBirthTaluka,@lBirthDistrict,@lBirthDateInWord,
				@lFamilyCast,@lFamilySubCast,@lCastCategoryId,NULL,@lHouseId,NULL,NULL,'',@rUserId,@rUserId,'',@lAdhaarNumber,@lMotherTongue,@lQuotaId,@lBirthState,@lBirthCountry

 
	IF(@lStatusId=1)		
		EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
				@lAdmissionStandardId,@lAdmissionDate,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
				NULL,NULL,NULL,NULL,NULL,@rBatchId,@rUserId,@rUserId,1
	ELSE
		EXEC [sStudent].[pStudentAdmissionAdd] @OutStudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
				@lAdmissionStandardId,@lAdmissionDate,NULL,@lLeftStandardId,@lLeftDate,NULL,NULL,NULL,@lLCReason,@lLCProgress,@lLCConduct,NULL,
				@lLCNumber,@lLCDate,@lLCRemark,NULL,NULL,@rBatchId,@rUserId,@rUserId,0
    
				 
END		

ELSE
BEGIN
    
      SET @1StudentId = (SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId) 
    	
     IF(@lRegistrationNumber='')
      SET @lRegistrationNumber=NULL
     	
      IF(@lStatusId=1)
		EXEC sStudent.pStudentMasterAdd @1StudentId,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,1,502,@rUserId,@rUserId,@rOrgGroupBatchId,@OutStudentId OUTPUT ,@lSUId
	  ELSE
		EXEC sStudent.pStudentMasterAdd @1StudentId,@lCode,@lRegistrationNumber,@lNumber,@lFirstName,@lMiddleName,@lLastName,@rOrgId,@lAdmissionCategoryId,3,502,@rUserId,@rUserId,@rOrgGroupBatchId,@OutStudentId OUTPUT,@lSUId
 
       
  
        SET @lClassId =(SELECT ClassId From sStudent.tAcademic where StudentId=@1StudentId AND BatchId = @rBatchId)
        --SET @lDivisionId =(SELECT DivisionId From sStudent.tAcademic where StudentId=@1StudentId AND BatchId = @rBatchId)
       -- SET @lRollNo =(SELECT RollNo From sStudent.tAcademic where StudentId=@1StudentId AND BatchId = @rBatchId)
		SET @lAcademicId =(SELECT Id From sStudent.tAcademic where StudentId=@1StudentId AND BatchId = @rBatchId)
		
        --print @lAcademicId
        --print @lClassId
  --      print @lDivisionId
		--print @1StudentId 
		--print @lRollNo 
		
           
      	EXEC sStudent.pAcademicAdd @lAcademicId,@1StudentId,@lClassId,@lDivisionId,@lRollNo,@rOrgId,@rBatchId,@rUserId,@rUserId,@lAdmissionCategoryId
        
        
        DECLARE @lPermanentStreetOne nvarchar(150) 
       DECLARE @lPermanentStreetTwo nvarchar(150)
       DECLARE @lPermanentStreetThree nvarchar(150)
       DECLARE @lPermanentCountry nvarchar(50) 
       DECLARE @lPermanentState nvarchar(50) 
       DECLARE @lPermanentCity nvarchar(50) 
       DECLARE @lPermanentZipCode nvarchar(20)
	   DECLARE @lPermanentContactNo nvarchar(20)
	   DECLARE @lEmergencyStreetOne nvarchar(150)
	   DECLARE @lEmergencyStreetTwo nvarchar(150)
	   DECLARE @lEmergencyStreetThree nvarchar(150)
	   DECLARE @lEmergencyCountry nvarchar(50)
	   DECLARE @lEmergencyState nvarchar(50)
	   DECLARE @lEmergencyCity nvarchar(50)
	   DECLARE @lEmergencyZipCode nvarchar(20)
       
       SET @lPermanentStreetOne =(SELECT PermanentStreetOne From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lPermanentStreetTwo =(SELECT PermanentStreetTwo From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lPermanentStreetThree =(SELECT PermanentStreetThree From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lPermanentCountry =(SELECT PermanentCountry From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lPermanentState =(SELECT PermanentState From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lPermanentCity =(SELECT PermanentCity From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lPermanentZipCode =(SELECT PermanentZipCode From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lPermanentContactNo =(SELECT PermanentContactNo From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lEmergencyStreetOne =(SELECT EmergencyStreetOne From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lEmergencyStreetTwo =(SELECT EmergencyStreetTwo From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lEmergencyStreetThree =(SELECT EmergencyStreetThree From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lEmergencyCountry =(SELECT EmergencyCountry From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lEmergencyState =(SELECT EmergencyState From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lEmergencyCity =(SELECT EmergencyCity From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       SET @lEmergencyZipCode =(SELECT EmergencyZipCode From sStudent.tStudentCommunication where StudentId=@1StudentId) 
       
       IF(@lPermanentStreetOne='' OR @lPermanentStreetOne IS NULL)
        SET @lPermanentStreetOne=NULL
        IF(@lPermanentStreetTwo='' OR @lPermanentStreetTwo IS NULL)
        SET @lPermanentStreetTwo=NULL 
         IF(@lPermanentStreetThree='' OR @lPermanentStreetThree IS NULL)
        SET @lPermanentStreetThree=NULL 
        IF(@lPermanentCountry='' OR @lPermanentCountry IS NULL)
        SET @lPermanentCountry=NULL 
          IF(@lPermanentState='' OR @lPermanentState IS NULL)
        SET @lPermanentState=NULL 
         IF(@lPermanentCity='' OR @lPermanentCity IS NULL)
        SET @lPermanentCity=NULL 
          IF(@lPermanentZipCode='' OR @lPermanentZipCode IS NULL)
        SET @lPermanentZipCode=NULL 
         IF(@lPermanentContactNo='' OR @lPermanentContactNo IS NULL)
        SET @lPermanentContactNo=NULL 
         IF(@lEmergencyStreetOne='' OR @lEmergencyStreetOne IS NULL)
        SET @lEmergencyStreetOne=NULL 
         IF(@lEmergencyStreetTwo='' OR @lEmergencyStreetTwo IS NULL)
        SET @lEmergencyStreetTwo=NULL 
        IF(@lEmergencyStreetThree='' OR @lEmergencyStreetThree IS NULL)
        SET @lEmergencyStreetThree=NULL
         IF(@lEmergencyCountry='' OR @lEmergencyCountry IS NULL)
        SET @lEmergencyCountry=NULL 
         IF(@lEmergencyState='' OR @lEmergencyState IS NULL)
        SET @lEmergencyState=NULL 
          IF(@lEmergencyCity='' OR @lEmergencyCity IS NULL)
        SET @lEmergencyCity=NULL 
         IF(@lEmergencyZipCode='' OR @lEmergencyZipCode IS NULL)
        SET @lEmergencyZipCode=NULL 
        
        
        EXEC sStudent.pStudentCommunicationAdd @1StudentId,@lPresentStreetOne,@lPresentStreetTwo,@lPresentStreetThree,
				@lPresentCountry,@lPresentState,@lPresentCity,@lPresentZipCode,@lPresentContactNo,@lPermanentStreetOne,@lPermanentStreetTwo,@lPermanentStreetThree,@lPermanentCountry,@lPermanentState,
				@lPermanentCity,@lPermanentZipCode,@lPermanentContactNo,@lEmergencyStreetOne,@lEmergencyStreetTwo,@lEmergencyStreetThree,@lEmergencyCountry,@lEmergencyState,@lEmergencyCity,@lEmergencyZipCode,@lEmergencyContactNo,@lParentContactNo,@lParentEmail,
				@lStudentContactNo,@lStudentEmail,@rUserId,@rUserId 
		
		DECLARE @lTransportModeId int
		DECLARE @lMotherTongueId int
		DECLARE @lNationalityId int
		DECLARE @lHobby nvarchar(50)
		DECLARE @lReferenceRemark nvarchar(100)
		
		SET @lTransportModeId = (SELECT TransportModeId From sStudent.tStudentOther where StudentId=@1StudentId)
		SET @lMotherTongueId = (SELECT MotherTongueId From sStudent.tStudentOther where StudentId=@1StudentId)
		SET @lNationalityId = (SELECT NationalityId From sStudent.tStudentOther where StudentId=@1StudentId)
		SET @lHobby = (SELECT Hobby From sStudent.tStudentOther where StudentId=@1StudentId)
		SET @lReferenceRemark = (SELECT ReferenceRemark From sStudent.tStudentOther where StudentId=@1StudentId)
		
		  IF(@lTransportModeId='' OR @lEmergencyZipCode IS NULL)
            SET @lTransportModeId=NULL 
           IF(@lMotherTongueId='' OR @lEmergencyZipCode IS NULL)
            SET @lMotherTongueId=NULL 
            IF(@lNationalityId='' OR @lNationalityId IS NULL)
            SET @lNationalityId=NULL 
             IF(@lHobby='' OR @lHobby IS NULL)
            SET @lHobby=NULL  
            IF(@lReferenceRemark='' OR @lReferenceRemark IS NULL)
            SET @lReferenceRemark=NULL  
				
		EXEC sStudent.pStudentOtherAdd @1StudentId,@lUIDNumber,@lDOB,@lGenderId,@lReligionId,@lBloodGroupId,@lBirthPlace,@lBirthTaluka,@lBirthDistrict,@lBirthDateInWord,
				@lFamilyCast,@lFamilySubCast,@lCastCategoryId,@lTransportModeId,@lHouseId,@lMotherTongueId,@lNationalityId,@lHobby,@rUserId,@rUserId,@lReferenceRemark,@lAdhaarNumber,@lMotherTongue,@lQuotaId,@lBirthState,@lBirthCountry
			
		
		--SET @lAdmissionDate =(SELECT AdmissionDate From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)	
		SET @lLeftStandardId =(SELECT LeftStandardId From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)	
		SET @lLeftDate =(SELECT LeftDate From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
		SET @lLCReason =(SELECT LeftReason From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
		SET @lLCProgress =(SELECT LCProgress From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
		SET @lLCConduct =(SELECT LCConduct From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
		SET @lLCNumber =(SELECT LCNumber From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
		SET @lLCDate =(SELECT LCDate From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
		SET @lLCRemark =(SELECT LCRemark From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
		
		DECLARE @lPreviousSchoolTypeId INT
		DECLARE @lPreviousStudentId bigint
		DECLARE @lAdmissionFormId bigint
		DECLARE @lAdmissionFormNumber nvarchar(20)		
		DECLARE @lAdmissionYear INT
		DECLARE @lLeftYear INT
		DECLARE @lInactiveDate date
		DECLARE @lInActiveReason nvarchar(200)
		DECLARE @lLCBook nvarchar(20)		
		DECLARE @lLCCopy tinyint
		DECLARE @lLCId bigint
		
		
	
		SET @lPreviousSchoolTypeId=(SELECT PreviousSchoolTypeId From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
		SET @lPreviousStudentId=(SELECT PreviousStudentId From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
		SET @lAdmissionFormId=(SELECT AdmissionFormId From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)

		SET @lAdmissionFormNumber=(SELECT AdmissionFormNumber From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
		--SET @lAdmissionStandardId =(SELECT AdmissionStandardId From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
		SET @lAdmissionYear =(SELECT AdmissionYear From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)

		SET @lLeftYear =(SELECT LeftYear From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
		SET @lInactiveDate =(SELECT InactiveDate From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
	    SET @lInActiveReason=(SELECT InActiveReason From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
	    SET @lLCBook=(SELECT LCBook From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
	    SET @lLCDate=(SELECT LCDate From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
	    SET @lLCCopy=(SELECT LCCopy From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
	    SET @lLCId=(SELECT LCId From sStudent.tStudentAdmission where StudentId=@1StudentId AND BatchId = @rBatchId)
	    
		--IF(@lStatusId=1)		
		--	EXEC [sStudent].[pStudentAdmissionAdd] @1StudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
		--			@lAdmissionStandardId,@lAdmissionDate,NULL,NULL,NULL,NULL,NULL,NULL,@lLCReason,@lLCProgress,@lLCConduct,NULL,
		--			@lLCNumber,@lLCDate,@lLCRemark,NULL,NULL,@rBatchId,@rUserId,@rUserId,0
		--			--EXEC [sStudent].[pStudentAdmissionAdd] @1StudentId,@lPreviousSchool,NULL,NULL,NULL,NULL,
		--			--NULL,NULL,NULL,@lLeftStandardId,@lLeftDate,NULL,NULL,NULL,@lLCReason,@lLCProgress,@lLCConduct,NULL,
		--			--@lLCNumber,@lLCDate,@lLCRemark,NULL,NULL,@rBatchId,@rUserId,@rUserId,0	
		--ELSE
			--EXEC [sStudent].[pStudentAdmissionAdd] @1StudentId,@lPreviousSchool,@lPreviousSchoolTypeId,@lPreviousStudentId,@lAdmissionFormId,@lAdmissionFormNumber,
			--		@lAdmissionStandardId,@lAdmissionDate,@lAdmissionYear,@lLeftStandardId,@lLeftDate,@lLeftYear,@lInactiveDate,@lInActiveReason,@lLCReason,@lLCProgress,@lLCConduct,@lLCBook,
			--		@lLCNumber,@lLCDate,@lLCRemark,@lLCCopy,@lLCId,@rBatchId,@rUserId,@rUserId,0			
		
     
END
		SET @lCount = @lCount - 1	
		COMMIT TRANSACTION			
END


	 SELECT 1
	END TRY
	BEGIN CATCH
	ROLLBACK TRANSACTION
	SELECT ERROR_MESSAGE(), ERROR_LINE()
	END CATCH
	
END
GO
PRINT N'Creating [sStudent].[pValidateImportStudent_New]...';


GO

Create PROCEDURE [sStudent].[pValidateImportStudent_New]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rOperation int=0   --1 For Insert,2 For Update
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lSUIdActivate nvarchar(50)=''
DECLARE @lIsActivateUniqueId bit = 0
DECLARE @lOrgGroupId int = 0
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
SELECT @lSUIdActivate = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 167 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId
	
IF (@lSUIdActivate = '') OR (@lSUIdActivate = 'False')
	SET @lIsActivateUniqueId = 0
ELSE
	SET @lIsActivateUniqueId = 1	
	
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
        @lCode nvarchar(50),
        @lClass nvarchar(100),
        @lDivision nvarchar(100),        
        @lRegistrationNumber nvarchar(20),  
        @lAdmissionDate nvarchar(15),        
        @lDOB nvarchar(15),             
        @1ReturnCode int = 1,
        @1ExistStudentCode nvarchar(max) = '',
        @1NotExistStudentCode nvarchar(max) = '',
        @1ExistStudentRegistrationNumber nvarchar(max) = '',
        @1ValidAdmissionDate nvarchar(max) = '',
        @1ValidDOB nvarchar(max) = '',
        @1DuplicateStudentCode nvarchar(max) = '',
        @1DuplicateStudentRegistrationNumber nvarchar(max) = '',
        @lSUId nvarchar(20),
        @1ExistStudentSUId nvarchar(max) = '',
        @1DuplicateStudentSUId nvarchar(max) = '',
        @lLeftDate nvarchar(15),
        @lLCDate nvarchar(15),
        @1ValidLeftDate nvarchar(max) = '',
        @1ValidLCDate nvarchar(max) = '',
        @lStatusId smallint,
        
        @lAdhaarNumber nvarchar(50),  
        @1DuplicateAdhaarNumber nvarchar(max) = '',
        
        @lUIDNumber nvarchar(50),  
        @1DuplicateUIDNumber nvarchar(max) = '',
        
        @1StudentId BIGINT = 0
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
CREATE TABLE #tTable1 
 (
		Id bigint identity,
        Code nvarchar(50),
        RegistrationNumber nvarchar(20),
        FirstName nvarchar(100),
        LastName nvarchar(100),
		Class nvarchar(100),
		Division nvarchar(100),
		AdmissionStandard nvarchar(100),
		AdmissionDate nvarchar(15),
        DOB nvarchar(15),
        Gender nvarchar(10),
        --AdmissionCategory nvarchar(100),
		Religion nvarchar(100),
		CastCategory nvarchar(100),
        SUId nvarchar(20),
        LeftDate nvarchar(15),
        LCDate nvarchar(15),
        LeftStandard nvarchar(100),
        StatusId smallint,
        AdhaarNumber varchar(100),
        UIDNumber varchar(100)
        --Id1 bigint NULL,
        --departmentId int NULL
 
  )
  INSERT INTO #tTable1
	(
	    Code,
	    RegistrationNumber, 
	    FirstName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    Religion,
	    CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber
    ) 
   SELECT
        Code,
	    RegistrationNumber, 
	    sSetup.fPortalXMLTagsReplaceReverse(FirstName) AS FirstName,
	    sSetup.fPortalXMLTagsReplaceReverse(LastName) AS LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    sSetup.fPortalXMLTagsReplaceReverse(Religion) AS Religion,
	    sSetup.fPortalXMLTagsReplaceReverse(CastCategory) AS CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber
   
   FROM OPENXML (@intDoc, '/Table/ImportStudent', 1)
   With
   (
        Code nvarchar(50) '@Code',
        RegistrationNumber nvarchar(20) '@RegistrationNumber',
        FirstName nvarchar(100) '@FirstName',
        LastName nvarchar(100) '@LastName',
		Class nvarchar(100) '@Class',
		Division nvarchar(100) '@Division',
		AdmissionStandard nvarchar(100) '@AdmissionStandard',
		AdmissionDate nvarchar(15) '@AdmissionDate',
		DOB nvarchar(15) '@DOB',
		Gender nvarchar(10) '@Gender',
		--AdmissionCategory nvarchar(100) '@AdmissionCategory',
		Religion nvarchar(100) '@Religion',
		CastCategory nvarchar(100) '@CastCategory',
		SUId nvarchar(20) '@SUId',
		LeftDate nvarchar(15) '@LeftDate',
		LCDate nvarchar(15) '@LCDate',
		LeftStandard nvarchar(100) '@LeftStandard',
		StatusId smallint '@StatusId',
		AdhaarNumber varchar(100) '@AdhaarNumber',
		UIDNumber varchar(100) '@UIDNumber'
   )   
EXEC sp_xml_removedocument @intDoc
		
SELECT @lCount =  COUNT(Id) FROM #tTable1

WHILE @lCount > 0 
  BEGIN
  
       SELECT         
         
         @lCode = Code, 
         @lRegistrationNumber = RegistrationNumber,
         @lAdmissionDate = AdmissionDate,
         @lDOB=DOB,
         @lSUId = SUId,
         @lLeftDate = LeftDate,
         @lLCDate = LCDate,
         @lStatusId = StatusId,
         @lAdhaarNumber = AdhaarNumber,
         @lUIDNumber = UIDNumber
        FROM #tTable1 WHERE Id = @lCount 

IF(@rOperation=2)
   BEGIN   
     IF Exists(SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)    
      SET @1StudentId = (SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId)
     ELSE
       SET @1NotExistStudentCode = @1NotExistStudentCode + @lCode + ','    
       print @1NotExistStudentCode
   END     
       
        
IF(@rOperation=1 OR @rOperation=0)     
 BEGIN    
    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	       END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId))         
          BEGIN
  			    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	       END	         
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT))         
          BEGIN
          
                IF(ISNULL(@lAdhaarNumber,'')!='')
                BEGIN
  			        SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
  			    END
	       END	
	     
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT))         
          BEGIN
         
                IF(ISNULL(@lUIDNumber,'')!='')
                BEGIN
                
  			        SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
  			    END    
	       END	
END


ELSE

BEGIN    

    IF Exists ((select 1 from sStudent.tStudentMaster where Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND Id<>@1StudentId))         
          BEGIN
  			    SET @1ExistStudentCode = @1ExistStudentCode + @lCode + ','
	       END	  
	IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SM.SUId COLLATE DATABASE_DEFAULT = @lSUId COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId AND SM.Id<>@1StudentId))         
          BEGIN
  			    SET @1ExistStudentSUId = @1ExistStudentSUId + @lSUId + ','
	       END	         
	IF Exists ((select 1 from sStudent.tStudentMaster where RegistrationNumber COLLATE DATABASE_DEFAULT = @lRegistrationNumber COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId AND Id<>@1StudentId))         
          BEGIN
				IF(ISNULL(@lRegistrationNumber,'')!='')
				BEGIN
  					SET @1ExistStudentRegistrationNumber = @1ExistStudentRegistrationNumber + CAST(@lRegistrationNumber as varchar(max)) + ','
				END
	       END
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.AdhaarNumber COLLATE DATABASE_DEFAULT = @lAdhaarNumber COLLATE DATABASE_DEFAULT AND SM.Id<>@1StudentId))         
          BEGIN
          
                IF(ISNULL(@lAdhaarNumber,'')!='')
                BEGIN
  			        SET @1DuplicateAdhaarNumber = @1DuplicateAdhaarNumber + @lAdhaarNumber + ','
  			    END
	       END	
	     
	IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lUIDNumber COLLATE DATABASE_DEFAULT AND SM.Id<>@1StudentId))         
          BEGIN
         
                IF(ISNULL(@lUIDNumber,'')!='')
                BEGIN
                
  			        SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
  			    END    
	       END	
END       
	       
	
	IF(ISDATE(@lAdmissionDate) = 0 AND @lAdmissionDate!='')
	BEGIN
		SET @1ValidAdmissionDate=@1ValidAdmissionDate + @lCode + '-' + @lAdmissionDate+','
	END
	IF(ISDATE(@lDOB) = 0 AND @lDOB!='')
	BEGIN
		SET @1ValidDOB=@1ValidDOB + @lCode + '-' + @lDOB+','
	END
	
	IF(ISDATE(@lLeftDate) = 0 AND @lLeftDate!='')
	BEGIN
		SET @1ValidLeftDate=@1ValidLeftDate + @lCode + '-' + @lLeftDate+','
	END
	
	IF(ISDATE(@lLCDate) = 0 AND @lLCDate!='')
	BEGIN
		SET @1ValidLCDate=@1ValidLCDate + @lCode + '-' + @lLCDate+','
	END
	
     SET @lCount = @lCount - 1	
   END	
   
   SELECT @lCount =  COUNT(Id) FROM #tTable1
 
	WHILE @lCount > 0 
		BEGIN
			SELECT         
         
			 @lClass = Class, 
			 @lDivision = Division
     
			FROM #tTable1 WHERE Id = @lCount
			    
		 IF(@rOperation=1)
		  BEGIN	
			IF NOT EXISTS (SELECT 1 FROM sSetup.tDivisionMaster DM 
					INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId 
						WHERE CM.Title COLLATE DATABASE_DEFAULT =@lClass COLLATE DATABASE_DEFAULT AND DM.Title COLLATE DATABASE_DEFAULT =@lDivision COLLATE DATABASE_DEFAULT AND DM.OrgId=@rOrgId)	
			BEGIN
				
				SELECT 'Enter proper value for Division ' + @lClass + ' ' + @lDivision AS StudentCode
				RETURN
			END
		  END	
			SET @lCount = @lCount - 1	
		END
   	      
   	    
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE Code IS NULL OR Code COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SELECT 'ID No Should not be empty' AS StudentCode
			END
		
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Number IS NULL OR Number='')
		--BEGIN
		--	SELECT 'Number Should not be empty' AS StudentCode
		--END
		--ELSE IF EXISTS(SELECT 1 FROM #tTable1 WHERE LastName IS NULL OR LastName COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'Surname Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE FirstName IS NULL OR FirstName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
		BEGIN
			SELECT 'First Name Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class IS NULL OR Class COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SELECT 'Class Should not be empty' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Division IS NULL OR Division COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SELECT 'Division Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard IS NULL OR AdmissionStandard='')
		--BEGIN
		--	SELECT 'Admission Standard Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender IS NULL OR Gender='')
		BEGIN
			SELECT 'Gender Should not be empty' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionCategory IS NULL OR AdmissionCategory='')
		--BEGIN
		--	SELECT 'Admission Category Should not be empty' AS StudentCode
		--END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionDate IS NULL OR AdmissionDate COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT) AND (@rOperation=1)
		BEGIN
			SELECT 'Admission Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Class COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId)) AND (@rOperation=1)
		BEGIN
			SELECT 'Enter proper value for Class as per Institute Setup > Class Master' AS StudentCode
		END				
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE AdmissionStandard  COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND AdmissionStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId)) AND (@rOperation=1)
		BEGIN
			SELECT 'Enter proper value for Admission Class as per Admin Tool > Institute Setup > Class Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Religion COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Religion COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tReligionMaster WHERE OrgGroupId=@rOrgGroupId))
		BEGIN
			SELECT 'Enter proper value / Check spelling for Religion per Admin Tool > Master > Religion Master' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE Gender COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND Gender COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tGenderMaster))
		BEGIN
			SELECT 'Enter proper value / Check spelling for gender ( Male / Female )' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE CastCategory COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT AND CastCategory COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sCommon.tCastCategoryMaster))
		BEGIN
			SELECT 'Enter proper value for Cast Category (OBC,SC,ST,GENERAL)' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1) AND (@rOperation=1)
		BEGIN
			SELECT 'Left Date Should not be empty or check the date format' AS StudentCode
		END
		ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE (LCDate IS NULL OR LCDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT) AND @lStatusId<>1)
		BEGIN
			SELECT 'LC Date Should not be empty or check the date format' AS StudentCode
		END
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE  LeftStandard COLLATE DATABASE_DEFAULT NOT IN(SELECT Title FROM sSetup.tClassMaster WHERE OrgId=@rOrgId) AND @lLeftDate!='')
		--BEGIN
		--	SELECT 'Enter proper value for Left Standard as per Institute Setup > Class Master' AS StudentCode
		--END	
		--ELSE IF EXISTS(SELECT 1 fROM #tTable1 WHERE LeftDate IS NULL OR LeftDate COLLATE DATABASE_DEFAULT ='' COLLATE DATABASE_DEFAULT AND LeftStandard COLLATE DATABASE_DEFAULT !='' COLLATE DATABASE_DEFAULT)
		--BEGIN
		--	SELECT 'LeftDate Should not be empty or check the date format' AS StudentCode
		--END
		ELSE
		BEGIN
		
		IF (@1NotExistStudentCode IS NOT NULL AND @1NotExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
		
			SET @1NotExistStudentCode = 'Not Exist Code ' + @1NotExistStudentCode
			Select @1NotExistStudentCode AS StudentCode
		END		
		
		
		SELECT @1DuplicateStudentCode=COALESCE(@1DuplicateStudentCode ,'') + Code + ',' FROM #tTable1 GROUP BY Code HAVING ( COUNT(Code) > 1 )	
		
	   
			
		SELECT @1DuplicateStudentSUId=COALESCE(@1DuplicateStudentSUId ,'') + SUId + ',' FROM #tTable1 GROUP BY SUId HAVING ( COUNT(SUId) > 1 )	
			IF(@1DuplicateStudentSUId IS NOT NULL AND @1DuplicateStudentSUId != '' AND @lIsActivateUniqueId=1)
				BEGIN
				
					SET @1DuplicateStudentSUId = 'Duplicate SUId ' + @1DuplicateStudentSUId
					SELECT @1DuplicateStudentSUId AS StudentCode
				END
			ELSE IF(@1DuplicateStudentCode IS NOT NULL AND @1DuplicateStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
				  
					SET @1DuplicateStudentCode = 'Duplicate Code ' + @1DuplicateStudentCode
					
					SELECT @1DuplicateStudentCode AS StudentCode
				END
			ELSE			
				BEGIN
				SELECT @1DuplicateStudentRegistrationNumber=COALESCE(@1DuplicateStudentRegistrationNumber ,'') + CONVERT(VARCHAR(20),RegistrationNumber) + ',' FROM #tTable1 GROUP BY RegistrationNumber HAVING ( COUNT(RegistrationNumber) > 1 AND ISNULL(RegistrationNumber,'')!='')	
				IF(@1DuplicateStudentRegistrationNumber IS NOT NULL AND @1DuplicateStudentRegistrationNumber  COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
				BEGIN
					SET @1DuplicateStudentRegistrationNumber = 'Duplicate Registration Number ' + @1DuplicateStudentRegistrationNumber
					SELECT @1DuplicateStudentRegistrationNumber AS StudentCode
				END
		
		ELSE IF (@1DuplicateAdhaarNumber IS NOT NULL AND @1DuplicateAdhaarNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
		  
			SET @1DuplicateAdhaarNumber = 'Exist Adhaar Number ' + @1DuplicateAdhaarNumber
			Select @1DuplicateAdhaarNumber AS StudentCode
		END
		
		
		ELSE IF (@1DuplicateUIDNumber IS NOT NULL AND @1DuplicateUIDNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1DuplicateUIDNumber = 'Exist UID Number ' + @1DuplicateUIDNumber
			Select @1DuplicateUIDNumber AS StudentCode
		END
		
		
		ELSE IF((@1ExistStudentSUId IS NULL OR @1ExistStudentSUId = '' OR @lIsActivateUniqueId=0) AND (@1ExistStudentCode IS NULL OR @1ExistStudentCode = '') AND (@1ExistStudentRegistrationNumber IS NULL OR @1ExistStudentRegistrationNumber = '')
		AND (@1ValidAdmissionDate IS NULL OR @1ValidAdmissionDate = '') AND (@1ValidDOB IS NULL OR @1ValidDOB = ''))
		BEGIN
		
			SELECT '' AS StudentCode
		END
		ELSE IF (@1ExistStudentSUId IS NOT NULL AND @1ExistStudentSUId != '' AND @lIsActivateUniqueId=1)
		BEGIN
			SET @1ExistStudentSUId = 'Exist SUId ' + @1ExistStudentSUId
			Select @1ExistStudentSUId AS StudentCode
		END
		
		
		
		
		ELSE IF (@1ExistStudentCode IS NOT NULL AND @1ExistStudentCode COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentCode = 'Exist Code ' + @1ExistStudentCode
			Select @1ExistStudentCode AS StudentCode
		END
		
		ELSE IF (@1ExistStudentRegistrationNumber IS NOT NULL AND @1ExistStudentRegistrationNumber COLLATE DATABASE_DEFAULT != '' COLLATE DATABASE_DEFAULT)
		BEGIN
			SET @1ExistStudentRegistrationNumber = 'Exist Registration Number ' + @1ExistStudentRegistrationNumber
			Select @1ExistStudentRegistrationNumber AS StudentCode
		END
		ELSE IF (@1ValidAdmissionDate IS NOT NULL AND @1ValidAdmissionDate != '')
		BEGIN
			SET @1ValidAdmissionDate = 'Wrong Admission Date ' + @1ValidAdmissionDate
			Select @1ValidAdmissionDate AS StudentCode
		END
		ELSE IF (@1ValidDOB IS NOT NULL AND @1ValidDOB != '')
		BEGIN
			SET @1ValidDOB = 'Wrong DOB ' + @1ValidDOB
			Select @1ValidDOB AS StudentCode
		END
		ELSE IF (@1ValidLeftDate IS NOT NULL AND @1ValidLeftDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLeftDate = 'Wrong LeftDate ' + @1ValidLeftDate
			Select @1ValidLeftDate AS StudentCode
		END
		ELSE IF (@1ValidLCDate IS NOT NULL AND @1ValidLCDate != '' AND @lLCDate!='')
		BEGIN
			SET @1ValidLCDate = 'Wrong LCDate ' + @1ValidLCDate
			Select @1ValidLCDate AS StudentCode
		END
		
		
		END
		END
END
GO
PRINT N'Creating [sTimetable].[pImportTimeTableFromExcel]...';


GO
CREATE PROCEDURE [sTimetable].[pImportTimeTableFromExcel]
	@rOrgGroupId int,
	@rStrXml nvarchar(MAX),
	@rTimeTableSchemaID int,
	@rOrgId int
   
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	
SET @rStrXml=REPLACE(@rStrXml,'&','AND') 
DECLARE @lInterrorCode INT,	@intDoc INT
DECLARE @lNextNumber BIGINT
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rStrXml
	 
	IF EXISTS(SELECT 1 FROM [sTimetable].[tTimeTable] WHERE TimeTableSchemaID=@rTimeTableSchemaID) 	
	 BEGIN   	    
	    SELECT -101 AS Result
	    RETURN;
	 END
	 
  BEGIN
	 
	CREATE TABLE #TempTimeTable
	(
		[AutoId] int identity,
		[RowNumber] [int] NULL,
		[TimeTableSchemaId] [int] NULL,		
		[EmployeeId] [bigint] NULL,
		[DivisionId] [int] NULL,
		[SubjectId] [int] NULL,
		[DayId] [int] NULL,
		[LectureNumber] [int] NULL
	)	
	 
	INSERT INTO #TempTimeTable 
	SELECT ROW_NUMBER() OVER(Partition by LectureNumber,DayId,DivisionId ORDER BY EmployeeId) AS RowNumber,@rTimeTableSchemaID,* FROM OPENXML (@intDoc, '/Table/TimeTableDetail', 1)
	--SELECT @rTimeTableSchemaID,* FROM OPENXML (@intDoc, '/Table/TimeTableDetail', 1)
	WITH(			
			EmployeeId bigint '@EmployeeId',
			DivisionId int '@DivisionId',
			SubjectId int '@SubjectId',
			DayId int '@DayId',		
			LectureNumber int '@LectureNumber'
		)	
	
	 CREATE TABLE #TempHeaderTimeTable
	 (
	    [AutoId] int identity,
	    [TimeTableSchemaId] [int] NULL,		
		[EmployeeId] [bigint] NULL,
		[DivisionId] [int] NULL,
		[SubjectId] [int] NULL,
		[DayId] [int] NULL,
		[LectureNumber] [int] NULL
	 )
	 
	 INSERT INTO #TempHeaderTimeTable
	 SELECT TimeTableSchemaId,EmployeeId,DivisionId,SubjectId,DayId,LectureNumber FROM #TempTimeTable WHERE RowNumber=1
	 
	 --SELECT *from #TempHeaderTimeTable
	 
	 DECLARE @lTimeTableHeaderCount int
	 SELECT @lTimeTableHeaderCount = COUNT(AutoId) FROM #TempHeaderTimeTable
		
		WHILE (@lTimeTableHeaderCount > 0)
		 BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sTimetable.tTimeTable', 0, 1, 1,@outNextNumber = @lNextNumber output
			
			INSERT INTO sTimetable.tTimeTable
				(
					Id,
					TimeTableSchemaID,
					EmployeeId,
					DivisionId,
					SubjectId,
					DayId,
					LectureNumber
				)	
			SELECT
					@lNextNumber,
					@rTimeTableSchemaID,
					EmployeeId,
					DivisionId,
					SubjectId,
					DayId,
					LectureNumber
			FROM #TempHeaderTimeTable WHERE AutoId = @lTimeTableHeaderCount	
			
			
			Declare @lDivisionId int
			Declare @lDayId int
			Declare @lLectureNumber int
			
			SET @lDivisionId=(SELECT DivisionId FROM #TempHeaderTimeTable WHERE AutoId = @lTimeTableHeaderCount)
			SET @lDayId=(SELECT DayId FROM #TempHeaderTimeTable WHERE AutoId = @lTimeTableHeaderCount)
			SET @lLectureNumber=(SELECT LectureNumber FROM #TempHeaderTimeTable WHERE AutoId = @lTimeTableHeaderCount)
			
			
			INSERT INTO sTimetable.tTimeTableDetail
			 SELECT @lNextNumber,EmployeeId,SubjectId,0 
			      FROM #TempTimeTable 
			  WHERE DivisionId=@lDivisionId AND DayId=@lDayId AND LectureNumber=@lLectureNumber AND RowNumber<>1
			
			
			SET @lTimeTableHeaderCount = @lTimeTableHeaderCount -1	
			
	     END
	      
        SELECT 1 AS Result
	 END	
		
END
GO

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