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

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


GO
ALTER TABLE [sAssessment].[tTempAllExam] ALTER COLUMN [SUId] NVARCHAR (25) NULL;


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


GO
ALTER TABLE [sFee].[tExemptionTypeMaster]
    ADD [Remark] NVARCHAR (500) NULL;


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


GO
ALTER TABLE [sHrm].[tEmployeeCustomSearch]
    ADD [DropDownStatusId] INT            NULL,
        [OrderBy]          NVARCHAR (MAX) NULL;


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


GO
ALTER TABLE [sStudent].[tStudentMaster] ALTER COLUMN [SUId] NVARCHAR (50) NULL;


GO
PRINT N'Creating [dbo].[tAlertRestrictionAllocation]...';


GO
CREATE TABLE [dbo].[tAlertRestrictionAllocation] (
    [EmpCode]       BIGINT   NULL,
    [ShiftDay]      INT      NULL,
    [FromShiftdate] DATETIME NULL,
    [ToShiftDate]   DATETIME NULL
);
GO

 
GO
PRINT N'Creating [sBiometric].[fBiometricTempMonthTransGet]...';


GO
CREATE FUNCTION [sBiometric].[fBiometricTempMonthTransGet]  (
    @rOrgId int ,
	@rDeptId int , 
	@rFromDate DateTime,
	@rToDate DateTime, 
	@rEmployeeId bigint
)

RETURNS @TempMonthTrans TABLE   
 (  
 Id int Identity,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20),
 ShiftName nvarchar(25) 
 )  
AS
Begin


  INSERT INTO @TempMonthTrans
SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt) ,01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt),01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt) ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt) ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN = '00:00' THEN 'H'   
			 WHEN (D01 = 'W' OR D01 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt) ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt) ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN = '00:00' THEN 'A' 
			 WHEN (D01 = 'H' OR D01 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN = '00:00' THEN 'A' 
			 ELSE D01 END ,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S  
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	
	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN = '00:00' THEN 'H'   
			 WHEN (D02 = 'W' OR D02 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN = '00:00' THEN 'A' 
			 WHEN (D02 = 'H' OR D02 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN = '00:00' THEN 'A' 
			 ELSE D02 END ,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S 
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN = '00:00' THEN 'H'   
			 WHEN (D03 = 'W' OR D03 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN = '00:00' THEN 'A' 
			 WHEN (D03 = 'H' OR D03 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN = '00:00' THEN 'A' 
			 ELSE D03 END ,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S 
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN = '00:00' THEN 'H'   
			 WHEN (D04 = 'W' OR D04 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN = '00:00' THEN 'A' 
			 WHEN (D04 = 'H' OR D04 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN = '00:00' THEN 'A' 
			 ELSE D04 END,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S 
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN = '00:00' THEN 'H'   
			 WHEN (D05 = 'W' OR D05 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN = '00:00' THEN 'A' 
			 WHEN (D05 = 'H' OR D05 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN = '00:00' THEN 'A' 
			 ELSE D05 END ,D05_IN,D05_OUT,D05_O,D01_L,D05_T,D05_E,D05_S 
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN = '00:00' THEN 'H'   
			 WHEN D06 = 'W' OR D06 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN = '00:00' THEN 'A' 
			 WHEN D06 = 'H' OR D06 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN = '00:00' THEN 'A' 
			 ELSE D06 END,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S  
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN = '00:00' THEN 'H'   
			 WHEN D07 = 'W' OR D07 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN = '00:00' THEN 'A' 
			 WHEN D07 = 'H' OR D07 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN = '00:00' THEN 'A' 
			 ELSE D07 END,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S 
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN = '00:00' THEN 'H'   
			 WHEN D08 = 'W' OR D08 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN = '00:00' THEN 'A' 
			 WHEN D08 = 'H' OR D08 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN = '00:00' THEN 'A' 
			 ELSE D08 END ,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN = '00:00' THEN 'H'   
			 WHEN D09 = 'W' OR D09 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN = '00:00' THEN 'A' 
			 WHEN D09 = 'H' OR D09 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN = '00:00' THEN 'A' 
			 ELSE D09 END ,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN = '00:00' THEN 'H'   
			 WHEN D10 = 'W' OR D10 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN = '00:00' THEN 'A' 
			 WHEN D10 = 'H' OR D10 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN = '00:00' THEN 'A' 
			 ELSE D10 END ,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1	

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN = '00:00' THEN 'H'   
			 WHEN D11 = 'W' OR D11 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN = '00:00' THEN 'A' 
			 WHEN D11 = 'H' OR D11 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN = '00:00' THEN 'A' 
			 ELSE D11 END ,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN = '00:00' THEN 'H'   
			 WHEN D12 = 'W' OR D12 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN = '00:00' THEN 'A' 
			 WHEN D12 = 'H' OR D12 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN = '00:00' THEN 'A' 
			 ELSE D12 END ,	D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN = '00:00' THEN 'H'   
			 WHEN D13 = 'W' OR D13 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN = '00:00' THEN 'A' 
			 WHEN D13 = 'H' OR D13 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN = '00:00' THEN 'A' 
			 ELSE D13 END ,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN = '00:00' THEN 'H'   
			 WHEN D14 = 'W' OR D14 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN = '00:00' THEN 'A' 
			 WHEN D14 = 'H' OR D14 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN = '00:00' THEN 'A' 
			 ELSE D14 END ,	D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN = '00:00' THEN 'H'   
			 WHEN D15 = 'W' OR D15 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN = '00:00' THEN 'A' 
			 WHEN D15 = 'H' OR D15 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN = '00:00' THEN 'A' 
			 ELSE D15 END ,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN = '00:00' THEN 'H'   
			 WHEN D16 = 'W' OR D16 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN = '00:00' THEN 'A' 
			 WHEN D16 = 'H' OR D16 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN = '00:00' THEN 'A' 
			 ELSE D16 END ,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN = '00:00' THEN 'H'   
			 WHEN D17 = 'W' OR D17 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN = '00:00' THEN 'A' 
			 WHEN D17 = 'H' OR D17 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN = '00:00' THEN 'A' 
			 ELSE D17 END ,	D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN = '00:00' THEN 'H'   
			 WHEN D18 = 'W' OR D18 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN = '00:00' THEN 'A' 
			 WHEN D18 = 'H' OR D18 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN = '00:00' THEN 'A' 
			 ELSE D18 END ,	D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S 
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN = '00:00' THEN 'H'   
			 WHEN D19 = 'W' OR D19 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN = '00:00' THEN 'A' 
			 WHEN D19 = 'H' OR D19 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN = '00:00' THEN 'A' 
			 ELSE D19 END ,	D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN = '00:00' THEN 'H'   
			 WHEN D20 = 'W' OR D20 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN = '00:00' THEN 'A' 
			 WHEN D20 = 'H' OR D20 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN = '00:00' THEN 'A' 
			 ELSE D20 END ,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN = '00:00' THEN 'H'   
			 WHEN D21 = 'W' OR D21 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN = '00:00' THEN 'A' 
			 WHEN D21 = 'H' OR D21 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN = '00:00' THEN 'A' 
			 ELSE D21 END ,	D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN = '00:00' THEN 'H'   
			 WHEN D22 = 'W' OR D22 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN = '00:00' THEN 'A' 
			 WHEN D22 = 'H' OR D22 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN = '00:00' THEN 'A' 
			 ELSE D22 END ,	D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN = '00:00' THEN 'H'   
			 WHEN D23 = 'W' OR D23 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN = '00:00' THEN 'A' 
			 WHEN D23 = 'H' OR D23 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN = '00:00' THEN 'A' 
			 ELSE D23 END ,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN = '00:00' THEN 'H'   
			 WHEN D24 = 'W' OR D24 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN = '00:00' THEN 'A' 
			 WHEN D24 = 'H' OR D24 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN = '00:00' THEN 'A' 
			 ELSE D24 END ,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN = '00:00' THEN 'H'   
			 WHEN (D25 = 'W' OR D25 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN = '00:00' THEN 'A' 
			 WHEN (D25 = 'H' OR D25 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN = '00:00' THEN 'A' 
			 ELSE D25 END ,	D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN = '00:00' THEN 'H'   
			 WHEN D26 = 'W' OR D26 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN = '00:00' THEN 'A' 
			 WHEN D26 = 'H' OR D26 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN = '00:00' THEN 'A' 
			 ELSE D26 END ,	D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN = '00:00' THEN 'H'   
			 WHEN D27 = 'W' OR D27 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN = '00:00' THEN 'A' 
			 WHEN D27 = 'H' OR D27 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN = '00:00' THEN 'A' 
			 ELSE D27 END ,	D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S
			 FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN = '00:00' THEN 'H'   
			 WHEN D28 = 'W' OR D28 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN = '00:00' THEN 'A' 
			 WHEN D28 = 'H' OR D28 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN = '00:00' THEN 'A' 
			 ELSE D28 END ,	D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1


	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](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN = '00:00' THEN 'H'   
			 WHEN D29 = 'W' OR D29 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN = '00:00' THEN 'A' 
			 WHEN D29 = 'H' OR D29 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN = '00:00' THEN 'A' 
			 ELSE D29 END ,	D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	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](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN = '00:00' THEN 'H'   
			 WHEN D30 = 'W' OR D30 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN = '00:00' THEN 'A' 
			 WHEN D30 = 'H' OR D30 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN = '00:00' THEN 'A' 
			 ELSE D30 END ,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	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](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN != '00:00' THEN 'PH'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN = '00:00' THEN 'H'   
			 WHEN D31 = 'W' OR D31 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN = '00:00' THEN 'A' 
			 WHEN D31 = 'H' OR D31 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Dt) ,MONTH(TM.Attn_Dt)  ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN = '00:00' THEN 'A' 
			 ELSE D31 END ,	D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S
			  FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END

	
	return

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


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


GO
ALTER VIEW [sCertificate].[vPrintTemplateStudentDetail]
 
AS  
  
SELECT 
			A.Id AS AcademicId,
		    DivM.Id AS DivisionId,
		    DivM.DisplayTitle AS DivisionName,
		    CM.Id AS ClassId,
		    CM.DisplayTitle AS ClassName,
		    CM.DisplayTitle+'-'+DivM.DisplayTitle AS ClassDivision,
		    DM.Id AS DepartmentId,
		    DM.DisplayTitle AS DepartmentName,
		    SM.FirstName AS FirstName,
		    SM.MiddleName AS MiddleName,
		    SM.LastName AS LastName,
		    SM.Code,
		    A.RollNo,
		    A.BatchId,
		    BM.Title AS BatchName,
		    CONVERT(VARCHAR(10),SO.DateOfBirth,103) AS DateOfBirth,
		    SA.PreviousSchool,
			ISNULL(GM.Title,'') AS Gender,
			SO.FamilyCast AS Caste,  
			SO.FamilySubCast AS SubCaste,
			SO.BirthPlace,
			SO.BirthDateInWord AS DOBInWords,
			SA.PreviousLCDate AS PreviousLCDate,
			SA.PreviousLCResult AS PreviousLCResult,
			SA.PreviousLCNumber AS PreviousLCNumber,
			SA.AdmissionNumber AS OldGRNo,
			SA.PassingYear AS PreviousSchoolYear,			
			SA.PreviousStandard AS PreviousStandard,
			SO.BirthTaluka AS BirthTaluka,
			SO.BirthState AS BirthState,
			SO.BirthCountry AS BirthCountry,
			SO.BirthDistrict AS BirthDistrict,
			ISNULL(SC.PermanentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'')+' '+ISNULL(SC.PresentZipCode,'') AS Address,
			SC.ParentContactNo AS ContactNo,		
			SC.ParentEmail AS Email,
			ISNULL(RM.Title,'') AS Religion,
			SO.FamilyCast AS FamilyCaste,
			ISNULL(CCM.Title,'') AS CasteCategory,
			ISNULL(NM.Title,'') AS Nationality,
			ISNULL(SO.MotherTongue,'') AS MotherTongue,
			ISNULL(BGM.Title,'') As BloodGroup,
			ISNULL(SO.AdhaarNumber,'') AS AadhaarNumber,
			ISNULL(PDCM.Title,'') AS PhysicalCategory,
			SF.FatherName AS FatherName,
			SF.FatherQualification AS FatherQualification,
			SF.FatherOccupation AS FatherOccupation,
			SF.FatherContactNo AS FatherContactNo,
			SF.FatherOfficeAddress AS FatherOfficeAddress,
			SF.FatherMail AS FatherEmail,
			SF.IsFatherExStudent AS FatherExStudent,
			SF.FatherPassOutYear AS FatherPassingYear,
			SF.FatherIncome AS FatherIncome,
			SF.MotherName AS MotherName,
			SF.MotherQualification AS MotherQualification,
			SF.MotherOccupation AS MotherOccupation,
			SF.MotherContactNo AS MotherContactNo,
			SF.MotherOfficeAddress AS MotherOfficeAddress,
			SF.MotherMail AS MotherEmail,
			SF.IsMotherExStudent AS MotherExStudent,
			SF.MotherPassOutYear AS MotherPassingYear,
			SF.MotherIncome AS MotherIncome,
			SA.AdmissionDate AS AdmissionDate,
			CM1.Title AS AdmissionStandard,
			SO.UIDNumber AS UIDNumber,
			ISNULL(StuA.BankAccountHolderName,'') AS BankHolderName,
			ISNULL(StuA.BankName,'') AS BankName,
			ISNULL(StuA.BankBranch,'') AS BankBranch,
			ISNULL(StuA.BankIFSCcode,'') AS BankIFSCcode,
			ISNULL(StuA.BankAccountNumber,'') AS BankAccountNo,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo

	FROM 
			sStudent.tAcademic A
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=SM.Id
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DivM ON DivM.Id=A.DivisionId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id = CM.DepartmentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = A.StudentId
			LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id=SO.BloodGroupId
			LEFT JOIN sCommon.tCastCategoryMaster CCM  ON CCM.Id=SO.CastCategoryId
			LEFT JoIN sCommon.tReligionMaster RM ON RM.Id=SO.ReligionId
			LEFT JOIN sCommon.tMotherTongueMaster MT ON MT.Id = SO.MotherTongueId
			LEFT JOIN sCommon.tCountryMaster NM ON NM.Id = SO.NationalityId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = A.StudentId
			LEFT JOIN sStudent.tStudentHealth SH ON SH.StudentId = A.StudentId
			LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
			LEFT JOIN sSetup.tClassMaster CM1 ON CM1.Id=SA.AdmissionStandardId
			LEFT JOIN sStudent.tStudentAdditional StuA ON StuA.StudentId = SM.Id
			LEFT JOIN sStudent.tStudentImages SI ON SM.Id = SI.StudentId
GO
PRINT N'Altering [sHrm].[vEmployeeColumnName]...';


GO

 



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


GO

 

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


 
GO
PRINT N'Altering [dbo].[pTransportStudentSearchGet]...';


GO
ALTER PROCEDURE [dbo].[pTransportStudentSearchGet]
	 
	 @rOrgId int,
	 @rTransportId int,
	 @rBusrouteId int,
	 @rStudentName nvarchar(100),
	 @rStudentCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int,
	 @rSUId nvarchar(max)='',
	 @rDepartmentId  int,
	 @rSurName nvarchar(100)='',
	 @rPickUpId int,
	 @rStatusId int = 0,
	 @rIsStudentImage bit = 0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 		
			IF(@rIsStudentImage = 0)
			BEGIN
				SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS BusRoute,
				ISNULL(BM1.Title,'') AS DropRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint ,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint ,
				ISnull(SD.SUID,'') AS SUID,
				0x00000000 AS StudentPhoto,
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				ISNULL(SC.ParentEmail,'') AS EMail
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				LEFT JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId 
				--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SD.StudentId
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
				AND ((SD.DepartmentId = @rDepartmentId ) OR (ISNULL(@rDepartmentId,0) = 0))
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
				AND ((SD.Lastname like @rSurName + '%') OR (ISNULL(@rSurName,'') = ''))
				AND ((BDM.Id=@rPickUpId) OR (@rPickUpId=0))
				AND ((SD.StatusId=@rStatusId) OR (@rStatusId=0))
				AND BMM.IsInContext = 1
				order by SD.ClassId,SD.Suid,SD.Code
			END
			IF(@rIsStudentImage = 1)
			BEGIN
				SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS BusRoute ,
				ISNULL(BM.Title,'') AS DropRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint ,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint ,
				ISnull(SD.SUID,'') AS SUID,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				ISNULL(SC.ParentEmail,'') AS EMail
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SD.StudentId
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
				AND ((SD.DepartmentId = @rDepartmentId ) OR (ISNULL(@rDepartmentId,0) = 0))
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
				AND ((SD.Lastname like @rSurName + '%') OR (ISNULL(@rSurName,'') = ''))
				AND ((BDM.Id=@rPickUpId) OR (@rPickUpId=0))
				AND ((SD.StatusId=@rStatusId) OR (@rStatusId=0))
				AND BMM.IsInContext = 1
				order by SD.ClassId,SD.Suid,SD.Code
			END
END
GO
PRINT N'Altering [sAcademic].[pGetLessonPlanApi]...';


GO
ALTER PROCEDURE [sAcademic].[pGetLessonPlanApi]

	 @rAcademicId bigint,
	 @rBatchId int,
	 @rDivisionId int,
	 @rSubjectId int,
	 @rFromDate datetime='',
     @rToDate datetime='',
	 @rIsCompleted int = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
    --for IsCompleted false
	IF (@rIsCompleted = 2)
	BEGIN
	 SET @rIsCompleted = 0
	END
	--for IsCompleted true
	ELSE IF(@rIsCompleted = 1)
	BEGIN
		SET @rIsCompleted = 1 
	END
	--for IsCompleted All
	ELSE
	BEGIN
	SET @rIsCompleted = 2
	END

	--Select @rIsCompleted
	SELECT 
		TM.Title AS TopicName,
		LP.NoOfPeriodRequired,
		LP.Objective,
		LP.IndicativeHomework,
		LP.Summary,
		LP.StartDate,
		LP.EndDate,
		--LP.IsCompleted,			
		CASE WHEN (LP.IsCompleted = 'True') THEN  'Completed' ELSE 'InCompleted' END AS IsCompleted,
		LP.LearningExperience,
		LP.ToolsAndTechniques,
		LP.EssentialMaterial,
		LP.AssessmentQuestion,
		LP.TeacherExample,
		LP.GuidedPractice,
		LP.IndependentPractice,
		LP.SubTopic,
		Em.FirstName+' '+EM.LastName AS TeacherName,
		LP.IsCompleted ,
		LP.Session ,
		LP.TrainingMethod ,
		LP.PeriodCount,
		SM.Title AS SubjectName
	FROM 
		--sAcademic.tLessonPlan LP
		--INNER JOIN  sAcademic.tTopicMaster TM ON TM.Id = LP.TopicId
		--INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = @rSubjectId
		--INNER JOIN sStudent.tAcademic AM ON AM.BatchId = @rBatchId AND AM.DivisionId = @rDivisionId
		--Left Join  sHrm.tEmployeeMaster EM ON Em.Id=Lp.EmployeeId
			sAcademic.tLessonPlan LP
		INNER JOIN  sAcademic.tTopicMaster TM ON TM.Id = LP.TopicId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TM.SubjectId
		INNER JOIN sStudent.tAcademic AM ON AM.BatchId = LP.BatchId AND AM.DivisionId = LP.DivisionId
		Left Join  sHrm.tEmployeeMaster EM ON Em.Id=Lp.EmployeeId
		
	WHERE 
		((LP.DivisionId = @rDivisionId)  OR (@rDivisionId = 0))
		AND ((LP.BatchId = @rBatchId) OR (@rBatchId = 0))
		--AND ((SM.Id = @rSubjectId) OR (SM.Id = 0))
		AND ((TM.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
		AND AM.Id = @rAcademicId
		--AND (LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='')
		 --   AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		AND ((LP.StartDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.StartDate <= @rToDate OR ISNULL(@rToDate,'')='')
		OR (LP.EndDate >= @rFromDate OR ISNULL(@rFromDate,'')='' )AND (LP.EndDate <= @rToDate OR ISNULL(@rToDate,'')='')
		)
		AND ((LP.IsCompleted = @rIsCompleted) OR (@rIsCompleted = 2))
		
	ORDER BY SM.Id
	
END
GO
PRINT N'Altering [sActivity].[pMyActivityGet]...';


GO
ALTER PROCEDURE [sActivity].[pMyActivityGet]
	 
	 @rSourceTypeId smallint,
	 @rSourceId bigint,
	 @rOrgId smallint,
	 @rBatchId int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON


BEGIN 
	IF(@rSourceTypeId=2003)
	BEGIN
		SELECT
				ISNULL(A.Id,0) as ActivityId,
				A.Title,
				A.ActivityTypeId,
				ATM.Title AS ActivityType,
				A.FromDate,
				A.ToDate,
				A.Remark,
				A.IsGroup,
				AP.Remark AS UserWiseRemark
		FROM 
				sActivity.tActivity A 
				INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
				INNER JOIN sStudent.vStudentAcademic SA ON SA.StudentId=@rSourceId AND SA.BatchId = @rBatchId
			    INNER JOIN sActivity.tActivityParticipant AP ON AP.ActivityId=A.Id AND AP.SourceTypeId=2003
			
		WHERE 
				AP.SourceTypeId = 2003 AND AP.SourceId = @rSourceId  AND A.BatchId=@rBatchId
		--	(A.Id IN(SELECT ActivityId FROM sActivity.tActivityParticipant WHERE SourceTypeId=2003) AND 
		--		SourceId=(SELECT AcademicId FROM sStudent.vStudentAcademic WHERE StudentId=@rSourceId 
		--			AND OrgId=@rOrgId AND BatchId=@rBatchId))
		--AND (A.BatchId=@rBatchId)
		ORDER BY A.FromDate DESC
	END
	ELSE
	BEGIN
		SELECT 
				ISNULL(A.Id,0) as ActivityId,
				A.Title,
				A.ActivityTypeId,
				ATM.Title AS ActivityType,
				A.FromDate,
				A.ToDate,
				A.Remark,
				A.IsGroup,
				AP.Remark AS UserWiseRemark
		FROM 
				sActivity.tActivity A 
				INNER JOIN sActivity.tActivityTypeMaster ATM ON ATM.Id=A.ActivityTypeId
			INNER JOIN sActivity.tActivityParticipant AP ON AP.ActivityId=A.Id AND AP.SourceId=@rSourceId AND AP.SourceTypeId=95
		--WHERE 
	  
		--	(A.Id IN(SELECT ActivityId FROM sActivity.tActivityParticipant WHERE SourceTypeId=95 AND 
		--		SourceId=(SELECT Id FROM sHrm.vExtEmployeeJobDetail WHERE EmployeeId=@rSourceId)))
		--AND (A.BatchId=@rBatchId)
		ORDER BY A.FromDate DESC
	END
END
GO
PRINT N'Altering [sAdmission].[pAdmissionGenerateReport]...';


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

AS
BEGIN
	 
	SET NOCOUNT ON;

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

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

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






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

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

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

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


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricFirstInTimeGet]
	 	 @rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)='',
		@rOrgId int,
		@rIntervalTime int
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
					SourceId bigint NOT NULL,
					In_Out_Time [datetime] NOT NULL,
					SourceTypeId int NOT NULL,
					CreatedDateTime [datetime] NOT NULL,
				)
			insert into #tTable
			select SourceId,min(In_Out_Time),SourceTypeId,min(CreatedDateTime) 
			from [sBiometric].[tCloudTransactionData] 
			WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]()) AND SourceTypeId=95 Group by SourceId,SourceTypeId
	
			--select * from #tTable

			SELECT 
				EM.MobileNumber AS MobileNo,	
				EM.CompanyEmail AS EmailId,
				replace (
				replace (
				replace (
				replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MsgText,
				@rSubject AS Subject,
				95 AS ReceiverSourceTypeId,
				EM.EmployeeId AS ReceiverSourceId,
				EM.EmployeeName AS EmployeeName,
				ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				95 AS SourceTypeId,
				EM.EmployeeId AS SourceId,
				EM.OrgId,
				OM.OrgGroupId
			FROM 
				#tTable temp
				Inner join sHrm.vEmployeeCommonDetail EM ON temp.SourceId=EM.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
			WHERE
				temp.CreatedDateTime >= DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]())
				AND EM.OrgID =@rOrgId

			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH


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


GO

ALTER PROCEDURE [sAlert].[pEmployeeBiometricLateTimeGet]
	 	 
	 	 @rOrgId int,
		 @rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()

	DECLARE @lDay int = 0
	SET @lDay = DAY(sCommon.fGetDate())

	DECLARE @lColumnName varchar(10) = ''
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'

	DECLARE @lGetConfigTime nvarchar(20) = ''
	SELECT @lGetConfigTime =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 398 AND SourceId = @rOrgId

	IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query = 'SELECT
					EC.MobileNumber AS MobileNo,	
					EC.CompanyEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[EmployeeName]'',EC.EmployeeName),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					95 AS ReceiverSourceTypeId,
					EC.EmployeeId AS ReceiverSourceId,
					EC.EmployeeName AS EmployeeName,
					ISNULL(EC1.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					95 AS SourceTypeId,
					EC.EmployeeId AS SourceId,
					EC.OrgId,
					OM.OrgGroupId,
					EM.Id AS EmployeeId,
					EM.Code,
					ISNULL(EM.FirstName, '''') + '' '' + ISNULL(EM.LastName, '''') AS  EmployeeName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle
		FROM 
				sHrm.tEmployeeMaster EM
				Inner join sHrm.vEmployeeCommonDetail EC ON EM.Id=EC.EmployeeId
				LEFT JOIN sHrm.tEmployeeCommunications EC1 ON EC1.EmployeeId = EC.EmployeeId
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = EM.Id AND MT.SourceTypeId = 95 
				INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
		WHERE
				EM.OrgID = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MONTH(MT.Attn_dt) = MONTH('''+CONVERT(nvarchar(20),@lDate)+''')
				AND '+@lColumnName+' > '''+@lGetConfigTime+'''
				AND EM.StatusId = 7	'
		--print (@Query)
		execute (@Query)	
	END

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


GO
 
 
 
ALTER PROCEDURE [sAlert].[pEventTemplateListGet]

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

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

END

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


GO

ALTER proc [sAlert].[pGetWebNotificationList]
@rSourceId bigint,
@rSourceTypeId int,
@rIsTop bit = 1

AS
BEGIN
	DECLARE @lnotifictiongrid NVARCHAR(max)=''

IF(@rIsTop = 1)
BEGIN
SELECT Top 10 @lnotifictiongrid = @lnotifictiongrid + '<a class="text-light-blue" onclick="window.open(' + '''' + Replace(S.Page,'~','') + '''' +');">
		<div class="notification-item"><p style="margin-bottom: 0.1rem" class="item-info">' + ISNULL(NL.MessageTitle,'')+'
		</p></div></a>'

 FROM
	[sAlert].[tNotificationLog]  NL
	INNER JOIN [sSecurity].[tScreen] S ON NL.StatusCode = S.Id
	WHERE OSTypeId  = 3 
	AND SourceId = @rSourceId
	AND SourceTypeId = @rSourceTypeId
	ORDER BY CreatedDateTime DESC

	select @lnotifictiongrid
	IF(@lnotifictiongrid <> '')
	BEGIN
		select '<ul aria-labelledby="dLabel"><div class="notifications-wrapper">' +
		isnull(@lnotifictiongrid,'')  +'</div></ul><u><a class="text-light-blue" onclick="NotificationClick(false)"><p style="margin-bottom: 0.1rem" class="item-info">' + 'Show More' +'
			</p></a></u>'  as NotificationGrid
	END
END
ELSE
BEGIN	
SELECT  @lnotifictiongrid = @lnotifictiongrid + '<a class="text-light-blue" onclick="window.open(' + '''' + Replace(S.Page,'~','') + '''' +');">
		<div class="notification-item"><p style="margin-bottom: 0.1rem" class="item-info">' + ISNULL(NL.MessageTitle,'')+'
		</p></div></a>'

 From
	[sAlert].[tNotificationLog]  NL
	INNER JOIN [sSecurity].[tScreen] S ON NL.StatusCode = S.Id
	WHERE OSTypeId  = 3 
	AND SourceId = @rSourceId
	AND SourceTypeId = @rSourceTypeId
	ORDER BY CreatedDateTime DESC
	
	select '<ul aria-labelledby="dLabel"><div class="notifications-wrapper">' + 
	isnull(@lnotifictiongrid,'')  +'</div></ul>'  as NotificationGrid
END


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


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricFirstInTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rIntervalTime int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
					SourceId bigint NOT NULL,
					In_Out_Time [datetime] NOT NULL,
					SourceTypeId int NOT NULL,
					CreatedDateTime [datetime] NOT NULL,
				)
			insert into #tTable
			select SourceId,min(In_Out_Time),SourceTypeId,min(CreatedDateTime) 
			from [sBiometric].[tCloudTransactionData] 
			WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId
	
			--select * from #tTable
			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace (
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentTime]',ISNULL(Convert(varchar,temp.In_Out_Time,108),'')),
				'[PresentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS EmployeeName,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId


			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				temp.CreatedDateTime >= DATEADD(minute,-(@rIntervalTime),[sCommon].[fGetDate]())
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1
			DROP TABLE #tTable
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH

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


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricLastOutTimeGet]
	@rTemplate nvarchar(max)='',
	@rSubject nvarchar(100)='',
	@rOrgId int,
	@rOrgGroupId int,
	@rIntervalTime int
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL,
					Interval int not NUll
				)

			insert #tShift
			Select 
				ShiftCode, 
				case When DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) < @rIntervalTime then DATEDIFF(MINUTE,CAST(OutTimeAlertTime AS Time),cast([sCommon].[fGetDate]() as Time)) else @rIntervalTime end 
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			AND IsOutTimeAlertTime=1
			AND CAST(OutTimeAlertTime AS Time)<cast([sCommon].[fGetDate]() as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
				SourceId bigint NOT NULL,
				In_Out_Time [datetime] NOT NULL,
				SourceTypeId int NOT NULL,
				Interval int NOT NULL
			)
			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MAX(In_Out_Time),SourceTypeId,tempShift.Interval 
				from [sBiometric].[tCloudTransactionData] CDT 
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId,tempShift.Interval
			End
			--select * from #tTable

			SELECT 
				SC.ParentContactNo AS MobileNo,	
				SC.ParentEmail AS EmailId,
				replace (
				replace(@rTemplate,'[StudentName]',SC.Name),
				'[TimeStamp]',ISNULL(Convert(varchar,temp.In_Out_Time,108),''))
				 AS MsgText,
				@rSubject AS Subject,
				2003 AS ReceiverSourceTypeId,
				SC.StudentId AS ReceiverSourceId,
				SC.Name AS StudentName,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
				2003 AS SourceTypeId,
				SC.StudentId AS SourceId,
				SC.OrgId,
				OM.OrgGroupId


			FROM 
				#tTable temp
				Inner join sStudent.vStudentCommunication SC ON temp.SourceId=SC.StudentId AND SC.IsActiveBatch=1
				INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
			WHERE
				temp.In_Out_Time >= DATEADD(minute,-(temp.Interval),[sCommon].[fGetDate]())
				AND SC.OrgID =@rOrgId
				AND SC.StatusId = 1

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Altering [sAlert].[pStudentBiometricLateTimeGet]...';


GO

ALTER PROCEDURE [sAlert].[pStudentBiometricLateTimeGet]
	 	 
	 	 @rOrgId int,
		@rTemplate nvarchar(max)='',
		@rSubject nvarchar(100)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	DECLARE @lDate date = ''
	SET @lDate = sCommon.fGetDate()

	DECLARE @lDay int = 0
	SET @lDay = DAY(sCommon.fGetDate())

	DECLARE @lColumnName varchar(10) = ''
	SET @lColumnName = 'MT.D' + CAST(@lDay AS VARCHAR) + '_IN'

	DECLARE @lGetConfigTime nvarchar(20) = ''
	SELECT @lGetConfigTime =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 399 AND SourceId = @rOrgId

	IF(@lGetConfigTime <> '' AND LEN(@lGetConfigTime) > 0)
	BEGIN
	DECLARE @Query NVARCHAR(MAX) = ''
	SET @Query ='SELECT
					SC.ParentContactNo AS MobileNo,	
					SC.ParentEmail AS EmailId,
					replace (
					replace (
					replace('''+CONVERT(nvarchar(MAX),@rTemplate)+''',''[StudentName]'',sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId)),
					''[LateTime]'','+@lColumnName+'),
					''[LateDate]'',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''''))
					 AS MsgText,
					'''+CONVERT(nvarchar(20),@rSubject)+''' AS Subject,
					2003 AS ReceiverSourceTypeId,
					SC.StudentId AS ReceiverSourceId,
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS StudentName,
					ISNULL(SC.WhatsAppContactNo,'''') AS WhatsAppContactNo,
					2003 AS SourceTypeId,
					SC.StudentId AS SourceId,
					SM.OrgId,
					OM.OrgGroupId,
					SM.Id AS StudentId,
					SM.Code,
					sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName,OM.StudentNameFormatId) AS  StudentName,
					 '+@lColumnName+' AS Time,
					OM.DisplayTitle AS OrganizationTitle	
		FROM 
				sStudent.tStudentMaster SM
				Inner join sStudent.tStudentCommunication SC ON SM.Id=SC.StudentId
				INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgID = OM.Id
				INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId = SM.Id AND MT.SourceTypeId = 2003
		WHERE
				SM.OrgId = '+CONVERT(nvarchar(20),@rOrgId)+'
				AND MONTH(MT.Attn_dt) = MONTH('''+CONVERT(nvarchar(20),@lDate)+''')
				AND '+@lColumnName+' > '''+@lGetConfigTime+'''
				AND SM.StatusId = 1'
				
		--print (@Query)
		execute (@Query)			
	END

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


GO


ALTER PROCEDURE [sAssessment].[pRptPassFailAnalysisSubjectWise]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 @rClass nvarchar(MAX)='',
	 @rStatusId int = 0,
	 @rSubject nvarchar(MAX)='',
	 @rClassStatusId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		 
	 select 	
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		CS.Id AS ClassSubjectId,
		SM.Id AS SubjectId,
		SM.Code AS SubjectName,
		Sm.OrderIndex As SubjectOrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		CM.OrderIndex AS ClassOrderIndex,
	 

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		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  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		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  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS FailStudent ,
	  ED.Minimum AS SubjectMinimum,
	  ED.Maximum AS SubjectMaximum,
	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
		INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		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  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND R.ResultStatus='PROMOTED' AND RD.Obtain<ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS PromotedStudentFail,

	  	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
		INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
		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  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND R.ResultStatus='PROMOTED' AND RD.Obtain>=ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0)) AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))) AS PromotedStudentPass
	  
	  
	 from		
		sAssessment.tExamMaster EM 
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=CS.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = CS.ClassId AND CM.BatchId = @rBatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON CLM.OrgId = OM.Id

	WHERE 		
		
		EM.BatchId = @rBatchId 
		AND  ((@rClassId > 0 AND cs.ClassId=@rClassId)
		OR (@rClassId = 0 AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')))		
		AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
		AND	CM.BatchId = @rBatchId
		AND EM.ExamSubGroupId = @rExamSubGroupId
		AND EM.BatchId = @rBatchId
		AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
		
END



-- UNION ALL
  
 --  select 	
	--	@rBuilder1 AS Builder1,
	--	Cm.Classid As ClassId,
	--	Dm.id As DivisionId,
	--	Cm.ClassName As Classname,
	--	DM.DisplayTitle As DivisionName,
	--	CS.Id AS ClassSubjectId,
	--	SM.Id AS SubjectId,
	--	SM.Code AS SubjectName,
	--	Sm.OrderIndex As SubjectOrderIndex,
	--	DM.OrderIndex AS DivisionOrderIndex,
	--	CM.OrderIndex AS ClassOrderIndex,
	 

	--  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	--	INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	--	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  
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS PassStudent,
  
	--(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	--	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	--	INNER JOIN sStudent.vStudentAcademic A ON R.AcademicId = A.AcademicId 
	--	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  
	--  where 
	--  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	--  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum AND ((A.StatusId=@rStatusId) OR (@rStatusId=0))) AS FailStudent 
	  
	  
	-- from		
	--	sAssessment.tExamMaster EM 
	--	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
	--	INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
	--	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	--	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
	--	INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=CS.ClassId
	--	INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
	--	INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = CS.ClassId AND CM.BatchId = @rBatchId
	--	INNER JOIN sSetup.tOrganizationMaster OM ON CLM.OrgId = OM.Id

	--WHERE 		
		
	--	EM.BatchId = @rBatchId 
	--	AND (CS.ClassId=@rClassId OR @rClassId=0) 
	--	AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
	--	AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
	--	AND	CM.BatchId = @rBatchId
	--	AND EM.ExamSubGroupId = @rExamSubGroupId
	--	AND EM.BatchId = @rBatchId
	--	AND (ISNULL(Dm.ClassId,0) IN( SELECT item FROM  sCommon.fnsplit(@rClass,','))OR @rClass='')
GO
PRINT N'Altering [sAssessment].[pRptResultListConsolidateWithSubExamGet]...';


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

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

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		Exam1CombineExamName Nvarchar(150),

		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),
		Exam2CombineExamName Nvarchar(150),
		
		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),
		Exam3CombineExamName Nvarchar(150),
		
		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),
		Exam4CombineExamName Nvarchar(150),
		
		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),
		Exam5CombineExamName Nvarchar(150),
		
		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),
		Exam6CombineExamName Nvarchar(150),
		
		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),
		Exam7CombineExamName Nvarchar(150),
		
		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),
		Exam8CombineExamName Nvarchar(150),
		
		
		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),
		Exam9CombineExamName Nvarchar(150),
		
		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),
		Exam10CombineExamName Nvarchar(150),
		
		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),
		Exam11CombineExamName Nvarchar(150),
		
		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),
		Exam12CombineExamName Nvarchar(150),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo int,
		AdmissionDate Date
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

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

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

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

	set @lCount = @lCount -1
	end
	

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign			
-- SELECT  AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T

 SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T

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


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

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

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		Exam1CombineExamName Nvarchar(150),
				
		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),
		Exam2CombineExamName Nvarchar(150),
		
		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),
		Exam3CombineExamName Nvarchar(150),
		
		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),
		Exam4CombineExamName Nvarchar(150),
		
		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),
		Exam5CombineExamName Nvarchar(150),
		
		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),
		Exam6CombineExamName Nvarchar(150),
		
		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),
		Exam7CombineExamName Nvarchar(150),
		
		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),
		Exam8CombineExamName Nvarchar(150),
		
		
		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),
		Exam9CombineExamName Nvarchar(150),
		
		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),
		Exam10CombineExamName Nvarchar(150),
		
		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),
		Exam11CombineExamName Nvarchar(150),
		
		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),
		Exam12CombineExamName Nvarchar(150),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo nvarchar(50),
		AdmissionDate Date,
		MiddleName nvarchar(50) ,
		FatherOccupation nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100)
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

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

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign ,	
 --  '' As FatherOccupation 		
 --SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet_Backup]...';


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

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

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		SchoolNameLabel nvarchar(200),
		MediumLabel nvarchar(100),
		NameLabel nvarchar(200),
		CodeLabel nvarchar(100),
		SUIDLabel nvarchar(100),
		ClassLabel nvarchar(100),
		BirthDateLabel nvarchar(100),
		RollNoLabel nvarchar(100),
		FatherNameLabel nvarchar(100),
		MotherNameLabel nvarchar(100),
		TotalWorkingDaysLabel nvarchar(100),
		TotalPresentDaysLabel nvarchar(100),
		HeightLabel nvarchar(100),
		WeightLabel nvarchar(100),
		SubjectLabel nvarchar(100),
		MaxMarksLabel nvarchar(100),
		TotalLabel nvarchar(100),
		GradeLabel nvarchar(100),
		GrandTotalLabel nvarchar(100),
		ResultStatusLabel nvarchar(100),
		RankNoLabel nvarchar(100),
		PercentileLabel nvarchar(100),
		PercentageLabel nvarchar(100),
		OverallGradeLabel nvarchar(100),
		DisplayAttendanceId int,
		ReportHeaderId int,
		StudentImage nvarchar(500)
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

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

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign			
--SELECT  '' AS Builder1,'' AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering [sAssessment].[pRptResultSheetStandardMultiExamGet_Old]...';


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

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

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo int,
		AdmissionDate Date
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

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

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign			
-- SELECT  AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering [sAssessment].[pRptResultSheetUniqFormat]...';


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

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

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		--IsDetail bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		--IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(50),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		ResultSheetAdditionalTitle nvarchar(100),
		SchoolNameLabel nvarchar(200),
		MediumLabel nvarchar(100),
		NameLabel nvarchar(200),
		CodeLabel nvarchar(100),
		SUIDLabel nvarchar(100),
		ClassLabel nvarchar(100),
		BirthDateLabel nvarchar(100),
		RollNoLabel nvarchar(100),
		FatherNameLabel nvarchar(100),
		MotherNameLabel nvarchar(100),
		TotalWorkingDaysLabel nvarchar(100),
		TotalPresentDaysLabel nvarchar(100),
		HeightLabel nvarchar(100),
		WeightLabel nvarchar(100),
		SubjectLabel nvarchar(100),
		MaxMarksLabel nvarchar(100),
		TotalLabel nvarchar(100),
		GradeLabel nvarchar(100),
		GrandTotalLabel nvarchar(100),
		ResultStatusLabel nvarchar(100),
		RankNoLabel nvarchar(100),
		PercentileLabel nvarchar(100),
		PercentageLabel nvarchar(100),
		OverallGradeLabel nvarchar(100),
		DisplayAttendanceId int,
		ReportHeaderId int,
		StudentImage varbinary(max)
		
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

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

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign			
--SELECT  '' AS Builder1,'' AS Builder2, T.* FROM sAssessment.tTempAllExam T

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


GO


ALTER PROCEDURE [sAssessment].[pRptResultWithSubjectAnalysisBatchwise]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 --@rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 --@rExamId int,
     --@rExamSubGroupId1 int=0,
     --@rExamSubGroupId2 int=0,
	 @rCode nvarchar(20),
	 @rFromRollNo int =0,
	 @rToRollNo int =0,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rResultStatus nvarchar(20)='',
	 @rDepartmentId int=0,
	 @rExamId1 int ,
	 @rExamId2 int ,
	 @rBatchId1 int,
	 @rBatchId2 int,
	 @rClassStatusId int=0 ,
	 @rIsDisplayAvgTotal bit=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
 
	BEGIN
	
CREATE TABLE #Temp_StudentId (StudentId bigint);
	INSERT INTO #Temp_StudentId
	SELECT A1.StudentId From sStudent.tAcademic A1 
	INNER JOIN
	sStudent.tAcademic A2 ON A1.StudentId = A2.StudentId 
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A1.StudentId
	WHERE A1.BatchId =  @rBatchId1 AND A2.BatchId = @rBatchId2
	AND (A1.ClassId=@rClassId OR @rClassId=0) 
	AND (A1.DivisionId=@rDivisionId OR @rDivisionId=0)
	AND ((A1.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
	AND ((A1.RollNo <= @rToRollNo) OR (@rToRollNo=0))
	AND ((SM.Code=@rCode) OR (@rCode=''))
	AND SM.StatusId = 1
	AND ((A1.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
	
	
CREATE TABLE #Temp_Academic (tempAcademicId bigint);
INSERT INTO #Temp_Academic 
SELECT  A.Id As tempAcademicId FROM sAssessment.tResult R 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId 
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentId
		WHERE BM.Id = @rBatchId2 AND R.ExamId =@rExamId2
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		  
	--SELECT * FROM #temp
	--RETURN 	

CREATE TABLE #tmp
(
IsDisplayAvgTotal int,
Builder1 nvarchar(max),
Builder2 nvarchar(max),
ExamId int,
Exam nvarchar(300),
BatchId int,
BatchName nvarchar(300),
Code nvarchar(200),
Name nvarchar(max),
RollNo int,
AcademicId bigint,
Obtain decimal(5,2),
ResultStatus nvarchar(100),
Class nvarchar(200),
ClassId int,
Division nvarchar(200),
DivisionId int,
DivisinOrderIndex int,
TotalMarks decimal(8,2),
TotalObtain decimal(8,2),
Percentage  decimal(5,2),
RankNumber int,
ResultGrade nvarchar(20),
ClassSubject nvarchar(200),
ResultDetailId bigint,
ResultId bigint,
SubjectId int,
Maximum decimal(10,2),
SubjectGrade nvarchar(200),
IsMarkInDecimal bit,
SubjectCode nvarchar(200),
SubjectOrderIndex int,
ClassOrderIndex int,
IsPresent bit,
IsGrade bit,
IsPercentage bit,
IsResultStatus bit,
IsRankNo  bit,
Minimum decimal(10,2),
GraceMark decimal(5,2),
DecimalFormat nvarchar(20),
IsOptional bit,
PresentDays decimal(6,2),
TotalDays decimal(6,2),
AvgTotal decimal(6,2)

)

INSERT INTO #tmp
	SELECT 
			@rIsDisplayAvgTotal AS IsDisplayAvgTotal,
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			EM.Id AS ExamId,
			ESGM.Title AS Exam,
			BM.Id As BatchId,
			BM.Title As BatchName,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 	
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			ISNULL(SR.PresentDays,0)AS PresentDays,
			ISNULL(SR.TotalDays,0)AS TotalDays,
			(CASE WHEN @rIsDisplayAvgTotal=1 THEN ROUND(((RD.Obtain*100)/ED.Maximum),0) ELSE RD.Obtain END)As AvgTotal
			
			--RD.SubjectGrade AS TermSubjectGrade,
			--RD.SubjectGrade AS SubjectGrade
			--1 As ExamNo
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId=EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			
	WHERE 
			
		EM.BatchId = @rBatchId1
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		--AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId1 = 0))		
		AND ((EM.Id=@rExamId1 )	OR (@rExamId1 = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	A.BatchId = @rBatchId1
		--AND BM.Id = @rBatchId1
		AND R.ExamId = @rExamId1
		 AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))

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

			--2 As ExamNo
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN #Temp_Academic temp ON temp.tempAcademicId= A.Id  
			INNER JOIN #Temp_StudentId TEMP2 ON TEMP2.StudentId = A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId=EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			INNER JOIN sStudent.tAcademic A2 ON A2.StudentId = TEMP2.StudentId AND A2.BatchId = @rBatchId1
			INNER JOIN sSetup.tClassMaster CM2 ON CM2.Id=A2.ClassId
			INNER JOIN sSetup.tDivisionMaster DM2 ON DM2.Id=A2.DivisionId
	WHERE 
			
		EM.BatchId = @rBatchId2
		--AND (A.ClassId=@rClassId OR @rClassId=0)  
		--AND (A.ClassId=temp.tempClassId )
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0))
		--AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		--AND (A.DivisionId=temp.tempDivisionId )
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		--AND ((ESGM.Id = @rExamSubGroupId2) OR (@rExamSubGroupId2 = 0))		
		AND ((EM.Id=@rExamId2 )	OR (@rExamId2 = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	((A.BatchId = @rBatchId2 ))
		--AND ((BM.Id = @rBatchId2))
		AND R.ExamId = @rExamId2
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		order by A.RollNo,ClassOrderIndex
	--	SELECT * FROM #temp
	--RETURN 
	--Select AvgTotal from #tmp tmp1 Where tmp1.ExamId = 993100076 AND tmp1.AcademicId = tmp.AcademicId
	Select *,
	(Select AvgTotal from #tmp tmp1 Where tmp1.ExamId = @rExamId1 AND tmp1.AcademicId = tmp.AcademicId AND tmp1.SubjectId = tmp.SubjectId)-
	(Select AvgTotal from #tmp tmp1 Where tmp1.ExamId = @rExamId2 AND tmp1.AcademicId = tmp.AcademicId AND tmp1.SubjectId = tmp.SubjectId) AS SubjectDifference,
	(Select TOP 1 Percentage from #tmp tmp1 Where tmp1.ExamId = @rExamId1 AND tmp1.AcademicId = tmp.AcademicId AND tmp1.SubjectId = tmp.SubjectId) - 
	(Select TOP 1 Percentage from #tmp tmp1 Where tmp1.ExamId = @rExamId2 AND tmp1.AcademicId = tmp.AcademicId AND tmp1.SubjectId = tmp.SubjectId) AS SubjectPerDifference,
	--(CASE WHEN IsDisplayAvgTotal = 1 AND IsPresent = 1 THEN AvgTotal
	--	  WHEN IsDisplayAvgTotal = 0 AND IsPresent = 1 THEN TotalObtain
	--	  ELSE 0
	--END ) AS SubjectWiseTotalDiff
	(Select (CASE WHEN IsDisplayAvgTotal = 1 THEN SUM(AvgTotal)
		  WHEN IsDisplayAvgTotal = 0 THEN SUM(TotalObtain)
		  ELSE 0 END )from #tmp tmp1 
		  Where tmp1.ExamId = @rExamId1 AND tmp1.AcademicId = tmp.AcademicId  Group By IsDisplayAvgTotal) - 
	(Select (CASE WHEN IsDisplayAvgTotal = 1 THEN SUM(AvgTotal)
		  WHEN IsDisplayAvgTotal = 0 THEN SUM(TotalObtain)
		  ELSE 0 END )from #tmp tmp1 
		  Where tmp1.ExamId = @rExamId2 AND tmp1.AcademicId = tmp.AcademicId  Group By IsDisplayAvgTotal)
	AS SubjectWiseTotalDiff

	  from #tmp tmp
		END
		DROP Table #Temp_Academic
		DROP Table #Temp_StudentId
		DROP TABLE #tmp
		
		----For Report Dataset
		--SELECT 
		--	@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2,
		--	EM.DisplayTitle AS Exam,
		--	EM.Id AS ExamId,
		--	StuM.Code,
		--	[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		--	A.RollNo,
		--	--temp.tempAcademicId,
		--	R.AcademicId,
		--	RD.Obtain,
		--	R.ResultStatus,
		--	CM.DisplayTitle AS Class,
		--	Cm.Id AS ClassId,
		--	DM.DisplayTitle AS Division,
		--	DM.Id AS DivisionId,
		--	DM.OrderIndex AS DivisinOrderIndex,
		--	R.TotalMarks,
		--	R.TotalObtain,
		--	R.Percentage,
		--	R.RankNumber,
		--	R.ResultGrade,
		--	SM.Title AS ClassSubject,
		--	RD.Id AS ResultDetailId,
		--	R.Id AS ResultId,
		--	CS.Id AS SubjectId,
		--	ED.Maximum,
		--	RD.SubjectGrade, 
			
		--	EM.IsMarksInDecimal,
		--	--SM.OrderIndex AS SubjectCode,
		--	SM.Code AS SubjectCode,
		--	ED.DisplayOrder AS SubjectOrderIndex,
		--	CM.OrderIndex AS ClassOrderIndex,
		--	RD.IsPresent,
		--	EM.IsGrade,
		--	EM.IsPercentage,
		--	EM.IsResultStatus,
		--	EM.IsRankNo ,
		--	ED.Minimum,
		--	RD.GraceMark,
		--	EM.DecimalFormat,
		--	CS.IsOptional,
		--	SR.PresentDays,
		--	SR.TotalDays,
		--	BM.Id As BatchId,
		--	BM.Title As BatchName
		--	FROM
		--	sAssessment.tResultDetail RD
		--	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		--	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
		--	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
		--	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
		--	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		--	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		--	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		--	INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id 
		--	LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id
		--	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		--	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		--	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		--	INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			


			--SELECT 
			--0 AS IsDisplayAvgTotal,
			--'' AS Builder1,
			--'' AS Builder2,
			--0 AS ExamId,
			--'' AS Exam,
			--0 As BatchId,
			--'' As BatchName,
			--''  AS Code,
			--'' AS Name,
			--0 AS RollNo,
			----temp.tempAcademicId,
			--0 AS AcademicId,
			--0 AS Obtain,
			--'' AS ResultStatus,
			--'' AS Class,
			--0  AS ClassId,
			--'' AS Division,
			--0 AS DivisionId,
			--0 AS DivisinOrderIndex,
			--0 AS TotalMarks,
			--0 AS TotalObtain,
			--0 AS Percentage,
			--0 AS RankNumber,
			--'' AS ResultGrade,
			--'' AS ClassSubject,
			--0 AS ResultDetailId,
			--0 AS ResultId,
			--0 AS SubjectId,
			--0 AS Maximum,
			--'' AS SubjectGrade, 
			
			--0 AS IsMarksInDecimal,
			----SM.OrderIndex AS SubjectCode,
			--'' AS SubjectCode,
			--0 AS SubjectOrderIndex,
			--0 AS ClassOrderIndex,
			--0 AS IsPresent,
			-- 0 AS IsGrade,
			--0 AS IsPercentage,
			--0 AS IsResultStatus,
			--0 AS IsRankNo ,
			--0 AS  Minimum,
			--0 AS GraceMark,
			--'' AS DecimalFormat,
			--0 AS IsOptional,
			--0 AS PresentDays,
			--0 AS TotalDays,
			--0 As AvgTotal,
			-- 0 AS SubjectDifference,
			-- 0 AS SubjectPerDifference,
			-- 0 AS SubjectWiseTotalDiff
END
GO
PRINT N'Altering [sAssessment].[pRptStudentAnalysisDetailsGet]...';


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

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

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2) Default 0,		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2) Default 0,	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2) Default 0,
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2) Default 0,	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2) Default 0,		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2) Default 0,		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2) Default 0,		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2) Default 0,	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2) Default 0,		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2) Default 0,		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2) Default 0,		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2) Default 0,		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		Remark2 nvarchar(1000),
		Remark3 nvarchar(1000),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150) default '',		
		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) default '',	
		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) default '',	
		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) default '',	
		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) default '',		
		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) default '',	
		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) default '',		
		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) default '',
		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) default '',	
		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) default '',	
		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) default '',	
		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) default '',	
		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 decimal(6,2),
		PresentDays decimal(6,2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		IsDisplayParentName bit,
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		MyGoal nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		MyInterestHobby nvarchar(200),
		MyStrength nvarchar(200),
		Achievements nvarchar(1000),
		
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50), 
		--IsDetail bit,
		IsPercentageDisplay bit,
		SubjectGroupId int,
		SubjectGroupTitle nvarchar(50),
		SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		ContactNo nvarchar(50),
		PresentAddress nvarchar(max),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		GeneralRemark nvarchar(1000),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		 
		HouseRemark nvarchar(1000),
		BloodGroup Nvarchar(100),
		TotalDays1 decimal(6,2),
		PresentDays1 decimal(6,2),
		TotalDays2 decimal(6,2),
		PresentDays2 decimal(6,2),
		TotalDays3 decimal(6,2),
		PresentDays3 decimal(6,2),
		TotalDays4 decimal(6,2),
		PresentDays4 decimal(6,2),
		TotalDays5 decimal(6,2),
		PresentDays5 decimal(6,2),
		TotalDays6 decimal(6,2),
		PresentDays6 decimal(6,2),
		TotalDays7 decimal(6,2),
		PresentDays7 decimal(6,2), 
		TotalDays8 decimal(6,2),
		PresentDays8 decimal(6,2),
		TotalDays9 decimal(6,2),
		PresentDays9 decimal(6,2),
		TotalDays10 decimal(6,2),
		PresentDays10 decimal(6,2),
		TotalDays11 decimal(6,2),
		PresentDays11 decimal(6,2),
		TotalDays12 decimal(6,2),
		PresentDays12 decimal(6,2),
		BatchIdText nvarchar(20),
		--IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		SubjectHighestDivisionGrade nvarchar(50),
		SubjectHighestDivisionMark decimal(5, 2),
		
		AchievementsTerm1 nvarchar(1000),
		AchievementsTerm2 nvarchar(1000),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 decimal(6,2),
		SR_PresentDaysTerm2 decimal(6,2),
		SR_TotalDaysTerm1 decimal(6,2),
		SR_TotalDaysTerm2 decimal(6,2),
		HouseId int,
		HouseName nvarchar(100),
		AdhaarNumber nvarchar(100),
		UIdNumber nvarchar(100),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		Gender nvarchar(100),
		CoordinatorEmployeeSign varbinary(max),
		StudentAddress nvarchar(max),
		SUId nvarchar(25),
		HighestDivisionMark decimal(5, 2),
		HighestDivisionGrade nvarchar(50),
		StreamTitle nvarchar(50),
		AdmissionNo int,
		AdmissionDate Date
		
	)	
	 --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,
	IsPercentageDisplay,
	SubjectGroupId,
	SubjectGroupTitle,
	SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	KrupaMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	ContactNo,
	PresentAddress,
	TeacherSignCaption,
	PrincipalSignCaption,
	ParentSignCaption,
	ImprovementArea,
	ProgressArea,
	GeneralRemark,
	MyActivity,
	ClassTeacherRemark,
	
	HouseRemark,
	BloodGroup,
	BatchIdText,
    --IsShowWithDetail,
    IsPresent,
    GradeTitle,
	
	SubjectHighestDivisionGrade,
	SubjectHighestDivisionMark,
	
	AchievementsTerm1,
	AchievementsTerm2,
	GeneralRemarkTerm1,
	GeneralRemarkTerm2,
	ResultRemark1Term1,
	ResultRemark2Term1,
	ResultRemark1Term2,
	ResultRemark2Term2,
	SR_HeightTerm1,
	SR_WeightTerm1,
	SR_HeightTerm2,
	SR_WeightTerm2,
	SR_PresentDaysTerm1,
	SR_PresentDaysTerm2,
	SR_TotalDaysTerm1,
	SR_TotalDaysTerm2,
	HouseName,
	HouseId,
	AdhaarNumber,
	UIdNumber,
	FatherContactNo ,
	MotherContactNo ,
	FatherMail ,
	MotherMail ,
	Gender,
	CoordinatorEmployeeSign,
	StudentAddress,
	SUId,
	HighestDivisionMark,
	HighestDivisionGrade,
	StreamTitle,
	AdmissionNo,
	AdmissionDate
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		Convert(nvarchar(50),@rClassId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,


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

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

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

 --         '' As  AchievementsTerm1,
 --         '' As  AchievementsTerm2,
 --         '' As GeneralRemarkTerm1,
 --         '' As GeneralRemarkTerm2,
 --         '' As ResultRemark1Term1,
 --          '' As ResultRemark2Term1,
 --          '' As ResultRemark1Term2,
 --         '' As ResultRemark2Term2,
 --         0 As SR_HeightTerm1,
 --         0 As SR_WeightTerm1,
 --         0 As SR_HeightTerm2,
 --         0 As SR_WeightTerm2,
 --         0 As SR_PresentDaysTerm1,
 --         0 As SR_PresentDaysTerm2,
 --         0 As SR_TotalDaysTerm1,
 --         0 As SR_TotalDaysTerm2,
 --         '' As HouseName,
 --         0 As HouseId,
 --         '' As AdhaarNumber,
 --         '' As UidNumber,
 --         '' As FatherContactNo,
 --         '' As MotherContactNo,
 --         '' As FatherMail,
 --         '' As MotherMail,
 --         '' AS Gender,
--			0x AS CoordinatorEmployeeSign			
-- SELECT  AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
 
	END
	--SELECT @rBuilder1 AS Builder1,@rBuilder2 AS Builder2, T.* FROM sAssessment.tTempAllExam T
	
--end
GO
PRINT N'Altering [sAttendance].[pAttendanceFollowupDetailGet]...';


GO
 
 
ALTER PROCEDURE [sAttendance].[pAttendanceFollowupDetailGet]
	 	 
	 	 @rClassId int=0,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rFollowupDate date,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @rPresentStatus int,
		 @rCode nvarchar(20)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT
	SA.AcademicId, 
	SA.ClassName +'-' + SA.DivisionName AS ClassDivision,
	SA.Code,
	SA.RollNo,
	SA.Name,
	SC.PresentContactNo,
	SC.PermanentContactNo,
	SC.EmergencyContactNo,
	SC.ParentContactNo,
	SC.StudentContactNo,
	--AF.Remark,
	CASE WHEN (ISNULL((SELECT 1 FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate),0)
	= 1 AND (AF.Remark IS NULL OR AF.Remark = '')) THEN (SELECT LeaveReason FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate)
	ELSE (
	replace (
	replace (
	replace (
	replace (
	replace (
	replace(AF.Remark,'\n','<br />'),
	'#amp;','&'),
	'#gt;','>'),
	'#quot;','\"'),
	'#lt;','<'),
	'#39;','''')) END AS Remark,
	ISNULL((SELECT 1 FROM [sAttendance].[tStudentLeaveRequest] WHERE AcademicId = SA.AcademicId AND @rFollowupDate BETWEEN LeaveFromDate AND LeaveToDate),0) AS IsOnLeave
	,ISNULL(SA.StudentId, 0) AS StudentId
	FROM
	sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
	--AND (SR.AttendanceTypeId = @rAttendanceTypeId)
	--AND (SR.AttendanceDate = @rFollowupDate)
	LEFT JOIN sAttendance.tAttendanceFollowup AF ON AF.AcademicId = SA.AcademicId AND SR.AttendanceTypeId = AF.AttendanceTypeId AND SR.AttendanceDate  = AF.FollowupDate
	LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
 
	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 SR.IsPresent = @rPresentStatus
		  AND (AD.AdmissionDate <= @rFollowupDate)
		  AND ((SA.Code=@rCode)OR (ISNULL(@rCode,'')=''))
		  AND (SR.AttendanceTypeId = @rAttendanceTypeId)
		  AND (SR.AttendanceDate = @rFollowupDate)
END
GO
PRINT N'Altering [sAttendance].[pAttendanceSummaryDashboard]...';


GO
 
ALTER  PROCEDURE [sAttendance].[pAttendanceSummaryDashboard]
	@rType nvarchar(20)='',
	@rOrgId int =0,
	@rAttendanceDate date ='',
	@rClassId int=0,
	@rDepartmentId int =0,
	@rDivisionId int=0
	--@rLibraryId int =0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 
BEGIN 
	IF(@rType = 'AttendanceList')
		BEGIN
			SELECT COUNT(SR.AcademicId)
					,ISNULL((SELECT COUNT(SR.AcademicId)
						FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId	 
							 AND SR.AttendanceDate = @rAttendanceDate WHERE SR.IsPresent=1 AND ((A.OrgId=@rOrgId)OR(@rOrgId=0))
							 AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS PresentCount,
					ISNULL((SELECT COUNT(SR.AcademicId)
					FROM sStudent.tAcademic A 
						INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id AND SR.AttendanceDate = @rAttendanceDate
						INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId	 
						  WHERE SR.IsPresent=0 AND  ((CM.Id =@rClassId)OR(@rClassId=0)) AND ((A.OrgId=@rOrgId)OR(@rOrgId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0)) ),0) AS AbsentCount,
				ISNULL((SELECT COUNT(SR.AcademicId)
				FROM  sStudent.tAcademic A 
				INNER JOIN sAttendance.tStudentLeaveRequest SLR ON SLR.AcademicId=A.Id  AND SLR.LeaveFromDate = @rAttendanceDate AND  SLR.LeaveToDate = @rAttendanceDate
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId	 
				WHERE ((CM.Id =@rClassId)OR(@rClassId=0)) AND ((A.OrgId=@rOrgId)OR(@rOrgId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))),0) AS LeaveCount
				FROM sStudent.tAcademic A 
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id  AND SR.AttendanceDate = @rAttendanceDate
				INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
			WHERE ((A.OrgId=@rOrgId)OR(@rOrgId=0)) AND ((CM.Id =@rClassId)OR(@rClassId=0))
							AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
		END
	ELSE IF(@rType = 'ClassWiseAttendance')
		BEGIN 
			SELECT CM.Id,CM.Title,ISNULL(T.PresentCount,0) AS PresentCount ,ISNULL(T1.AbsentCount,0) As AbsentCount,CM.OrderIndex
				FROM sSetup.tClassMaster CM
						LEFT JOIN sStudent.tAcademic A ON CM.Id = A.ClassId	
						LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id  AND SR.AttendanceDate = @rAttendanceDate
						LEFT JOIN 
							(SELECT COUNT(A.Id) AS PresentCount,A.ClassId FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
							WHERE SR.IsPresent=1 AND  AttendanceDate = @rAttendanceDate
							GROUP BY A.ClassId 
						)T ON T.ClassId = A.ClassId
						
						LEFT JOIN 
							(SELECT COUNT(A.Id) AS AbsentCount,A.ClassId FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
							WHERE SR.IsPresent=0 AND  AttendanceDate = @rAttendanceDate
							GROUP BY A.ClassId 
						)T1 ON T1.ClassId = A.ClassId 
						--AND T.ClassId = T1.ClassId
			WHERE ((CM.OrgId=@rOrgId)OR (@rOrgId=0))
			AND ((CM.Id =@rClassId)OR(@rClassId=0))
			AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
				GROUP BY CM.Title, CM.Id,T.PresentCount,T1.AbsentCount,CM.OrderIndex
				ORDER BY CM.OrderIndex
		END
	
	ELSE 
		BEGIN 
		
			SELECT CM.Id,(CM.Title +' - '+ DM.Title) AS  Title ,ISNULL(T.PresentCount,0) AS PresentCount ,ISNULL(T1.AbsentCount,0) As AbsentCount,DM.OrderIndex
				FROM sSetup.tClassMaster CM
						INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id 
						LEFT JOIN sStudent.tAcademic A  ON CM.Id = A.ClassId AND DM.Id = A.DivisionId
						LEFT JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id  AND SR.AttendanceDate = @rAttendanceDate
						LEFT JOIN 
							(SELECT COUNT(A.Id) AS PresentCount,A.ClassId,A.DivisionId FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = A.DivisionId
							WHERE SR.IsPresent=1 AND  AttendanceDate = @rAttendanceDate
							GROUP BY A.ClassId,A.DivisionId
						)T ON T.ClassId = A.ClassId AND T.DivisionId = A.DivisionId
						
						LEFT JOIN 
							(SELECT COUNT(A.Id) AS AbsentCount,A.ClassId,A.DivisionId FROM sStudent.tAcademic A 
							INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=A.Id 
							INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId
							INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId =  CM.Id AND DM.Id = A.DivisionId
							WHERE SR.IsPresent=0 AND  AttendanceDate = @rAttendanceDate
							GROUP BY A.ClassId,A.DivisionId
						)T1 ON T1.ClassId = A.ClassId AND T1.DivisionId = A.DivisionId
						--AND T.ClassId = T1.ClassId
			WHERE ((CM.OrgId=@rOrgId)OR (@rOrgId=0))
			AND ((CM.Id =@rClassId)OR(@rClassId=0))
			AND ((DM.Id =@rDivisionId)OR(@rDivisionId=0))
			AND((CM.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
				GROUP BY CM.Title, CM.Id,T.PresentCount,T1.AbsentCount,DM.OrderIndex,DM.Title
				ORDER BY DM.OrderIndex
		END
END
GO
PRINT N'Altering [sAttendance].[pRptStudentwiseAbsentDaysGet]...';


GO
ALTER PROCEDURE [sAttendance].[pRptStudentwiseAbsentDaysGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rAttendanceTypeId tinyint,
	 @rSubjectId int,
	 @rFromDate date,
	 @rToDate date,
	 @rStudentCode nvarchar(20),
	 @rDepartmentId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 
	SELECT 
			DISTINCT(SA.AcademicId),
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,			
			sAttendance.fAttendanceGet(SA.AcademicId,@rAttendanceTypeId,@rSubjectId,@rFromDate,@rToDate) AS AttendanceDate,
			AbsentCount=(SELECT COUNT(1) FROM sAttendance.tStudentRegister SR1 
				WHERE SR1.AcademicId=SA.AcademicId 
				AND ((SR1.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
				AND ((SR1.SubjectId=@rSubjectId) OR (@rSubjectId=0))
				AND ((SR1.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
				AND ((SR1.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND SR1.IsPresent=0),
		   SA.DivisionOrder,
		   SC.ParentContactNo
	FROM 
			sStudent.vStudentAcademic SA
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId
		INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SR.AttendanceTypeId=@rAttendanceTypeId) OR (@rAttendanceTypeId=0))
		AND ((SR.SubjectId=@rSubjectId) OR (@rSubjectId=0))
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (SR.IsPresent = 0)
		AND (SA.StatusId != 3)
		AND ((SA.Code=@rStudentCode) OR (@rStudentCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		GROUP BY SA.AcademicId,SA.ClassId,SA.DivisionId,SA.ClassName,SA.DivisionName,SA.Code,SA.RollNo,SA.Name,SA.DivisionOrder,SC.ParentContactNo
END
GO
PRINT N'Altering [sAttendance].[pYearlyRegisterGet]...';


GO

ALTER PROCEDURE [sAttendance].[pYearlyRegisterGet]

	 
	 @rAcademicId bigint=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0,
	 @rAttendanceTypeId tinyint=1,
	 @rStatus int=0,
	 @rDepartmentId int=0,
	 @rStudentCode nvarchar(20) = ''
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
DECLARE @Month1 nvarchar(20),@Month2 nvarchar(20),@Month3 nvarchar(20),
        @Month4 nvarchar(20),@Month5 nvarchar(20),@Month6 nvarchar(20),
		@Month7 nvarchar(20),@Month8 nvarchar(20),@Month9 nvarchar(20),
		@Month10 nvarchar(20),@Month11 nvarchar(20),@Month12 nvarchar(20)
	 
	 Select @Month1 = Month1 FROM sAttendance.tYearlyRegister WHERE Month1 IS NOT NULL
	 Select @Month2 = Month2 FROM sAttendance.tYearlyRegister WHERE Month2 IS NOT NULL
	 Select @Month3 = Month3 FROM sAttendance.tYearlyRegister WHERE Month3 IS NOT NULL
	 Select @Month4 = Month4 FROM sAttendance.tYearlyRegister WHERE Month4 IS NOT NULL
	 Select @Month5 = Month5 FROM sAttendance.tYearlyRegister WHERE Month5 IS NOT NULL
	 Select @Month6 = Month6 FROM sAttendance.tYearlyRegister WHERE Month6 IS NOT NULL
	 Select @Month7 = Month7 FROM sAttendance.tYearlyRegister WHERE Month7 IS NOT NULL
	 Select @Month8 = Month8 FROM sAttendance.tYearlyRegister WHERE Month8 IS NOT NULL
	 Select @Month9 = Month9 FROM sAttendance.tYearlyRegister WHERE Month9 IS NOT NULL
	 Select @Month10 = Month10 FROM sAttendance.tYearlyRegister WHERE Month10 IS NOT NULL
	 Select @Month11 = Month11 FROM sAttendance.tYearlyRegister WHERE Month11 IS NOT NULL
	 Select @Month12 = Month12 FROM sAttendance.tYearlyRegister WHERE Month12 IS NOT NULL
        
SELECT 
	A.Id AS AcademicId,
	A.RollNo,
	SM.Code,
	ISNULL(YR.AvergeAttendance,0) AS AvergeAttendance,
	YR.TotalDays,
	YR.PresentDays,
	
	ISNULL(YR.Month1,@Month1) AS Month1,
	ISNULL(YR.PresentDays1,0) AS PresentDays1,
	ISNULL(YR.TotalDays1,0) AS TotalDays1,
	
	ISNULL(YR.Month2,@Month2) AS Month2,
	ISNULL(YR.PresentDays2,0) AS PresentDays2,
	ISNULL(YR.TotalDays2,0) AS TotalDays2,
	
	ISNULL(YR.Month3,@Month3) AS Month3,
	ISNULL(YR.PresentDays3,0) AS PresentDays3,
	ISNULL(YR.TotalDays3,0) AS TotalDays3,
	
	ISNULL(YR.Month4,@Month4) AS Month4,
	ISNULL(YR.PresentDays4,0) AS PresentDays4,
	ISNULL(YR.TotalDays4,0) AS TotalDays4,
	
	ISNULL(YR.Month5,@Month5) AS Month5,
	ISNULL(YR.PresentDays5,0) AS PresentDays5,
	ISNULL(YR.TotalDays5,0) AS TotalDays5,
	
	ISNULL(YR.Month6,@Month6) AS Month6,
	ISNULL(YR.PresentDays6,0) AS PresentDays6,
	ISNULL(YR.TotalDays6,0) AS TotalDays6,
	
	ISNULL(YR.Month7,@Month7) AS Month7,
	ISNULL(YR.PresentDays7,0) AS PresentDays7,
	ISNULL(YR.TotalDays7,0) AS TotalDays7,
	
	ISNULL(YR.Month8,@Month8) AS Month8,
	ISNULL(YR.PresentDays8,0) AS PresentDays8,
	ISNULL(YR.TotalDays8,0) AS TotalDays8,
	
	ISNULL(YR.Month9,@Month9) AS Month9,
	ISNULL(YR.PresentDays9,0) AS PresentDays9,
	ISNULL(YR.TotalDays9,0) AS TotalDays9,
	
	ISNULL(YR.Month10,@Month10) AS Month10,
	ISNULL(YR.PresentDays10,0) AS PresentDays10,
	ISNULL(YR.TotalDays10,0) AS TotalDays10,
	
	ISNULL(YR.Month11,@Month11) AS Month11,
	ISNULL(YR.PresentDays11,0) AS PresentDays11,
	ISNULL(YR.TotalDays11,0) AS TotalDays11,
	
	ISNULL(YR.Month12,@Month12) AS Month12,
	ISNULL(YR.PresentDays12,0) AS PresentDays12,
	ISNULL(YR.TotalDays12,0) AS TotalDays12,
	
	SM.FirstName + ' ' + ' '+ SM.MiddleName+ ' ' + SM.LastName As Name,	
	SM.StatusID,
	SO.UIDNumber,
	SO.AdhaarNumber,
	A.ClassId AS ClassId,
	A.DivisionId AS DivisionId,
	(SELECT Title FROM sSetup.tClassMaster WHERE Id = A.ClassId) AS ClassTitle,
	(SELECT OrderIndex FROM sSetup.tClassMaster WHERE Id = A.ClassId) AS ClassOrderIndex,
	(SELECT Title FROM sSetup.tDivisionMaster WHERE Id = A.DivisionId) AS DivisionTitle,
	(SELECT OrderIndex FROM sSetup.tDivisionMaster WHERE Id = A.DivisionId) AS DivisionOrderIndex,
	--CM.Title AS ClassTitle,
	--DM.Title AS DivisionTitle,
	--CM.OrderIndex AS ClassOrderIndex,
	--DM.OrderIndex AS DivisionOrderIndex
	[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS NameAsPerOrgWise
from
	sAttendance.tYearlyRegister YR
	INNER JOIN sStudent.tAcademic A ON A.Id=YR.AcademicId
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId 	
	INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = A.StudentId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	--INNER JOIN sSetup.tClassMaster CM ON A.ClassId = CM.Id
	--INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = A.DivisionId
where 


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


GO
ALTER PROCEDURE [sBiometric].[pRptMonthlySummaryListGet]

	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int = 0,
	@rDeptId int = 0,
	@rForYear int=0,
	@rForMonth int=0,	 
	@rEmployeeStatusId int=0,
	@rEmployeeId bigint = 0,
	@rOrgGroupId int = 0,
	@OrgGroupDepartmentId 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),  
 LateBy nvarchar(20),   
 EarlyBy nvarchar(20), 
 )  
  INSERT INTO #TempMonthTrans  
   
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 01) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='W') AND D01_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )='H') AND D01_IN = '00:00' THEN 'H'   
			 WHEN (D01 = 'W' OR D01 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN = '00:00' THEN 'A' 
			 WHEN (D01 = 'H' OR D01 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN != '00:00' THEN 'P'
			 WHEN D01 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN = '00:00' THEN 'A' 
			 --WHEN  AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D01_IN != '00:00' THEN 'P'  
			 --WHEN D01 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,01,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D01_IN != '00:00' THEN 'P'
			 ELSE D01 END ,	
	D01_L,D01_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	
	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 02) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='W') AND D02_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )='H') AND D02_IN = '00:00' THEN 'H'   
			 WHEN (D02 = 'W' OR D02 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN = '00:00' THEN 'A' 
			 WHEN (D02 = 'H' OR D02 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN != '00:00' THEN 'P'
			 WHEN D02 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN = '00:00' THEN 'A' 
			 --WHEN D02 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D02_IN != '00:00' THEN 'P'  
			 --WHEN D02 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,02,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D02_IN != '00:00' THEN 'P'
			 ELSE D02 END ,	
	D02_L,D02_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 03) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='W') AND D03_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )='H') AND D03_IN = '00:00' THEN 'H'   
			 WHEN (D03 = 'W' OR D03 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN = '00:00' THEN 'A' 
			 WHEN (D03 = 'H' OR D03 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN != '00:00' THEN 'P'
			 WHEN D03 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN = '00:00' THEN 'A' 
			 --WHEN D03 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D03_IN != '00:00' THEN 'P'  
			 --WHEN D03 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,03,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D03_IN != '00:00' THEN 'P'
			 ELSE D03 END ,	
	D03_L,D03_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 04) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='W') AND D04_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )='H') AND D04_IN = '00:00' THEN 'H'   
			 WHEN (D04 = 'W' OR D04 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN = '00:00' THEN 'A' 
			 WHEN (D04 = 'H' OR D04 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN != '00:00' THEN 'P'
			 WHEN D04 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN = '00:00' THEN 'A' 
			 --WHEN D04 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D04_IN != '00:00' THEN 'P'  
			 --WHEN D04 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,04,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D04_IN != '00:00' THEN 'P'
			 ELSE D04 END ,	
	D04_L,D04_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 05) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='W') AND D05_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )='H') AND D05_IN = '00:00' THEN 'H'   
			 WHEN (D05 = 'W' OR D05 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN = '00:00' THEN 'A' 
			 WHEN (D05 = 'H' OR D05 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN != '00:00' THEN 'P'
			 WHEN D05 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN = '00:00' THEN 'A' 
			 --WHEN D05 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D05_IN != '00:00' THEN 'P'  
			 --WHEN D05 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,05,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D05_IN != '00:00' THEN 'P'
			 ELSE D05 END ,	
	D05_L,D05_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 06) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='W') AND D06_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )='H') AND D06_IN = '00:00' THEN 'H'   
			 WHEN (D06 = 'W' OR D06 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN = '00:00' THEN 'A' 
			 WHEN (D06 = 'H' OR D06 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN != '00:00' THEN 'P'
			 WHEN D06 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN = '00:00' THEN 'A' 
			 --WHEN D06 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D06_IN != '00:00' THEN 'P'  
			 --WHEN D06 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,06,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D06_IN != '00:00' THEN 'P'
			 ELSE D06 END ,	
	D06_L,D06_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 07) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='W') AND D07_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )='H') AND D07_IN = '00:00' THEN 'H'   
			 WHEN (D07 = 'W' OR D07 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN = '00:00' THEN 'A' 
			 WHEN (D07 = 'H' OR D07 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN != '00:00' THEN 'P'
			 WHEN D07 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN = '00:00' THEN 'A' 
			 --WHEN D07 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D07_IN != '00:00' THEN 'P'  
			 --WHEN D07 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,07,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D07_IN != '00:00' THEN 'P'
			 ELSE D07 END ,	
	D07_L,D07_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 08) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='W') AND D08_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )='H') AND D08_IN = '00:00' THEN 'H'   
			 WHEN (D08 = 'W' OR D08 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN = '00:00' THEN 'A' 
			 WHEN (D08 = 'H' OR D08 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN != '00:00' THEN 'P'
			 WHEN D08 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN = '00:00' THEN 'A' 
			 --WHEN D08 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D08_IN != '00:00' THEN 'P'  
			 --WHEN D08 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,08,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D08_IN != '00:00' THEN 'P'
			 ELSE D08 END ,	
	D08_L,D08_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 09) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='W') AND D09_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )='H') AND D09_IN = '00:00' THEN 'H'   
			 WHEN (D09 = 'W' OR D09 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN = '00:00' THEN 'A' 
			 WHEN (D09 = 'H' OR D09 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN != '00:00' THEN 'P'
			 WHEN D09 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN = '00:00' THEN 'A' 
			 --WHEN D09 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D09_IN != '00:00' THEN 'P'  
			 --WHEN D09 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,09,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D09_IN != '00:00' THEN 'P'
			 ELSE D09 END ,	
	D09_L,D09_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 10) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='W') AND D10_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )='H') AND D10_IN = '00:00' THEN 'H'   
			 WHEN (D10 = 'W' OR D10 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN = '00:00' THEN 'A' 
			 WHEN (D10 = 'H' OR D10 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN != '00:00' THEN 'P'
			 WHEN D10 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN = '00:00' THEN 'A' 
			 --WHEN D10 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D10_IN != '00:00' THEN 'P'  
			 --WHEN D10 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,10,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D10_IN != '00:00' THEN 'P'
			 ELSE D10 END ,	
	D10_L,D10_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1	

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 11) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='W') AND D11_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )='H') AND D11_IN = '00:00' THEN 'H'   
			 WHEN (D11 = 'W' OR D11 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN = '00:00' THEN 'A' 
			 WHEN (D11 = 'H' OR D11 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN != '00:00' THEN 'P'
			 WHEN D11 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN = '00:00' THEN 'A' 
			 --WHEN D11 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D11_IN != '00:00' THEN 'P'  
			 --WHEN D11 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,11,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D11_IN != '00:00' THEN 'P'
			 ELSE D11 END ,
	D11_L,D11_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 12) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='W') AND D12_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )='H') AND D12_IN = '00:00' THEN 'H'   
			 WHEN (D12 = 'W' OR D12 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN = '00:00' THEN 'A' 
			 WHEN (D12 = 'H' OR D12 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN != '00:00' THEN 'P'
			 WHEN D12 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN = '00:00' THEN 'A' 
			 --WHEN D12 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D12_IN != '00:00' THEN 'P'  
			 --WHEN D12 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,12,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D12_IN != '00:00' THEN 'P'
			 ELSE D12 END ,	
	D12_L,D12_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 13) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='W') AND D13_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )='H') AND D13_IN = '00:00' THEN 'H'   
			 WHEN (D13 = 'W' OR D13 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN = '00:00' THEN 'A' 
			 WHEN (D13 = 'H' OR D13 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN != '00:00' THEN 'P'
			 WHEN D13 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN = '00:00' THEN 'A' 
			 --WHEN D13 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D13_IN != '00:00' THEN 'P'  
			 --WHEN D13 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,13,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D13_IN != '00:00' THEN 'P'
			 ELSE D13 END ,	
	D13_L,D13_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 14) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='W') AND D14_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )='H') AND D14_IN = '00:00' THEN 'H'   
			 WHEN (D14 = 'W' OR D14 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN = '00:00' THEN 'A' 
			 WHEN (D14 = 'H' OR D14 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN != '00:00' THEN 'P'
			 WHEN D14 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN = '00:00' THEN 'A' 
			 --WHEN D14 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D14_IN != '00:00' THEN 'P'  
			 --WHEN D14 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,14,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D14_IN != '00:00' THEN 'P'
			 ELSE D14 END ,	
	D14_L,D14_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 15) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='W') AND D15_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )='H') AND D15_IN = '00:00' THEN 'H'   
			 WHEN (D15 = 'W' OR D15 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN = '00:00' THEN 'A' 
			 WHEN (D15 = 'H' OR D15 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN != '00:00' THEN 'P'
			 WHEN D15 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN = '00:00' THEN 'A' 
			 --WHEN D15 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D15_IN != '00:00' THEN 'P'  
			 --WHEN D15 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,15,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D15_IN != '00:00' THEN 'P'
			 ELSE D15 END ,	
	D15_L,D15_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 16) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='W') AND D16_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )='H') AND D16_IN = '00:00' THEN 'H'   
			 WHEN (D16 = 'W' OR D16 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN = '00:00' THEN 'A' 
			 WHEN (D16 = 'H' OR D16 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN != '00:00' THEN 'P'
			 WHEN D16 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN = '00:00' THEN 'A' 
			 --WHEN D16 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D16_IN != '00:00' THEN 'P'  
			 --WHEN D16 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,16,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D16_IN != '00:00' THEN 'P'
			 ELSE D16 END ,	
	D16_L,D16_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 17) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='W') AND D17_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )='H') AND D17_IN = '00:00' THEN 'H'   
			 WHEN (D17 = 'W' OR D17 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN = '00:00' THEN 'A' 
			 WHEN (D17 = 'H' OR D17 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN != '00:00' THEN 'P'
			 WHEN D17 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN = '00:00' THEN 'A' 
			 --WHEN D17 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D17_IN != '00:00' THEN 'P'  
			 --WHEN D17 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,17,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D17_IN != '00:00' THEN 'P'
			 ELSE D17 END ,	
	D17_L,D17_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 18) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='W') AND D18_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )='H') AND D18_IN = '00:00' THEN 'H'   
			 WHEN (D18 = 'W' OR D18 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN = '00:00' THEN 'A' 
			 WHEN (D18 = 'H' OR D18 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN != '00:00' THEN 'P'
			 WHEN D18 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN = '00:00' THEN 'A' 
			 --WHEN D18 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D18_IN != '00:00' THEN 'P'  
			 --WHEN D18 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,18,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D18_IN != '00:00' THEN 'P'
			 ELSE D18 END ,	
	D18_L,D18_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 19) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='W') AND D19_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )='H') AND D19_IN = '00:00' THEN 'H'   
			 WHEN (D19 = 'W' OR D19 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN = '00:00' THEN 'A' 
			 WHEN (D19 = 'H' OR D19 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN != '00:00' THEN 'P'
			 WHEN D19 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN = '00:00' THEN 'A' 
			 --WHEN D19 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D19_IN != '00:00' THEN 'P'  
			 --WHEN D19 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,19,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D19_IN != '00:00' THEN 'P'
			 ELSE D19 END ,	
	D19_L,D19_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 20) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='W') AND D20_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )='H') AND D20_IN = '00:00' THEN 'H'   
			 WHEN (D20 = 'W' OR D20 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN = '00:00' THEN 'A' 
			 WHEN (D20 = 'H' OR D20 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN != '00:00' THEN 'P'
			 WHEN D20 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN = '00:00' THEN 'A' 
			 --WHEN D20 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D20_IN != '00:00' THEN 'P'  
			 --WHEN D20 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,20,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D20_IN != '00:00' THEN 'P'
			 ELSE D20 END ,		
	D20_L,D20_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 21) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='W') AND D21_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )='H') AND D21_IN = '00:00' THEN 'H'   
			 WHEN (D21 = 'W' OR D21 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN = '00:00' THEN 'A' 
			 WHEN (D21 = 'H' OR D21 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN != '00:00' THEN 'P'
			 WHEN D21 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN = '00:00' THEN 'A' 
			 --WHEN D21 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D21_IN != '00:00' THEN 'P'  
			 --WHEN D21 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,21,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D21_IN != '00:00' THEN 'P'
			 ELSE D21 END ,	
	D21_L,D21_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 22) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='W') AND D22_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )='H') AND D22_IN = '00:00' THEN 'H'   
			 WHEN (D22 = 'W' OR D22 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN = '00:00' THEN 'A' 
			 WHEN (D22 = 'H' OR D22 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN != '00:00' THEN 'P'
			 WHEN D22 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN = '00:00' THEN 'A' 
			 --WHEN D22 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D22_IN != '00:00' THEN 'P'  
			 --WHEN D22 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,22,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D22_IN != '00:00' THEN 'P'
			 ELSE D22 END ,		
	D22_L,D22_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 23) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='W') AND D23_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )='H') AND D23_IN = '00:00' THEN 'H'   
			 WHEN (D23 = 'W' OR D23 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN = '00:00' THEN 'A' 
			 WHEN (D23 = 'H' OR D23 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN != '00:00' THEN 'P'
			 WHEN D23 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN = '00:00' THEN 'A' 
			 --WHEN D23 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D23_IN != '00:00' THEN 'P'  
			 --WHEN D23 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,23,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D23_IN != '00:00' THEN 'P'
			 ELSE D23 END ,	
	D23_L,D23_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 24) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='W') AND D24_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )='H') AND D24_IN = '00:00' THEN 'H'   
			 WHEN (D24 = 'W' OR D24 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN = '00:00' THEN 'A' 
			 WHEN (D24 = 'H' OR D24 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN != '00:00' THEN 'P'
			 WHEN D24 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN = '00:00' THEN 'A' 
			 --WHEN D24 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D24_IN != '00:00' THEN 'P'  
			 --WHEN D24 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,24,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D24_IN != '00:00' THEN 'P'
			 ELSE D24 END ,	
	D24_L,D24_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 25) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='W') AND D25_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )='H') AND D25_IN = '00:00' THEN 'H'   
			 WHEN (D25 = 'W' OR D25 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN = '00:00' THEN 'A' 
			 WHEN (D25 = 'H' OR D25 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN != '00:00' THEN 'P'
			 WHEN D25 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN = '00:00' THEN 'A' 
			 --WHEN D25 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D25_IN != '00:00' THEN 'P'  
			 --WHEN D25 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,25,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D25_IN != '00:00' THEN 'P'
			 ELSE D25 END ,	
	D25_L,D25_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 26) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='W') AND D26_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )='H') AND D26_IN = '00:00' THEN 'H'   
			 WHEN (D26 = 'W' OR D26 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN = '00:00' THEN 'A' 
			 WHEN (D26 = 'H' OR D26 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN != '00:00' THEN 'P'
			 WHEN D26 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN = '00:00' THEN 'A' 
			 --WHEN D26 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D26_IN != '00:00' THEN 'P'  
			 --WHEN D26 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,26,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D26_IN != '00:00' THEN 'P'
			 ELSE D26 END ,	
	D26_L,D26_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 27) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='W') AND D27_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )='H') AND D27_IN = '00:00' THEN 'H'   
			 WHEN (D27 = 'W' OR D27 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN = '00:00' THEN 'A' 
			 WHEN (D27 = 'H' OR D27 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN != '00:00' THEN 'P'
			 WHEN D27 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN = '00:00' THEN 'A' 
			 --WHEN D27 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D27_IN != '00:00' THEN 'P'  
			 --WHEN D27 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,27,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D27_IN != '00:00' THEN 'P'
			 ELSE D27 END ,	
	D27_L,D27_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1

	UNION ALL

	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 28) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='W') AND D28_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )='H') AND D28_IN = '00:00' THEN 'H'   
			 WHEN (D28 = 'W' OR D28 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN = '00:00' THEN 'A' 
			 WHEN (D28 = 'H' OR D28 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN != '00:00' THEN 'P'
			 WHEN D28 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN = '00:00' THEN 'A' 
			 --WHEN D28 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D28_IN != '00:00' THEN 'P'  
			 --WHEN D28 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,28,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D28_IN != '00:00' THEN 'P'
			ELSE D28 END ,	D28_L,D28_E
			FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
			WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
			AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1


	IF  @rForMonth <> 2 or ((@rForYear % 4 = 0 AND @rForYear % 100 <> 0) OR @rForYear % 400 = 0 And @rForMonth  =2)
	BEGIN
		INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 29) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='W') AND D29_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )='H') AND D29_IN = '00:00' THEN 'H'   
			 WHEN (D29 = 'W' OR D29 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN = '00:00' THEN 'A' 
			 WHEN (D29 = 'H' OR D29 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN != '00:00' THEN 'P'
			 WHEN D29 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN = '00:00' THEN 'A' 
			 --WHEN D29 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D29_IN != '00:00' THEN 'P'  
			 --WHEN D29 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,29,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D29_IN != '00:00' THEN 'P'
			 ELSE D29 END ,	
	D29_L,D29_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END
	
	IF @rForMonth <> 2
	BEGIN
	INSERT INTO #TempMonthTrans
	SELECT EmployeeId,cast(rtrim(YEAR(attn_dt) *10000+ Month(attn_dt) *100+ 30) as datetime),
			CASE WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='W') AND D30_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )='H') AND D30_IN = '00:00' THEN 'H'   
			 WHEN (D30 = 'W' OR D30 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN = '00:00' THEN 'A' 
			 WHEN (D30 = 'H' OR D30 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN != '00:00' THEN 'P'
			 WHEN D30 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN = '00:00' THEN 'A' 
			 --WHEN D30 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D30_IN != '00:00' THEN 'P'  
			 --WHEN D30 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,30,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D30_IN != '00:00' THEN 'P'
			 ELSE D30 END ,	
	D30_L,D30_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END
	
	IF @rForMonth 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](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='W') AND D31_IN = '00:00' THEN 'W'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN != '00:00' THEN 'PW'
			 WHEN ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )='H') AND D31_IN = '00:00' THEN 'H'   
			 WHEN (D31 = 'W' OR D31 = 'PW') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'W' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN = '00:00' THEN 'A' 
			 WHEN (D31 = 'H' OR D31 = 'PH') AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN != '00:00' THEN 'P'
			 WHEN D31 = 'H' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN = '00:00' THEN 'A' 
			 --WHEN D31 = 'PH' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='H') AND D31_IN != '00:00' THEN 'P'  
			 --WHEN D31 = 'PW' AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , @rForYear ,@rForMonth ,31,BM.Id ,@rDeptId,EM.OrgID )!='W') AND D31_IN != '00:00' THEN 'P'
			 ELSE D31 END ,	
	D31_L,D31_E FROM sBiometric.tMonthTrans TM INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id =TM.EmployeeId INNER JOIN sSetup.tBatchMaster BM  ON BM.OrgId=EM.OrgID
	            WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
	                  AND DATEPART(MONTH,ATTN_DT)=@rForMonth AND DATENAME(YEAR,ATTN_DT) = @rForYear  AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND BM.IsActive = 1
	END


	SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		MT.EmployeeId,
		MT.EmpCode,
		EM.FirstName + ' ' + EM.LastName AS EmployeeName,  
		MT.Tot_Attn  AS TotalPresentDays,
		MT.Tot_Abs AS TotalAbsentDays,
		MT.Tot_WeekOFF AS TotalWeekOffs,
		MT.Tot_Holiday AS TotalHolidays,
		OM.Id AS OrganizationId,
		OM.DisplayTitle AS OrganizationTitle,
		OM.OrderIndex AS OrganizationOrderIndex,
		EM.Number AS EmployeeNumber,
		DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays,
		MT.Count_Late AS Count_Late,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='A') AS WeekOffsWiseTotalAbsentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='W') AS WeekOffsWiseTotalWeekOffs,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='H') AS WeekOffsWiseTotalHolidays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND (PresentStatus='P' OR PresentStatus='PW')) AS WeekOffsWiseTotalPresentDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='HD') AS WeekOffsWiseTotalHalfDays,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='LH') AS WeekOffsWiseTotalLessHours,
		(SELECT COUNT(Id) FROM #TempMonthTrans WHERE EmployeeId=MT.EmployeeId AND PresentStatus='E') AS WeekOffsWiseTotalErrorCase

	FROM
	sBiometric.tMonthTrans MT
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId --AND SourceTypeId = 95
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	WHERE
	(EM.OrgId = @rOrgId OR @rOrgId = 0)
	AND YEAR(MT.Attn_Dt) = @rForYear
	AND (MONTH(MT.Attn_dt) = @rForMonth )
	AND (EJD.OrganizationDepartmentId = @rDeptId OR @rDeptId = 0)		 	
	AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
	AND ISNULL(EM.IsOtherUser,0) = 0 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND (OM.OrgGroupId = @rOrgGroupId)
	AND ((EJD.OrgGroupDepartmentId = @OrgGroupDepartmentId) OR (@OrgGroupDepartmentId=0)) 

	DROP Table #TempMonthTrans
END
GO
PRINT N'Altering [sCanteen].[pAttendanceForBreakListGet]...';


GO
ALTER PROCEDURE [sCanteen].[pAttendanceForBreakListGet]
	 	 
	 	@rBreakTypeId int,	
		@rStudentCode nvarchar(20),
		@rFromAttendanceDate date,
		@rToAttendanceDate date,
	 	@rSuid nvarchar(50)
	 	--@rPresent int
	 	
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			SA.StudentId As SourceId,
			SA.Code AS StudentCode,
			SA.Name,
			SA.SUId,
			ATR.BreakDate,
			BTM.Title AS BreakType			
			
	 FROM  
			sStudent.vStudentAcademic SA 
			INNER JOIN sCanteen.tRegisterForBreak RB ON SA.StudentId = RB.SourceId AND RB.SourceTypeId = 2003 
			 INNER JOIN sCanteen.tAttendanceForBreak ATR ON ATR.SourceId=SA.StudentId 
		   INNER JOIN sCanteen.tBreakTypeMaster BTM	ON BTM.Id=  RB.BreakTypeId 
			
			
			--INNER JOIN sHostel.tAssignRoom AR ON SA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
		 --   INNER JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId = AR.SourceId 
			--LEFT JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id=ATR.AbsentReasonId
			--INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId 
	  --      INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
	  --      INNER JOIN sHostel.tHostelAttendanceTypeMaster ATM ON ATM.Id=ATR.HostelAttendanceTypeId
	  --      LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
	    
			
  WHERE 
	 ((ATR.BreakTypeId=@rBreakTypeId) OR (@rBreakTypeId=0))
	 
	  AND ((SA.Code = @rStudentCode) OR (@rStudentCode=''))
	
	  AND ((ATR.BreakDate >= @rFromAttendanceDate) OR (ISNULL(@rFromAttendanceDate,'') = ''))
	  AND ((ATR.BreakDate <= @rToAttendanceDate) OR (ISNULL(@rToAttendanceDate,'') = ''))
	   AND ((SA.SUId=@rSuid) OR (@rSuid=''))	 	
      ORDER BY ATR.BreakDate DESC
END
GO
PRINT N'Altering [sCanteen].[pCanteenIssueMasterGet]...';


GO
ALTER PROCEDURE [sCanteen].[pCanteenIssueMasterGet]
	
	@rId bigint = 0,
	@rCanteenId int ,
	@rFromDate date,
	@rToDate date,
	@rSUID nvarchar(50)=''

	--@rCode nvarchar(max)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	 SELECT 
	        CI.Id,
			CI.CanteenId,
			CI.SourceTypeId,
			CI.SourceId,
			CI.IssueDate,
			CI.TotalAmount,
			CI.CreatedDateTime,
			(CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Code,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.Code, '') ElSE ''
			 END) AS Code,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.Name,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.FirstName +' ' + EM.MiddleName + ' ' + EM.LastName ,'') ElSE CI.OtherName
			 END) AS Name,
			 ISNULL(CI.OtherName,'') AS OtherName,
			 (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.OrgId,'')
			WHEN  CI.SourceTypeId=95  THEN isnull(EM.OrgId, '') ElSE ''
			 END) AS OrgId,
			  (CASE WHEN CI.SourceTypeId=2003 THEN  isnull(SMast.SUId,'')
			 ElSE ''
			 END) AS SUId
		
	   FROM sCanteen.tCanteenIssue CI
	   LEFT JOIN  sStudent.vStudentLastAcademic SMast ON SMast.StudentId = CI.SourceId AND CI.SourceTypeId = 2003  
       LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = CI.SourceId AND CI.SourceTypeId = 95
     
      
	  
	  WHERE ((CI.Id = @rId) OR (@rId = 0))
		  AND CI.CanteenId = @rCanteenId
		  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		 AND ((CI.IssueDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		 AND ((SMast.SUID = @rSUID) OR (ISNULL(@rSUID,'')=''))
	 --  AND ((CI.IssueDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	 AND ISNULL(EM.IsOtherUser,0) = 0 
order by CI.IssueDate desc
	  --EXEC [sCanteen].[pCanteenIssueDetailGet] @rId,@rCanteenId
END
GO
PRINT N'Altering [sCertificate].[pCharacterAdd]...';


GO


ALTER PROCEDURE [sCertificate].[pCharacterAdd]

	@rId bigint
   ,@rAcademicId bigint
   ,@rNumber int
   ,@rCharacterDate date
   ,@rCreatedUserId bigint
   ,@rOrgId int
   ,@rRemark nvarchar(200)
   ,@rBatchId int
   ,@rIsNumberBatchWise bit = 0
	       
           	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	BEGIN TRY
	BEGIN TRANSACTION	
	
	If(@rIsNumberBatchWise = 1)	
	BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tCharacter WHERE OrgId=@rOrgId AND BatchId = @rBatchId
		END	
		
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tCharacter WHERE Number=@rNumber AND OrgId=@rOrgId AND BatchId = @rBatchId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
	END
	ELSE
	BEGIN
		IF(@rNumber = 0)	
		BEGIN
			SELECT @rNumber = ISNULL(MAX(Number),0) + 1 FROM sCertificate.tCharacter WHERE OrgId=@rOrgId 
		END	
		
		IF(@rId = 0)	
		BEGIN
			IF EXISTS(SELECT 1 FROM sCertificate.tCharacter WHERE Number=@rNumber AND OrgId=@rOrgId)
			BEGIN
				SELECT -103 AS Result
				RETURN
			END
		END
	END
		
	 DECLARE @lNextNumber BIGINT
 
	  IF(@rId = 0)	
		BEGIN
			EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sCertificate.tCharacter', 0, 1, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sCertificate.tCharacter
			(
				Id
			   ,AcademicId
			   ,Number
			   ,characterDate
			   ,OrgId
			   ,CreatedUserId
			   ,CreatedDateTime
			   ,Remark
			   ,BatchId
			)
			VALUES
			(	@lNextNumber
			   ,@rAcademicId
			   ,@rNumber
			   ,@rCharacterDate
			   ,@rOrgId
			   ,@rCreatedUserId
			   ,sCommon.fGetDate() 
			   ,@rRemark
			   ,@rBatchId
			)
		END
		ELSE
		BEGIN
			SET @lNextNumber = @rId
			UPDATE  sCertificate.tCharacter
			SET
				AcademicId=@rAcademicId,
				characterDate=@rCharacterDate,
				UpdatedUserId=@rCreatedUserId,
				UpdatedDateTime=sCommon.fGetDate(),
				Remark=@rRemark,
				BatchId = @rBatchId
			  WHERE Id = @rId
		END  	
	SELECT @lNextNumber AS Result
	COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		Select error_message()
	END CATCH	
	
END
GO
PRINT N'Altering [sCertificate].[pRptLeavingCertificateGet]...';


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

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

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


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


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


GO

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

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

			UNION ALL

			SELECT
			 CS.CircularId,
			 CS.SourceTypeId,
			 CS.SourceId,
			 DM.DisplayTitle AS Source,
			 'Department' AS SourceType,
			 '' AS RollNo,
             '' AS Code,
             DM.Title AS ClassDepartment,
             OM.DisplayTitle AS OrgName,
             AM.Title As AssignedTo,
			 ISNULL(CS.AssigneeToId, 0) AS AssigneeToId

			FROM sCommunication.tCircularScope CS
			INNER JOIN sSetup.tDepartmentMaster DM
				ON CS.SourceId=DM.Id
			INNER JOIN sSetup.tOrganizationMaster OM
				ON DM.OrgId=OM.Id 
			LEFT JOIN sCommon.tAssigneeMaster AM 
				ON AM.Id = CS.AssigneeToId
			WHERE CS.CircularId=@rCircularId AND CS.SourceTypeId=2017

			UNION ALL

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

			UNION ALL

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


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


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


GO
ALTER PROCEDURE [sCommunication].[pCircularViewGet]
	@rCircularId bigint,
	@rClassId int=0,
	@rDivisionId int=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON;

BEGIN

	BEGIN TRY
	 BEGIN TRANSACTION	
		 BEGIN
		 SELECT 
			 CASE WHEN CV.SourceTypeId = 2003 THEN  SM.Code WHEN CV.SourceTypeId = 95 THEN EM.Code END as Code,
			 CASE WHEN CV.SourceTypeId = 2003 THEN  SM.FirstName +' '+ SM.LastName WHEN CV.SourceTypeId = 95 THEN EM.FirstName +' '+ EM.LastName END as Name,
			 CV.ViewByDateTime			 
		 FROM
			 sCommunication.tCircularView as CV
			 LEFT JOIN sStudent.tStudentMaster SM on SM.Id = CV.SourceId AND CV.SourceTypeId = 2003
			 LEFT JOIN sStudent.tAcademic A ON A.StudentId = SM.Id AND CV.SourceTypeId = 2003
			 LEFT JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId AND CV.SourceTypeId = 2003
			 LEFT JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId AND CV.SourceTypeId = 2003
			 LEFT JOIN sHrm.tEmployeeMaster EM on EM.Id = CV.SourceId AND CV.SourceTypeId = 95
		 WHERE
			CircularId = @rCircularId AND CV.SourceId != ''
			AND ((CM.Id=@rClassId)OR(@rClassId=0))
			AND((DM.Id=@rDivisionId)OR(@rDivisionId=0))
		 GROUP BY CV.CircularId, CV.ViewByDateTime,CV.SourceTypeId,SM.Code,SM.FirstName,SM.LastName,EM.Code,EM.FirstName,EM.LastName

		SELECT 1 AS RESULT
        END  
	COMMIT TRANSACTION
	END TRY

	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH
END
GO
PRINT N'Altering [sFee].[pApplyExemptionType]...';


GO
ALTER PROCEDURE [sFee].[pApplyExemptionType]
	
	@rOrgId int,
	@rBatchId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint,
	@rExemptionTypeId int,
	@rAcademicId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
	DECLARE @lClassId int
	DECLARE @lDivisionId int
	DECLARE @lAdmissionCategoryId int
	DECLARE @lExemptionTypeId int
	DECLARE @lCalculationTypeId tinyint
	
	SELECT @lClassId=ClassId,@lDivisionId=DivisionId,@lAdmissionCategoryId=AdmissionCategoryId,@lExemptionTypeId=ExemptionTypeId 
	FROM sStudent.vStudentAcademic 
	WHERE AcademicId = @rAcademicId AND BatchId=@rBatchId AND OrgId = @rOrgId AND OrgGroupBatchId=@rOrgGroupBatchId
	
	SELECT @lCalculationTypeId=ISNULL(CalculationTypeId,0) FROM sFee.tExemptionTypeMaster WHERE Id = @lExemptionTypeId
	
	-- Exemption Type Temp Table
	CREATE TABLE #TempExemptionType
	(
		[AutoId] int identity,
		[AcademicId] bigint NULL,
		[RollNo] int NULL,
		[Name] nvarchar(500) NULL,
		[Code] nvarchar(20) NULL,
		[ClassId] int NULL,
		[DivisionId] int NULL,
		[ClassName] nvarchar(100) NULL,
		[DivisionName] nvarchar(100) NULL,
		[DivisionOrder] int NULL,
		[ClassDivision] nvarchar(200) NULL,
		[FeeSetupId] int NULL,
		[IsVariable] bit NULL,
		[Amount] decimal(12,2) NULL,
		[StartDate] date NULL,
		[EndDate] date NULL,
		[FAAmount] decimal(12,2) NULL,
		[DiscountAmount] decimal(12,2) NULL,
		[AdditionalAmount] decimal(12,2) NULL,
		[PaidAmount] decimal(12,2) NULL,
		[PendingAmount] decimal(12,2) NULL,
		[Remark] nvarchar(200) NULL,
		[FeeId] int NULL,
		[FeeName] nvarchar(100) NULL,
		[OrgId] int NULL,
		[OrgName] nvarchar(100) NULL,
		[OrgOrderIndex] int NULL,
		[ReceiptBookId] int NULL,
		[ReceiptBookTitle] nvarchar(100) NULL,
		[ReceiptOrderIndex] int NULL,
		[OrgGroupBatchId] int NULL,
		[DepartmentId] int NULL,
		[DepartmentName] nvarchar(100) NULL,
		[ParentContactNo] nvarchar(100) NULL,
		[ExemptionTypeId] int NULL,
	)
	-- End Exemption Type Temp Table
	
	
	
	INSERT INTO #TempExemptionType 
	SELECT 
		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) + ISNULL(FA.VariableAmount,0.00) 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,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		FS.ReceiptBookId,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.OrgGroupBatchId,
		SA.DepartmentId,
		SA.DepartmentName,
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
		@lExemptionTypeId
  FROM 
  
			 sStudent.vStudentAcademic SA
		INNER JOIN 
		(
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName			 
			FROM sFee.tFeeSetup FS1
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
			AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
			WHERE 
			    SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND	((FS1.ClassId=@lClassId) OR (@lClassId=0))				
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=0)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				
				UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName 
				
			FROM sFee.tFeeSetup FS1
		INNER JOIN sFee.tFeeOptional FO
			ON FO.FeeSetupId=FS1.Id
	    INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
		INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
			AND ((SA1.ClassId=@lClassId) OR (@lClassId=0)) AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
			AND ((SA1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
		INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
		WHERE
		        SA1.OrgGroupBatchId = @rOrgGroupBatchId
				AND ((FS1.ClassId=@lClassId) OR (@lClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@lAdmissionCategoryId) OR (@lAdmissionCategoryId=0))
				AND (FS1.IsOptional=1)
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))				
				
		) 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.ClassId=@lClassId OR @lClassId=0) 
				AND ((SA1.DivisionId=@lDivisionId) OR (@lDivisionId=0))
				AND (SA1.DivisionId=@lDivisionId OR @lDivisionId=0)
				
			WHERE		
				(R.SourceTypeId = 2001)
				AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND (R.IsObsolete = 0) 
				AND ((SA1.OrgGroupBatchId = @rOrgGroupBatchId))
				AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				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
	WHERE	
			SA.AcademicId = @rAcademicId
			AND SA.OrgId = @rOrgId 
			AND SA.BatchId=@rBatchId
			AND SA.OrgGroupBatchId = @rOrgGroupBatchId
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=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)
			
			
		DECLARE @lCode nvarchar(20)
		SELECT @lCode=A.Code FROM #TempExemptionType A
		INNER JOIN sFee.tExemptionTypeDetail ETD ON ETD.FeeId = A.FeeId AND ETD.ExemptionTypeId = @lExemptionTypeId
		WHERE AcademicId = @rAcademicId 
		AND ((@lCalculationTypeId=1 AND A.PendingAmount < (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)) OR (@lCalculationTypeId=2 AND A.PendingAmount < ISNULL(ETD.ExemptionPercentage,0)))
		IF @lCode IS NOT NULL
		BEGIN
				SELECT -101 AS Result,@lCode AS Code
			    RETURN
		END 
		
	BEGIN TRY 
	BEGIN TRANSACTION
	BEGIN -- Update Fee Allocation
		UPDATE AL 
		SET
		    DiscountAmount = R.Result,
			UpdatedUserId = @rCreatedUserId,
			UpdatedDateTime = sCommon.fGetDate()
		FROM
		(
		SELECT		
			 CASE
             WHEN @lCalculationTypeId= 1 THEN (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)
             WHEN @lCalculationTypeId = 2 THEN ISNULL(ETD.ExemptionPercentage,0)
             END AS Result,
			 ISNULL(A.Amount,0) AS Amount,
			 ISNULL(ETD.ExemptionPercentage,0) AS ExemptionPercentage,
			 A.ExemptionTypeId,
			 A.PendingAmount,
			 A.AcademicId,
			 A.FeeSetupId
		FROM #TempExemptionType A
	    INNER JOIN sFee.tExemptionTypeDetail ETD ON ETD.FeeId = A.FeeId AND ETD.ExemptionTypeId = @lExemptionTypeId
		) 
		R  INNER JOIN	sFee.tFeeAllocation AL ON AL.SourceId = R.AcademicId AND AL.FeeSetupId = R.FeeSetupId
		WHERE
		((@lCalculationTypeId=1 AND R.Amount >= (((ISNULL(R.Amount,0)) * (ISNULL(R.ExemptionPercentage,0)))/100)) OR (@lCalculationTypeId=2 AND R.Amount >= ISNULL(R.ExemptionPercentage,0)))
	END	

	BEGIN -- Insert Fee Allocation
		INSERT INTO sFee.tFeeAllocation
		(
		SourceTypeId,
		SourceId,
		FeeSetupId,
		VariableAmount,
		DiscountAmount,
		CreatedUserId,
		CreatedDateTime
		)
		SELECT		
			 2001,
			 A.AcademicId,
			 A.FeeSetupId,
			 A.FAAmount,
			 CASE
             WHEN @lCalculationTypeId= 1 THEN  (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)
             WHEN @lCalculationTypeId = 2 THEN ROUND(ISNULL(ETD.ExemptionPercentage,0),0)
             END,
			 @rCreatedUserId,
			 sCommon.fGetDate()
		FROM #TempExemptionType A 
	    INNER JOIN sFee.tExemptionTypeDetail ETD ON ETD.FeeId = A.FeeId AND ETD.ExemptionTypeId = @lExemptionTypeId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId = A.AcademicId AND FA.FeeSetupId = A.FeeSetupId 
		WHERE FA.SourceId IS NULL AND FA.FeeSetupId IS NULL
		AND 
		((@lCalculationTypeId=1 AND A.Amount >= (((ISNULL(A.Amount,0)) * (ISNULL(ETD.ExemptionPercentage,0)))/100)) OR (@lCalculationTypeId=2 AND A.Amount >= ISNULL(ETD.ExemptionPercentage,0)))
	END
	DROP TABLE #TempExemptionType
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY
BEGIN CATCH 
		DROP TABLE #TempExemptionType
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Altering [sFee].[pDepositAddBulkGet]...';


GO
ALTER PROCEDURE [sFee].[pDepositAddBulkGet]
           @rOrgId int,    
           @rCode nvarchar(max),
           @rStrSuid nvarchar(max)='',
           @rBatchId int,
           @rClassId int,
           @rDivisionId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    SELECT  
			vSA.OrgId,
			vSA.Code,
			vSA.Name AS StudentName,        
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
			ISNULL(vSA.SUId,'') AS SUId,
			VSA.AcademicId,
			VSA.OrganiZationName
  FROM 		
			sStudent.vStudentAcademic vSA
  WHERE  
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
	    AND vSA.BatchID=@rBatchId
	    AND VSA.StatusId=1
	    AND (ISNULL(VSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='') 
	    AND (ISNULL(VSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
	    AND (vSA.ClassId=@rClassId OR @rClassId=0)
	    AND (vSA.DivisionId=@rDivisionId OR @rDivisionId=0)
		Order By VSA.RollNo
END
GO
PRINT N'Altering [sFee].[pDepositAdjustmentBulkGet]...';


GO
ALTER PROCEDURE [sFee].[pDepositAdjustmentBulkGet]
           @rOrgId int,    
           @rCode nvarchar(max),
           @rStrSuid nvarchar(max)='',
           @rBatchId int,
           @rClassId int,
           @rDivisionId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    SELECT  
			vSA.OrgId,
			vSA.Code,
			vSA.Name AS StudentName,        
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
			ISNULL(vSA.SUId,'') AS SUId,
			VSA.AcademicId,
			VSA.OrganiZationName,
			(
			(SELECT 
			ISnull (SUM(DAJ.Amount),0)
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			Where (DAJ.DepositHeadId = DA.DepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 			
			AND VA.StudentId =  vSA.StudentId )
			+ 
				(SELECT ISnull (SUM(DR.RefundAmount),0)  AS Debit
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			Where (DR.DepositHeadId = DA.DepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 			
			AND VA.StudentId =  vSA.StudentId)
			) AS AdjustmentAmount
  FROM 		
			sStudent.vStudentAcademic vSA
			LEFT JOIN [sFee].[tDepositAdjustment] DA ON DA.AcademicId = vSA.AcademicId
  WHERE  
			(vSA.OrgId=@rOrgId OR @rOrgId=0)
			AND vSA.BatchID=@rBatchId
			AND VSA.StatusId=1
			AND (ISNULL(VSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='') 
			AND (ISNULL(VSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='')
			AND (vSA.ClassId=@rClassId OR @rClassId=0)
			AND (vSA.DivisionId=@rDivisionId OR @rDivisionId=0) 
			GROUP BY vSA.OrgId,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName,vSA.SUId,VSA.AcademicId,VSA.OrganiZationName, DA.DepositHeadId, vSA.StudentId,VSA.RollNo
			Order By VSA.RollNo
END
GO
PRINT N'Altering [sFee].[pDepositRefundBulkGet]...';


GO
ALTER PROCEDURE [sFee].[pDepositRefundBulkGet]
           @rOrgId int,    
           @rCode nvarchar(max),
           @rStrSuid nvarchar(max)='',
           @rBatchId int,
           @rClassId int,
           @rDivisionId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    SELECT  
			vSA.OrgId,
			vSA.Code,
			vSA.Name AS StudentName,        
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
			ISNULL(vSA.SUId,'') AS SUId,
			VSA.AcademicId,
			VSA.OrganiZationName
  FROM 		
			sStudent.vStudentAcademic vSA
  WHERE  
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
	    AND vSA.BatchID=@rBatchId
	    AND VSA.StatusId=1
	    AND (ISNULL(VSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='') 
	    AND (ISNULL(VSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
	    AND (vSA.ClassId=@rClassId OR @rClassId=0)
	    AND (vSA.DivisionId=@rDivisionId OR @rDivisionId=0)
		Order By VSA.RollNo
END
GO
PRINT N'Altering [sFee].[pFeeAllocationGet]...';


GO

ALTER PROCEDURE [sFee].[pFeeAllocationGet]
	 
		
		@rSourceId bigint ,
		@rSourceTypeId int,
		@rBatchId int,
		@rStudentId bigint =0
		
	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
		-- Added
		DECLARE @lExemptionTypeId int = 0
		DECLARE @lExemptionType nvarchar(100) = ''
		
		SELECT @lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId, @lExemptionTypeId = ExemptionTypeId FROM sStudent.vStudentAcademic WHERE AcademicId=@rSourceId
		
		-- Added
		SELECT @lExemptionType = Title FROM [sFee].[tExemptionTypeMaster] WHERE Id = @lExemptionTypeId
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,
			ISNULL(FA.NotApplicableRemark,'') AS NotApplicableRemark,
			ISNULL(FA.AdditionalRemark,'') AS AdditionalRemark,
			ISNULL(FA.DiscountRemark,'') AS ExemptionRemark,
			FM.OrderIndex,
			0 AS ReceiptNumber,
			'1900-01-01'AS ReceiptDate,
			ISNULL(FS.ReceiptBookId,0) AS ReceiptBookId,
			FS.CollectionGroupId,
			FM.FeeHeadId,
			FS.FeeDuration,
			ISNULL(FM.Code,'') AS FeeCode,
			CASE 
			      WHEN (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) > 0)
			          AND (ISNULL(FS.StartDate,'1900-01-01') > GETDATE()) AND (ISNULL(FS.Amount,0) > 0 OR ISNULL(FA.VariableAmount,0.00)>0) THEN 'To Pay' 
                  WHEN (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 (GETDATE() > ISNULL(FS.StartDate,'1900-01-01')) AND (ISNULL(FS.Amount,0) > 0 OR ISNULL(FA.VariableAmount,0.00)>0) THEN 'Unpaid' 
				  WHEN (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) <= 0)
				      AND (ISNULL(FS.Amount,0) > 0 OR ISNULL(FA.VariableAmount,0.00)>0) THEN 'Paid'
				 ELSE
				 '' END AS Status,
			@lExemptionType AS ExemptionType
  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
		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
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


GO
 
ALTER PROCEDURE [sFee].[pFeeCustomSearchGet]
(
	@rOrgGroupBatchId int,
	@rOrgId smallint,
	@rBatchId int,
	@rOrderBy nvarchar(max) = 'ReceiptNumber',
	@rCode [nvarchar](20) = '',
	@rFirstName [nvarchar](50) = '',	
	@rLastName [nvarchar](50) = '',	
	@rDivisionId nvarchar(max) = '',
	@rReceiptBookId nvarchar(max) = '',
	@rFromReceiptDate Date = '0001-01-01',
	@rToReceiptDate Date = '9999-12-31',
	@rFromReceiptNo int,
	@rToReceiptNo int,
	@rCreatedUserId bigint,
	@rIsObsolete bit,
	@rDropDownStatusId int,
	@rDropDownClassId int,
	@rDropDownDivisionId int,
	@rDropDownReceiptBookId int,
	@rDepartmentId int=0,
	@rPageIndex int = null,
	@rAdmissionCategoryId int = 0
 )
AS
SET NOCOUNT ON
BEGIN
	create table #TEMPFee
	(
		tid int identity(1,1),t_AcedemicId bigint,t_ReceiptId bigint
	)
	
	DECLARE @Sql nvarchar(MAX)
	IF(@rFromReceiptDate IS NULL)
		SET @rFromReceiptDate='0001-01-01'
	IF(@rToReceiptDate IS NULL)
		SET @rToReceiptDate='9999-12-31'

		
	SET @rCode = sCommon.fSearchStringGet(@rCode)
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	select @rPageIndex = case when isnull(@rPageIndex,0) = 0 then 1 else @rPageIndex end
	
	SELECT FCS.AcademicId,FCS.ClassId,FCS.DivisionId,FCS.RollNo,FCS.OrgGroupBatchId,
	FCS.OrgId,FCS.BatchId,FCS.OrgGroupBatch,FCS.Organization,FCS.Batch,FCS.StudentId,
	FCS.Code,FCS.Number,FCS.FirstName,FCS.LastName,FCS.Name,FCS.StatusId,FCS.ClassName,
	FCS.DivisionName,FCS.StatusName,FCS.ReceiptId,FCS.ReceiptNumber,FCS.ReceiptDate,
	FCS.ReceiptAmount,FCS.ChequeNo,FCS.BankName,FCS.Remark,FCS.IsObsolete,FCS.FeeReceiptBookId,
	FCS.ReceiptBookCode,FCS.ReceiptBookName,FCS.Address1,FCS.Address2,FCS.BankAccountNumber,
	FCS.PayTypeId,FCS.PayType,FCS.CreatedUserId,FCS.CreatedUserName, FCS.ParentContactNo
	into sFee.tTempFee1
	FROM sFee.vFeeCustomSearch FCS
	INNER JOIN sSetup.tClassMaster CM ON CM.Id = FCS.ClassId
	WHERE (FCS.OrgGroupBatchId = @rOrgGroupBatchId)
	AND	((FCS.OrgId = @rOrgId) OR (@rOrgId=0))
	AND ((FCS.BatchId = @rBatchId) OR (@rBatchId=0))
	AND ((FCS.Code Like @rCode + '%') OR (@rCode = ''))
	AND ((FCS.FirstName Like @rFirstName  + '%') OR (@rFirstName = ''))
	AND ((FCS.LastName Like @rLastName + '%')OR(@rLastName = ''))
	AND ((FCS.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo =0))
	AND ((FCS.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo=0))
	AND ((ISNULL(FCS.ReceiptDate,'0001-01-01') >= @rFromReceiptDate) OR (ISNULL(@rFromReceiptDate,'') = ''))
	AND ((ISNULL(FCS.ReceiptDate,'9999-12-31') <= @rToReceiptDate) OR (ISNULL(@rToReceiptDate,'') = ''))
	AND (FCS.DivisionId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionId,','))OR @rDivisionId='')
	AND (FCS.FeeReceiptBookId In( SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookId,','))OR @rReceiptBookId='')
	AND ((FCS.CreatedUserId=@rCreatedUserId) OR (@rCreatedUserId=0))
	AND (FCS.IsObsolete=@rIsObsolete)
	AND ((FCS.StatusId = @rDropDownStatusId) OR (@rDropDownStatusId=0))
	AND ((FCS.ClassId = @rDropDownClassId) OR (@rDropDownClassId=0))
	AND ((FCS.DivisionId = @rDropDownDivisionId) OR (@rDropDownDivisionId=0))
	AND ((FCS.FeeReceiptBookId = @rDropDownReceiptBookId) OR (@rDropDownReceiptBookId=0))
	AND ((Cm.DepartmentId =@rDepartmentId ) OR (@rDepartmentId=0))
	AND ((FCS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
	
	SET @rOrderBy=Replace(@rOrderBy,'ID No','Code')
	SET @rOrderBy=Replace(@rOrderBy,'GR No','Code')
	
	SET @sql='SELECT Code AS Code,Name,ReceiptNumber,ReceiptDate,ReceiptAmount,
	PayType,ChequeNo,BankName,ReceiptBookName,Remark,OrgId,BatchId
	FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	SET @sql='INSERT INTO #TEMPFee SELECT AcademicId, ReceiptId
	FROM sFee.tTempFee1 ORDER BY '+@rOrderBy
	
	exec(@Sql)
	
	declare @lTotalRecords int,@lPageSize int = 10,@lPaging varchar(max)='',@lResult varchar(max)=''
	select @lTotalRecords = count(*) from #TEMPFee
	
	select @lPaging = @lPaging + dbo.fnc_SearchPagingFormat(@rPageIndex,@lTotalRecords,@lPageSize)
	
	select @lResult = @lResult + '<tr attrId="' + convert(varchar,isnull(t_AcedemicId,0)) + '"
	attrCode="' + isnull(Code,'') + '"
	attrReceiptNo="' + isnull(convert(varchar,ReceiptNumber),'') + '"
	attrBatchId="' + convert(varchar,@rBatchId) + '"
	attrOrgId="' + convert(varchar,@rOrgId) + '"
	attrOrgGroupBatchId="' + convert(varchar,@rOrgGroupBatchId) + '">
	<td><a style="cursor:pointer;" onclick="SecectThisRecord(this);">Select</a></td><td>' + isnull(Code,'') + '</td>
	<td>' + isnull(Name,'') + '</td><td>' + isnull(convert(varchar,ReceiptNumber),'') + '</td>
	<td>' + isnull(convert(varchar,ReceiptDate,103),'') + '</td>
	<td>' + isnull(convert(varchar,ReceiptAmount),'') + '</td><td>' + isnull(PayType,'') + '</td>
	<td>' + isnull(ChequeNo,'') + '</td><td>' + isnull(BankName,'') + '</td>
	<td>' + isnull(ReceiptBookName,'') + '</td><td>' + isnull(Remark,'') + '</td></tr>'
	from sFee.tTempFee1,#TEMPFee where t_AcedemicId = AcademicId AND t_ReceiptId = ReceiptId
	and tid between ((@lPageSize * (@rPageIndex - 1)) + 1) AND (@lPageSize * @rPageIndex)
	
	select @lPaging as UserPaging,@lResult as UserResult,@lTotalRecords as UserTotal
			
	DROP Table sFee.tTempFee1
	drop Table #TEMPFee
END
GO
PRINT N'Altering [sFee].[pFeeDiscountReceiptListGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeDiscountReceiptListGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(20)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(50) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='' 

 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN       
 SELECT 
  A.StatusId,    
  R.Id AS ReceiptId,    
  R.SourceId AS SourceId,    
  R.SourceTypeId AS SourceTypeId,    
  CASE WHEN R.SourceTypeId=2001 THEN 'Student'    
  ELSE  'Employee' END AS SourceType,    
  --STM.Title     
  A.Code AS Code,    
  A.Name,    
  R.ReceiptNumber,    
  R.ReceiptDate,    
  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,    
  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
  ISNULL(R.DiscountAmount,0)AS DiscountAmount,    
  R.PayTypeId,    
  PTM.Title AS PayType,    
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
  --R.ChequeNo,    
  R.BankName,    
  R.ReceiptBookId,    
  RBM.Title AS ReceiptBook,    
  R.IsObsolete,    
  A.OrgId,    
  OM.DisplayTitle AS Organization,    
  R.BatchId,    
  BM.Title AS Batch,    
  R.Remark,    
  ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,    
  ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,    
  ISNULL(R.ChequeDate,'') AS ChequeDate,    
  ISNULL(R.CollectionGroupId,0) AS CollectionGroupId,    
  Cm.title,    
  CM.Id,    
  ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
  CM.Title +' - '+ DM.Title AS Class,    
  A.SUId,    
  ISNULL(R.AmountAfterDiscount,0)AS AmountAfterDiscount,    
  ISNULL(R.CGSTPercentage,0)AS CGSTPercentage,    
  ISNULL(R.SGSTPercentage,0)AS SGSTPercentage,    
  ISNULL(R.CGSTAmount,0)AS CGSTAmount,    
  ISNULL(R.SGSTAmount,0)AS SGSTAmount,    
  ISNULL(R.DepositedLedgerId,0) AS DepositedLedgerId,    
  R.CreatedDateTime AS ReceiptCreatedDateTime,
  ISNULL(R.ReceiptPrintGroupId,'') AS ReceiptPrintGroupId    
  FROM     
   sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND (R.IsDiscountCoupon = 1)

 ORDER BY R.ReceiptNumber DESC    
END
GO
PRINT N'Altering [sFee].[pFeeExportDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pFeeExportDetailsGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(40)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(50) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='',
  @rCancelStatusId int = 0
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN       

CREATE Table #FeeReceiptDetail
		(
		StatusId bigint,
		ReceiptId bigint,
		FeeCode nvarchar(100),
		FeeAmount decimal(12,2),
		Organization nvarchar(max),
		Batch nvarchar(100),
		BatchId bigint,
		Code nvarchar(20),
		ClassDiv nvarchar(200),
		Name nvarchar(300),
		ReceiptNumber nvarchar(200),
		ReceiptDate Date,
		ReceiptAmount decimal(12,2),
		PayType nvarchar(300),
		ChequeNo nvarchar(40),
		Remark nvarchar(max),
		ChequeDate nvarchar(50),
		InvoiceNumber int,
		ReceiptCreatedDateTime datetime,
		BankName nvarchar(200),
		ReceiptBookName nvarchar(100),
		TotalReceiptAmount decimal(12,2),
		DiscountAmount decimal(12,2),
		VariableAmount decimal(12,2),
		ExemptionAmount decimal(12,2),
		AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2)
		
		)


INSERT INTO #FeeReceiptDetail
 SELECT 
    A.StatusId,    
	R.Id AS ReceiptId,
	FM.Code,
	RD.Amount,
	OM.DisplayTitle AS Organization,  
	BM.Title AS Batch,
	BM.Id AS BatchId,
	A.Code AS Code, 
	CM.Title +' - '+ DM.Title AS ClassDiv,
	A.Name,    
	R.ReceiptNumber,   
	R.ReceiptDate,     
	ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,
	PTM.Title AS PayType,    
	CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
	R.Remark,
	CONVERT(VARCHAR(10), R.ChequeDate, 103)AS ChequeDate, 
	--ISNULL(CAST(R.ChequeDate AS Date),'') AS ChequeDate, 
	ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	R.CreatedDateTime AS ReceiptCreatedDateTime,
	R.BankName,    
	RBM.Title AS ReceiptBook,    
    ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
    ISNULL(R.DiscountAmount,0)AS DiscountAmount,
	FA.VariableAmount,
	FA.DiscountAmount AS ExemptionAmount,
	FA.AdditionalAmount,
	FA.NotApplicableAmount
	
	
  
  FROM     
  
     sFee.tReceipt R    
  INNER JOIN sStudent.vStudentAcademic A    
   ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
   
  INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
  INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
  INNER JOIN sCommon.tSourceTypeMaster STM    
   ON STM.Id=R.SourceTypeId    
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
   ON PTM.Id=R.PayTypeId    
  INNER JOIN sFee.tReceiptBookMaster RBM    
   ON RBM.Id=R.ReceiptBookId    
  INNER JOIN sSetup.tOrganizationMaster OM    
   ON OM.Id=A.OrgId    
    AND OM.OrgGroupId=@rOrgGroupId    
  INNER JOIN sSetup.tBatchMaster BM    
   ON BM.Id=R.BatchId     
   AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
  LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
  INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
  LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
  
  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
  LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=A.AcademicId
  
WHERE     
 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
 AND (R.SourceTypeId=2001)    
 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
 AND (R.IsObsolete=@rIsObsolete)    
 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
 ORDER BY R.ReceiptNumber DESC   
 
 --Select * from #FeeReceiptDetail
 DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

    SELECT @cols = STUFF((SELECT  DISTINCT ',' + QUOTENAME(ID.FeeCode)
                       FROM #FeeReceiptDetail ID FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')   
 
    SELECT @query = 
    'SELECT  
			P.*,
            ID.VariableAmount,
            ID.ExemptionAmount,
            ID.AdditionalAmount,
            ID.NotApplicableAmount ,
			ID.DiscountAmount
     FROM
    (SELECT  
	
		ReceiptId ,
		Organization ,
		Batch ,
		Code ,
		ClassDiv ,
		Name ,
		ReceiptNumber ,
		ReceiptDate ,
		ReceiptAmount ,
		Remark,
		PayType ,
		ChequeNo ,
		ChequeDate, 
		BankName ,
		ReceiptBookName ,
		InvoiceNumber,    
		ReceiptCreatedDateTime,
		TotalReceiptAmount ,
		FeeCode, 
        FeeAmount
		    		
    FROM #FeeReceiptDetail)X
    PIVOT 
    (
         SUM(FeeAmount) 
         FOR [FeeCode] IN (' +  @cols + ')
    ) P
    LEFT JOIN
	(
		SELECT
		    ReceiptId,
			SUM(VariableAmount) AS VariableAmount,
			SUM(ExemptionAmount) AS ExemptionAmount,
			SUM(AdditionalAmount) AS AdditionalAmount,
			SUM(NotApplicableAmount) AS NotApplicableAmount,
			(DiscountAmount) AS DiscountAmount
		FROM  
			#FeeReceiptDetail
			GROUP BY ReceiptId,DiscountAmount
    ) ID ON ID.ReceiptId = P.ReceiptId
	Order By P.ReceiptNumber DESC
    '
	EXECUTE(@query) 
END
GO
PRINT N'Altering [sFee].[pFeePendingListGet]...';


GO
ALTER PROCEDURE [sFee].[pFeePendingListGet]
		
		@rOrgGroupBatchId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rCode nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rLastName nvarchar(100) = '',
		@rReceiptBookId int=0,
		@rOrgId int=0,
		@rBatchId int=0,
		@rDepartmentId int=0,
		@rSUId nvarchar(50) = '',
		@rUptoDate date='',
		@rFromNextFollowupDate date='',
		@rToNextFollowupDate date=''
		
		
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END		 
BEGIN 	
	
	DECLARE @p AS TempPendingFee
	
	INSERT INTO @p 
	SELECT 
		SA.AcademicId,
		SA.RollNo,
		SA.Name,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.ClassName,
		SA.DivisionName,
		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.ReceiptBookId,
		FS.FeeName,
		FS.FeeCode,
		SA.OrgId,
		O.Title AS OrgName,
		O.OrderIndex AS OrgOrderIndex,
		ISNULL(RBM.Title,'') AS ReceiptBookTitle,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
		SA.BatchId,
		BM.Title AS BatchName,
		'',
		'',
		'',
		ISNULL(SA.SUID,'') AS SUID,
		SA.ClassOrderIndex,
		SA.DivisionOrder,
		FS.OrderIndex
  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.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId				
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			WHERE 
			    ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				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 ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				
			UNION ALL
				
			SELECT 
				FS1.FeeId,
				FS1.Id,
				ISNULL(FS1.IsOptional,0)AS IsOptional,
				ISNULL(FS1.IsVariable,0)AS IsVariable,
				ISNULL(FS1.Amount,0)AS Amount,
				ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
				ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
				FS1.BatchId,
				ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
				SA1.AcademicId,
				FM.Title AS FeeName,
				FM.Code AS FeeCode,
				FM.OrderIndex
			FROM 
				sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
			WHERE
		        ((SA1.OrgGroupBatchId = @rOrgGroupBatchId)  OR (@rOrgGroupBatchId=0))
				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 ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
		) FS ON FS.AcademicId=SA.AcademicId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
		LEFT JOIN
		(
		    SELECT 
					ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
		    FROM
				sFee.tReceipt R 
				INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId				
				AND (SA1.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 ((SA1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
				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 sSetup.tBatchMaster BM ON BM.Id=SA.BatchId	
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (SA.OrgGroupBatchId = AR.OrgGroupBatchId)) 
         LEFT JOIN
		(
			SELECT 
				AT.SourceId,
				B.OrgGroupBatchId 
			FROM 
				sTransport.tAssignRoute AT 
				INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
				INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		) RT ON RT.SourceId = SA.StudentId 
		AND ((SA.OrgGroupBatchId = RT.OrgGroupBatchId))
		AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	WHERE	
			((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0)) 
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.Code=@rSUId) OR (@rSUId=''))
			AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
			AND ((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))
			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 SA.	StatusId = 1
			AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			
			ORDER BY SA.RollNo
 
			SELECT
				Temp.OrgId,			 
				Temp.ReceiptBookId,
				Temp.AcademicId,
				Temp.DivisionId,
				Temp.ClassDivision,
				Temp.RollNo, 
				Temp.Name,
				Temp.Code,
				Temp.ReceiptBookTitle,
				Temp.OrgName,
				SUM(Temp.PendingAmount) AS PendingAmount, 
				[sFee].[fPendingFeeNamesGet](Temp.AcademicId,Temp.ReceiptBookId,	@p) AS PendingFeeName,
				Temp.ReceiptOrderIndex,
				Temp.BatchId,
				Temp.BatchName,
				SA.SUId AS SUId,
				FF.NextFollowupDate,
				ISNULL(SC.IsStopApplicationAccess,0) as IsStopApplicationAccess,
				ISNULL(SC.StudentCustomAlert,'') as StudentCustomAlert,
				ISNULL(SC.ParentContactNo,'')AS ParentContactNo,
				ISNULL(SC.StudentContactNo,'')AS StudentContactNo,
				ISNULL(SC.WhatsAppContactNo,'')AS WhatsAppContactNo,
				Temp.ClassOrderIndex,
				Temp.DivisionOrderIndex
			FROM @p Temp
			LEFT JOIN 
			(
				SELECT AcademicId,ReceiptBookId,NextFollowupDate 
				FROM 
				(
				SELECT AcademicId,ReceiptBookId,NextFollowupDate, 
				ROW_NUMBER() OVER(PARTITION BY AcademicId,ReceiptBookId ORDER BY NextFollowupDate DESC) AS RowNumber
				FROM sFee.tFeeFollowup FF 
				) AS T
				WHERE RowNumber = 1 
			) FF ON FF.AcademicId = Temp.AcademicId AND FF.ReceiptBookId = Temp.ReceiptBookId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = Temp.AcademicId AND SA.OrgId = Temp.OrgId
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId 
		WHERE 
			((FF.NextFollowupDate >= @rFromNextFollowupDate) OR (ISNULL(@rFromNextFollowupDate,'') = ''))
			AND ((FF.NextFollowupDate <= @rToNextFollowupDate) OR (ISNULL(@rToNextFollowupDate,'') = ''))
		GROUP BY 
			Temp.OrgId,Temp.AcademicId,Temp.ReceiptBookId,Temp.DivisionId,Temp.BatchId,
			Temp.ClassDivision,Temp.RollNo, Temp.Name,Temp.Code,Temp.ReceiptBookTitle,
			Temp.OrgName,Temp.ReceiptOrderIndex,Temp.BatchName,FF.NextFollowupDate,
			SC.IsStopApplicationAccess,SC.StudentCustomAlert,SC.ParentContactNo,SC.StudentContactNo,SC.WhatsAppContactNo,SA.SUId,Temp.ClassOrderIndex,
			Temp.DivisionOrderIndex
			ORDER BY Temp.AcademicId
END
GO
PRINT N'Altering [sFee].[pFeeReceiptListGet]...';


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


GO
ALTER PROCEDURE [sFee].[pFeeRefundReceiptListGet]    
      
  @rOrgGroupBatchId int,    
  @rAdmissionCategoryId int,    
  @rClassId int,    
  @rDivisionId int,    
  @rIdNo nvarchar(20)='',    
  @rFirstName nvarchar(100)='',    
  @rFromReceiptNumber int=0,    
  @rToReceiptNumber int=0,    
  @rReceiptBookId int=0,    
  @rSourceTypeId int=0,    
  @rPayTypeId int,    
  @rChequeNo nvarchar(20)='',    
  @rFromDate date,    
  @rToDate date,    
  @rIsObsolete bit,    
  @rOrgId smallint,    
  @rBatchId int,    
  @rOrgGroupId smallint,    
  @rCreatedUserName nvarchar(100),    
  @rCreatedUserId bigint,    
  @rDepartmentId int=0,    
  @rFromChequeDate date='',    
  @rToChequeDate date='',    
  @rSUId nvarchar(50) = '',    
  @rLastName nvarchar(100) = '',  
  @rPayTypeIds nvarchar(max) = '',
  @rBankName nvarchar(100)='',
  @rCancelStatusId int = 0,
  @rIsFeeWise bit = 0
      
 WITH EXECUTE AS CALLER    
AS    
SET NOCOUNT ON    
        
    BEGIN    
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)    
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)    
		SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)   
		SET @rBankName = sCommon.fSearchStringGet(@rBankName)    
    END 
	
BEGIN     

IF(@rIsFeeWise = 0)
BEGIN
	SELECT 
	  A.StatusId,    
	  R.Id AS ReceiptId,    
	  R.SourceId AS SourceId,    
	  R.SourceTypeId AS SourceTypeId,    
	  CASE WHEN R.SourceTypeId=2001 THEN 'Student'    
	  ELSE  'Employee' END AS SourceType,    
	  --STM.Title     
	  A.Code AS Code,    
	  A.Name,    
	  R.ReceiptNumber,    
	  R.ReceiptDate,    
	  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,    
	  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
	  ISNULL(R.DiscountAmount,0)AS DiscountAmount,    
	  R.PayTypeId,    
	  PTM.Title AS PayType,    
	  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
	  --R.ChequeNo,    
	  R.BankName,    
	  R.ReceiptBookId,    
	  RBM.Title AS ReceiptBook,    
	  R.IsObsolete,    
	  A.OrgId,    
	  OM.DisplayTitle AS Organization,    
	  R.BatchId,    
	  BM.Title AS Batch,    
	  R.Remark,    
	  ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,    
	  ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,    
	  ISNULL(R.ChequeDate,'') AS ChequeDate,    
	  ISNULL(R.CollectionGroupId,0) AS CollectionGroupId,    
	  Cm.title,    
	  CM.Id,    
	  ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	  CM.Title +' - '+ DM.Title AS Class,    
	  A.SUId,    
	  ISNULL(R.AmountAfterDiscount,0)AS AmountAfterDiscount,    
	  ISNULL(R.CGSTPercentage,0)AS CGSTPercentage,    
	  ISNULL(R.SGSTPercentage,0)AS SGSTPercentage,    
	  ISNULL(R.CGSTAmount,0)AS CGSTAmount,    
	  ISNULL(R.SGSTAmount,0)AS SGSTAmount,    
	  ISNULL(R.DepositedLedgerId,0) AS DepositedLedgerId,    
	  R.CreatedDateTime AS ReceiptCreatedDateTime,
	  ISNULL(R.ReceiptPrintGroupId,'') AS ReceiptPrintGroupId,
	  0 AS FeeId,
	  '' AS FeeName,
	  0 AS FeeAmount,
	  0 AS FeeSetupId,
	  ISNULL(RF.Id,0) As RefundId
	FROM     
		sFee.tReceipt R    
		INNER JOIN sStudent.vStudentAcademic A    
		ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		Left Join sFee.tReceiptRefund RF ON RF.ReceiptId = R.Id   
		INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
		INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
		INNER JOIN sCommon.tSourceTypeMaster STM    
		ON STM.Id=R.SourceTypeId    
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
		ON PTM.Id=R.PayTypeId    
		INNER JOIN sFee.tReceiptBookMaster RBM    
		ON RBM.Id=R.ReceiptBookId    
		INNER JOIN sSetup.tOrganizationMaster OM    
		ON OM.Id=A.OrgId    
		AND OM.OrgGroupId=@rOrgGroupId    
		INNER JOIN sSetup.tBatchMaster BM    
		ON BM.Id=R.BatchId     
		AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
		INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
		LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
	WHERE     
		 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
		 AND (R.SourceTypeId=2001)    
		 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
		 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
		 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
		 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
		 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
		 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
		 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
		 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
		 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
		 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
		 AND (R.IsObsolete=@rIsObsolete)    
		 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
		 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
		 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
		 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
		 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
		 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
		 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
		 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
		 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
		 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
		 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
	 ORDER BY R.ReceiptNumber DESC   
END
ELSE IF(@rIsFeeWise = 1)
BEGIN
	SELECT 
	  A.StatusId,    
	  R.Id AS ReceiptId,    
	  R.SourceId AS SourceId,    
	  R.SourceTypeId AS SourceTypeId,    
	  CASE WHEN R.SourceTypeId=2001 THEN 'Student'    
	  ELSE  'Employee' END AS SourceType,    
	  --STM.Title     
	  A.Code AS Code,    
	  A.Name,    
	  R.ReceiptNumber,    
	  R.ReceiptDate,    
	  ISNULL(R.ReceiptAmount,0)AS ReceiptAmount,    
	  ISNULL(R.TotalReceiptAmount,0)AS TotalReceiptAmount,    
	  ISNULL(R.DiscountAmount,0)AS DiscountAmount,    
	  R.PayTypeId,    
	  PTM.Title AS PayType,    
	  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,    
	  --R.ChequeNo,    
	  R.BankName,    
	  R.ReceiptBookId,    
	  RBM.Title AS ReceiptBook,    
	  R.IsObsolete,    
	  A.OrgId,    
	  OM.DisplayTitle AS Organization,    
	  R.BatchId,    
	  BM.Title AS Batch,    
	  R.Remark,    
	  ISNULL(R.IsChequeCleared,0) AS IsChequeCleared,    
	  ISNULL(R.ChequeClearDate,'') AS ChequeClearDate,    
	  ISNULL(R.ChequeDate,'') AS ChequeDate,    
	  ISNULL(R.CollectionGroupId,0) AS CollectionGroupId,    
	  Cm.title,    
	  CM.Id,    
	  ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,    
	  CM.Title +' - '+ DM.Title AS Class,    
	  A.SUId,    
	  ISNULL(R.AmountAfterDiscount,0)AS AmountAfterDiscount,    
	  ISNULL(R.CGSTPercentage,0)AS CGSTPercentage,    
	  ISNULL(R.SGSTPercentage,0)AS SGSTPercentage,    
	  ISNULL(R.CGSTAmount,0)AS CGSTAmount,    
	  ISNULL(R.SGSTAmount,0)AS SGSTAmount,    
	  ISNULL(R.DepositedLedgerId,0) AS DepositedLedgerId,    
	  R.CreatedDateTime AS ReceiptCreatedDateTime,
	  ISNULL(R.ReceiptPrintGroupId,'') AS ReceiptPrintGroupId,
	  FM.Id AS FeeId,
	  FM.Title AS FeeName,
	  RD.Amount AS FeeAmount,
	  FS.Id AS FeeSetupId,
	  ISNULL(RF.Id,0) As RefundId
	FROM     
		sFee.tReceipt R    
		INNER JOIN sFee.tReceiptDetail RD ON R.Id = RD.ReceiptId
		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sStudent.vStudentAcademic A    
		ON A.AcademicId=R.SourceId AND (A.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)   
		Left Join sFee.tReceiptRefund RF ON RF.ReceiptId = R.Id
		INNER JOIN  sSetup.tClassMaster CM ON CM.Id = A.ClassId     
		INNER JOIN  sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId     
		INNER JOIN sCommon.tSourceTypeMaster STM    
		ON STM.Id=R.SourceTypeId    
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM    
		ON PTM.Id=R.PayTypeId    
		INNER JOIN sFee.tReceiptBookMaster RBM    
		ON RBM.Id=R.ReceiptBookId    
		INNER JOIN sSetup.tOrganizationMaster OM    
		ON OM.Id=A.OrgId    
		AND OM.OrgGroupId=@rOrgGroupId    
		INNER JOIN sSetup.tBatchMaster BM    
		ON BM.Id=R.BatchId     
		AND BM.OrgGroupBatchId=@rOrgGroupBatchId    
		LEFT JOIN sSecurity.tUser U ON U.Id=R.CreatedUserId    
		INNER JOIN sFee.vUserReceiptBook URB ON URB.Id=RBM.Id AND URB.UserId=@rCreatedUserId    
		LEFT JOIN sFee.tFeeInvoice FI ON FI.Id = R.FeeInvoiceId    
	WHERE     
		 ((A.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))    
		 AND (R.SourceTypeId=2001)    
		 AND ((A.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))    
		 AND ((R.ReceiptNumber>=@rFromReceiptNumber)OR(@rFromReceiptNumber=0))    
		 AND ((R.ReceiptNumber<=@rToReceiptNumber)OR(@rToReceiptNumber=0))    
		 AND ((R.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))    
		 AND ((R.PayTypeId=@rPayTypeId)OR(@rPayTypeId=0))    
		 AND ((ISNULL(R.PayTypeId,0) IN ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rPayTypeIds,','))) OR (ISNULL(@rPayTypeIds,'')=''))
		 AND ((R.ChequeNo like @rChequeNo) OR(ISNULL(@rChequeNo,'')=''))    
		 AND ((STM.Id=@rSourceTypeId)OR(@rSourceTypeId=0))    
		 AND ((R.ReceiptDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))    
		 AND ((R.ReceiptDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))    
		 AND (R.IsObsolete=@rIsObsolete)    
		 AND ((A.OrgId=@rOrgId) OR (@rOrgId=0))    
		 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))    
		 AND ((ISNULL(U.DisplayTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))    
		 AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))    
		 AND ((A.ClassId=@rClassId) OR (@rClassId=0))     
		 AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))    
		 AND ((R.ChequeDate>=@rFromChequeDate)OR(ISNULL(@rFromChequeDate,'')=''))    
		 AND ((R.ChequeDate<=@rToChequeDate)OR(ISNULL(@rToChequeDate,'')=''))    
		 AND ((A.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))    
		 AND ((A.LastName like @rLastName) OR (ISNULL(@rLastName,'')=''))  
		 AND ((R.BankName like @rBankName) OR(ISNULL(@rBankName,'')=''))    
		 AND ((R.CancelStatusId = @rCancelStatusId) OR(@rCancelStatusId=0)) ----Added By Dhruv for Issue No.11130    
	 ORDER BY R.ReceiptNumber DESC   
END  
  
END
GO
PRINT N'Altering [sFee].[pPendingFeeDashboardGet]...';


GO

ALTER PROCEDURE [sFee].[pPendingFeeDashboardGet]

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

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

SELECT @rOrgGroupBatchId = Id FROM sSetup.tOrgGroupBatchMaster WHERE CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND OrgGroupId = @rOrgGroupId

IF (@rType = 1)
 BEGIN
IF(@rFilterType = 'Organizationwise')		
	BEGIN 
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.OrgId,O.Title,FHM.Id,FHM.Title,FHM.OrderIndex
			ORDER BY OrgId,FHM.OrderIndex
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.OrgId,O.Title,FS.FeeId,FS.FeeName,FS.OrderIndex
			ORDER BY OrgId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		SELECT
			SA.OrgId,
			O.Title AS OrgName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.OrgId,O.Title,CGM.Id,CGM.Title,CGM.OrderIndex
			ORDER BY OrgId,CGM.Id
	 END
	END
ELSE IF(@rFilterType = 'Departmentwise')
	BEGIN
	 IF(@rFeeType = 'FeeHeadwise')
	 BEGIN
		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.DepartmentId,SA.DepartmentName,FHM.Id,FHM.Title,FHM.OrderIndex
			ORDER BY DepartmentId,FHM.Id
	 END
	 ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.DepartmentId,SA.DepartmentName,FS.FeeId,FS.FeeName,FS.OrderIndex
			ORDER BY DepartmentId,FS.FeeId
	 END
	 ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		SELECT
			SA.DepartmentId,
		    SA.DepartmentName,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY SA.DepartmentId,SA.DepartmentName,CGM.Id,CGM.Title,CGM.OrderIndex
			ORDER BY DepartmentId,CGM.Id
	 END
	END
ELSE IF(@rFilterType = 'ReceiptBookwise')
	BEGIN
	IF(@rFeeType = 'FeeHeadwise')
	BEGIN
	 SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex
		FROM
			sStudent.tAcademic SA
			INNER JOIN [sStudent].[tStudentMaster] SM ON SA.StudentId = SM.Id 
			INNER JOIN [sSetup].[tBatchMaster] BM ON SA.BatchId = BM.Id
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) FS ON FS.AcademicId=SA.Id
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			WHERE
			  BM.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SM.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY FS.ReceiptBookId,RBM.Title,FHM.Id,FHM.Title,FHM.OrderIndex
			ORDER BY ReceiptBookId,FHM.Id
	 END
	ELSE IF(@rFeeType = 'FeeMasterwise')
	 BEGIN
		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			FS.FeeId,
			FS.FeeName,
			FS.OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.ReceiptBookId,
					FM.OrderIndex
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FS.FeeHeadId	
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY FS.ReceiptBookId,RBM.Title,FS.FeeId,FS.FeeName,FS.OrderIndex
			ORDER BY ReceiptBookId,FS.FeeId
	 END
	ELSE IF(@rFeeType = 'CollectionGroupwise')
	 BEGIN
		SELECT
			FS.ReceiptBookId,
		    ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
			ISNULL(CGM.Title,'') AS CollectionGroupName,
			ISNULL(CGM.OrderIndex,0) AS OrderIndex
		FROM
			sStudent.vStudentAcademic SA
			INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.Id As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
 				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
				INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
				AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE 
					BM.OrgGroupBatchId = @rOrgGroupBatchId
					AND (FS1.IsOptional=0)
				UNION ALL
				SELECT 
					FS1.FeeId,
					ISNULL(FS1.Amount,0)AS Amount,
					FM.Title AS FeeName,
					FM.FeeHeadId,
					SA1.AcademicId As AcademicId,
					FS1.Id,
					FS1.StartDate,
					FS1.CollectionGroupId,
					FS1.ReceiptBookId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
				INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId
				INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
				WHERE
						SA1.OrgGroupBatchId = @rOrgGroupBatchId
						AND (FS1.IsOptional=1)
				) FS ON FS.AcademicId=SA.AcademicId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
				LEFT JOIN
				(
					SELECT 
					    ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
					FROM
						sFee.tReceipt R 
						INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
						INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
						INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
						INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
						INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
					WHERE		
						(R.SourceTypeId = 2001)
						AND (R.IsObsolete = 0) 
						AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
						AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
						AND (R.ReceiptDate <= @rUptoDate)  
						GROUP BY FeeSetupId,R.SourceId
				) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
				LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id
				INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			WHERE
			  SA.OrgGroupBatchId = @rOrgGroupBatchId
			  AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
			  AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			GROUP BY FS.ReceiptBookId,RBM.Title,CGM.Id,CGM.Title,CGM.OrderIndex
			--ORDER BY ReceiptBookId,CGM.Id
			ORDER BY CGM.OrderIndex
	 END
	END 
  END
ELSE IF(@rType = 2)
		BEGIN
				SELECT 
					SA.OrgId,
					SA.OrganizationName as OrgName,
					SA.ClassId,
					SA.ClassName,
					SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00))AS PendingAmount
				FROM 
					sStudent.vStudentAcademic SA
					INNER JOIN 
					(
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.Id AS AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 
						FROM sFee.tFeeSetup FS1
						INNER JOIN sStudent.tAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId 
						INNER JOIN sStudent.tStudentMaster SM ON SA1.StudentId = SM.Id			 
						AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE 
							BM.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=0)
						UNION ALL
				
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							SA1.AcademicId,
							FM.Title AS FeeName,
							FM.FeeHeadId,
							FS1.CollectionGroupId,
							FM.OrderIndex AS FeeOrderIndex			 			 
						FROM sFee.tFeeSetup FS1
						INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id
						INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
						INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
						INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId
						WHERE
							SA1.OrgGroupBatchId = @rOrgGroupBatchId
							AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
							AND (FS1.IsOptional=1)
					) FS ON FS.AcademicId=SA.AcademicId
					LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
					LEFT JOIN
					(
						SELECT 
								ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
						FROM
							sFee.tReceipt R 
							INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
							INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
							INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
							INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId
							INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SA1.BatchId			
							 
						WHERE		
							(R.SourceTypeId = 2001)
							AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
							AND (R.IsObsolete = 0) 
							AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId))
							AND (R.OrgGroupBatchId = @rOrgGroupBatchId)
							AND (R.ReceiptDate <= @rUptoDate) -- added condition after nes issue on 09/08/2016
							GROUP BY FeeSetupId,R.SourceId
					) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
					 INNER JOIN sSetup.tOrganizationMaster O ON	
					 SA.OrgId = O.Id
					 INNER JOIN sFee.tReceiptBookMaster RBM 
						ON FS.ReceiptBookId=RBM.Id
					 LEFT JOIN sFee.tCollectionGroupMaster CGM
						ON FS.CollectionGroupId=CGM.Id	
					 LEFT JOIN sStudent.tStudentCommunication SC 
						ON SC.StudentId = SA.StudentId
					 LEFT JOIN sStudent.tStudentOther SO 
						ON SO.StudentId = SA.StudentId
					 INNER JOIN sFee.tFeeHeadMaster FHM
						ON FHM.Id = FS.FeeHeadId	
				  LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
				  LEFT JOIN
					(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
					INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
					ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  
				WHERE	
				 SA.OrgGroupBatchId = @rOrgGroupBatchId
                 AND (SA.StatusId = @rStudentStatus OR @rStudentStatus=0)
                 AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
				 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
				 AND (ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00) -ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00) != 0)			
				GROUP BY 
						SA.ClassId,SA.ClassName,SA.OrgId,SA.OrganizationName
				Order By
						SA.ClassId
		END
END
GO
PRINT N'Altering [sFee].[pRptDepositAddSummaryPayTypeWise]...';


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


GO
ALTER PROCEDURE [sFee].[pRptDepositAdjustmentDetailGet] 
		
	 @rDepositHeadId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rOrgId int,
	 @rORgGroupBatchId int = 0,
     @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 
			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,
			 ISNULL(ETM.Title,'')AS ExpenseType
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ETM ON ETM.Id =DAJ.FeeDepositExpenseTypeId
			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.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 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,'')=''))
 
END
GO
PRINT N'Altering [sFee].[pRptDepositRefundSummaryPayTypeWise]...';


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


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


GO
ALTER PROC [sFee].[pRptDepositWisetransactionList] 
		
	 @rDepositHeadId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
	 @rOrgGroupBatchId int = 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 * 
	FROM	
	(
	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,
			VA.OrganizationName AS Oraganization

			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.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
		    AND ((VA.BatchId = @rBatchId)OR(@rBatchId=0))
		    AND ((VA.ClassId = @rClassId)OR(@rClassId=0))
		    AND ((VA.DivisionId = @rDivisionId)OR(@rDivisionId=0))
			AND ((DA.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=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,
			 VA.OrganizationName AS Oraganization

			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 ((VA.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
			AND ((DAJ.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=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,
			VA.OrganizationName AS Oraganization
		     
			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 ((VA.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
			AND ((DR.OrgGroupBatchId = @rOrgGroupBatchId)OR(@rOrgGroupBatchId=0))
			AND ((convert(date,DR.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((convert(date,DR.CreatedDateTime)<=@rTodate) OR (ISNULL(@rToDate,'')=''))
    ) A
	Order by A.DepositDate Asc
 
END
GO
PRINT N'Altering [sFee].[pRptExpenseTypeWiseDepositList]...';


GO
ALTER PROC [sFee].[pRptExpenseTypeWiseDepositList]

	     
		   @rOrgId int,
		   @rOrgGroupBatchId int = 0,          
           @rDepositHeadId int=0,         
           @rFromDate date='',
           @rToDate date='',           
           @rStudentName nvarchar(100)='',
		  @rStudentCode nvarchar(100)='',
		  @rClassId int=0,
		  @rDivisionId int=0,
		  @rIsBasedOnSUId bit = 0,
		  @rDepartmentId int=0,
		  @rSUId nvarchar(50)='',
		  @rBatchId int=0,
		  @rBuilder1 nvarchar(max)='',
	      @rBuilder2 nvarchar(max)='',
		  @rOrderBy int = 0
	    
   
AS
BEGIN
		SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Amount,
			VA.RollNo AS RollNo,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.Studentid   AS AcademicId ,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    'Add' AS GroupType,
	        '' As ExpenseType,
	         DA.Id As GroupID,
	          @rBuilder1 As builder1,
			  @rOrderBy AS OrderBy
		    
			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 ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND ((VA.ClassId = @rClassId) OR (@rClassId = 0))
		    AND ((VA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		    AND ((VA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		    AND ((VA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		    AND (VA.OrgId=@rOrgId OR @rOrgId=0)
		    AND (DA.DepositHeadId = @rDepositHeadId)
			AND (VA.BatchId=@rBatchId OR @rBatchId=0)
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((DA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))

	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			-ISnull (DAJ.Amount,0)  AS Amount,
			VA.RollNo AS RollNo,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     'Adjustment' AS GroupType,
		     ES.Title As ExpenseType,
		     DAJ.Id As GroupID,
		     @rBuilder1 As builder1,
			 @rOrderBy AS OrderBy
		    
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ES ON ES.Id=DAJ.FeeDepositExpenseTypeId
			Where 
				((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.ClassId = @rClassId) OR (@rClassId = 0))
		    AND ((VA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		    AND ((VA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		    AND ((VA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		    AND (VA.OrgId=@rOrgId OR @rOrgId=0)
		    AND (DAJ.DepositHeadId = @rDepositHeadId)
			AND (VA.BatchId=@rBatchId OR @rBatchId=0)
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			-ISnull (DR.RefundAmount,0)  AS Amount,
			VA.RollNo AS RollNo,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId, 
		    'Refund' AS GroupType,
		    '' As ExpenseType,
		    DR.Id As GroupID,
		    @rBuilder1 As builder1,
			@rOrderBy AS OrderBy
			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 ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.ClassId = @rClassId) OR (@rClassId = 0))
		    AND ((VA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		    AND ((VA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		    AND ((VA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		    AND (VA.OrgId=@rOrgId OR @rOrgId=0)
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((DR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		    AND (DR.DepositHeadId = @rDepositHeadId)
			AND (VA.BatchId=@rBatchId OR @rBatchId=0)
END
GO
PRINT N'Altering [sFee].[pRptFeeInvoiceRegisterGet]...';


GO
ALTER PROCEDURE [sFee].[pRptFeeInvoiceRegisterGet]
		
		@rOrgGroupBatchId int,
		@rOrgId int=0,
		@rBatchId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rIdNo nvarchar(20)='',
		@rFirstName nvarchar(100)='',
		@rReceiptBookId int=0,
		@rFromInvoiceNumber int=0,
		@rToInvoiceNumber int=0,
		@rFromDate date='',
		@rToDate date='',
		@rOrgGroupId int,
		@rCollectionGroupId int = 0,
		@rDepartmentId int=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		END			 
			 
BEGIN
		CREATE Table #InvoiceDetail
		(
		FeeInvoiceId bigint,
		FeeCode nvarchar(100),
		FeeAmount decimal(12,2),
		FeeOrder int,
		OrganizationName nvarchar(200),
		SUId nvarchar(50),
		Code nvarchar(20),
		ClassDiv nvarchar(200),
		RollNo int,
		Name nvarchar(300),
		InvoiceNumber int,
		InvoiceDate Date,
		InvoiceAmount decimal(12,2),
		ReceiptBookName nvarchar(100),
		CollectionGroupName nvarchar(100),
		VariableAmount decimal(12,2),
		DiscountAmount decimal(12,2),
		AdditionalAmount decimal(12,2),
		NotApplicableAmount decimal(12,2)
		)
		
		INSERT INTO #InvoiceDetail
		SELECT
			FeeInvoiceId,
			FM.Code,
			ID.Amount,
			FM.OrderIndex,
			SA.OrganizationName,
			SA.SUId,
			SA.Code,
			SA.ClassName+' - '+ SA.DivisionName AS Class,
			RollNo,
			Name,
			FI.InvoiceNumber,
			FI.InvoiceDate,
			FI.InvoiceAmount,
			RBM.Title,
			CGM.Title,
			FA.VariableAmount,
			FA.DiscountAmount,
			FA.AdditionalAmount,
			FA.NotApplicableAmount
		FROM
		sFee.tFeeInvoiceDetail ID 
		INNER JOIN sFee.tFeeSetup FS ON ID.FeeSetupId = FS.Id  
		INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
		INNER JOIN sFee.tFeeInvoice FI ON FI.Id = ID.FeeInvoiceId AND FI.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=FI.SourceId	
			AND (SA.ClassId=@rClassId OR @rClassId=0) 
			AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND (SA.AdmissionCategoryId=@rAdmissionCategoryId OR @rAdmissionCategoryId=0)
		INNER JOIN sSetup.tClassMaster CM ON Cm.Id = SA.ClassId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id=FI.ReceiptBookId
		INNER JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FI.CollectionGroupId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FI.SourceTypeId= FA.SourceTypeId AND FI.SourceId= FA.SourceId
		WHERE 
		((SA.Code like @rIdNo) OR (ISNULL(@rIdNo,'')=''))	
		AND (FI.SourceTypeId=2001)
		AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		AND ((FI.InvoiceNumber>=@rFromInvoiceNumber)OR(@rFromInvoiceNumber=0))
		AND ((FI.InvoiceNumber<=@rToInvoiceNumber)OR(@rToInvoiceNumber=0))
		AND ((FI.ReceiptBookId=@rReceiptBookId)OR(@rReceiptBookId=0))
		AND ((FI.CollectionGroupId=@rCollectionGroupId)OR(@rCollectionGroupId=0))
		AND ((FI.InvoiceDate>=@rFromDate)OR(ISNULL(@rFromDate,'')=''))
		AND ((FI.InvoiceDate<=@rToDate)OR(ISNULL(@rToDate,'')=''))
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((FI.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((CM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		ORDER BY FI.InvoiceNumber DESC
			
	DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

    SELECT @cols = STUFF((SELECT  DISTINCT ',' + QUOTENAME(ID.FeeCode)
                       FROM #InvoiceDetail ID FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')   
 
    SELECT @query = 
    'SELECT  
			P.*,
            ID.VariableAmount,
            ID.DiscountAmount,
            ID.AdditionalAmount,
            ID.NotApplicableAmount 
     FROM
    (SELECT  
        FeeInvoiceId,   
        OrganizationName,
        SUId,
        Code,
        ClassDiv,
        RollNo,
        Name,
        InvoiceNumber,
        CONVERT(varchar(11),InvoiceDate,103) AS InvoiceDate,
        FeeCode, 
        FeeAmount,
        ReceiptBookName,
        CollectionGroupName,
        InvoiceAmount
    FROM #InvoiceDetail)X
    PIVOT 
    (
         SUM(FeeAmount) 
         FOR [FeeCode] IN (' +  @cols + ')
    ) P
    LEFT JOIN
	(
		SELECT
		    FeeInvoiceId,
			SUM(VariableAmount) AS VariableAmount,
			SUM(DiscountAmount) AS DiscountAmount,
			SUM(AdditionalAmount) AS AdditionalAmount,
			SUM(NotApplicableAmount) AS NotApplicableAmount
		FROM  
			#InvoiceDetail
			GROUP BY FeeInvoiceId
    ) ID ON ID.FeeInvoiceId = P.FeeInvoiceId
    '
	EXECUTE(@query)
END
GO
PRINT N'Altering [sFee].[pRptFeePendingDetailListGet]...';


GO

ALTER PROCEDURE [sFee].[pRptFeePendingDetailListGet]  

	@rReportId int=0,  
	@rReceiptBookId int=0,
	@rReceiptBookIds nvarchar(max) = '',
	@rAdmissionCategoryId int=0,  
	@rClassId int=0,  
	@rDivisionId int=0,  
	@rUptoDate date='',  
	@rBatchId int=0,  
	@rUserId bigint=0,  
	@rBuilder1 nvarchar(max) = '',  
	@rBuilder2 nvarchar(max) = '',  
	@rIsDetail bit=0,  
	@rOrgId int=0,  
	@rOrgGroupBatchId int=0,  
	@rStatusId int=0,  
	@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) = '',  
	@rPayDate date='',  
	@rCollectionGroupId int =0,  
	@rCastCategoryId int = 0,
	@rReportType int=0,
	@rClassStatusId int=0 ,
	@rCollectionGrupId nvarchar(max) ='',
	@rClassIds nvarchar(max) = '',
	@rDivisionIds nvarchar(max) = ''
	 
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 
	
	CREATE TABLE #TempIsOptional
	(
		FeeId int,  
		Id int,  
		IsOptional bit,  
		IsVariable bit,  
		Amount decimal(12,2),  
		StartDate date,  
		EndDate date,  
		BatchId int,  
		ReceiptBookId int,  
		AcademicId bigint,  
		FeeName nvarchar(100),  
		FeeHeadId int,
		CollectionGroupId int,
		CollectionGroup nvarchar(max),
		FeeOrderIndex int,
		CollectionGroupOrderIndex int,
		CollectionGroupMasterRemark nvarchar(500)
	)
	
	INSERT INTO #TempIsOptional
		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,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup,
			FM.OrderIndex,
			CGM.OrderIndex  AS CollectionGroupOrderIndex,
			CGM.Remark AS CollectionGroupMasterRemark   
		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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			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  
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.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.ReceiptBookId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=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 (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='') 
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  

	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,
			ISNULL(CGM.Id,0) AS CollectionGroupId,
		    ISNULL(CGM.Title,'') AS CollectionGroup,
			FM.OrderIndex,
			CGM.OrderIndex  AS CollectionGroupOrderIndex,
			CGM.Remark AS CollectionGroupMasterRemark   
		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 SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.ClassId = FS1.ClassId  
			
			AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
			AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0)) 
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))  
			INNER JOIN sSetup.tBatchMaster BM ON FS1.BatchId = BM.Id AND BM.OrgGroupBatchId = @rOrgGroupBatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS1.CollectionGroupId=CGM.Id 
			--AND RBM.Id = CGM.ReceiptBookId 
			AND CGM.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.ReceiptBookId IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rReceiptBookIds,',')) OR @rReceiptBookIds='')
			AND ((FS1.CollectionGroupId=@rCollectionGroupId) OR (@rCollectionGroupId=0))  
			AND (FS1.IsOptional=1)  
			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 (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
			AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')   
	 
	CREATE TABLE #TempReceipt
	(
		PaidAmount decimal(12,2),
		FeeSetupId int,
		SourceId bigint  
	)
	
	INSERT INTO #TempReceipt
	SELECT   
		ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId  
	FROM  
		sFee.tReceipt R   
		INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id   
		INNER JOIN 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 (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		AND ((SA1.DivisionId=@rDivisionId) OR (@rDivisionId=0))  
		AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
		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) -- added condition after nes issue on 09/08/2016  
		-- OR (@rOrgGroupBatchId = @rOrgGroupBatchId))  
		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  
	
	CREATE TABLE #TempAssignRoute
	(
		SourceId bigint  
	)
	
	INSERT INTO #TempAssignRoute
	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))
	
	IF(@rReportType=1)
	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.FeeName,  
		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.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		--ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
		SA.OrgGroupBatchId,  
		SA.DepartmentId,  
		SA.DepartmentName,  
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,  
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,  
		@rPayDate AS PayDate ,  
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,  
		ISNULL(CCM.Title,'') AS CastCategoryName,  
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate  ,
		FS.CollectionGroupId,
		FS.CollectionGroup,
		SA.BatchName,
		ISNULL(SSF.FatherName, '') AS FatherName,
		ISNULL(SSF.FatherContactNo, '') AS FatherContactNo,
		ISNULL(SSF.MotherName, '') AS MotherName,
		ISNULL(SSF.MotherContactNo, '') AS MotherContactNo,
		FS.FeeOrderIndex AS FeeOrderIndex,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
	 SA.GenderId,
	 SA.FirstName as StudentName,
	 FS.CollectionGroupOrderIndex,
	 SA.SUId AS SUId,
	 FS.CollectionGroupMasterRemark,
	 SA.LastName as LastName

	FROM   
		sStudent.vStudentAcademic SA  
		INNER JOIN #TempIsOptional FS ON FS.AcademicId=SA.AcademicId  
		LEFT JOIN sFee.tFeeAllocation FA  
		ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId  
		LEFT JOIN #TempReceipt R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId  
		INNER JOIN sSetup.tOrganizationMaster O ON   
		SA.OrgId = O.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM   
		ON FS.ReceiptBookId=RBM.Id  
		LEFT JOIN sStudent.tStudentCommunication SC   
		ON SC.StudentId = SA.StudentId  
		LEFT JOIN sStudent.tStudentOther SO   
		ON SO.StudentId = SA.StudentId  
		LEFT JOIN sCommon.tCastCategoryMaster CCM   
		ON CCM.Id = SO.CastCategoryId    
		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 #TempAssignRoute RT ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
	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='')       
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0)) 
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	Order by SA.RollNo  
	END
	ELSE
	BEGIN
	SELECT   
		@rBuilder1 AS Builder1,  
		@rBuilder2 AS Builder2,  
		@rIsDetail AS IsDetail,  
		@rIsFilter As IsFilter,  
		@rIsHeader As IsHeader,  
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
		SA.AcademicId,  
		SA.RollNo,  
		SA.Name,  
		SA.Code,  
		SA.ClassId,  
		SA.DivisionId,  
		SA.ClassName,  
		SA.DivisionName,  
		SA.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(FAS.PaidAmount,0) AS PaidAmount,
		ISNULL(FAS.ToPayAmount,0.00) PendingAmount,
		ISNULL(FA.Remark,'') AS Remark,  
		--FS.FeeName,  
		FM.Title AS FeeName,  
		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,    
		ISNULL(FS.ReceiptBookId,'0') As ReceiptBookId,  
		ISNULL(RBM.FullTitle,'') AS ReceiptBookFullTitle,
		ISNULL(RBM.Address1,'') AS RecieptBookAddress1,
		IsNULL(RBM.Address2,'') As RecieptBookAddress2,
		IsNULL(RBM.Remark1,'') As Remark1,
		ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
		SA.OrgGroupBatchId,  
		SA.DepartmentId,  
		SA.DepartmentName,  
		ISNULL(SC.ParentContactNo,'') AS ParentContactNo,  
		ISNULL(SO.ReferenceRemark,'') AS ReferenceRemark,  
		@rPayDate AS PayDate ,  
		ISNULL(CCM.MainCastCategoryId,0) AS CastCategoryId,  
		ISNULL(CCM.Title,'') AS CastCategoryName,  
		ISNULL(CCM.OrderIndex,'') AS CastCategoryOrderIndex,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = @rReportId AND OrgId=SA.OrgId),0) AS ReportTemplate,
		ISNULL(CGM.Id,0) AS CollectionGroupId,
		ISNULL(CGM.Title,'') AS CollectionGroup,
		SA.BatchName,
		ISNULL(SSF.FatherName, '') AS FatherName,
		ISNULL(SSF.FatherContactNo, '') AS FatherContactNo,
		ISNULL(SSF.MotherName, '') AS MotherName,
		ISNULL(SSF.MotherContactNo, '') AS MotherContactNo,
		FM.OrderIndex AS FeeOrderIndex,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS [Address],
		ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
		CGM.OrderIndex  AS CollectionGroupOrderIndex,
		SA.SUId AS SUId
	FROM   
		sStudent.vStudentAcademic SA		
		INNER JOIN sFee.tFeeAllocationStudent FAS ON FAS.AcademicId=  SA.AcademicId	
		INNER JOIN sFee.tFeeSetup FS ON FS.ID=FAS.FeeSetupId	
		INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS.FeeId
		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=FM.FeeHeadId
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FAS.FeeSetupId AND FA.SourceId=SA.AcademicId  
		LEFT JOIN sStudent.tStudentCommunication SC	ON SC.StudentId = SA.StudentId  
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId  
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = SO.CastCategoryId
		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))
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON FS.CollectionGroupId=CGM.Id 
		AND CGM.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sStudent.tStudentFamily SSF ON SSF.StudentId = SA .StudentId
	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 ISNULL(FAS.ToPayAmount,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='')       
		AND ((CCM.Id=@rCastCategoryId) OR (@rCastCategoryId=0))   
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
		AND (ISNULL(CGM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rCollectionGrupId,','))OR @rCollectionGrupId='')
	Order by SA.RollNo  
	END
	
	DROP TABLE #TempIsOptional
	DROP TABLE #TempReceipt
	DROP TABLE #TempAssignRoute


	
	--SELECT 
	--    '' as Builder1,  
	--	'' as Builder2,  
	--	Convert(bit,0) as IsDetail,  
	--	Convert(bit,0) as IsFilter,  
	--	Convert(bit,0) as IsHeader,  
	--	Convert(bit,0) as IsDisplayOrgGroup,  
	--	0 as AcademicId,  
	--	0 As RollNo,  
	--	'' as Name,  
	--	'' As Code,  
	--	0 as ClassId,  
	--	0 as DivisionId,  
	--	'' as ClassName,  
	--	'' as DivisionName,  
	--	0 as DivisionOrder,  
	--	 '' as ClassDivision,  
	--	0 as FeeSetupId,  
	--	Convert(bit,0) as IsVariable,  
	--	 0.00 As Amount,  
	--	'2001-01-30' AS StartDate,  
	--	'2001-01-30' As EndDate,  
	--	0.00 As FAAmount,  
	--	0.00 As DiscountAmount,  
	--	0.00 As AdditionalAmount,  
	--	0.00 As PaidAmount,
	--	0.00 As  PendingAmount,
	--	'' AS Remark,  
	--	--FS.FeeName,  
	--	'' AS FeeName,  
	--	0 AS FeeHeadId,  
	--	'' AS FeeHeadName,  
	--	0 As FeeHeadOrderIndex,  
	--	0 As OrgId,  
	--	'' AS OrgName,  
	--	0 AS OrgOrderIndex,  
	--	0 AS ReceiptBookId,   
	--	'' AS ReceiptBookTitle,  
	--	0 AS ReceiptOrderIndex,    
	--	'' AS ReceiptBookFullTitle,
	--	'' AS RecieptBookAddress1,
	--	'' AS RecieptBookAddress2,
	--	'' As Remark1,
	--	0 As OrgGroupBatchId,  
	--	0 As DepartmentId,  
	--	'' AS DepartmentName,  
	--	'' AS ParentContactNo,  
	--	'' AS ReferenceRemark,  
	--	'2001-01-30' AS PayDate ,  
	--	0 AS CastCategoryId,  
	--	'' AS CastCategoryName,  
	--	0 AS CastCategoryOrderIndex,
	--	'' AS ReportTemplate,
	--	0 AS CollectionGroupId,
	--	'' AS CollectionGroup,
	--	'' AS BatchName,
	--	'' AS FatherName,
	--	 '' AS FatherContactNo,
	--	 '' AS MotherName,
	--	 '' AS MotherContactNo,
	--	0 AS FeeOrderIndex,
	--	'' AS Address,
	--	'' AS StudentContactNo,
	--    '' as StudentName,
	--	0 As GenderId,
	-- 0 AS CollectionGroupOrderIndex,
	-- 0 AS SUId,
	-- '' AS CollectionGroupMasterRemark   
	-- '' AS LastName

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


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

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

			''  AdditionalRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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 (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')  
			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(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
			) FS ON FS.AcademicId=SA.AcademicId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			LEFT JOIN
			(
				SELECT 
						ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId ,R.SourceId
				FROM
						sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id 
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=R.SourceId 
					AND ((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.ClassId=@rClassId OR @rClassId=0) 
					AND (SA1.DivisionId=@rDivisionId OR @rDivisionId=0)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
			AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
			AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))  	
			AND (tSA.AdmissionDate <= @rUptoDate)
			AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
			AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
		Order by SA.RollNo
	END

	ELSE
	BEGIN
		SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsDetail AS IsDetail,
			@rIsFilter As IsFilter,
			@rIsHeader As IsHeader, 
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SA.AcademicId,
			SA.RollNo,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.StatusId,
			SA.DivisionOrder AS DivisionOrderIndex,
			SA.ClassOrderIndex AS ClassOrderIndex,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FS.Id AS FeeSetupId,
			ISNULL(FS.IsVariable,0)AS IsVariable,
			ISNULL(FS.Amount,0)AS Amount,
			ISNULL(FS.StartDate,'1900-01-01')AS StartDate,
			ISNULL(FS.EndDate,'1900-01-01')AS EndDate,
			ISNULL(FA.VariableAmount,0.00)AS FAAmount,
			ISNULL(FA.DiscountAmount,0.00)AS DiscountAmount,
			ISNULL(FA.AdditionalAmount,0.00)AS AdditionalAmount,
			ISNULL(FA.NotApplicableAmount,0.00)AS NotApplicableAmount,
			ISNULL(R.PaidAmount,0) AS PaidAmount,
			ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)AS PendingAmount,
			ISNULL(FA.Remark,'') AS Remark,
			--CASE WHEN ISNULL(FA.Remark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,2) END as RemarkWithComma,
			'' RemarkWithComma,
			--CASE WHEN ISNULL(FA.DiscountRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,1) END as ExampltedRemark,

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

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

			--CASE WHEN ISNULL(FA.AdditionalRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,3) END as AdditionalRemark,
			''  AdditionalRemark,
			--CASE WHEN ISNULL(FA.NotApplicableRemark,'') ='' THEN ''	ELSE [sFee].[fFeeAllocationRemarkGet](FA.SourceId,4) END as NotApplicableRemark,
			'' NotApplicableRemark,
			FS.ReceiptBookId,
			FS.FeeName,
			--FS.FeeCode,
			SA.OrgId,
			O.DisplayTitle AS OrgName,
			O.OrderIndex AS OrgOrderIndex,
			ISNULL(RBM.Title,'') AS ReceiptBookTitle,
			ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,
			SA.DepartmentId,
			SA.DepartmentName,
			SA.ExemptionTypeId,
			ISNULL(ETM.Title,'') AS ExemptionType,
			FHM.Id AS FeeHeadId,
			FHM.Title AS FeeHeadName,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			@rFeeGroupId As FeeGroup,
			SA.OrgGroupBatchId AS BatchId,
			SA.BatchName AS BatchName,
			0.00 AS CancelAmount
	  FROM 
			sStudent.vStudentAcademic SA
			INNER JOIN sStudent.tStudentAdmission tSA ON tSA.StudentId = SA.StudentId
			INNER JOIN 
			(
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0))
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				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 (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')  
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
					UNION ALL
					
				SELECT 
					FS1.FeeId,
					FS1.Id,
					ISNULL(FS1.IsOptional,0)AS IsOptional,
					ISNULL(FS1.IsVariable,0)AS IsVariable,
					ISNULL(FS1.Amount,0)AS Amount,
					ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
					ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
					FS1.BatchId,
					ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
					SA1.AcademicId,
					FM.Title AS FeeName,
					--FM.Code AS FeeCode,
					FM.FeeHeadId
				FROM sFee.tFeeSetup FS1
			INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
			INNER JOIN sFee.tFeeMaster FM ON FM.Id=FS1.FeeId
			INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId=FO.SourceId AND FS1.BatchId = SA1.BatchId
			AND SA1.ClassId=FS1.ClassId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				AND ((SA1.ClassId=@rClassId) OR (@rClassId=0)) 
				AND ((SA1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
				AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 
			WHERE
				((FS1.ClassId=@rClassId) OR (@rClassId=0))
				AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
				AND ((FS1.AdmissionCategoryId=@rAdmissionCategoryId) OR (@rAdmissionCategoryId=0))
				AND ((FS1.ReceiptBookId=@rReceiptBookId) OR (@rReceiptBookId=0))
				AND (FS1.IsOptional=1)
				AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
				AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
				AND ((SA1.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
				AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
				AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
				AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
				AND (ISNULL(FS1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
				AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
			) 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)
					AND (ISNULL(SA1.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
					AND (ISNULL(SA1.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='')
				WHERE		
					(R.SourceTypeId = 2001)
					AND (R.IsObsolete = 0) 
					AND	((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND (SA1.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId=0)
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))
					AND ((SA1.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
					AND (R.ReceiptDate <= @rUptoDate)
					AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
					AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')
					AND (LEFT(SA1.OrgGroupBatchId,4) = @rOrgGroupId OR @rOrgGroupId=0)
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='') 
						GROUP BY FeeSetupId,R.SourceId
			
			) R ON R.FeeSetupId = FS.Id AND SA.AcademicId = R.SourceId
			 INNER JOIN sSetup.tOrganizationMaster O ON SA.OrgId = O.Id
			 INNER JOIN sFee.tReceiptBookMaster RBM ON FS.ReceiptBookId=RBM.Id
			 INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FS.FeeHeadId	
			 LEFT JOIN sFee.tExemptionTypeMaster ETM ON ETM.Id = SA.ExemptionTypeId
			 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			 LEFT JOIN
			(SELECT AT.SourceId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
			WHERE	
			((@rIsExemption = 0 AND  1=1) OR (@rIsExemption = 1  AND  ISNULL(FA.DiscountAmount,0) > 0))
			AND	((SA.BatchId=@rBatchId) OR (@rBatchId=0))   
			AND	((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))   
			AND (SA.StatusId=@rStatusId OR @rStatusId=0)
			--AND ((FS.StartDate <= @rUptoDate) OR (ISNULL(@rUptoDate,'') = ''))
			AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
			AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
			AND ((SA.Code=@rCode) OR (@rCode=''))
			AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))		
			AND ((SA.ExemptionTypeId=@rExemptionTypeId) OR (@rExemptionTypeId=0))		
			AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
			AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			 AND (
					 (@rFilterId = 0) -- All
					 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
					 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
					 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
					 )	
		AND (O.OrgGroupId = @rOrgGroupId OR @rOrgGroupId=0)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')  
		 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0)) 
		 AND (ISNULL(SA.ClassId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rClassIds,','))OR @rClassIds='')
		 AND (ISNULL(SA.DivisionId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rDivisionIds,','))OR @rDivisionIds='') 	
		Order by SA.RollNo
	END
	
	
	
END
GO
PRINT N'Altering [sFee].[pRptStudentDepositListGet]...';


GO
ALTER PROCEDURE [sFee].[pRptStudentDepositListGet]
          
          @rOrgGroupId smallint,
		   @rOrgId int,
		   @rOrgGroupBatchId int = 0,        
           @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(50)='',
		  @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,
		D.DepositDate
		
  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  (SA.OrgGroupBatchId=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
		 
		
		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 [sFee].[pRptStudentFeeDetailsGet]...';


GO
ALTER PROCEDURE [sFee].[pRptStudentFeeDetailsGet]
@rSourceId bigint = 0,
@rBatchId int = 0

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN 
	SELECT 
		SA.AcademicId AS SourceId,
		SA.[Name] AS StudentName,
		SA.BatchId,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.AcademicId AS SourceIdText,
		2001 AS SourceTypeId,
		SA.ClassName,
		SA.DivisionName,
		SA.BatchName,
		SA.RollNo,
		ACM.Title AS FeeCategory,
		ISNULL(SA1.AdmissionNumber,'') AS AdmissionNumber
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN [sStudent].[tAdmissionCategoryMaster] ACM ON ACM.Id = SA.AdmissionCategoryId
		LEFT JOIN sStudent.tStudentAdmission SA1 ON SA1.StudentId = SA.StudentId
	WHERE 
		SA.AcademicId = @rSourceId 		
		AND SA.BatchId = @rBatchId
END
GO
PRINT N'Altering [sFee].[pRptStudentLedgerGet]...';


GO
ALTER PROC [sFee].[pRptStudentLedgerGet]

	 @rAcademicId bigint,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rDepositHeadId int,
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rBatchId int
AS
BEGIN
WITH Tb0 as
( 
			SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		     DA.CreatedDateTime,
		     '' AS ExpenseType,
			 VA.RollNo,
			 SA.AdmissionNumber
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = VA.StudentId
			Where 
		   ((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			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
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		    DAJ. CreatedDateTime,
		   ISNULL(ETM.Title,'')AS ExpenseType,
		   VA.RollNo,
		   SA.AdmissionNumber
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  INNER JOIN sFee.tFeeDepositExpenseTypeMaster ETM ON ETM.Id =DAJ.FeeDepositExpenseTypeId
			  INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = VA.StudentId
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			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
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.AcademicId AS AcademicId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     CAse WHEN @rIsBasedOnSUId=1  THEN ISNUll(VA.SUId,'')  ELSE VA.Code END As  SUId,
		    DR.CreatedDateTime,
		     '' AS ExpenseType,
			 VA.RollNo,
			 SA.AdmissionNumber
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			  INNER JOIN sStudent.tStudentAdmission SA ON SA.StudentId = VA.StudentId
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			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
)
,Tb1 as
( 
	SELECT DepositDate,Credit,Debit,Row_Number() over (order by CreatedDateTime asc) as OrderId,AcademicId,Code,SUId,StudentName,Class ,CreatedDateTime,ExpenseType,RollNo,AdmissionNumber FROM Tb0
)

--SELECT * FROM Tb1

  SELECT T1.DepositDate,
         T1.[Credit],
         T1.[Debit],(Sum(T2.Credit) - Sum(T2.Debit)) as Balance,
         T1.SUId,
         T1.Code,
         T1.StudentName,
         T1.Class,
        T1.CreatedDateTime,
        T1.ExpenseType,
		T1.RollNo,
		T1.AdmissionNumber,
		@rIsBasedOnSUId AS BasedOnSUID

		 FROM Tb1 as T1
		 INNER JOIN Tb1 as T2 ON T1.OrderId >= T2.OrderId
		 Group By T1.DepositDate,T1.Credit,T1.Debit,T1.AcademicId,T1.SUId,T1.Code,T1.StudentName,T1.Class,T1.CreatedDateTime,T1.ExpenseType,T1.RollNo,T1.AdmissionNumber
		 Order by T1.CreatedDateTime 
END
GO
PRINT N'Altering [sFee].[pRptTotalDepositTransaction]...';


GO
ALTER PROC [sFee].[pRptTotalDepositTransaction] 

	 @rDepositHeadId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rOrgId int,
	 @rOrgGroupBatchId int = 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='',
	 @rIsBasedOnSUId bit = 0
	 
AS
BEGIN	
	
	SELECT 
	   A.Code,
	   A.StudentId,
	   A.StudentName,
	   A.Class,
	   SUM(ISNULL(A.DepositeAmount,0)) AS TotalDeposite,
	   SUM(ISNULL(A.AdjustmentAmount,0)) AS AdjustmentAmount,
	   A.FeeDepositExpenseTypeId,
	   A.ExpenseType,
	   SUM(ISNULL(A.DepositeAmount,0)) - SUM(ISNULL(A.AdjustmentAmount,0))-SUM(ISNULL(A.RefundAmount,0)) RemainingAmount,
	   SUM(ISNULL(A.RefundAmount,0)) AS RefundAmount
	FROM
	   (
		SELECT 
		    VA.Code As Code,
			VA.StudentId AS StudentId,
		    VA.Name As StudentName,
		    VA.ClassName + ' - ' + VA.DivisionName AS Class,
			ISNULL(DA.Amount,0) AS DepositeAmount,
			0 AS AdjustmentAmount,
			0 AS FeeDepositExpenseTypeId,
			'Deposit' AS ExpenseType,
			0 As RefundAmount
		FROM sStudent.vStudentAcademic  VA
			LEFT JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
		Where 
		    ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DA.DepositHeadId = @rDepositHeadId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))	
			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 ((VA.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((DA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			--AND ((convert(date,DA.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    --AND ((convert(date,DA.CreatedDateTime)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
			AND ((convert(date,DA.DepositDate)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    AND ((convert(date,DA.DepositDate)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
		
		UNION ALL

		SELECT 
		    VA.Code As Code,
			VA.StudentId AS StudentId,
		    VA.Name As StudentName,
		    VA.ClassName + ' - ' + VA.DivisionName AS Class,
			0 AS DepositeAmount,
			ISNULL(DAJ.Amount,0) AS AdjustmentAmount,
			DAJ.FeeDepositExpenseTypeId,
			DETM.Title as ExpenseType,
			0 As RefundAmount
		FROM sStudent.vStudentAcademic  VA
			LEFT JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			LEFT JOIN sFee.tFeeDepositExpenseTypeMaster DETM ON DETM.Id = DAJ.FeeDepositExpenseTypeId
		Where 
		    ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DAJ.DepositHeadId = @rDepositHeadId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))	
			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 ((VA.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((DAJ.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			--AND ((convert(date,DAJ.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    --AND ((convert(date,DAJ.CreatedDateTime)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
			AND ((convert(date,DAJ.AdjustmentDate)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    AND ((convert(date,DAJ.AdjustmentDate)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
		

		UNION ALL

		SELECT 
		    VA.Code As Code,
			VA.StudentId AS StudentId,
		    VA.Name As StudentName,
		    VA.ClassName + ' - ' + VA.DivisionName AS Class,
			0 AS DepositeAmount,
			0 AS AdjustmentAmount,
			'' AS FeeDepositExpenseTypeId,
			'Refund' as ExpenseType,
			ISNULL(DR.RefundAmount,0) As RefundAmount
		FROM sStudent.vStudentAcademic  VA
			LEFT JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId 
		Where 
		    ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DR.DepositHeadId = @rDepositHeadId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))	
			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 ((VA.DepartmentId = @rDepartmentId)OR(@rDepartmentId=0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			AND ((DR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
			--AND ((convert(date,DR.CreatedDateTime)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    --AND ((convert(date,DR.CreatedDateTime)<=@rToDate) OR (ISNUll(@rToDate,'')='')
			AND ((convert(date,DR.RefundDate)>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
		    AND ((convert(date,DR.RefundDate)<=@rToDate) OR (ISNUll(@rToDate,'')=''))
		
	) A
	Group By A.Code,A.StudentId,A.StudentName,A.Class,A.FeeDepositExpenseTypeId,A.ExpenseType

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


GO
ALTER PROCEDURE [sFee].[pStudentDepositListGet]
          
	@rOrgGroupId smallint,
	@rOrgId int,          
	@rDepositHeadId int=0,         
	@rFromDate date='',
	@rToDate date='',        
	--@rCode nvarchar(20)='',          
	@rStudentName nvarchar(300)='',
	@rStudentCode nvarchar(100)='',
	@rClassId int=0,
	@rDivisionId int=0,
	@rIsBasedOnSUId bit = 0,
	@rDepartmentId int=0,
	@rSUId nvarchar(50)='',
	@rBatchId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)=''

           
AS
SET NOCOUNT ON
 
BEGIN
		SET @rStudentName = sCommon.fSearchStringGet(@rStudentName)

SELECT * FROM (


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

		
UNION ALL

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

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

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

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


GO
ALTER PROCEDURE [sFee].[pStudentLedgerGet]  
   
  @rCode  nvarchar(20)='',  
  @rSUId nvarchar(50)='',  
  @rDepositHeadId int,  
  @rOrgId int,  
  @rBatchId int=0,  
  @rAcademicId bigint=0  
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON   
BEGIN   
 SELECT A.DepositDate ,  
        A.Credit,  
        A.Debit,  
  A.ExpenseType,  
  A.TransactionType, 
  A.BatchName, 
  (CASE WHEN A.Debit = 0 THEN 'Credited' ELSE 'Debited' END)AS PayType  
         FROM(  
   SELECT   
   DA.DepositDate AS DepositDate,  
   ISnull (DA.Amount,0) AS Credit,  
      0 AS Debit,  
   '' AS ExpenseType,  
   'Deposit Add' AS TransactionType  ,
   DA.CreatedDateTime,
   VA.BatchName
   FROM sStudent.vStudentAcademic  VA  
   INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId   
   Where   
   ((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))  
   AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))  
   AND (DA.DepositHeadId = @rDepositHeadId)   
   AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))   
   AND VA.StudentId= @rAcademicId  
   ---AND VA.BatchId = @rBatchId  
   UNION ALL   
   SELECT   
   DAJ.AdjustmentDate As DepositDate,  
   0  AS Credit,  
   ISnull (DAJ.Amount,0)  AS Debit,  
   ISNULL(ETM.Title,'')AS ExpenseType,  
   ('Expense'+' '+ISNULL(ETM.Title,'')) AS TransactionType  ,
   DAJ.CreatedDateTime,
   VA.BatchName
   FROM sStudent.vStudentAcademic  VA  
     INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId  
     INNER JOIN sFee.tFeeDepositExpenseTypeMaster ETM ON ETM.Id =DAJ.FeeDepositExpenseTypeId  
   Where   
   ((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))  
   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  
   AND VA.StudentId = @rAcademicId  
   UNION ALL   
   SELECT   
   DR.RefundDate As DepositDate,  
   0  AS Credit,  
   ISnull (DR.RefundAmount,0)  AS Debit,  
   '' AS ExpenseType,  
   'Deposit Refund' AS TransactionType ,
    DR.CreatedDateTime,
	VA.BatchName
   FROM sStudent.vStudentAcademic  VA  
     INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId  
   Where   
   ((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))  
   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  
      AND VA.StudentId = @rAcademicId  
   )A   
   Order BY A.DepositDate,A.CreatedDateTime
     
END
GO
PRINT N'Altering [sHostel].[pAttendanceListGet]...';


GO
ALTER PROCEDURE [sHostel].[pAttendanceListGet]
	 	 
	 	@rRoomId int,
		@rHostelId int,
		@rStudentCode nvarchar(20),
		@rFromAttendanceDate date,
		@rToAttendanceDate date,
	 	@rSuid nvarchar(50),
	 	@rPresent int,
	 	@rHostelAttendanceTypeId int,
	 	@rOrgGroupBatchId int,
	 	@rBuildingId int=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT 
			SA.StudentId,
			SA.Code AS StudentCode,
			SA.Name,
			SA.SUId,
			ATR.AttendanceDate,
			ISNULL(ATR.IsPresent,'true') as IsPresent,
			ISNULL(ATR.AbsentReasonId,0) as AbsentReasonId,
			ARM.Title AS AbsentReasonName,
			RM.Title As RoomName,
			ATM.Title As AttendanceType
	 FROM  
			sStudent.vStudentAcademic SA 
			INNER JOIN sHostel.tAssignRoom AR ON SA.StudentId = AR.SourceId AND AR.SourceTypeId=2003
		    INNER JOIN sHostel.tAttendanceRegister ATR ON ATR.StudentId = AR.SourceId 
			LEFT JOIN sAttendance.tAbsentReasonMaster ARM ON ARM.Id=ATR.AbsentReasonId
			INNER JOIN sHostel.tRoomMaster RM ON RM.Id = AR.RoomId 
	        INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
	        INNER JOIN sHostel.tHostelAttendanceTypeMaster ATM ON ATM.Id=ATR.HostelAttendanceTypeId
	        LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
	    
			
  WHERE 
	 ((AR.RoomId=@rRoomId) OR (@rRoomId=0))
	 AND ATR.HostelId = @rHostelId
	  AND ((SA.Code = @rStudentCode) OR (@rStudentCode=''))
	  AND ((ATR.IsPresent=@rPresent) OR (@rPresent=2))
	  AND ((ATR.AttendanceDate >= @rFromAttendanceDate) OR (ISNULL(@rFromAttendanceDate,'') = ''))
	  AND ((ATR.AttendanceDate <= @rToAttendanceDate) OR (ISNULL(@rToAttendanceDate,'') = ''))
	   AND ((SA.SUId=@rSuid) OR (@rSuid=''))
	  AND  ((ATR.HostelAttendanceTypeId=@rHostelAttendanceTypeId) OR (@rHostelAttendanceTypeId=0))
	  AND SA.OrgGroupBatchId= @rOrgGroupBatchId
	  AND ATR.OrgGroupBatchId= @rOrgGroupBatchId
	    AND AR.OrgGroupBatchId= @rOrgGroupBatchId
	  AND (BM.Id=@rBuildingId OR @rBuildingId=0)
      ORDER BY ATR.AttendanceDate DESC
END
GO
PRINT N'Altering [sHostel].[pAttendanceRegisterDetailsGet]...';


GO
ALTER PROCEDURE [sHostel].[pAttendanceRegisterDetailsGet]
          
           @rHostelId int,
           @rOrgId int,
           @rSourceTypeId smallint,
           @rCode nvarchar(20),
           @rFromAllocateDate date,
           @rToAllocateDate date,
           @rToVacantDate date='',
           @rFromVacantDate date='',
           @rSUID nvarchar(50),
           @rOrgGroupBatchId int
           
          
AS
SET NOCOUNT ON

BEGIN
SELECT  
		OM.DisplayTitle AS OrganizationName,
        (CASE WHEN HA.SourceTypeId = 95 THEN	'Employee'
			 WHEN HA.SourceTypeId = 2003 THEN	'Student' END) AS SourceType,

		(CASE WHEN HA.SourceTypeId = 95 THEN	Emp.Code
			 WHEN HA.SourceTypeId = 2003 THEN	SM.Code END) AS SourceCode, 	
		
		(CASE WHEN HA.SourceTypeId = 95 THEN	''
			 WHEN HA.SourceTypeId = 2003 THEN	SM.SUId END) AS SUId, 	

		(CASE WHEN HA.SourceTypeId = 95 THEN Emp.EmployeeName
			WHEN HA.SourceTypeId = 2003 THEN SM.LastName + ' ' + SM.FirstName  END) AS SourceName,
			
		(CASE WHEN HA.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN HA.SourceTypeId = 2003 THEN (sStudent.fStudentCurrentDivisionGet(SM.StudentId)) END) AS ClassDepartmentName,		
		 
		 HA.SourceTypeId,
		 HA.SourceId,
		 HA.AllocateDate,
		(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
		 ISNULL(HA.VacantReason,'') AS VacantReason

  FROM 
		sHostel.tHostelAdmission HA
        LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = HA.SourceId AND HA.SourceTypeId = 95 
		LEFT JOIN sStudent.vStudentAcademic SM
			ON SM.StudentId = HA.SourceId AND HA.SourceTypeId = 2003 AND SM.OrgGroupBatchId=@rOrgGroupBatchId 	
		LEFT JOIN sSetup.tOrganizationMaster OM ON (OM.Id = SM.OrgId) OR (OM.Id = Emp.OrgId)  	
  WHERE 
	
	(HA.Hosteld=@rHostelId)
	AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
	AND ((HA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='') 
        OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
	AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
	AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
	AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
	AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
	AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
	AND HA.OrgGroupBatchId=@rOrgGroupBatchId
	order by  HA.AllocateDate desc
END
GO
PRINT N'Altering [sHostel].[pChangeRoomGet]...';


GO
ALTER PROCEDURE [sHostel].[pChangeRoomGet]
          
           @rHostelId int,
           @rOrgId int,
           @rSourceTypeId smallint,
           @rCode nvarchar(20),
           @rFromLogDate date,
           @rToLogDate date,
           @rSUID nvarchar(50),
           @rOrgGroupBatchId int
          
AS
SET NOCOUNT ON

BEGIN
SELECT  
		OM.DisplayTitle AS OrganizationName,
        (CASE WHEN CR.SourceTypeId = 95 THEN	'Employee'
			 WHEN CR.SourceTypeId = 2003 THEN	'Student' END) AS SourceType,

		(CASE WHEN CR.SourceTypeId = 95 THEN	Emp.Code
			 WHEN CR.SourceTypeId = 2003 THEN	SM.Code END) AS SourceCode, 	
			 
		(CASE WHEN CR.SourceTypeId = 95 THEN	''
			 WHEN CR.SourceTypeId = 2003 THEN	SM.SUId END) AS SUId, 		 

		(CASE WHEN CR.SourceTypeId = 95 THEN Emp.EmployeeName
			WHEN CR.SourceTypeId = 2003 THEN SM.Name  END) AS SourceName,
			
		(CASE WHEN CR.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN CR.SourceTypeId = 2003 THEN (sStudent.fStudentCurrentDivisionGet(SM.StudentId)) END) AS ClassDepartmentName,	
		 RM.Title AS RoomName,
		 CR.SourceTypeId,
		 CR.SourceId,
		(CASE WHEN CR.LogDate = '1900-01-01' THEN ''
			ELSE CR.LogDate END) AS LogDate,	
		 ISNULL(CR.ChangeReason,'') AS ChangeReason

  FROM 
		sHostel.tChangeRoom CR
		INNER JOIN sHostel.tRoomMaster RM ON RM.Id = CR.RoomId
        LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = CR.SourceId AND CR.SourceTypeId = 95 
		LEFT JOIN sStudent.vStudentAcademic SM
			ON SM.StudentId = CR.SourceId AND CR.SourceTypeId = 2003 AND SM.OrgGroupBatchId=@rOrgGroupBatchId			
		LEFT JOIN sSetup.tOrganizationMaster OM ON (OM.Id = SM.OrgId) OR (OM.Id = Emp.OrgId)  	
  WHERE 
	
	(RM.HostelId=@rHostelId)
	AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
	AND ((CR.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='') 
        OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
	AND ((CR.LogDate >= @rFromLogDate) OR (ISNULL(@rFromLogDate,'') = ''))
	AND ((CR.LogDate <= @rToLogDate) OR (ISNULL(@rToLogDate,'') = ''))
	AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
	AND CR.OrgGroupBatchId=@rOrgGroupBatchId
	order by  CR.LogDate desc
END
GO
PRINT N'Altering [sHostel].[pDepositAdjustmentBulkGet]...';


GO
ALTER PROCEDURE [sHostel].[pDepositAdjustmentBulkGet]
           @rOrgId int,    
           @rCode nvarchar(max),
           @rHostelId int,
           @rOrgGroupBatchId int,
           @rStrSuid nvarchar(max)='',
           @rRoomCategoryId int,
           @rBuildingId int,
           @rRoomId int
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
    SELECT  
		vSA.OrgId,
		vSA.StudentId AS StudentId,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(vSA.SUId,'') AS SUId,
        VSA.AcademicId,
        RCM.Title AS RoomCategory,
        RM.Title As Room
  FROM 		
			sStudent.vStudentAcademic vSA
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=VSA.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
			INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
			AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
		    LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
  WHERE  
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (RM.HostelId=@rHostelId)
		AND ((VSA.OrgGroupBatchId=@rOrgGroupBatchId))
		AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId))
		AND RM.IsObsolete=0
	    AND (BM.Id=@rBuildingId OR @rBuildingId=0)
	    AND (RM.Id=@rRoomId OR @rRoomId=0)
	    AND (ISNULL(VSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='') 
	    AND (ISNULL(VSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
		Order By VSA.SUId,VSA.Code
END
GO
PRINT N'Altering [sHostel].[pHostelAdmissionGet]...';


GO
ALTER PROCEDURE [sHostel].[pHostelAdmissionGet]
          
           @rHostelId int,
           @rOrgId int,
           @rSourceTypeId smallint,
           @rCode nvarchar(20),
           @rFromAllocateDate date,
           @rToAllocateDate date,
           @rToVacantDate date='',
           @rFromVacantDate date='',
           @rSUID nvarchar(50),
           @rOrgGroupBatchId int
           
          
AS
SET NOCOUNT ON

BEGIN
SELECT  
		OM.DisplayTitle AS OrganizationName,
        (CASE WHEN HA.SourceTypeId = 95 THEN	'Employee'
			 WHEN HA.SourceTypeId = 2003 THEN	'Student' END) AS SourceType,

		(CASE WHEN HA.SourceTypeId = 95 THEN	Emp.Code
			 WHEN HA.SourceTypeId = 2003 THEN	SM.Code END) AS SourceCode, 	
		
		(CASE WHEN HA.SourceTypeId = 95 THEN	''
			 WHEN HA.SourceTypeId = 2003 THEN	SM.SUId END) AS SUId, 	

		(CASE WHEN HA.SourceTypeId = 95 THEN Emp.EmployeeName
			WHEN HA.SourceTypeId = 2003 THEN SM.LastName + ' ' + SM.FirstName  END) AS SourceName,
			
		(CASE WHEN HA.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN HA.SourceTypeId = 2003 THEN (sStudent.fStudentCurrentDivisionGet(SM.StudentId)) END) AS ClassDepartmentName,		
		 
		 HA.SourceTypeId,
		 HA.SourceId,
		 HA.AllocateDate,
		(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
		 ISNULL(HA.VacantReason,'') AS VacantReason

  FROM 
		sHostel.tHostelAdmission HA
        LEFT JOIN sHrm.vExtEmployeeMaster Emp
			ON Emp.Id = HA.SourceId AND HA.SourceTypeId = 95 
		LEFT JOIN sStudent.vStudentAcademic SM
			ON SM.StudentId = HA.SourceId AND HA.SourceTypeId = 2003 AND SM.OrgGroupBatchId=@rOrgGroupBatchId 	
		LEFT JOIN sSetup.tOrganizationMaster OM ON (OM.Id = SM.OrgId) OR (OM.Id = Emp.OrgId) 
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = SM.OrgGroupBatchId AND BM.Id = SM.BatchId
  WHERE 
	
	(HA.Hosteld=@rHostelId)
	AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
	AND ((HA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
	AND (((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='') 
        OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')=''))
	AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
	AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
	AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
	AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
	AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
	AND HA.OrgGroupBatchId=@rOrgGroupBatchId
	AND BM.IsInContext = 1
	order by  HA.AllocateDate desc
END
GO
PRINT N'Altering [sHostel].[PHostelDepositListGet]...';


GO
ALTER PROCEDURE [sHostel].[PHostelDepositListGet]
	 
	      @rHostelId int,
	      @rRoomId int,
          @rOrgGroupBatchId int,
          @rStudentCode   nvarchar(max)='',
          @rSUId nvarchar(max)='',
          @rHostelDepositHeadId int
     
          
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	SELECT
	    DHM.Title AS DepositHeadName,
		DA.Id AS DepositId,
	    DA.Studentid AS Studentid,
		DA.Amount,
		DA.DepositDate,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
       ISNULL(VSA.SUID,'') AS SUID,
       RM.Title AS Room,
       	DA.HostelDepositHeadId
  FROM 		
		sHostel.tAssignRoom AR 
		INNER JOIN sStudent.vStudentAcademic vSA ON vSA.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId 
		INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id
	
		WHERE	
			 (DA.HostelId=@rHostelId)
			AND DA.OrgGroupBatchId=@rOrgGroupBatchId
		    AND AR.OrgGroupBatchId=@rOrgGroupBatchId
			AND vSA.OrgGroupBatchId=@rOrgGroupBatchId
			AND ((DA.HostelDepositHeadId = @rHostelDepositHeadId) OR (ISNULL(@rHostelDepositHeadId,0) = 0))
			AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
			AND (ISNULL(vSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
	        AND (ISNULL(vSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
	    
			Order By VSA.SUID,VSA.Code
END
GO
PRINT N'Altering [sHostel].[pHostelStudentGatePassBulkGet]...';


GO
ALTER PROCEDURE [sHostel].[pHostelStudentGatePassBulkGet]
           @rOrgId int,    
           @rCode nvarchar(max),
           @rHostelId int,
           @rOrgGroupBatchId int,
           @rStrSuid nvarchar(max)='',
           @rRoomCategoryId int,
           @rBuildingId int,
           @rRoomId int,
           @rEntryModeStatusId smallint=0,
          @rBulkNumber nvarchar(20)
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 


	IF (@rBulkNumber = '-1')
	BEGIN
	  SELECT  
		vSA.OrgId,
		vSA.StudentId AS StudentId,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(vSA.SUId,'') AS SUId,
        VSA.AcademicId,
        RCM.Title AS RoomCategory,
        RM.Title As Room,
        --   '' as VisitorName ,--HSGP.VisitorName,
        ----CASE when HSGP.BulkNumber=0 THEN '' ELSE HSGP.BulkNumber END 
        --'' as BulkNumber , --  HSGP.BulkNumber,
        0 AS OrgGroupBatchId,
        0 as HostelStudentGatePassId
  FROM 		
			sStudent.vStudentAcademic vSA
			
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=VSA.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			
			INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
			AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
		    LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
		    --LEFT JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId 
  WHERE  
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		--AND (HSGP.BulkNumber=@rBulkNumber OR @rBulkNumber=-1)
		AND (RM.HostelId=@rHostelId)
		AND ((VSA.OrgGroupBatchId=@rOrgGroupBatchId))
		AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId))
		AND RM.IsObsolete=0
	    AND (BM.Id=@rBuildingId OR @rBuildingId=0)
	    AND (RM.Id=@rRoomId OR @rRoomId=0)
	    AND (ISNULL(VSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='') 
	    AND (ISNULL(VSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
	    
		Order By VSA.RollNo
	END
	
	
	ELSE 
	BEGIN
	
	
    SELECT  
		vSA.OrgId,
		vSA.StudentId AS StudentId,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        ISNULL(vSA.SUId,'') AS SUId,
        VSA.AcademicId,
        RCM.Title AS RoomCategory,
        RMM.Title As Room,
        HSGP.VisitorName,
        HSGP.BulkNumber,
        IsNull(HSGP.Id,0) AS HostelStudentGatePassId,
        	HSGP.RelationshipId,		
			RM.Title AS Relationship,
			HSGP.Relation,
			HSGP.VisitorName,
			HSGP.VisitorMobile,
			HSGP.HostelGatePassReasonId,
			HGRM.Title AS HostelGetPassReason,
			HSGP.Remark,
			HSGP.OrgGroupBatchId,
			HSGP.GatePassDate,
			HSGP.EntryModeStatusId,
			HSGP.GatePassInDate,
			 CONVERT(varchar(15),CAST(HSGP.GatePassTime AS TIME),100) As GatePassTime,
			  CONVERT(varchar(15),CAST(HSGP.GatePassInTime AS TIME),100) As GatePassInTime,
			  SM.Title AS EntryModeStatus
  FROM 		
			sStudent.vStudentAcademic vSA
			
			INNER JOIN sHostel.tAssignRoom AR ON AR.SourceId=VSA.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			
			INNER JOIN sHostel.tRoomCategoryMaster RCM ON RCM.HostelId=HM.Id AND RCM.Id = RM.RoomCateGoryId
			AND (RCM.Id=@rRoomCategoryId OR @rRoomCategoryId=0)
		    LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
		   LEFT JOIN sHostel.tHostelStudentGatePass HSGP ON HSGP.StudentId = vSA.StudentId  AND  ((HSGP.OrgGroupBatchId=@rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
		   LEFT JOIN sHostel.tHostelGatePassReasonMaster HGRM ON HGRM.Id=HSGP.HostelGatePassReasonId
		   LEFT JOIN sCommon.tRelationshipMaster RMM ON RMM.Id=HSGP.RelationshipId
			LEFT JOIN sCommon.tStatusMaster SM ON SM.Id=HSGP.EntryModeStatusId
  WHERE  
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (HSGP.BulkNumber=@rBulkNumber OR @rBulkNumber='-1')
		AND (RM.HostelId=@rHostelId)
		AND ((VSA.OrgGroupBatchId=@rOrgGroupBatchId))
		AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId))
		AND RM.IsObsolete=0
	    AND (BM.Id=@rBuildingId OR @rBuildingId=0)
	    AND (RM.Id=@rRoomId OR @rRoomId=0)
	    AND (ISNULL(VSA.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rStrSuid,',')) OR @rStrSuid='') 
	    AND (ISNULL(VSA.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rCode,',')) OR @rCode='') 
	    AND HSGP.BulkNumber IS not null
	    AND HSGP.EntryModeStatusId=581
	   -- AND vSA.StudentId in (select* from sHostel.tHostelStudentGatePass WHERe BulkNumber=@rBulkNumber )
		Order By VSA.RollNo
END
END
GO
PRINT N'Altering [sHostel].[pHostelStudentSearchGet]...';


GO
ALTER PROCEDURE [sHostel].[pHostelStudentSearchGet]
	 
	 @rOrgId int,
	 @rHostelId int,
	 @rRoomId int,
	 @rStudentId bigint,
	 @rStudentName nvarchar(100),
	 @rStudentCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int,
	 @rSUId nvarchar(max)='',
	 @rDepartmentId  int,
	 @rOrgGroupId smallint=0,
	 @rBuildingId int=0,
	 @rSurName nvarchar(100)='',
	 @rIsSelfPermissionToGoOut int=0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 		
			SELECT 		
			O.DisplayTitle AS Organization,
			HM.Title AS Hostel,
			RM.Title AS Room,
			SD.Code AS StudentCode,
			SD.Name AS StudentName,
			SD.ClassName + ' - ' + SD.DivisionName AS Class,
			SD.DivisionName AS Division,
			SD.StudentId,			
			SD.ClassId,
			SD.DivisionId,
			HM.Id AS HostelId,
			RM.Id AS RoomId,
			O.Id AS OrgId,
			ISNULL(AR.BedNumber,'') AS BedNumber ,
			ISnull(SD.SUID,'') AS SUID,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISnull(SD.DepartmentName,'') As DepartmentName,
			[sHostel].[fAssignRoomAssetGet](HM.Id,RM.Id,SD.StudentId) AS AssetNumber,
			ISNULL(SC.PresentCity,'') AS City,
			ISNULL(SC.ParentContactNo,'') AS ContactNo,
			ISNULL(SC.ParentEmail,'') AS EMail,
			ISNULL(HA.IsSelfPermissionToGoOut,0) AS IsSelfPermissionToGoOut,
			SD.BatchId
			
			FROM sHostel.tAssignRoom AR 
			INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
			INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
			INNER JOIN sSetup.tOrganizationMaster O ON O.Id = SD.OrgId
			--INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SD.BatchId AND BM.IsActive = 1
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SD.StudentId
			LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
			LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
			INNER JOIN  sHostel.tHostelAdmission HA On HA.SourceId=AR.SourceId AND AR.SourceTypeId = 2003 AND HA.OrgGroupBatchId=@rOrgGroupBatchId
			Where 
			AR.SourceTypeId = 2003
			AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
			AND (AR.OrgGroupBatchId=@rOrgGroupBatchId)
			AND ((SD.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((HM.Id = @rHostelId) OR (ISNULL(@rHostelId,0) = 0))
			AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
			AND ((SD.StudentId = @rStudentId) OR (ISNULL(@rStudentId,0) = 0))
			AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
			AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
			--AND ((SD.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
			AND ((SD.firstname like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
			AND ((SD.DepartmentId = @rDepartmentId ) OR (ISNULL(@rDepartmentId,0) = 0))
			--AND ((SD.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND HM.OrgGroupId=@rOrgGroupId
			AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
	        AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
	        AND ((SD.Lastname like @rSurName + '%') OR (ISNULL(@rSurName,'') = ''))
	        AND ((BM.Id=@rBuildingId )OR (@rBuildingId=0))
	        AND ((IsSelfPermissionToGoOut=@rIsSelfPermissionToGoOut) OR(ISnull(@rIsSelfPermissionToGoOut,0)=0))
            
			order by SD.ClassId,RM.Id 


--			 declare @quer varchar(max)=''
--SELECT @quer='SELECT 	O.DisplayTitle AS Organization,RM.Title AS Room,
--			SD.Code AS StudentCode,
--			SD.Name AS StudentName ,
--			HM.Title AS Hostel,
--			SD.ClassName  + SD.DivisionName AS Class,
--			SD.DivisionName AS Division,
--			SD.StudentId,
--			SD.ClassId,
--			SD.DivisionId,
--			HM.Id AS HostelId,
--			RM.Id AS RoomId,
--			O.Id AS OrgId,
--			ISNULL(AR.BedNumber,'''') AS BedNumber ,
--			ISnull(SD.SUID,'''') AS SUID,
--			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
--			ISnull(SD.DepartmentName,'''') As DepartmentName,
--			[sHostel].[fAssignRoomAssetGet](HM.Id,RM.Id,SD.StudentId) AS AssetNumber,
--			ISNULL(SC.PresentCity,'''') AS City,
--			ISNULL(SC.ParentContactNo,'''') AS ContactNo,
--			ISNULL(SC.ParentEmail,'''') AS EMail,
--			ISNULL(HA.IsSelfPermissionToGoOut,0) AS IsSelfPermissionToGoOut
--			FROM sHostel.tAssignRoom AR 
--			INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
--			INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
--			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
--			INNER JOIN sSetup.tOrganizationMaster O ON O.Id = SD.OrgId
--      		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SD.StudentId
--			LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
--			LEFT JOIN sHostel.tBuildingMaster BM ON BM.HostelId=HM.Id AND BM.Id = RM.BuildingId
--			INNER JOIN  sHostel.tHostelAdmission HA On HA.SourceId=AR.SourceId AND AR.SourceTypeId = 2003 AND HA.OrgGroupBatchId='+COnvert(varchar,@rOrgGroupBatchId)+'
--			Where 
--			AR.SourceTypeId =2003
--			AND HM.OrgGroupId='+convert(varchar,@rOrgGroupId)+'
--			AND SD.OrgGroupBatchId='+convert(varchar,@rOrgGroupBatchId)+'
--			AND AR.OrgGroupBatchId='+convert(varchar,@rOrgGroupBatchId)+'
--			AND ((O.Id = '+convert(varchar,@rOrgId) + ') OR ('+Convert(varchar,@rOrgId) +'=0)) 
--			AND ((HM.Id= '+convert(varchar,@rStudentId) + ') OR (' + Convert(varchar,ISNULL(@rStudentId,0)) + ' = 0))
--			AND ((RM.Id= '+convert(varchar,@rRoomId) + ') OR (' + Convert(varchar,ISNULL(@rRoomId,0)) + ' = 0))
--			AND ((SD.StudentId= '+convert(varchar,@rHostelId) + ') OR (' + Convert(varchar,ISNULL(@rHostelId,0)) + ' = 0))
--			AND ((SD.ClassId= '+convert(varchar,@rClassId) + ') OR (' + Convert(varchar,ISNULL(@rClassId,0))+ ' = 0))
--			AND ((SD.DivisionId= '+convert(varchar,@rDivisionId) + ' OR ' +Convert(varchar,ISNULL(@rDivisionId,0))+ ' = 0))
--			AND ((SD.DepartmentId= '+convert(varchar,@rDepartmentId) + ' OR ' + Convert(varchar,ISNULL(@rDepartmentId,0))+ ' = 0))
--			AND HM.OrgGroupId= '+convert(varchar,@rOrgGroupId) + '
--			AND ((BM.Id= '+convert(varchar,@rBuildingId) + ' OR ' + Convert(varchar,ISNULL(@rBuildingId,0)) + ' = 0))
--			AND ((IsSelfPermissionToGoOut= '+convert(varchar,@rIsSelfPermissionToGoOut) + ' OR ' + Convert(varchar,ISNULL(@rIsSelfPermissionToGoOut,0))+ ' = 0))
--			AND ((SD.Name like ''' + @rStudentName + ''') OR (''' + @rStudentName + ''' = ''''))
--			AND ((SD.Lastname like '''+@rSurName + ''')OR (''' + @rSurName + ''' = ''''))
--			AND ((ISNULL(SD.SUID,'''') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit('''+@rSUId+''','','')))    OR (''' +  @rSUId + ''' = '''')) 
--			AND ((ISNULL(SD.Code,'''') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit('''+@rStudentCode+''','','')))    OR (''' +  @rStudentCode + ''' = '''')) 
			 
			 
--			order by SD.ClassId,RM.Id '
--		   			Exec   (@quer)
END
GO
PRINT N'Altering [sHostel].[pRptAddressLabelGet]...';


GO
ALTER PROCEDURE [sHostel].[pRptAddressLabelGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rStudentName nvarchar(100)='',
	 @rStudentCode nvarchar(100)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rIsBasedOnSUId bit = 0,
	 @rDepartmentId int=0,
	 @rSUId nvarchar(50)='',
	 @rRoomId int=0, 
	 @rFromAllocateDate date,
	 @rToAllocateDate Date
	 
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	SELECT 
	HM.Title,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.OrgId,
		SA.DivisionId,
		SA.DivisionOrder,
		@rIsBasedOnSUId AS IsBasedOnSUId ,
		CD.PresentStreetOne AS Address1,
		CD.PresentStreetTwo AS Address2,
		CD.PresentStreetThree AS Address3,
		CD.PresentCountry AS AddressCountry,
		CD.PresentState AS AddressState,
		CD.PresentCity AS AddressCity,
		CD.PresentZipCode AS AddressZipCode,
		CD.PresentContactNo AS ContactNo,
		CD.ParentContactNo ,
		CD.StudentContactNo,
		CD.ParentEmail,
		CD.StudentEmail,
		SA.Name,
		SA.Code,
		SA.SUId,
		RM.Title As Room,
		[sHostel].[fAssignRoomAssetNumberGet](HM.Id,RM.Id,ISNULL(SA.StudentId,0)) As AssetNumber,
		SA.ClassName ,
		SA.DivisionName
			
			
	FROM 
		sStudent.vStudentAcademic SA 
		LEFT JOIN sStudent.tStudentCommunication CD ON  SA.StudentId=CD.StudentId
		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
		INNER JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = SA.BatchId
	 
	WHERE 
 --(SA.OrgGroupBatchId = @rOrgGroupBatchId)

		((RM.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 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.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
		AND ((SA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND (SA.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND (AR.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
	    AND BM.IsInContext = 1
		 
END
GO
PRINT N'Altering [sHostel].[pRptDepositWisetransactionList]...';


GO
ALTER PROC [sHostel].[pRptDepositWisetransactionList]

	 @rDepositHeadId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rOrgGroupBatchId int = 0,
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
     @rDepartmentId int=0,
     @rClassId int=0,
     @rDivisionId int=0,
     @rStudentName  nvarchar(100)='',
     @rRoomId int
      
AS
BEGIN
		SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    'DepositAdd' AS GroupType,
	        --'' As ExpenseSubType,
	        DA.Id As GroupID
		    
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sFee.tDepositAdd DA  ON VA.AcademicId = DA.AcademicId 
			Where 
		  ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DA.DepositHeadId = @rDepositHeadId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))	
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (ISNULL(@rOrgGroupBatchId,0) = 0))
			AND ((DA.OrgGroupBatchId = @rOrgGroupBatchId) OR (ISNULL(@rOrgGroupBatchId,0) = 0)) 			
			
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			ISnull (DAJ.Amount,0)  AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     'DepositAdjustment' AS GroupType,
		     --ES.Title As ExpenseSubType,
		     DAJ.Id As GroupID
		    
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositAdjustment DAJ ON DAJ.AcademicId = VA.AcademicId
			  --INNER JOIN sHostel.tHostelExpenseSubTypeMaster ES ON ES.Id=DAJ.HostelExpenseSubTypeId
		     
			Where 
				((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DAJ.DepositHeadId = @rDepositHeadId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (ISNULL(@rOrgGroupBatchId,0) = 0))
			AND ((DAJ.OrgGroupBatchId = @rOrgGroupBatchId) OR (ISNULL(@rOrgGroupBatchId,0) = 0)) 			
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			ISnull (DR.RefundAmount,0)  AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId, 
		    'DepositRefund' AS GroupType,
		    --'' As ExpenseSubType,
		    DR.Id As GroupID
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sFee.tDepositRefund DR ON DR.AcademicId = VA.AcademicId
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DR.DepositHeadId = @rDepositHeadId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND ((VA.OrgGroupBatchId = @rOrgGroupBatchId) OR (ISNULL(@rOrgGroupBatchId,0) = 0))
			AND ((DR.OrgGroupBatchId = @rOrgGroupBatchId) OR (ISNULL(@rOrgGroupBatchId,0) = 0)) 		    


 
END
GO
PRINT N'Altering [sHostel].[pRptExpenseTypeWiseDepositList]...';


GO
ALTER PROC [sHostel].[pRptExpenseTypeWiseDepositList]

	 @rHostelId int,
	 @rStudentCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rOrgGroupBatchId int,
     @rBuilder1 nvarchar(max)='',
     @rBuilder2 nvarchar(max)='',
     @rDepartmentId int=0,
     @rClassId int=0,
     @rDivisionId int=0,
     @rStudentName  nvarchar(100)='',
    -- @rRoomId int,
     @rFromAllocateDate date,
	 @rToAllocateDate Date
      
AS
BEGIN
		SELECT 
			@rBuilder2 AS Builder2,
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    'Add' AS GroupType,
	        '' As ExpenseSubType,
	        '' AS ExpenseType,
	        DA.Id As GroupID,
			HM.ReportOrgTitle AS ReportOrgTitle,
			HM.SmallAddress1 AS SmallAddress1,
			HM.SmallAddress2 AS SmallAddress2
		    
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sHostel.tHostelDepositAdd DA  ON VA.StudentId = DA.StudentId  
			INNER JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=DA.StudentId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DA.HostelId
			Where 
		  ((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DA.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))	
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	        AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
			
	UNION
			SELECT 
			@rBuilder2 AS Builder2,
			DAJ.AdjustmentDate As DepositDate,
			-ISnull (DAJ.Amount,0)  AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     'Adjustment' AS GroupType,
		     ES.Title As ExpenseSubType,
		     HT.Title AS ExpenseType,
		     DAJ.Id As GroupID,
			 '' AS ReportOrgTitle,
			 '' AS SmallAddress1,
			 '' AS SmallAddress2
		    
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositAdjustment DAJ ON DAJ.StudentId = VA.StudentId
			  INNER JOIN sHostel.tHostelExpenseSubTypeMaster ES ON ES.Id=DAJ.HostelExpenseSubTypeId
		      INNER JOIN sHostel.tHostelExpenseTypeMaster HT ON HT.Id= ES.ExpenseTypeId
			INNER JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=DAJ.StudentId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
			Where 
				((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DAJ.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DAJ.OrgGroupBatchId = @rOrgGroupBatchId
		    AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	        AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
	 UNION
			SELECT 
			@rBuilder2 AS Builder2,
			DR.RefundDate As DepositDate,
			-ISnull (DR.RefundAmount,0)  AS Amount,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId, 
		    'Refund' AS GroupType,
		    '' As ExpenseSubType,
		    '' AS ExpenseType,
		    DR.Id As GroupID,
			'' AS ReportOrgTitle,
			'' AS SmallAddress1,
			'' AS SmallAddress2
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = VA.StudentId
			   INNER JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=DR.StudentId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
			Where 
			((VA.Code like @rStudentCode) OR (ISNULL(@rStudentCode,'') = ''))
			AND DR.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DR.OrgGroupBatchId = @rOrgGroupBatchId
		    AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	      AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))


 
END
GO
PRINT N'Altering [sHostel].[pRptHostelAdmissionListGet]...';


GO
ALTER PROCEDURE [sHostel].[pRptHostelAdmissionListGet]
          
           @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
	       @rHostelId int,
			@rOrgGroupBatchId int,
			@rOrgId int,
			@rRoomId int=0,
			@rStudentName nvarchar(100)='',
			@rStudentCode nvarchar(100)='',
			@rClassId int=0,
			@rDivisionId int=0,
			--@rIsBasedOnSUId bit = 0,
			@rDepartmentId int=0,
			@rSUId nvarchar(50)='' , 
			@rCode nvarchar(20)='',          		         
           --@rHostelDepositHeadId int=0,
           @rFromDate date,
           @rToDate date
                                                  				  		            
AS
SET NOCOUNT ON

BEGIN
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		vSA.SUId,
		vSA.AcademicId AS AcademicId,
		vSA.StudentId AS StudentId,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
		OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
		RM.Id AS RoomId,
		RM.Title AS RoomName,
		--CASE WHEN @rIsBasedOnSUId=0 THEN  vSA.Code Else ISNULL(vSA.suid,'') END AS SUId,
	 HA.AllocateDate AS AdmissionDate
		
	
		
  FROM 		sHostel.tHostelAdmission HA
			LEFT JOIN sStudent.vStudentAcademic vSA ON vSA.StudentId = HA.SourceId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id=HA.Hosteld
			LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=HA.SourceId
			LEFT JOIN sHostel.tRoomMaster RM ON RM.Id= AR.RoomId   
            INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = vSA.BatchId
		--sStudent.vStudentAcademic vSA		
		--INNER JOIN sHostel.tHostelAdmission HA ON HA.SourceId = vSA.AcademicId
		--INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = vSA.StudentId
		--INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DR.HostelDepositHeadId
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		--INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DR.HostelId
		--LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=DR.StudentId  AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	 --   LEFT JOIN sHostel.tRoomMaster RM ON RM.Id= AR.RoomId   
		
  WHERE  
		
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)		
		AND ((HA.AllocateDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		AND ((HA.AllocateDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))		
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (HA.Hosteld=@rHostelId)
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((vSA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vSA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((vSA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((vSA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((vSA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (vSA.SUId like @rSUId OR ISNULL(@rSUId,'')='') 
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (HA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND BM.IsInContext = 1
		--GROUP BY
		
		--DHM.Title,DR.HostelDepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		--DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName,OM.Id,OM.DisplayTitle ,HM.ReportOrgTitle,HM.SmallAddress1,HM.SmallAddress2,RM.Id ,RM.Title,vSA.SUId 
		Order By HA.AllocateDate desc
END
GO
PRINT N'Altering [sHostel].[pRptHostelDepositAddGet]...';


GO
ALTER PROCEDURE [sHostel].[pRptHostelDepositAddGet]
          
		     @rOrgId int,          
             @rHostelDepositHeadId int=0,
             @rFromAmount decimal(12,2)=0,
             @rToAmount decimal(12,2)=0,
             @rFromDepositDate date='',
             @rToDepositDate date='',
          -- @rBatchId int,
             @rCode nvarchar(20)='',
             @rHostelId int,
             @rRoomId int=0,
             @rStudentName nvarchar(100)='',
			 @rStudentCode nvarchar(100)='',
			 @rClassId int=0,
		     @rDivisionId int=0,
			 @rIsBasedOnSUId bit = 0,
			 @rDepartmentId int=0,
			 @rSUId nvarchar(50)='',
			 @rOrgGroupBatchId int,
			 @rBuilder1 nvarchar(max)='',
			 @rBuilder2 nvarchar(max)='',
			 @rFromAllocateDate date=null,
	         @rToAllocateDate Date=null
           
AS
SET NOCOUNT ON 

BEGIN
SELECT  
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.DepositDate,
		DA.PayTypeId,	
		DA.ChequeNo,
		DA.BankName,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
        HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
		RM.Id AS RoomId,
		RM.Title AS RoomName,
		CASE WHEN @rIsBasedOnSUId=0 THEN  vSA.Code Else ISNULL(vSA.suid,'') END AS SUId,
		PTM.Title AS PayType,
		U.DisplayTitle AS Username,
		U.Id As UserId
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositAdd DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DA.HostelId  
	    LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=DA.StudentId  AND  AR.OrgGroupBatchId=@rOrgGroupBatchId
	    LEFT JOIN sHostel.tRoomMaster RM ON RM.Id= AR.RoomId  
	    INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=DA.PayTypeId
	    LEFT JOIN sSecurity.tUser U ON U.Id=DA.CreatedUserId
	    LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = vSA.BatchId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.DepositDate >= @rFromDepositDate) OR (ISNULL(@rFromDepositDate,'') = ''))
		AND ((DA.DepositDate <= @rToDepositDate) OR (ISNULL(@rToDepositDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DA.HostelId=@rHostelId)
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((vSA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vSA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((vSA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((vSA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((vSA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (vSA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (DA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
	    AND BM.IsInContext = 1
		Order By DA.DepositDate
END
GO
PRINT N'Altering [sHostel].[pRptHostelDepositAdjustmentGet]...';


GO
ALTER PROCEDURE [sHostel].[pRptHostelDepositAdjustmentGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int=0,
           @rFromAmount decimal(12,2)=0,
           @rToAmount decimal(12,2)=0,
           @rFromAdjustmentDate date='',
           @rToAdjustmentDate date='',
           --@rBatchId int,
           @rCode nvarchar(20)='',
           @rHostelId int,@rRoomId int=0,
           @rStudentName nvarchar(100)='',
		   @rStudentCode nvarchar(100)='',
		   @rClassId int=0,
		   @rDivisionId int=0,
		   @rIsBasedOnSUId bit = 0,
		   @rDepartmentId int=0,
		   @rSUId nvarchar(50)='',
		   @rOrgGroupBatchId int,
		   @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
	       @rFromAllocateDate date=null,
	       @rToAllocateDate Date=null
           
AS
SET NOCOUNT ON

BEGIN
SELECT  
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.HostelDepositHeadId,
		DA.StudentId AS StudentId,
		vSA.AcademicId AS AcademicId,
		DA.Amount,
		DA.AdjustmentDate,
		DA.Remark,
		DA.CreatedDateTime,
		vSA.Code,
        vSA.Name AS StudentName,        
        vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,
        OM.Id AS OrgId,
        OM.DisplayTitle AS OrganizationName,
         HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
		RM.Id AS RoomId,
		RM.Title AS RoomName,
		CASE WHEN @rIsBasedOnSUId=0 THEN  vSA.Code Else ISNULL(vSA.suid,'') END AS SUId
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN  sHostel.tHostelDepositAdjustment DA ON DA.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DA.HostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DA.HostelId 
		LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=DA.StudentId AND  AR.OrgGroupBatchId=@rOrgGroupBatchId
	    LEFT JOIN sHostel.tRoomMaster RM ON RM.Id= AR.RoomId  
	     LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DA.Amount >= @rFromAmount) OR (@rFromAmount = 0))
		AND ((DA.Amount <= @rToAmount) OR (@rToAmount = 0))
		AND ((DA.AdjustmentDate >= @rFromAdjustmentDate) OR (ISNULL(@rFromAdjustmentDate,'') = ''))
		AND ((DA.AdjustmentDate <= @rToAdjustmentDate) OR (ISNULL(@rToAdjustmentDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DA.HostelId=@rHostelId)
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((vSA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vSA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((vSA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((vSA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((vSA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (vSA.SUId like @rSUId OR ISNULL(@rSUId,'')='')
	    AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND (DA.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
		Order By DA.CreatedDateTime
END
GO
PRINT N'Altering [sHostel].[pRptHostelDepositMinusGet]...';


GO
ALTER PROCEDURE [sHostel].[pRptHostelDepositMinusGet]
          
     @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rRoomId int=0,
	 @rStudentName nvarchar(100)='',
	 @rStudentCode nvarchar(100)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rIsBasedOnSUId bit = 0,
	 @rDepartmentId int=0,
	 @rSUId nvarchar(50)='',
	 @rFromAllocateDate date,
	 @rToAllocateDate Date
           
AS
SET NOCOUNT ON

BEGIN
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		'Student' AS SourceType,
		2003 AS SourceTypeId,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.SUId AS SUId,
		SA.Code as SourceCode,
		SA.Name as StudentName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		SA.RollNo,
--		DA.HostelDepositHeadId,
--		DHM.Title AS DepositHeadName,
		SA.OrgId,
		SA.OrganizationName,
		(D.TotalDeposit - A.TotalAdjustment) AS MinusAmount,
		RM.Title AS Room,
		HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2
		
  FROM 		
		sStudent.vStudentAcademic SA
		LEFT  JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND AR.OrgGroupBatchId=@rOrgGroupBatchId
		LEFT JOIN sHostel.tRoomMaster RM ON  RM.Id=AR.RoomId 
	    LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId 
		LEFT JOIN
		(SELECT SUM(ISNULL(DA.Amount,0)) AS TotalDeposit,DA.StudentId,DA.HostelId FROM sHostel.tHostelDepositAdd DA WHERE DA.HostelId = @rHostelId  AND DA.OrgGroupBatchId=@rOrgGroupBatchId GROUP BY DA.StudentId,DA.HostelId  )D 
		ON D.StudentId=SA.StudentId
		LEFT JOIN 
		(select SUM(ISNULL(AD.Amount,0)) AS TotalAdjustment,AD.StudentId   FROM sHostel.tHostelDepositAdjustment AD WHERE AD.HostelId = @rHostelId   AND AD.OrgGroupBatchId=@rOrgGroupBatchId GROUP BY AD.StudentId) A 
		ON A.StudentId=SA.StudentId
		--INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = D.HostelDepositHeadId
		LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
		
  WHERE  
       
       D.TotalDeposit - A.TotalAdjustment < 0 
		AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((D.HostelId=@rHostelId) OR (@rHostelId=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 (SA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
		
END
GO
PRINT N'Altering [sHostel].[pRptHostelDepositRefundGet]...';


GO
ALTER PROCEDURE [sHostel].[pRptHostelDepositRefundGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int=0,
           @rFromRefundAmount decimal(12,2)=0,
           @rToRefundAmount decimal(12,2)=0,
           @rFromRefundDate date='',
           @rToRefundDate date='',
           @rHostelId int,
           @rCode nvarchar(20)='',
           @rRoomId int=0,
           @rStudentName nvarchar(100)='',
		   @rStudentCode nvarchar(100)='',
		   @rClassId int=0,
		   @rDivisionId int=0,
		   @rIsBasedOnSUId bit = 0,
		   @rDepartmentId int=0,
		   @rSUId nvarchar(50)='',
		   @rOrgGroupBatchId int,
		   @rBuilder1 nvarchar(max)='',
	       @rBuilder2 nvarchar(max)='',
	       @rFromAllocateDate date=null,
	       @rToAllocateDate Date=null
          
AS
SET NOCOUNT ON

BEGIN
SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			DHM.Title AS DepositHeadName,
			DR.HostelDepositHeadId,
			DR.StudentId AS StudentId,
			vSA.AcademicId AS AcademicId,
			DR.RefundDate,
			DR.PayTypeId,
			DR.ChequeNo,
			DR.BankName,
			DR.Remark,
			DR.CreatedDateTime,
			vSA.Code,
			vSA.Name AS StudentName,        
			vSA.ClassName+' - '+vSA.DivisionName AS ClassDivisionName,

			CASE  WHEN ISNULL(DR.RefundAmount,0) <> 0 THEN ISNULL(DR.RefundAmount,0) ELSE
			(SELECT ISNULL(SUM(D.Amount),0) FROM sHostel.tHostelDepositAdd D 
			INNER JOIN sHostel.tHostelDepositRefund DR1 ON DR1.HostelDepositHeadId=D.HostelDepositHeadId AND DR1.StudentId=D.StudentId AND D.StudentId = DR.StudentId AND DR1.OrgGroupBatchId=@rOrgGroupBatchId
			WHERE D.HostelDepositHeadId = DR1.HostelDepositHeadId AND D.StudentId=DR1.StudentId AND D.OrgGroupBatchId=@rOrgGroupBatchId)         
			- (SELECT ISNULL(SUM(DA.Amount),0) AS TotalAmount FROM sHostel.tHostelDepositAdjustment DA 
			INNER JOIN sHostel.tHostelDepositRefund DR2 ON DR2.HostelDepositHeadId=DA.HostelDepositHeadId AND DR2.StudentId=DA.StudentId AND DA.StudentId= DR.StudentId AND DA.OrgGroupBatchId=@rOrgGroupBatchId
			WHERE DA.HostelDepositHeadId = DR2.HostelDepositHeadId AND DA.StudentId=DR2.StudentId  AND  DR2.OrgGroupBatchId=@rOrgGroupBatchId) END AS RefundAmount,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrganizationName,
			HM.ReportOrgTitle,
			HM.SmallAddress1,
			HM.SmallAddress2,
			RM.Id AS RoomId,
			RM.Title AS RoomName,
			CASE WHEN @rIsBasedOnSUId=0 THEN  vSA.Code Else ISNULL(vSA.suid,'') END AS SUId,
			U.Id As UserId,
			U.DisplayTitle AS Username
		
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = vSA.StudentId
		INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = DR.HostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		INNER JOIN sHostel.tHostelMaster HM ON HM.Id=DR.HostelId
		LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=DR.StudentId  AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	    LEFT JOIN sHostel.tRoomMaster RM ON RM.Id= AR.RoomId   
	    LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=DR.CreatedUserId
  WHERE  
		--vSA.BatchId = @rBatchId 
		 (vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DR.HostelDepositHeadId=@rHostelDepositHeadId OR @rHostelDepositHeadId=0)
		AND ((DR.RefundAmount >= @rFromRefundAmount) OR (@rFromRefundAmount = 0))
		AND ((DR.RefundAmount <= @rToRefundAmount) OR (@rToRefundAmount = 0))
		AND ((DR.RefundDate >= @rFromRefundDate) OR (ISNULL(@rFromRefundDate,'') = ''))
		AND ((DR.RefundDate <= @rToRefundDate) OR (ISNULL(@rToRefundDate,'') = ''))
		AND ((vSA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
		AND (DR.HostelId=@rHostelId)
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		AND ((vSA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((vSA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((vSA.Code Like @rStudentCode) OR (ISNULL(@rStudentCode,'')=''))
		AND ((vSA.FirstName like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((vSA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		AND (vSA.SUId like @rSUId OR ISNULL(@rSUId,'')='') 
		AND (vSA.OrgGroupBatchId=@rOrgGroupBatchId)
		AND (DR.OrgGroupBatchId=@rOrgGroupBatchId)
		   AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
		GROUP BY
		DHM.Title,DR.HostelDepositHeadId,DR.StudentId,vSA.AcademicId,DR.RefundAmount,DR.RefundDate,DR.PayTypeId,
		DR.ChequeNo,DR.BankName,DR.Remark,DR.CreatedDateTime,vSA.Code,vSA.Name,vSA.ClassName,vSA.DivisionName,OM.Id,OM.DisplayTitle ,HM.ReportOrgTitle,HM.SmallAddress1,HM.SmallAddress2,RM.Id ,RM.Title,vSA.SUId,U.Id,U.DisplayTitle
		Order By DR.RefundDate
END
GO
PRINT N'Altering [sHostel].[pRptRoomwiseStudentListGet]...';


GO
ALTER PROCEDURE [sHostel].[pRptRoomwiseStudentListGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rHostelId int,
	 @rOrgGroupBatchId int,
	 @rOrgId int,
	 @rRoomId int=0,
	 @rStudentName nvarchar(100)='',
	 @rStudentCode nvarchar(100)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rIsBasedOnSUId bit = 0,
	 @rDepartmentId int=0,
	 @rSUId nvarchar(50)='',
	 @rFromAllocateDate date='',
	 @rToAllocateDate Date=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 


	SELECT
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
       'Student' AS SourceType,
		2003 AS SourceTypeId,
		ISNULL(SA.StudentId,0) as SourceId,
		SA.SUId AS SUId,
		SA.Code as SourceCode,
		SA.Name as SourceName,
		SA.ClassName+'-'+SA.DivisionName as ClassDivisionName,
		SA.ClassId,
		SA.ClassName AS ClassName,
		SA.RollNo,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		RM.Title AS Room,
		SC.ParentContactNo,
		SA.OrgId,
		OM.DisplayTitle AS OrganizatinName,
		SA.DivisionId,
		SA.DivisionOrder,
		@rIsBasedOnSUId AS IsBasedOnSUId,
		HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
	   (SELECT sum(Total) FROM(SELECT Max(StudentsPerRoom) AS Total FROM sHostel.tRoomMaster RM 
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003   AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sStudent.vStudentAcademic SA ON AR.SourceId=SA.StudentId 
		WHERE ((RM.HostelId=@rHostelId) OR (@rHostelId=0)) AND  SA.OrgGroupBatchId = @rOrgGroupBatchId AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		GRoup By RM.Id)A) AS TotalStudentPerRoom
		
	FROM sHostel.tRoomMaster RM 
		LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003   AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sStudent.vStudentAcademic SA ON AR.SourceId=SA.StudentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId AND BM.IsActive = 1
		LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId=SC.StudentId
		LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
		LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
	    LEFT JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
	    INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = SA.BatchId
	    
	WHERE 
       (SA.OrgGroupBatchId = @rOrgGroupBatchId)
		 AND ((SA.OrgId = @rOrgId) OR (@rOrgId=0))
		AND ((RM.HostelId=@rHostelId) OR (@rHostelId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		--AND ((RM.Id=@rRoomId) OR (@rRoomId=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 ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
	    AND BM.IsInContext = 1
	END
GO
PRINT N'Altering [sHostel].[pRptStudentDepositListGet]...';


GO
ALTER PROCEDURE [sHostel].[pRptStudentDepositListGet]
          
		   @rOrgId int,          
           @rHostelDepositHeadId int=0,
           @rFromAmount decimal(12,2)=0,
           @rToAmount decimal(12,2)=0,
           @rFromDepositDate date='',
           @rToDepositDate date='',
          -- @rBatchId int,
           @rCode nvarchar(20)='',
           @rHostelId int,
           @rRoomId int=0,
           @rStudentName nvarchar(100)='',
		  @rStudentCode nvarchar(100)='',
		  @rClassId int=0,
		  @rDivisionId int=0,
		  @rIsBasedOnSUId bit = 0,
		  @rDepartmentId int=0,
		  @rSUId nvarchar(50)='',
		  @rOrgGroupBatchId int=0,
		  @rBuilder1 nvarchar(max)='',
	      @rBuilder2 nvarchar(max)='',
	      --@rFromDate date='',
	     -- @rTodate date='',
	      @rFromAllocateDate date,
	       @rToAllocateDate Date
           
AS
SET NOCOUNT ON
 
BEGIN
SELECT 
        @rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rHostelDepositHeadId AS HostelDepositHeadId,
		--DHM.Title AS DepositHeadName,
		(SELECT [sHostel].[fDepositHeadNameGet](@rHostelId,@rHostelDepositHeadId)) 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,
        HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2,
		RM.Id AS RoomId,
		RM.Title AS RoomName,
		CASE WHEN @rIsBasedOnSUId=0 THEN SA.Code Else ISNULL(SA.suid,'') END AS SUId
		
  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.StudentId,ISNull(DA.HostelDepositHeadId,0) AS HostelDepositHeadId FROM sHostel.tHostelDepositAdd DA WHERE DA.HostelId = @rHostelId AND  (DA.OrgGroupBatchId=@rOrgGroupBatchId)  AND DA.HostelDepositHeadId=@rHostelDepositHeadId GROUP  BY DA.StudentId,DA.HostelId,HostelDepositHeadId)D 
		ON D.StudentId=SA.StudentId
		LEFT JOIN 
		(SELECT SUM(ISNULL(AD.Amount,0)) AS TotalAdjustment,AD.StudentId,ISNULL(AD.HostelDepositHeadId,0) AS HostelDepositHeadId FROM sHostel.tHostelDepositAdjustment AD WHERE AD.HostelId = @rHostelId AND (AD.OrgGroupBatchId=@rOrgGroupBatchId) AND AD.HostelDepositHeadId=@rHostelDepositHeadId GROUP BY AD.StudentId,HostelDepositHeadId)A 
		ON A.StudentId=SA.StudentId
		LEFT JOIN 
		(SELECT SUM(ISNULL(DR.RefundAmount,0)) AS TotalRefund,DR.StudentId,ISNULL(DR.HostelDepositHeadId,0) AS HostelDepositHeadId FROM sHostel.tHostelDepositRefund DR WHERE DR.HostelId = @rHostelId AND (DR.OrgGroupBatchId=@rOrgGroupBatchId) AND  DR.HostelDepositHeadId=@rHostelDepositHeadId GROUP BY DR.StudentId,HostelDepositHeadId)R
		ON R.StudentId=SA.StudentId
    	INNER JOIN sHostel.tHostelDepositHeadMaster DHM ON DHM.Id = @rHostelDepositHeadId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		INNER JOIN sHostel.tHostelAdmission HAM ON HAM.SourceId=AR.SourceId AND HAM.SourceTypeId=2003 AND  HAM.OrgGroupBatchId = @rOrgGroupBatchId
		INNER JOIN sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = SA.BatchId
  WHERE  
		(SA.OrgId=@rOrgId OR @rOrgId=0)
		AND ((SA.Code=@rCode) OR (ISNULL(@rCode,'')=''))
	    AND (HM.Id=@rHostelId)
	    AND (DHM.Id=@rHostelDepositHeadId)
		AND ((RM.Id=@rRoomId) OR (@rRoomId=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 (SA.OrgGroupBatchId=@rOrgGroupBatchId)
	    AND ((HAM.AllocateDate >= @rFromAllocateDate ) OR (ISNULL(@rFromAllocateDate,'') = ''))
	    AND ((HAM.AllocateDate <= @rToAllocateDate ) OR (Isnull(@rToAllocateDate,'') = ''))
		AND BM.IsInContext = 1
		--AND ((D.DepositDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
		--AND ((D.DepositDate <= @rTodate) OR (ISNULL(@rTodate,'') = ''))
		
END
GO
PRINT N'Altering [sHostel].[pRptStudentLedgerGet]...';


GO
ALTER PROCEDURE [sHostel].[pRptStudentLedgerGet]
	 
	
	 @rHostelId int,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rHostelDepositHeadId int,
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
     @rOrgGroupBatchId int=0
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 
Declare @lbal decimal
SET @lbal=0;
 select
        A.DepositDate,
        A.Credit,
        A.Debit,
CASE WHEN @rIsBasedOnSUId=0 THEN  A.Code Else ISNULL(A.suid,'') END AS Code,
        A.StudentName,
        RM.Title AS Room,
        A.Class ,
        A.Credit - A.Debit AS Bal
  FROM
 (
			SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		   VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		   -- @lbal+ISnull (DA.Amount,0)-0 As balance 
		   ISnull(DA.Amount,0)-0 As balance 
		    
			FROM sStudent.vStudentLastAcademic  VA
			INNER JOIN sHostel.tHostelDepositAdd DA  ON VA.StudentId = DA.StudentId 
			Where 
		  ((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DA.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.HostelDepositHeadId = @rHostelDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			UNION ALL 
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		    -- @lbal+0-ISnull (DAJ.Amount,0) As balance 
		     0-ISnull(DAJ.Amount,0) As balance 
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositAdjustment DAJ ON DAJ.StudentId = VA.StudentId 
		     
			Where 
				((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DAJ.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND DAJ.OrgGroupBatchId=@rOrgGroupBatchId
			AND VA.OrgGroupBatchId=@rOrgGroupBatchId
			UNION ALL 
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		    -- @lbal+0-ISnull (DR.RefundAmount,0) As balance 
		    0-ISnull(DR.RefundAmount,0) As balance
			FROM sStudent.vStudentLastAcademic  VA
			  INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = VA.StudentId
		     
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DR.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND DR.OrgGroupBatchId=@rOrgGroupBatchId
			AND VA.OrgGroupBatchId=@rOrgGroupBatchId
			) A
			LEFT JOIN sHostel.tAssignRoom  AR ON AR.SourceId=A.StudentId AND  AR.SourceTypeId = 2003 AND AR.OrgGroupBatchId=@rOrgGroupBatchId
		
			LEFT JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
			--Group By A.DepositDate,A.Credit,A.Debit,A.Code,A.SUId,A.StudentName,Rm.title,A.Class,  A.Balance
			order by  A.DepositDate 
END
GO
PRINT N'Altering [sHostel].[pRptVacantStudentList]...';


GO
ALTER PROCEDURE [sHostel].[pRptVacantStudentList]
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='', 
		@rHostelId int =0,
		@rOrgId int = 0,
		@rSourceTypeId smallint=0,
		@rCode nvarchar(20)=NULL,
		--@rFromAllocateDate date = '',
		--@rToAllocateDate date ='',
		@rToVacantDate date='',
		@rFromVacantDate date='',
		@rSUID nvarchar(50) = null,
		@rOrgGroupBatchId int = 0,
		@rRoomId int=0,
		@rStudentName nvarchar(100)='',
		@rStudentCode nvarchar(100)='',
		@rClassId int=0,
		@rDivisionId int=0,
		@rIsBasedOnSUId bit = 0,
		@rDepartmentId int=0

 WITH EXECUTE AS CALLER                  
AS
SET NOCOUNT ON
declare @lsumtotal As int=0

BEGIN

	SELECT   
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		OM.DisplayTitle AS OrganizationName,
        (CASE WHEN HA.SourceTypeId = 95 THEN	'Employee'
			 WHEN HA.SourceTypeId = 2003 THEN	'Student' END) AS SourceType,

		(CASE WHEN HA.SourceTypeId = 95 THEN	Emp.Code
			 WHEN HA.SourceTypeId = 2003 THEN	SM.Code END) AS SourceCode, 	
		
		(CASE WHEN HA.SourceTypeId = 95 THEN	''
			 WHEN HA.SourceTypeId = 2003 THEN	SM.SUId END) AS SUId, 	

		(CASE WHEN HA.SourceTypeId = 95 THEN Emp.EmployeeName
			WHEN HA.SourceTypeId = 2003 THEN SM.LastName + ' ' + SM.FirstName  END) AS SourceName,
			
		(CASE WHEN HA.SourceTypeId = 95 THEN Emp.DepartmentName
			WHEN HA.SourceTypeId = 2003 THEN (sStudent.fStudentCurrentDivisionGet(SM.StudentId)) END) AS ClassDepartmentName,		
		 
		 HA.SourceTypeId,
		 HA.SourceId,
		 HA.AllocateDate,
		(CASE WHEN HA.VacantDate = '1900-01-01' THEN ''
			ELSE HA.VacantDate END) AS VacantDate,	
		 ISNULL(HA.VacantReason,'') AS VacantReason,
		SM.ClassName+'-'+SM.DivisionName as ClassDivisionName,
		SM.ClassId,
		SM.ClassName AS ClassName,
		SM.RollNo,
		RM.StudentsPerRoom,
		HTM.Title as HostelType,
		HM.Title AS HostelName,
		ISNULL(RM.Title,'') AS Room,
		SC.ParentContactNo,
		SM.OrgId,
		OM.DisplayTitle AS OrganizatinName,
		SM.DivisionId,
		SM.DivisionOrder,
		@rIsBasedOnSUId AS IsBasedOnSUId,
		HM.ReportOrgTitle,
		HM.SmallAddress1,
		HM.SmallAddress2


	FROM 
		sHostel.tHostelAdmission HA
		LEFT JOIN sHrm.vExtEmployeeMaster Emp
		ON Emp.Id = HA.SourceId AND HA.SourceTypeId = 95 
		LEFT JOIN sStudent.vStudentAcademic SM
		ON SM.StudentId = HA.SourceId AND HA.SourceTypeId = 2003 AND SM.OrgGroupBatchId=@rOrgGroupBatchId 	
		LEFT JOIN sSetup.tOrganizationMaster OM ON (OM.Id = SM.OrgId) OR (OM.Id = Emp.OrgId)  
		LEFT JOIN sHostel.tRoomMaster RM ON RM.Id = HA.RoomId 
		--LEFT JOIN sHostel.tAssignRoom AR ON RM.Id=AR.RoomId AND AR.SourceTypeId=2003   AND  AR.OrgGroupBatchId = @rOrgGroupBatchId
		--INNER JOIN sStudent.vStudentAcademic SA ON AR.SourceId=SA.StudentId
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		--LEFT JOIN sSetup.tBatchMaster BM ON BM.Id=SA.BatchId AND BM.IsActive = 1
		LEFT JOIN sStudent.tStudentCommunication SC ON SM.StudentId=SC.StudentId
		LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
		LEFT JOIN sHostel.tHostelTypeMaster HTM ON HTM.Id=HM.HostelTypeId
	WHERE 
		(HA.Hosteld=@rHostelId)
		AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
		AND ((RM.Id=@rRoomId) OR (@rRoomId=0))
		--AND ((HA.SourceTypeId=@rSourceTypeId) OR (@rSourceTypeId=0))
		--AND ((@rSourceTypeId =2003 OR(@rSourceTypeId=0)) AND SM.Code LIKE @rCode) OR (ISNULL(@rCode,'')='') 
		--OR ((@rSourceTypeId =95 OR(@rSourceTypeId=0)) AND Emp.Code LIKE @rCode) OR (ISNULL(@rCode,'')='')
		AND ((SM.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SM.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
		AND ((SM.Code Like @rStudentCode + '%') OR (ISNULL(@rStudentCode,'')=''))
		AND ((SM.FirstName like  @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
		AND ((SM.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0))
		--AND ((HA.AllocateDate >= @rFromAllocateDate) OR (ISNULL(@rFromAllocateDate,'') = ''))
		--AND ((HA.AllocateDate <= @rToAllocateDate) OR (ISNULL(@rToAllocateDate,'') = ''))
		AND ((HA.VacantDate >= @rFromVacantDate) OR (ISNULL(@rFromVacantDate,'') = ''))
		AND ((HA.VacantDate <= @rToVacantDate) OR (ISNULL(@rToVacantDate,'') = ''))
		AND ((SM.SUId=@rSUID) OR (ISNULL(@rSUID,'') = ''))
		AND HA.OrgGroupBatchId=@rOrgGroupBatchId
		AND HA.VacantDate IS NOT NULL
		--ORDER BY HA.AllocateDate desc
		--GROUP BY HA.RoomId,OM.DisplayTitle,HM.SmallAddress1,HM.SmallAddress2,HM.ReportOrgTitle,SC.ParentContactNo,SM.OrgId,SM.DivisionOrder,SM.DivisionId,HA.SourceTypeId,HM.Title,RM.title,Emp.Code,HTM.Title,SM.Code,SM.SUId,Emp.EmployeeName,SM.FirstName,SM.LastName,Emp.DepartmentName,SM.StudentId,HA.SourceId,HA.AllocateDate,HA.VacantDate,HA.VacantReason,SM.ClassName,SM.DivisionName,SM.ClassId,SM.RollNo,RM.StudentsPerRoom
END
GO
PRINT N'Altering [sHostel].[pStudentDetailListGet]...';


GO
ALTER PROCEDURE [sHostel].[pStudentDetailListGet]
	 
	 @rHostelId int,
	 @rSUId nvarchar(50),
	 @rCode nvarchar(20),
	 @rOrgId int,
	 @rOrgGroupBatchId int
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	SELECT 
			--O.DisplayTitle AS Organization,
			--O.Id AS OrgId,
			RM.Title AS Room,
			SD.Code AS StudentCode,
			SD.Name AS StudentName,
			ISNULL(RAM.AssetNumber,'') AS AssetNumber,
			ISNULL(AM.Title,'') AS AssetType,
			ISNULL(RC.Title,'') As RoomCategory,
			ARA.RoomAssetId ,
			SD.StudentId  AS SourceId,
			AR.SourceTypeId AS SourceTypeId,
			AR.RoomId,
			ISNULL(SC.PresentStreetone,'') + ' ' + ISNULL(SC.PresentStreetTwo,'') + ' ' + ISNULL(SC.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SC.ParentContactNo,'') AS StudentContactNo,
			SD.ClassName + ' ' + SD.DivisionName AS Class,
			Isnull(SD.SUID,'') AS SUID,
			Ar.OrgGroupBatchId
			
			
			
	FROM sStudent.vStudentAcademic SD   
			INNER JOIN sHostel.tAssignRoom AR ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003   AND AR.OrgGroupBatchId=@rOrgGroupBatchId
			LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
			INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id 
			INNER JOIN sHostel.tRoomCategoryMaster RC ON RC.ID=RM.RoomCategoryId
			INNER JOIN sHostel.tHostelMaster HM ON HM.Id = RM.HostelId
			--INNER JOIN sSetup.tOrganizationMaster O ON O.Id = SD.OrgId
	        LEFT JOIN sHostel.tAssignRoomAsset  ARA ON ARA.SourceId=AR.SourceId AND  ARA.SourceTypeId=2003 AND ARA.OrgGroupBatchId=@rOrgGroupBatchId
	        LEFT JOIN sHostel.tRoomAssetMaster RAM ON RAM.Id=ARA.RoomAssetId AND ARA.SourceId=SD.StudentId  
            LEFT JOIN sHostel.tAssetTypeMaster  AM ON RAM.AssetTypeId=AM.Id
	WHERE 
	    HM.Id = @rHostelId
	    AND ((SD.SUID=@rSUId)OR (ISNULL(@rSUId,'')=''))
	    AND ((SD.Code=@rCode)OR (ISNULL(@rCode,'')=''))
	    AND ((SD.OrgId=@rOrgId)OR (ISNULL(@rOrgId,'')=''))
	    AND SD.OrgGroupBatchId=@rOrgGroupBatchId
	    AND AR.OrgGroupBatchId=@rOrgGroupBatchId
	    --AND ((RM.Id = @rRoomId) OR (ISNULL(@rRoomId,0) = 0))
END
GO
PRINT N'Altering [sHostel].[pStudentLedgerGet]...';


GO
ALTER PROCEDURE [sHostel].[pStudentLedgerGet]
	 
	
	 @rHostelId int,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rHostelDepositHeadId int,
	 @rOrgId int,
	 @rOrgGroupBatchId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 
 SELECT A.Date,
        A.Credit,
        A.Debit
          FROM(
			SELECT 
			DA.DepositDate AS Date,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sHostel.tHostelDepositAdd DA  ON VA.StudentId = DA.StudentId 
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DA.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DA.OrgGroupBatchId = @rOrgGroupBatchId
			UNION ALL 
			SELECT 
			DAJ.AdjustmentDate As Date,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositAdjustment DAJ ON DAJ.StudentId = VA.StudentId
		     
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DAJ.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DAJ.OrgGroupBatchId = @rOrgGroupBatchId
			UNION ALL 
			SELECT 
			DR.RefundDate As Date,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = VA.StudentId
		     
			Where 
			((VA.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DR.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
		   AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		   AND DR.OrgGroupBatchId = @rOrgGroupBatchId
			)A 
			Order BY A.Date
END
GO
PRINT N'Altering [sHostel].[pStudentLedgerGet_NEW]...';


GO
ALTER PROC [sHostel].[pStudentLedgerGet_NEW]

	 @rHostelId int,
	 @rCode  nvarchar(20)='',
	 @rSUId nvarchar(50)='',
	 @rHostelDepositHeadId int,
	 @rOrgId int,
     @rIsBasedOnSUId bit = 0,
      @rOrgGroupBatchId int
AS
BEGIN

--WITH Tb0 as
--( 
			SELECT A.*, RM.Title AS Room,
         HM.Title As HostelName,
         HM.SmallAddress1 AS SmallAddress1,
         HM.SmallAddress2 AS SmallAddress2,
       HM.ReportOrgTitle AS ReportOrgTitle from (SELECT 
			DA.DepositDate AS DepositDate,
			ISnull (DA.Amount,0) AS Credit,
		    0 AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') As  SUId,
		     DA.CreatedDateTime
		    
			FROM sStudent.vStudentAcademic  VA
			INNER JOIN sHostel.tHostelDepositAdd DA  ON VA.StudentId = DA.StudentId 
			Where 
		  ((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DA.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DA.HostelDepositHeadId = @rHostelDepositHeadId)
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0)) 
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DA.OrgGroupBatchId = @rOrgGroupBatchId
			
	UNION
			SELECT 
			DAJ.AdjustmentDate As DepositDate,
			0  AS Credit,
			ISnull (DAJ.Amount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName, 
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		     ISNUll(VA.SUId,'') As  SUId,
		     DAJ.CreatedDateTime
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositAdjustment DAJ ON DAJ.StudentId = VA.StudentId
		     
			Where 
				((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DAJ.HostelId = @rHostelId
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DAJ.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DAJ.OrgGroupBatchId = @rOrgGroupBatchId
	 UNION
			SELECT 
			DR.RefundDate As DepositDate,
			0  AS Credit,
			ISnull (DR.RefundAmount,0)  AS Debit,
		    VA.Code As Code,
		    VA.Name As StudentName,
		    VA.StudentId AS StudentId,
		    VA.ClassName + ' ' + VA.DivisionName AS Class,
		    ISNUll(VA.SUId,'') AS  SUId,
		     DR.CreatedDateTime
			FROM sStudent.vStudentAcademic  VA
			  INNER JOIN sHostel.tHostelDepositRefund DR ON DR.StudentId = VA.StudentId
			Where 
			((VA.Code like @rCode) OR (ISNULL(@rCode,'') = ''))
			AND DR.HostelId = @rHostelId 
			AND ((VA.SUId like @rSUId) OR (ISNULL(@rSUId,'')=''))
			AND (DR.HostelDepositHeadId = @rHostelDepositHeadId) 
			AND ((VA.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			AND VA.OrgGroupBatchId = @rOrgGroupBatchId
		    AND DR.OrgGroupBatchId = @rOrgGroupBatchId
		    )  A
		   INNER JOIN sHostel.tAssignRoom  AR ON AR.SourceId=A.StudentId AND  AR.SourceTypeId = 2003 AND AR.OrgGroupBatchId = @rOrgGroupBatchId
           INNER JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id
           INNER JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
           ORDER BY CreatedDateTime
--)
--,Tb1 as
--( 
--	SELECT DepositDate,Credit,Debit,Row_Number() over (order by  CreatedDateTime asc) as [OrderId],StudentId,Code,SUId,StudentName,Class FROM Tb0
--)
 
--  SELECT T1.[DepositDate],
--         T1.[Credit],
--         T1.[Debit],(Sum(T2.Credit) - Sum(T2.Debit)) as Balance,
--         CASE WHEN @rIsBasedOnSUId=0 THEN  T1.Code Else ISNULL(T1.SUId,'') END AS Code,
--         T1.StudentName,
--         RM.Title AS Room,
--         T1.Class,
--         HM.Title As HostelName,
--         HM.SmallAddress1 AS SmallAddress1,
--         HM.SmallAddress2 AS SmallAddress2,
--         HM.ReportOrgTitle AS ReportOrgTitle
-- FROM Tb1 as T1
--INNER JOIN Tb1 as T2 ON T1.[OrderId] >= T2.[OrderId] 
--LEFT JOIN sHostel.tAssignRoom  AR ON AR.SourceId=T1.StudentId AND  AR.SourceTypeId = 2003
--LEFT JOIN sHostel.tRoomMaster RM ON AR.RoomId = RM.Id
--LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId
--Group By T1.[DepositDate],T1.[Credit],T1.[Debit],T1.StudentId,T1.SUId,T1.Code,T1.StudentName,T1.Class,RM.Title,HM.Title,HM.SmallAddress1,HM.SmallAddress2,
--HM.ReportOrgTitle
-- Order by T1.[DepositDate]
END
GO
PRINT N'Altering [sHostel].[pUserControlFeePaidStudentSearchGet]...';


GO
ALTER PROCEDURE [sHostel].[pUserControlFeePaidStudentSearchGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rSUId nvarchar(50)=''
	--@rHostelId int=0
	--@rIsStudentHostelFeePaid int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
 IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			DISTINCT
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.BatchId,
			SA.SUId
  FROM 
          sStudent.vStudentAcademic SA 
          INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
		  INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
		  INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId 
		  INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId AND FHM.Number = 1002
       
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
		AND ( SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			DISTINCT
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId 
  FROM 
          sStudent.vStudentAcademic SA 
          INNER JOIN sFee.tFeeAllocation FA ON FA.SourceId = SA.AcademicId
		  INNER JOIN sFee.tFeeSetup FS ON FS.Id = FA.FeeSetupId
		  INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId 
		  INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId AND FHM.Number = 1002
              
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
		
END
GO
PRINT N'Altering [sHostel].[pUserControlStudentSearchGet]...';


GO
ALTER PROCEDURE [sHostel].[pUserControlStudentSearchGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rSUId nvarchar(50)='',
	@rHostelId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 

DECLARE @lInContextBatch int
SELECT @lInContextBatch = Id From sSetup.tBatchMaster BM Where BM.OrgGroupBatchId = @rOrgGroupBatchId AND IsInContext = 1


		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END

		IF(@rRollNo=0) 
		SET @rRollNo=NULL

 IF(@rRollNo IS NULL)
	BEGIN

	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.BatchId,
			SA.SUId,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo
  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 sSetup.tBatchMaster BM ON BM.OrgGroupBatchId = AR.OrgGroupBatchId AND BM.Id = SA.BatchId
		  INNER JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
		AND ( SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
		AND  RM.HostelId=@rHostelId
	  AND ( AR.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)
	  AND BM.IsInContext = 1

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId 
  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           
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
		AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND(SA.BatchId=@rBatchId)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 	
		AND  RM.HostelId=@rHostelId
		  AND ( AR.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
		
END
GO
PRINT N'Altering [sHrm].[pEmployeeAllDetailGet]...';


GO
ALTER PROCEDURE [sHrm].[pEmployeeAllDetailGet]
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int,
    @rSUId nvarchar(50)='',
    @rUserId bigint=0,
    @rMultiCode nvarchar(max)=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
			ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
			ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			ISNULL(SI.QRCode, CONVERT(VARBINARY(MAX),0)) AS QRCode
			
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
			ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
			ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			ISNULL(SI.QRCode, CONVERT(VARBINARY(MAX),0)) AS QRCode
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)	
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
  
	
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 = '',
	@rNumber int,
	@rProbationUptoDate Date = '',
	@rAhdocUptoDate Date = '',
	@rPermanentDate Date = '',
	@rCustomTagId nvarchar(max) = '',
	@rDateOfResignation Date = '',
	@rIsOtherUser int=0,
	@rOrgGroupId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY	
	 BEGIN TRANSACTION	
	
	--if @rColumnName <> ''
	--begin
	--	select @rColumnName = left(@rColumnName,len(@rColumnName)-1)
	--end
	
	IF(@rDOBFromDate IS NULL)
		SET @rDOBFromDate=''
	IF(@rDOJFromDate IS NULL)
		SET @rDOJFromDate=''
	IF(@rLeftFromDate IS NULL)
		SET @rLeftFromDate=''
	IF(@rDOBToDate IS NULL)
		SET @rDOBToDate=''
	IF(@rDOJToDate IS NULL)
		SET @rDOJToDate=''
	IF(@rLeftToDate ='9999-12-31 00:00:00')
		SET @rLeftToDate=''

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

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

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

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

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

				exec(@Sql)
		
				DROP Table sHrm.tTempEmployee2
				DROP Table sHrm.tTempEmployee
		END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sHrm].[pGetDropDowns]...';


GO

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

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

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

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


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

	        
		select @lAvailableEmployeeCustomRes = @lAvailableEmployeeCustomRes +'<option class=EmployeeCustom value="|' + Title + '||">|' + Title + '||</option>'
		from @lEmployeeCustomFields

		
	
	select @lStatusRes as StatusRes,@lColumnRes as AvailableRes,@lReportList as ReportList,
	@lOrganizationRes as OrganizationRes,@lPayRollYear as PayRollYear,@lPayrollColumn as PayrollColumn,
	@lPayrollReportList as PayrollReportList, @lSavedReport AS SavedReportList,@lCustomtagdrop AS customtaghklist,@lAvailableEmployeeCustomRes as AvailableEmployeeCustomRes
	
end
GO
PRINT N'Altering [sHrm].[pRptEmployeeProfileGet]...';


GO
ALTER PROCEDURE [sHrm].[pRptEmployeeProfileGet]
(

		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rPayrollId int,
		@rPayrollGroupId int,
		@rPayrollYearId int,
    	@rEmployeeId bigint,
		@rEmployeeCode nvarchar(200),
		@rEmployeeName nvarchar(200),
	    @rOrderByField nvarchar(20)='',
		@rOrgId int = 0,
		@rDepartmentId int = 0,
		@rStatusId int = 0,
	 @rEmployeeGroupId int = 0
)
AS
SET NOCOUNT ON

BEGIN

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

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

		SELECT 
				@rOrderByField AS OrderByField,
				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				EM.EmployeeId AS EmployeeId,
				tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS Name,
				DM.Id AS DepartmentId,
				DM.Title AS DepartmentName,
				CONVERT(date,EJD.DateOfJoining) AS DateOfJoining,
				EM.Code AS Code,
				CONVERT(date,EJD.DateOfleaving) AS DateOfleaving,
				EDM.Title AS Designation,
				EPD.Qualification,
				EM.GenderTitle,
				CONVERT(date,EPD.DateOfBirth) AS DateOfBirth,
				EPD.UIDNumber,
				EC.PersonalEmail AS Email,
				ESO.BankName,
				ESO.AccountNumber,
				ESO.EPFNumber,
				ESO.PanNumber,
				EC.MobileNumber,
				ISNULL(DATEDIFF(YY,EJD.DateOfJoining,EJD.DateOfleaving),'')AS EXPYEAR,
				ISNULL(DATEDIFF(MM,EJD.DateOfJoining,EJD.DateOfleaving),'') AS EXPMONTH,
				EM.FirstName,
				EM.LastName,
				tEM.Number,
				--@lIsOnPrePrinted AS IsOnPrePrinted,
				--@lIsDisplayImageHeader AS IsDisplayImageHeader,
				--ISNULL(OI.PayrollHeaderA4,0x) AS PayrollHeader
				(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
				--ISNULL(PM.PayrollHeader,0x) AS PayrollHeader,
				ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId ,
				ISNULL(ESO.BasicPay,0)AS BasicPay,
				EM.EmployeeGroupId,
				EGM.Title AS EmployeeGroupTitle
				--,PP.SalaryMonth
		FROM 
			sPayroll.tPayProcess PP
			INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
			INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
			INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
			INNER JOIN  sHrm.tEmployeeCommunications EC ON EC.EmployeeId=EM.EmployeeId
			INNER JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EM.EmployeeId
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=EJD.OrganizationDepartmentId
			INNER JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
			INNER JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
			--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
			INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
			INNER JOIN sHrm.tEmployeeGroupMaster EGM ON EGM.Id = EM.EmployeeGroupId
		WHERE 
				(EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
			AND((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
			 AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
			 AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
			 AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
			 AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
			 AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
			 AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
			 AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
			 AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
		END
GO
PRINT N'Altering [sLibrary].[pBookMasterAdd]...';


GO
ALTER PROCEDURE [sLibrary].[pBookMasterAdd]
	 
	
	@rId bigint,
	@rCode nvarchar(25),
	@rTitle nvarchar(100),
	@rPublisher nvarchar(200),
	@rSupplier nvarchar(200),
	@rAuthor nvarchar(200),
	@rSubject nvarchar(200),
	@rLanguage nvarchar(200),
	@rLocation nvarchar(200),
	@rEdition nvarchar(50),
	@rISBNNumber nvarchar(100),
	@rPrice decimal(12,2),
	@rCurrency nvarchar(100),
	@rBookTag nvarchar(200),
	@rBookCustomTag nvarchar(200),
	@rBookAgeGroupId int,
	@rResourceTypeId int,
	@rOrgGroupId int,
	@rBatchId int,
	@rLibraryId int,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rBookDepartment nvarchar(150),
	@rClassNumber nvarchar(50),
	@rBookVolume smallint,
	@rNoOfCopies smallint,
	@rClassificationNo nvarchar(50),
	@rAccessionNo nvarchar(50),
	@rNoOfPages int,
	@rPurchaseDate date,
	@rBookRemark  nvarchar(300),
	@rBillNumber nvarchar(100),
	@rYearOfPublication nvarchar(50),
	@rBookEntryDate date,
	@rBookImage varbinary(max)=null,
	@rBookGroup1Id int=0,
	@rBookGroup2Id int=0,
	@rOrderIndex int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	IF(@rId = 0)
    BEGIN
		IF Exists(Select @rCode from sLibrary.tBookMaster where Code=@rCode AND LibraryId = @rLibraryId AND Id!=@rId)
		BEGIN
			Select -103 AS Result
			RETURN
		END
		
		IF Exists(Select 1 from sLibrary.tBookMaster where AccessionNo=@rAccessionNo AND LibraryId = @rLibraryId AND Id <> @rId)
		BEGIN
			Select -107 AS Result
			RETURN
		END
	END
	ELSE
		BEGIN
		IF Exists(Select 1 from sLibrary.tBookMaster where AccessionNo=@rAccessionNo AND LibraryId = @rLibraryId AND Id!=@rId)
		BEGIN
			Select -107 AS Result
			RETURN
		END
	 
 		IF Exists(Select @rCode from sLibrary.tBookMaster where Code=@rCode AND LibraryId = @rLibraryId  AND Id!=@rId)
		BEGIN
			Select -103 AS Result
			RETURN
		END
	END

	BEGIN TRY
	BEGIN TRANSACTION	
		
    IF(@rId = 0)
    BEGIN
    
    DECLARE @lNextNumber BIGINT   
    
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sLibrary.tBookMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sLibrary.tBookMaster
		(
			Id,
			Code,
			Title,
			Publisher,
			Supplier,
			Author,
			BookSubject,
			BookLanguage,
			Location,
			Edition,
			ISBNNumber,
			Price,
			Currency,
			BookTag,
			BookCustomTag,
			BookAgeGroupId,
			ResourceTypeId,
			CreatedUserId,
			CreatedDateTime,
			LibraryId,
			BookDepartment,
			ClassNumber,
			BookVolume,
			NoOfCopies,
			ClassificationNo ,
			AccessionNo,
			NoOfPages,
			PurchaseDate,
			BookRemark,
			BillNumber,
			YearOfPublication,
			BookEntryDate,
			BookImage,
			BookGroup1Id,
			BookGroup2Id,
			OrderIndex
			
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rTitle,
		    @rPublisher,
		    @rSupplier,
			@rAuthor,
			@rSubject,
			@rLanguage,
			@rLocation,
			@rEdition,
			@rISBNNumber,
			@rPrice,
			@rCurrency,
			@rBookTag,
			@rBookCustomTag,
			@rBookAgeGroupId,
			@rResourceTypeId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rLibraryId,
			@rBookDepartment,
			@rClassNumber,
			@rBookVolume,
			@rNoOfCopies,
			@rClassificationNo ,
			@rAccessionNo,
			@rNoOfPages,
			@rPurchaseDate,
			@rBookRemark,
			@rBillNumber,
			@rYearOfPublication,
			@rBookEntryDate,
			@rBookImage,
			@rBookGroup1Id,
			@rBookGroup2Id,
			@rOrderIndex
		)
		
	  EXECUTE sLibrary.pBookLogAdd NULL,NULL,2009,@lNextNumber,null,null,521,NULL,1,@rOrgGroupId,@rBatchId,@rCreatedUserId,@rLibraryId,NULL
	  
	  SELECT @lNextNumber AS Result
	END
	ELSE
	BEGIN
	    SET @lNextNumber = @rId
	    UPDATE  sLibrary.tBookMaster
	    SET
			Code=@rCode,
			Title=@rTitle,
			Publisher=@rPublisher,
			Supplier=@rSupplier,
			Author=@rAuthor,
			BookSubject=@rSubject,
			BookLanguage=@rLanguage,
			Location=@rLocation,
			Edition=@rEdition,
			ISBNNumber=@rISBNNumber,
			Price=@rPrice,
			Currency=@rCurrency,
			BookTag=@rBookTag,
			BookCustomTag=@rBookCustomTag,
			BookAgeGroupId=@rBookAgeGroupId,
			ResourceTypeId=@rResourceTypeId,						
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			BookDepartment=@rBookDepartment,
			ClassNumber=@rClassNumber,
			BookVolume=@rBookVolume,
			NoOfCopies=@rNoOfCopies,
			ClassificationNo=@rClassificationNo ,
			AccessionNo=@rAccessionNo,
			NoOfPages=@rNoOfPages,
			PurchaseDate=@rPurchaseDate,
			BookRemark=@rBookRemark,
			BillNumber=@rBillNumber,
			YearOfPublication=@rYearOfPublication,
			BookEntryDate=@rBookEntryDate,
			BookImage=@rBookImage,
			BookGroup1Id=@rBookGroup1Id,
			BookGroup2Id=@rBookGroup2Id,
			OrderIndex=@rOrderIndex
	      WHERE Id = @rId 
	      SELECT @lNextNumber AS Result
    END	
		
COMMIT TRANSACTION
END TRY
	BEGIN CATCH
	    ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH  
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),
	 @rOrderIndex int=0
	
	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 nvarchar(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),
	@lOrderIndex int
	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,''),
	@lOrderIndex=ISNULL(@rOrderIndex,0)

	 
	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,
	ISNULL(BM.OrderIndex,0) AS OrderIndex
 
	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 N''' + @lTitle + ''') OR (''' + @lTitle + ''' = '''')) 
	AND ((BM.AccessionNo like ''' + @lAccession + ''') OR (''' + @lAccession + ''' = '''')) 
	AND ((BM.Publisher like N''' + @lPublisher + ''') OR (''' + @lPublisher + ''' = '''')) 
	AND ((BM.Supplier like ''' + @lSupplier + ''') OR (''' + @lSupplier + ''' = '''')) 
	AND ((BM.Author like N''' + @lAuthor + ''') OR (''' + @lAuthor + ''' = '''')) 
	AND ((BM.BookSubject like N''' + @lSubject + ''') OR (''' + @lSubject + ''' = ''''))  
	AND ((BM.BookLanguage like N''' + @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) +')
	ORDER BY BM.OrderIndex ASC'
	--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].[pBulkBookLogListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pBulkBookLogListGet]
	 
	 @rReaderSourceTypeId smallint,
	 @rReaderCode nvarchar(20),
	 @rReaderName nvarchar(200),
	 @rResourceCode nvarchar(25),
	 @rResourceName nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rStatusId int,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rLibraryId int,
	 @rIsCurrentStatus bit,
	 @rOrgGroupBatchId int = 0,
	 @rSUId nvarchar(50)='',
	 @rDepartmentId int = 0,
	 @rClassId int = 0,
	 @rDivisionId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		SET @rReaderCode = sCommon.fSearchStringGet(@rReaderCode)
		SET @rReaderName = sCommon.fSearchStringGet(@rReaderName)
		SET @rResourceCode = sCommon.fSearchStringGet(@rResourceCode)
		SET @rResourceName = sCommon.fSearchStringGet(@rResourceName)
		
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Student' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			SA.Code AS ReaderCode,
			SA.Name AS ReaderName,
			SA.ClassName+'-'+SA.DivisionName AS ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId = 521 AND ISNULL(BL.UpdatedUserId,0)!=1 Then 'Return' WHEN BL.StatusId = 521 AND ISNULL(BL.UpdatedUserId,0)=1 Then 'Release' ELSE SM.Title END AS TransactionStatus,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2,
	        ISnull(SA.SUId,'') AS SUId,
	        BMM.Title AS BatchName,
	        OM.Title AS OrgName
	        
	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 
			INNER JOIN sSetup.tBatchMaster BMM ON BMM.Id = BL.BatchId AND BMM.IsInContext = 1 --AND BMM.IsActive = 1
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BL.OrgId
			--INNER JOIN sStudent.vStudentLastAcademic SA ON SA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003
			--AND SA.BatchId = BL.BatchId
			--AND SA.IsActiveBatch = 1
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
			AND ((SA.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
			AND ((SA.Name Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
			AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
			AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
			AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((BL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0))
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
			AND ((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
			AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			--AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		    AND ((BL.IsCurrentStatus = @rIsCurrentStatus) OR (@rIsCurrentStatus = 0))
			AND (BL.ReaderSourceTypeId != 0)
	UNION

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Employee' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			EM.Code AS ReaderCode,
			EM.FirstName+' '+EM.LastName AS ReaderName,
			ODM.Title as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			CASE WHEN BL.StatusId = 521 AND ISNULL(BL.UpdatedUserId,0)!=1 Then 'Return' WHEN BL.StatusId = 521 AND ISNULL(BL.UpdatedUserId,0)=1 Then 'Release' ELSE SM.Title END AS TransactionStatus,
			BL.IsCurrentStatus,
			BL.CreatedDateTime ,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2,
	        '' AS SUId,
	        '' AS BatchName,
	        '' AS OrgName
	         
	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 sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
			AND ((EM.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
			AND ((EM.FirstName+' '+EM.LastName Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
			AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
			AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
			AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((BL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0))
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
			AND (BL.ReaderSourceTypeId != 0)
			AND ((BL.IsCurrentStatus = @rIsCurrentStatus) OR (@rIsCurrentStatus = 0))
			AND ISNULL(EM.IsOtherUser,0) = 0 
	UNION 

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'' AS ReaderSourceType,
			0 AS ReaderSourceTypeId,
			0 AS ReaderSourceId,
			'' AS ReaderCode,
			'' AS ReaderName,
			'' as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			SM.Title AS TransactionStatus,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2,
	        '' AS SUId,
	        '' AS BatchName,
	        '' AS OrgName
			
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			LEFT JOIN sLibrary.tLibraryMaster LM ON LM.Id=BL.LibraryId
	WHERE 
			(ISNULL(BL.ReaderSourceTypeId,0)=@rReaderSourceTypeId AND @rReaderSourceTypeId=0)
			AND (('' Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
			AND (('' Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
			AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
			AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
			AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((BL.StatusId = @rStatusId) OR (ISNULL(@rStatusId,0) = 0))
			AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
			AND (BL.LibraryId=@rLibraryId)
			AND (BL.ReaderSourceTypeId != 0)
			AND ((BL.IsCurrentStatus = @rIsCurrentStatus) OR (@rIsCurrentStatus = 0))
END
GO
PRINT N'Altering [sLibrary].[pReturnDueListGet]...';


GO
ALTER PROCEDURE [sLibrary].[pReturnDueListGet]
	 @rReaderSourceTypeId smallint,
	 @rReaderCode nvarchar(20),
	 @rReaderName nvarchar(200),
	 @rResourceCode nvarchar(25),
	 @rResourceName nvarchar(100),
	 @rDueDate date,
	 @rOrgId smallint,
	 @rBatchId int,
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='',
	 @rLibraryId int,
	 @rOrgGroupId int=0,
	 @rSUId nvarchar(50)='',
	 @rClassId int=0,
	 @rDepartmentId int=0,
	 @rDivisionId int=0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 	
		
		SET @rReaderCode = sCommon.fSearchStringGet(@rReaderCode)
		SET @rReaderName = sCommon.fSearchStringGet(@rReaderName)
		SET @rResourceCode = sCommon.fSearchStringGet(@rResourceCode)
		SET @rResourceName = sCommon.fSearchStringGet(@rResourceName)
		
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Student' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			VA.Code AS ReaderCode,
			VA.Name AS ReaderName,
			VA.ClassName+'-'+VA.DivisionName AS ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			CASE WHEN BL.StatusId = 521 Then 'Return' ELSE SM.Title END AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			SC.ParentContactNo AS MobileNo,
			SC.ParentEmail AS EmailId,
			replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1),'[Name]',VA.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS EmailTemplate,
			replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=2),'[Name]',VA.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS SMSTemplate,

			 replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=3),'[Name]',VA.Name),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS MobileTemplate,

			 (SELECT E.MailSubject FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1) AS MailSubject,
			 LM.Id AS LibraryId,
			 LM.Title AS LibraryName,
			 LM.ReportOrgTitle,
	         LM.SmallAddress1,
	         LM.SmallAddress2,
	         VA.SUId
			 
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			--INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND BL.BatchId = SC.BatchId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 
			INNER JOIN sStudent.vStudentLastAcademic VA ON VA.StudentId=BL.ReaderSourceId AND BL.ReaderSourceTypeId=2003 AND BL.BatchId = VA.BatchId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
		AND ((VA.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND ((VA.Name Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		--AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.DueDate<=@rDueDate) AND (BL.IsCurrentStatus=1)
		AND (BL.StatusId = 523) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
		AND ((VA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
		AND ((VA.ClassId=@rClassId)OR(@rClassId=0))
		AND ((VA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND(VA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
	UNION ALL

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'Employee' AS ReaderSourceType,
			ISNULL(BL.ReaderSourceTypeId,0) AS ReaderSourceTypeId,
			ISNULL(BL.ReaderSourceId,0) AS ReaderSourceId,
			EC.Code AS ReaderCode,
			EC.FirstName+' '+EC.LastName AS ReaderName,
			EC.DepartmentName as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			CASE WHEN BL.StatusId = 521 Then 'Return' ELSE SM.Title END AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			EC.PhoneNoCompany AS MobileNo,
			EC.CompanyEmail AS EmailId,
			replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1),'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS EmailTemplate,
			 replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=2),'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS SMSTemplate,
			  replace (
			replace (
			replace (
			replace((SELECT E.Template FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND AlertModeId=3),'[Name]',EC.EmployeeName),
			'[BookCode]',BM.Code),
			'[BookName]',BM.Title),
			'[DueDate]',BL.DueDate)
			 AS MobileTemplate,
			 (SELECT E.MailSubject FROM sAlert.tEventTemplate E WHERE E.OrgId=BL.OrgId AND E.EventId=11 AND E.AlertModeId=1) AS MailSubject,
			 LM.Id AS LibraryId,
			 LM.Title AS LibraryName,
			 LM.ReportOrgTitle,
	         LM.SmallAddress1,
	         LM.SmallAddress2,
	         '' AS SUId
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sHrm.vEmployeeCommunication EC ON EC.Id=BL.ReaderSourceId AND BL.ReaderSourceTypeId=95 AND BL.OrgId=EC.OrgId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
			
	WHERE 
			(BL.ReaderSourceTypeId=@rReaderSourceTypeId OR @rReaderSourceTypeId=0)
		AND ((EC.Code Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND ((EC.FirstName+' '+EC.LastName Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		--AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.StatusId = 523) 
		AND (BL.DueDate<=@rDueDate) AND  (BL.IsCurrentStatus=1)
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
		AND(EC.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
		
	UNION ALL

	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			BL.Id AS BookLogId,
			'' AS ReaderSourceType,
			0 AS ReaderSourceTypeId,
			0 AS ReaderSourceId,
			'' AS ReaderCode,
			'' AS ReaderName,
			'' as ClassDept,
			BL.ResourceSourceTypeId,
			BL.ResourceSourceId,
			BM.Code AS ResourceCode,
			BM.Title AS ResourceName,
			BL.LogDate,
			BL.DueDate,
			BL.StatusId,
			SM.Title AS StatusName,
			BL.IsCurrentStatus,
			BL.CreatedDateTime,
			'' AS MobileNo,
			'' AS EmailId,
			'' AS EmailTemplate,
			'' AS SMSTemplate,
			'' AS MailSubject,
			'' AS MobileTemplate,
			LM.Id AS LibraryId,
			LM.Title AS LibraryName,
			LM.ReportOrgTitle,
	        LM.SmallAddress1,
	        LM.SmallAddress2,
	        '' AS SUId
	FROM 
			sLibrary.tBookLog BL
			INNER JOIN sLibrary.tLibraryMaster LM ON LM.Id = BL.LibraryId
			INNER JOIN sLibrary.tBookMaster BM ON BM.Id=BL.ResourceSourceId
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id=BL.StatusId
	WHERE 
			(ISNULL(BL.ReaderSourceTypeId,0)=@rReaderSourceTypeId AND @rReaderSourceTypeId=0)
		AND (('' Like @rReaderCode) OR (ISNULL(@rReaderCode,'') = ''))
		AND (('' Like @rReaderName) OR (ISNULL(@rReaderName,'') = ''))
		AND ((BM.Code Like @rResourceCode) OR (ISNULL(@rResourceCode,'') = ''))
		AND ((BM.Title Like @rResourceName) OR (ISNULL(@rResourceName,'') = ''))
		--AND ((BL.LogDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		--AND ((BL.LogDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND (BL.StatusId = 523) 
		AND (BL.DueDate<=@rDueDate) AND (BL.IsCurrentStatus=1) 
		AND ((BL.OrgId=@rOrgId) OR (@rOrgId=0))
		AND ((BL.BatchId=@rBatchId) OR (@rBatchId=0))
		AND ((BL.LibraryId=@rLibraryId) OR (@rLibraryId=0))
		AND LM.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Altering [sMis].[pRptStudentBirthdayList]...';


GO

ALTER PROCEDURE [sMis].[pRptStudentBirthdayList]
	 
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rOrgMainGroupId int,
	@rOrgSubGroupId int,
	@rOrgGroupId int,
	@rOrgId smallint,
	--@rOrgGroupBatchId int, 
	@rDepartmentId int,
	@rClassId int,
	@rDivisionId int,
    @rStudentStatusId int=0,
	@rMonth tinyint =0,

	@rIsTestMainGroup bit =0,
	@rIsTestSubGroup bit =0,	
	@rIsTestOrg bit=0,
	@rIsTestDepartment bit=0,
	@rIsTestClass bit=0,
	@rIsTestDivision bit=0,
	@rStrOrgMainGroupId nvarchar(max) = '',
	@rStrOrgSubGroupId nvarchar(max) = '',
	@rStrOrgId nvarchar(max) = '',
	@rStrDepartmentId nvarchar(max) = '',
	@rStrClassId nvarchar(max) = '',
	@rIsDisplayOrgGroup bit=0
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

Declare @lIDConfigValue nvarchar(50)='' 


 SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId

	SELECT  
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			@rIsTestMainGroup AS IsTestMainGroup,
			@rIsTestSubGroup AS IsTestSubGroup,
			@rIsTestOrg AS IsTestOrg,
			@rIsTestDepartment AS IsTestDepartment,
			@rIsTestClass AS IsTestClass,
			@rIsTestDivision AS IsTestDivision,
			@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
			SD.AcademicId,
			SD.StudentId, 
			SD.ClassId,
			SD.DivisionId,
			SD.ClassDivision,
			SD.Code,
			SD.RollNo,			
			SD.FirstName,
			SD.MiddleName,			
			SD.LastName,
			SD.Name,		
			SD.ClassName,
			SD.DivisionName,
			SD.StatusName,
			SD.StatusId,
			SD.LCProgress,
			SD.Religion,
			SD.FamilyCast,
			SD.FamilySubCast,
			SD.LCConduct,
			SD.BirthPlace,
			SD.BirthTaluka,
			SD.BirthDistrict,
			SD.LeftDate,
			SD.PreviousSchool,
			SD.DateOfBirth,
			SD.BirthDateInWord,
			SD.LeftReason,
			SD.AdmissionDate,
			SD.AdmissionStandard,
			SD.LeftStandard,
			SD.LCNumber,
			SD.LCDate,
			SD.StudentPhoto,
			SD.BloodGroup,
			SD.PresentAddress,
			SD.ContactNo,
			SD.Batch,
			SD.InactiveDate,
			OM.Title AS OrgName,
			SF.MotherName,
			SD.DivisionOrder,
			SD.Number AS StudentNumber,
			SF.FatherName,
			SD.Nationality,
			SD.MotherTongue,
			SD.BirthState,
			SD.BirthCountry,
			SD.SUId,
            SD.AdhaarNumber,
            SD.ClassStatusId,
            SD.ClassStatusName,
			SD.UIDNumber,
			SD.Gender,
			SF.FatherOfficeContactNo,
			SF.MotherOfficeContactNo,
			OMGM.Id AS OrgMainGroupId,
			OMGM.Title AS OrgMainGroupTitle,
			OSGM.Id AS OrgSubGroupId,
			OSGM.Title AS OrgSubGroupTitle,
			OM.Id AS OrgId,
			OM.DisplayTitle AS OrgDisplayTitle,
			SD.DepartmentId,
			DM.Title AS Department,
			@lIDConfigValue AS ItemValue 
	FROM 
			sStudent.vStudentAllDetail SD
			INNER JOIN	sSetup.tClassMaster CM	ON CM.Id=SD.ClassId	
			INNER JOIN sSetup.tDepartmentMaster DM ON DM.Id=CM.DepartmentId		
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SD.OrgId	
			INNER JOIN sSetup.tOrgGroupMaster OG ON OG.Id = OM.OrgGroupId
			INNER JOIN sSetup.tOrgSubGroupMaster OSGM ON OSGM.Id = OM.OrgSubGroupId
			INNER JOIN sSetup.tOrgMainGroupMaster OMGM ON OMGM.Id = OSGM.OrgMainGroupId
			--INNER JOIN sSetup.tOrgGroupBatchMaster OBM ON OBM.OrgGroupId = OG.Id
			INNER JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			--INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SD.ClassID AND BC.BatchId = SD.BatchId 
			--LEFT JOIN sStudent.tStudentAdmission SAM ON SD.StudentId=SAM.StudentId
			--AND ((SAM.AdmissionDate>=@rFromAdmissionDate)OR(ISNULL(@rFromAdmissionDate,'')=''))    
			--AND ((SAM.AdmissionDate<=@rToAdmissionDate)OR(ISNULL(@rToAdmissionDate,'')=''))  
			--AND	SAM.BatchId = @rBatchId   
	WHERE 
		((SD.OrgId=@rOrgId) OR (@rOrgId=0))
		And ((SD.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SD.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SD.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		And (Month(SD.DateOfBirth)=@rMonth OR @rMonth = 0)
		AND	((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
		AND ((OMGM.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
		AND ((OSGM.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
		AND ((OM.Id=@rOrgId) OR (@rOrgId=0))
		AND ((SD.StatusId  = @rStudentStatusId) OR (@rStudentStatusId = 0))
		AND (OMGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgMainGroupId,','))OR @rStrOrgMainGroupId='')
		AND (OSGM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrOrgSubGroupId,','))OR @rStrOrgSubGroupId='')
		AND (OM.Id IN (SELECT cast (item as int) FROM  sCommon.fnsplit(@rStrOrgId,','))OR @rStrOrgId='')
		AND (DM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrDepartmentId,','))OR @rStrDepartmentId='')
		AND (CM.Id IN (SELECT cast(item as int) FROM  sCommon.fnsplit(@rStrClassId,','))OR @rStrClassId='')
		AND SD.IsActiveBatch = 1
	 Order by
	 SD.RollNo
	 --SD.AcademicId,SD.StudentId
END
GO
PRINT N'Altering [sSecurity].[pAppPermissionGet]...';


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

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


GO
ALTER PROCEDURE [sSetup].[pPortalStudentMasterUpdate]
	 
	
	@rStrXml [nvarchar](max),
	@rDivisionId int, 
	@rOrgGroupBatchId int=0,
	@rOrgGroupId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

SET @rStrXml=REPLACE(@rStrXml,'&','AND')

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 
	 BEGIN	
	if Not Exists(SELECT A.Id FROM OPENXML (@loDoc, '/Table/StudentMaster', 1)
		WITH (Id bigint)A
		INNER JOIN   sStudent.tStudentMaster SM ON SM.Id =A.Id )
	BEGIN
		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 
			Return
		END
	END
	UPDATE sStudent.tStudentMaster
		SET
			Code = A.Code,
			Number = A.Number,
			FirstName = sSetup.fPortalXMLTagsReplaceReverse(A.FirstName),
			MiddleName = sSetup.fPortalXMLTagsReplaceReverse(A.MiddleName),
			LastName = sSetup.fPortalXMLTagsReplaceReverse(A.LastName),
			OrgId = A.OrgId,
			StatusId = A.StatusId,
			RecordStatusId = A.RecordStatusId,
			UpdatedUserId = A.UpdatedUserId,
			CreatedDateTime = A.CreatedDateTime,
			UpdatedDateTime = A.UpdatedDateTime,
			ReferenceSourceId = A.ReferenceSourceId,
			AdmissionCategoryId = A.AdmissionCategoryId,
			RegistrationNumber = A.RegistrationNumber,
			IsBlackList = A.IsBlackList,
			BlackListReason = sSetup.fPortalXMLTagsReplaceReverse(A.BlackListReason),
			SUId = A.SUId
		 FROM
		 (
		SELECT		
			Id,
			Code,
			Number,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			StatusId,
			RecordStatusId,
			UpdatedUserId,
			CreatedDateTime,		
			UpdatedDateTime,
			ReferenceSourceId,
			AdmissionCategoryId,
			RegistrationNumber,
			IsBlackList,
			BlackListReason,
			SUId
						
		FROM OPENXML (@loDoc, '/Table/StudentMaster', 1)
		WITH ( 
				Id bigint,
				Code nvarchar(20),
				Number bigint,					
				FirstName nvarchar(100),
				MiddleName nvarchar(100),
				LastName nvarchar(100),
				OrgId smallint,
				StatusId smallint,
				RecordStatusId smallint,
				UpdatedUserId bigint,
				CreatedDateTime DateTime,
				UpdatedDateTime DateTime,
				ReferenceSourceId bigint,
				AdmissionCategoryId int,
				RegistrationNumber nvarchar(20),
				IsBlackList bit,
				BlackListReason nvarchar(100),
				SUId nvarchar(50)
			  )) A
			  WHERE sStudent.tStudentMaster.Id = A.Id
		
		
		
		 INSERT INTO sStudent.tStudentMaster
		(
			Id,
			Code,
			Number,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			UpdatedUserId,
			CreatedDateTime,
			UpdatedDateTime,
			ReferenceSourceId,
			AdmissionCategoryId,
			RegistrationNumber,
			IsBlackList,
			BlackListReason,
			SUId
			)
		SELECT		
			A.Id,
			A.Code,
			A.Number,
			sSetup.fPortalXMLTagsReplaceReverse(A.FirstName),
			sSetup.fPortalXMLTagsReplaceReverse(A.MiddleName),
			sSetup.fPortalXMLTagsReplaceReverse(A.LastName),
			A.OrgId,
			A.StatusId,
			A.RecordStatusId,
			A.CreatedUserId,
			A.UpdatedUserId,		
			A.CreatedDateTime,
			A.UpdatedDateTime,
			A.ReferenceSourceId,
			A.AdmissionCategoryId,
			A.RegistrationNumber,
			A.IsBlackList,
			sSetup.fPortalXMLTagsReplaceReverse(A.BlackListReason),
			A.SUId
						
		FROM OPENXML (@loDoc, '/Table/StudentMaster', 1)
		WITH ( 
				Id bigint,
				Code nvarchar(20),
				Number bigint,					
				FirstName nvarchar(100),
				MiddleName nvarchar(100),
				LastName nvarchar(100),
				OrgId smallint,
				StatusId smallint,
				RecordStatusId smallint,
				CreatedUserId bigint,
				UpdatedUserId bigint,
				CreatedDateTime DateTime,
				UpdatedDateTime DateTime,
				ReferenceSourceId bigint,
				AdmissionCategoryId int,
				RegistrationNumber nvarchar(20),
				IsBlackList bit,
				BlackListReason nvarchar(100),
				SUId nvarchar(50)
			  ) A LEFT JOIN sStudent.tStudentMaster S
			  ON A.Id = S.Id WHERE S.Id IS NULL
		
		 EXEC sp_xml_removedocument @loDoc
        SELECT 1 AS Result
	 END	
	
	END TRY
	
	BEGIN CATCH 
		
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pDeletedStudentMasterDataLog]...';


GO
ALTER PROCEDURE [sStudent].[pDeletedStudentMasterDataLog]	
	@rXmldoc [nvarchar](max)
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lCount INT
DECLARE @lInterrorCode INT,
		@intDoc INT,
		@lFeeId int,
        @lCode nvarchar(20),       
        @lNumber int,
        @lTitle nvarchar(100),
        @lFeeHeadId int,
        @1ExistCode nvarchar(max) = '',
        @1ExistNumber nvarchar(max) = '',
        @1ExistTitle nvarchar(max) = '',
        @1DuplicateCode nvarchar(max) = '',
        @1DuplicateNumber nvarchar(max) = '',
        @1DuplicateTitle nvarchar(max) = ''
       
EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc
 
  INSERT INTO sStudent.tStudentMasterDelete
	(
	    Id ,
		Code,
		Number,
		FirstName,
		MiddleName,
		LastName,
		OrgId,
		StatusId,
		RecordStatusId,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,
		ReferenceSourceId,
		AdmissionCategoryId,
		RegistrationNumber,
		IsBlackList,
		BlackListReason,
		SUId,
		EnrollmentStatusId,
		StudentUId,
		StudentGroupId,
		StudentOtherGroupId,
		DeletededUser,
		DeletedDateTime
    ) 
   SELECT
		 Id ,
		Code,
		Number,
		FirstName,
		MiddleName,
		LastName,
		OrgId,
		StatusId,
		RecordStatusId,
		CreatedUserId,
		CreatedDateTime,
		UpdatedUserId,
		UpdatedDateTime,
		ReferenceSourceId,
		AdmissionCategoryId,
		RegistrationNumber,
		IsBlackList,
		BlackListReason,
		SUId,
		EnrollmentStatusId,
		StudentUId,
		StudentGroupId,
		StudentOtherGroupId,
		DeletedUser,
		getdate()
   
   FROM OPENXML (@intDoc, '/Table/DeletedStudentMasterData', 1)
   With
   (
        Id bigint '@Id',
		Code nvarchar(20) '@Code',
		Number bigint '@Number',
		FirstName nvarchar(100) '@FirstName',
		MiddleName nvarchar(100) '@MiddleName',
		LastName nvarchar(100) '@LastName',
		OrgId smallint '@OrgId',
		StatusId smallint '@StatusId',
		RecordStatusId smallint '@RecordStatusId',
		CreatedUserId bigint '@CreatedUserId',
		CreatedDateTime DateTime '@CreatedDateTime',
		UpdatedUserId bigint '@UpdatedUserId',
		UpdatedDateTime DateTime '@UpdatedDateTime',
		ReferenceSourceId bigint '@ReferenceSourceId',
		AdmissionCategoryId int '@AdmissionCategoryId',
		RegistrationNumber nvarchar(20) '@RegistrationNumber',
		IsBlackList bit '@IsBlackList',
		BlackListReason nvarchar(100) '@BlackListReason',
		SUId nvarchar(50) '@SUId',
		EnrollmentStatusId int '@EnrollmentStatusId',
		StudentUId bigint '@StudentUId',
		StudentGroupId int '@StudentGroupId',
		StudentOtherGroupId int '@StudentOtherGroupId',
		DeletedUser nvarchar(100) '@DeletedUser'   
   )   
EXEC sp_xml_removedocument @intDoc

SELECT 1 AS Result
			
END
GO
PRINT N'Altering [sStudent].[pEnrollmentStatusGet]...';


GO
ALTER PROCEDURE [sStudent].[pEnrollmentStatusGet]
	 
	 
	 @rOrgId smallint=0,
	 @rBatchId int = 0,
	 @rDepartmentId int=0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rAcademicId bigint=0,
	 @rStatusId int=0,
	 @rCode nvarchar(20)='',
	@rSUId nvarchar(50)='',
	@rEnrollmentStatusId int=0,
	@rFromDate date='',
	@rToDate date=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON		
BEGIN 	 
		
	SELECT 
			ES.StatusDate,
			SA.SUId,
			SA.Code,
			SA.ClassName+'-'+SA.DivisionName AS DivDept,
			SA.RollNo,
			SA.Name,
			ES.Remark,
			EM.Title AS EnrollmentStatusName,
			SA.BatchId	,
			ES.AcademicId,
			SA.OrgId,
			SA.BatchId,
			SA.DepartmentId,
			SA.ClassId,
			SA.DivisionId,
			ES.EnrollmentStatusId
  FROM 
			sStudent.tEnrollmentStatusStudent ES
			LEFT JOIN sStudent.vStudentAcademic SA ON SA.AcademicId =ES.AcademicId
			LEFT JOIN  sStudent.tEnrollmentStatusMaster EM ON EM.Id=ES.EnrollmentStatusId
			LEFT JOIN sStudent.tStatusMaster SM ON  SM.Id = EM.StatusId 
			--INNER JOIN sActivity.tEventSchedule ES ON EA.EventScheduleId=ES.Id 
			--INNER JOIN sActivity.tEventTypeMaster EM ON EM.Id = ES.EventTypeId
  WHERE 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.SUId like @rSUId) OR (ISNULL(@rSUId,'') = '')) 
			AND(SA.OrgId=@rOrgId)
			AND((SA.BatchId=@rBatchId )or( @rBatchId = 0))
			AND((SA.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
		AND((ES.EnrollmentStatusId=@rEnrollmentStatusId )or( @rEnrollmentStatusId = 0))
			--AND ((ES.CreatedDateTime >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			----AND ((ES.ToDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((ES.StatusDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((ES.StatusDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
				AND((SA.AcademicId=@rAcademicId)OR(@rAcademicId=0)) 
				AND ((EM.StatusId=@rStatusId)OR(@rStatusId=0)) 
			ORDER BY ES.CreatedDateTime desc
END
GO
PRINT N'Altering [sStudent].[pIDRegisterGet]...';


GO
ALTER PROCEDURE [sStudent].[pIDRegisterGet]   
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int=0,
	@rBatchId int=0,
	@rFromCode nvarchar(20)='',
	@rToCode nvarchar(20)='',
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rMiddleName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rOrgGroupBatchId int=0,
	@rDepartmentId int=0,
	@rBatchStatusId smallint=0,
	@rSUId nvarchar(50)=''

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN
	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 104 AND SourceTypeId = 1016 AND SourceId = @rOrgId

		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rMiddleName = sCommon.fSearchStringGet(@rMiddleName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	END
	IF(@lConfigValue = 'True')
	BEGIN
		SELECT 
			ISNULL(A.Id,0) AS AcademicId,	  
			ISNULL(A.ClassId,0) AS ClassId,
			ISNULL(A.DivisionId,0) AS DivisionId,
			ISNULL(A.RollNo,0) AS RollNo,
			ISNULL(A.OrgId,0) AS OrgId,
			ISNULL(A.BatchId,0) AS BatchId,
			SM.Id AS StudentId,
			ISNULL(SM.Code,'') AS Code,
			ISNULL(SM.Number,0) AS Number,
			ISNULL(SM.RegistrationNumber,0) AS RegistrationNumber,
			ISNULL(SM.FirstName,'') AS FirstName,
			ISNULL(SM.MiddleName,'') AS MiddleName,
			ISNULL(SM.LastName,'') AS LastName,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			Convert(Nvarchar(20),A.RollNo) + '-' + SM.FirstName+' '+SM.LastName AS RollNoName,	  
			ISNULL(SM.StatusId,0) AS StatusId,
			ISNULL(CM.DisplayTitle,'')  AS ClassName,
			ISNULL(DM.DisplayTitle,'') AS DivisionName,
			ISNULL(CM.DisplayTitle +'-'+DM.DisplayTitle,'') AS ClassDivision,
			ISNULL(STM.Title,'') AS StatusName,	  
			ISNULL(SM.RecordStatusId,0) AS RecordStatusId,	  
			ISNULL(DM.InchargeEmployeeId,0) AS InchargeEmployeeId, 
			ISNULL(BM.OrgGroupBatchId,0) AS OrgGroupBatchId,	  
			--SM.AdmissionCategoryId,
			ISNULL(A.AdmissionCategoryId,0) AS AdmissionCategoryId,
			DM.OrderIndex DivisionOrder,
			ISNULL(BM.IsActive,0) AS IsActiveBatch,
			ISNULL(BM.Title,'') AS BatchName,
			ISNULL(DeptM.Id,0) AS DepartmentId,
			ISNULL(DeptM.Title,'') AS DepartmentName,
			ISNULL(SM.IsBlackList,0) AS IsBlackList,
			ISNULL(SM.BlackListReason,'') BlackListReason,
			CM.OrderIndex AS ClassOrderIndex,
			ISNULL(A.ExemptionTypeId,0) AS ExemptionTypeId,
			ISNULL(OM.DisplayTitle,'')  AS DisplayTitle,
			ISNULL(OM.StreetOne,'') AS StreetOne,
			ISNULL(OM.StreetTwo,'') AS StreetTwo,
			ISNULL(OM.StreetThree,'') AS StreetThree,
			ISNULL(OM.ZipCode,'') AS ZipCode,
			ISNULL(SM.SUId,'') AS SUId ,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			ISNULL(OM.ReportOrgTitle,'') AS ReportOrgTitle,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SD.StatusName,'') AS StatusName,
			ISNULL(SD.StatusId,0) AS StatusId,
			ISNULL(SD.LCProgress,'') AS LCProgress,
			ISNULL(SD.Religion,'') AS Religion,
			ISNULL(SD.FamilyCast,'') AS FamilyCast,
			ISNULL(SD.FamilySubCast,'') AS FamilySubCast,
			ISNULL(SD.LCConduct,'') AS LCConduct,
			ISNULL(SD.BirthPlace,'') AS BirthPlace,
			ISNULL(SD.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SD.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SD.LeftDate,'') AS LeftDate,
			ISNULL(SD.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SD.DateOfBirth,'') AS DateOfBirth,
			ISNULL(SD.BirthDateInWord,'') AS BirthDateInWord,
			ISNULL(SD.LeftReason,'') AS LeftReason,
			ISNULL(SD.AdmissionDate,'') AS AdmissionDate,
			ISNULL(SD.AdmissionStandard,'') AS AdmissionStandard,
			ISNULL(SD.LeftStandard,'') AS LeftStandard,
			ISNULL(SD.LCNumber,0) AS LCNumber,
			ISNULL(SD.LCDate,'') AS LCDate,
			ISNULL(SD.StudentPhoto,0x) AS StudentPhoto,
			ISNULL(SD.BloodGroup,'') AS BloodGroup,
			ISNULL(SD.PresentAddress,'') AS PresentAddress,
			ISNULL(SD.ContactNo,0) AS ContactNo,
			ISNULL(SD.Batch,'') AS Batch,
			ISNULL(SD.InactiveDate,'') AS InactiveDate,
			ISNULL(OM.Title,'') AS OrgName,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SD.DivisionOrder,0) AS DivisionOrder,
			ISNULL(SD.Number,'') AS StudentNumber,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SD.Nationality,'') AS Nationality,
			ISNULL(SD.MotherTongue,'') AS MotherTongue,
			ISNULL(SD.BirthState,'') AS BirthState,
			ISNULL(SD.BirthCountry,'') AS BirthCountry,
			ISNULL(SD.SUId,0) AS SUId,
            ISNULL(SD.AdhaarNumber,0) AS AdhaarNumber,
            ISNULL(SD.ClassStatusId,0) AS ClassStatusId,
            ISNULL(SD.ClassStatusName,'') AS ClassStatusName


		FROM 
				(
SELECT Id 
FROM (select A.ID,
             ROW_NUMBER() over (partition by studentId ORDER BY BM.OrderIndex DESC) as MAX_ID
      from sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
      ) x
WHERE MAX_ID = 1	
) LA INNER JOIN sStudent.tAcademic A ON LA.Id = A.Id
			
			INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = A.Id
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			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 sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			INNER JOIN sStudent.tStatusMaster STM
			ON STM.Id=SM.StatusId
			INNER JOIN sSetup.tDepartmentMaster DeptM
			ON DeptM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM 
			ON SM.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SM.Id
		WHERE 
			((A.ClassId=@rClassId)OR(@rClassId=0))
			AND((A.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			--AND ((SM.Code >= CASE WHEN @lConfigValue ='FALSE' THEN CONVERT(int,@rFromCode) ELSE @rFromCode END) 
			--	OR (CASE WHEN @lConfigValue ='FALSE' THEN @rFromCode)
			AND((SM.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = '')) 
			AND((SM.Code <= @rToCode) OR (ISNULL(@rToCode,'') = '')) 
			AND((SM.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SM.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = ''))
			AND((SM.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND((STM.Id=@rStatusId)OR(@rStatusId=0))	
			AND((A.BatchId=@rBatchId)OR(@rBatchId=0))	
			AND((OM.Id=@rOrgId)OR(@rOrgId=0))
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
			AND((DeptM.Id=@rDepartmentId)OR(@rDepartmentId=0))
			AND((A.RollNo=@rRollNo)OR(@rRollNo=0))	
			AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
			ORDER BY SM.Number
	END
	ELSE
	BEGIN
			SELECT 
			ISNULL(A.Id,0) AS AcademicId,	  
			ISNULL(A.ClassId,0) AS ClassId,
			ISNULL(A.DivisionId,0) AS DivisionId,
			ISNULL(A.RollNo,0) AS RollNo,
			ISNULL(A.OrgId,0) AS OrgId,
			ISNULL(A.BatchId,0) AS BatchId,
			SM.Id AS StudentId,
			ISNULL(SM.Code,'') AS Code,
			ISNULL(SM.Number,0) AS Number,
			ISNULL(SM.RegistrationNumber,0) AS RegistrationNumber,
			ISNULL(SM.FirstName,'') AS FirstName,
			ISNULL(SM.MiddleName,'') AS MiddleName,
			ISNULL(SM.LastName,'') AS LastName,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			Convert(Nvarchar(20),A.RollNo) + '-' + SM.FirstName+' '+SM.LastName AS RollNoName,	  
			ISNULL(SM.StatusId,0) AS StatusId,
			ISNULL(CM.DisplayTitle,'')  AS ClassName,
			ISNULL(DM.DisplayTitle,'') AS DivisionName,
			ISNULL(CM.DisplayTitle +'-'+DM.DisplayTitle,'') AS ClassDivision,
			ISNULL(STM.Title,'') AS StatusName,	  
			ISNULL(SM.RecordStatusId,0) AS RecordStatusId,	  
			ISNULL(DM.InchargeEmployeeId,0) AS InchargeEmployeeId, 
			ISNULL(BM.OrgGroupBatchId,0) AS OrgGroupBatchId,	  
			--SM.AdmissionCategoryId,
			ISNULL(A.AdmissionCategoryId,0) AS AdmissionCategoryId,
			DM.OrderIndex DivisionOrder,
			ISNULL(BM.IsActive,0) AS IsActiveBatch,
			ISNULL(BM.Title,'') AS BatchName,
			ISNULL(DeptM.Id,0) AS DepartmentId,
			ISNULL(DeptM.Title,'') AS DepartmentName,
			ISNULL(SM.IsBlackList,0) AS IsBlackList,
			ISNULL(SM.BlackListReason,'') BlackListReason,
			CM.OrderIndex AS ClassOrderIndex,
			ISNULL(A.ExemptionTypeId,0) AS ExemptionTypeId,
			ISNULL(OM.DisplayTitle,'')  AS DisplayTitle,
			ISNULL(OM.StreetOne,'') AS StreetOne,
			ISNULL(OM.StreetTwo,'') AS StreetTwo,
			ISNULL(OM.StreetThree,'') AS StreetThree,
			ISNULL(OM.ZipCode,'') AS ZipCode,
			ISNULL(SM.SUId,'') AS SUId ,
			ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			ISNULL(OM.ReportOrgTitle,'') AS ReportOrgTitle,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			ISNULL(SC.StudentContactNo,'') AS StudentContactNo,
			ISNULL(SD.StatusName,'') AS StatusName,
			ISNULL(SD.StatusId,0) AS StatusId,
			ISNULL(SD.LCProgress,'') AS LCProgress,
			ISNULL(SD.Religion,'') AS Religion,
			ISNULL(SD.FamilyCast,'') AS FamilyCast,
			ISNULL(SD.FamilySubCast,'') AS FamilySubCast,
			ISNULL(SD.LCConduct,'') AS LCConduct,
			ISNULL(SD.BirthPlace,'') AS BirthPlace,
			ISNULL(SD.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SD.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SD.LeftDate,'') AS LeftDate,
			ISNULL(SD.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SD.DateOfBirth,'') AS DateOfBirth,
			ISNULL(SD.BirthDateInWord,'') AS BirthDateInWord,
			ISNULL(SD.LeftReason,'') AS LeftReason,
			ISNULL(SD.AdmissionDate,'') AS AdmissionDate,
			ISNULL(SD.AdmissionStandard,'') AS AdmissionStandard,
			ISNULL(SD.LeftStandard,'') AS LeftStandard,
			ISNULL(SD.LCNumber,0) AS LCNumber,
			ISNULL(SD.LCDate,'') AS LCDate,
			ISNULL(SD.StudentPhoto,0x) AS StudentPhoto,
			ISNULL(SD.BloodGroup,'') AS BloodGroup,
			ISNULL(SD.PresentAddress,'') AS PresentAddress,
			ISNULL(SD.ContactNo,0) AS ContactNo,
			ISNULL(SD.Batch,'') AS Batch,
			ISNULL(SD.InactiveDate,'') AS InactiveDate,
			ISNULL(OM.Title,'') AS OrgName,
			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SD.DivisionOrder,0) AS DivisionOrder,
			ISNULL(SD.Number,'') AS StudentNumber,
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SD.Nationality,'') AS Nationality,
			ISNULL(SD.MotherTongue,'') AS MotherTongue,
			ISNULL(SD.BirthState,'') AS BirthState,
			ISNULL(SD.BirthCountry,'') AS BirthCountry,
			ISNULL(SD.SUId,0) AS SUId,
            ISNULL(SD.AdhaarNumber,0) AS AdhaarNumber,
            ISNULL(SD.ClassStatusId,0) AS ClassStatusId,
            ISNULL(SD.ClassStatusName,'') AS ClassStatusName


		FROM 
				(
SELECT Id 
FROM (select A.ID,
             ROW_NUMBER() over (partition by studentId ORDER BY BM.OrderIndex DESC) as MAX_ID
      from sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id
      ) x
WHERE MAX_ID = 1	
) LA INNER JOIN sStudent.tAcademic A ON LA.Id = A.Id
			
			INNER JOIN sStudent.vStudentAllDetail SD ON SD.AcademicId = A.Id
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=SD.StudentId
			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 sSetup.tBatchMaster BM ON BM.Id = A.BatchId 
			INNER JOIN sStudent.tStatusMaster STM
			ON STM.Id=SM.StatusId
			INNER JOIN sSetup.tDepartmentMaster DeptM
			ON DeptM.Id=CM.DepartmentId
			INNER JOIN sSetup.tOrganizationMaster OM 
			ON SM.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SM.Id
		WHERE 
			((A.ClassId=@rClassId)OR(@rClassId=0))
			AND((A.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SM.Code >= CONVERT(int,@rFromCode)) OR (ISNULL(@rFromCode,0) = 0)) 
			AND((SM.Code <= CONVERT(int,@rToCode)) OR (ISNULL(@rToCode,0) = 0)) 
			AND((SM.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SM.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = ''))
			AND((SM.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND((STM.Id=@rStatusId)OR(@rStatusId=0))	
			AND((A.BatchId=@rBatchId)OR(@rBatchId=0))	
			AND((OM.Id=@rOrgId)OR(@rOrgId=0))
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
			AND((DeptM.Id=@rDepartmentId)OR(@rDepartmentId=0))
			AND((A.RollNo=@rRollNo)OR(@rRollNo=0))	
			AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
			ORDER BY SM.Number
	END

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=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(50),
		@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,
		@lPreviousStandard nvarchar(100),
		@lWhatsAppContactNo nvarchar(20),
		@lTribeId int = 0,
		@lTribe 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)	
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(50),
		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),
		PreviousStandard Nvarchar(100) ,
		WhatsAppContactNo nvarchar(20),
		TribeId int null,
		Tribe 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,
		PreviousStandard,
		WhatsAppContactNo,
		TribeId,
		Tribe
	)
	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,
		PreviousStandard,
		WhatsAppContactNo,
		0,
		Tribe
			
	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(50) '@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',
		PreviousStandard nvarchar(100) '@PreviousStandard',
		WhatsAppContactNo nvarchar(20) '@WhatsAppContactNo',
		Tribe nvarchar(100) '@Tribe'
	)
	
 
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 =''
		Set @lPreviousStandard = ''
		SET @lWhatsAppContactNo = ''
		SET @lTribeId = null
		SET @lTribe = ''
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,
		@lPreviousStandard = PreviousStandard,
		@lWhatsAppContactNo = WhatsAppContactNo,
		@lTribe = Tribe

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
	SELECT	@lTribeId  = ID FROM sCommon.tTribeMaster WHERE Title = @lTribe
	
	PRINT(@lTribeId)
	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(@lTribeId IS NULL)
		SET	@lTribeId = 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,1
	
	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,NULL,NULL,NULL,NULL,NULL,@lWhatsAppContactNo

	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,@rBatchId,@lTribeId

 
	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,Null,Null,Null,Null,Null,Null,Null,
				Null,@lPreviousStandard,Null,Null,Null,Null
	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,Null,Null,Null,Null,Null,Null,Null,
				Null,@lPreviousStandard,Null,Null,Null,Null
    
				 
END		

ELSE
BEGIN
    
      SET @1StudentId = (SELECT Id FROM sStudent.tStudentMaster WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT AND OrgId = @rOrgId) 
    
      UPDATE sStudent.tStudentMaster SET RegistrationNumber = @lRegistrationNumber, FirstName = @lFirstName, MiddleName = @lMiddleName, LastName=@lLastName, SUId=@lSUId, UpdatedUserId=@rUserId,UpdatedDateTime=getdate() WHERE Id=@1StudentId
    Print @lClassId
    Print @lDivisionId
      UPDATE sStudent.tAcademic SET DivisionId=@lDivisionId,RollNo=@lRollNo,UpdatedUserId=@rUserId,UpdatedDateTime=getdate() WHERE StudentId=@1StudentId AND BatchId=@rBatchId AND OrgId=@rOrgId
      
      UPDATE sStudent.tStudentAdmission SET AdmissionStandardId = @lAdmissionStandardId, AdmissionDate = @lAdmissionDate, PreviousSchool = @lPreviousSchool,
      LeftStandardId = @lLeftStandardId, LeftDate = @lLeftDate, LCNumber = @lLCNumber, LCDate = @lLCDate, LCRemark = @lLCRemark, 
      LCConduct = @lLCConduct, LCProgress = @lLCProgress, LeftReason = @lLCReason, UpdatedUserId=@rUserId,UpdatedDateTime=getdate(),PreviousStandard=@lPreviousStandard WHERE StudentId=@1StudentId
      
      UPDATE sStudent.tStudentOther SET DateOfBirth = @lDOB, GenderId = @lGenderId, BloodGroupId = @lBloodGroupId, ReligionId = @lReligionId,
      FamilyCast = @lFamilyCast, FamilySubCast = @lFamilySubCast, CastCategoryId = @lCastCategoryId, BirthPlace = @lBirthPlace, BirthTaluka = @lBirthTaluka,
	  BirthDistrict = @lBirthDistrict, BirthState =@lBirthState, BirthCountry =@lBirthCountry, AdhaarNumber = @lAdhaarNumber, MotherTongue = @lMotherTongue,
	  QuotaId = @lQuotaId, UIDNumber = @lUIDNumber, HouseId = @lHouseId, UpdatedUserId=@rUserId,UpdatedDateTime=getdate(), TribeId = @lTribeId WHERE StudentId = @1StudentId
	  
	  UPDATE sStudent.tStudentCommunication SET PresentStreetOne=@lPresentStreetOne, PresentStreetTwo=@lPresentStreetTwo, PresentStreetThree=@lPresentStreetThree,
	  PresentCountry=@lPresentCountry, PresentState=@lPresentState, PresentCity=@lPresentCity, PresentZipCode=@lPresentZipCode,PresentContactNo=@lPresentContactNo,
	  EmergencyContactNo=@lEmergencyContactNo, ParentContactNo=@lParentContactNo, ParentEmail=@lParentEmail, StudentContactNo=@lStudentContactNo,
	  StudentEmail=@lStudentEmail, UpdatedUserId=@rUserId,UpdatedDateTime=getdate() WHERE StudentId = @1StudentId
     
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'Altering [sStudent].[pImportStudent_New]...';


GO
ALTER 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(50),
		@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(50),
		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(50) '@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) 
    
      UPDATE sStudent.tStudentMaster SET RegistrationNumber = @lRegistrationNumber, FirstName = @lFirstName, MiddleName = @lMiddleName, LastName=@lLastName, SUId=@lSUId, UpdatedUserId=@rUserId,UpdatedDateTime=getdate() WHERE Id=@1StudentId
    Print @lClassId
    Print @lDivisionId
      UPDATE sStudent.tAcademic SET DivisionId=@lDivisionId,RollNo=@lRollNo,UpdatedUserId=@rUserId,UpdatedDateTime=getdate() WHERE StudentId=@1StudentId AND BatchId=@rBatchId AND OrgId=@rOrgId
      
      UPDATE sStudent.tStudentAdmission SET AdmissionStandardId = @lAdmissionStandardId, AdmissionDate = @lAdmissionDate, PreviousSchool = @lPreviousSchool,
      LeftStandardId = @lLeftStandardId, LeftDate = @lLeftDate, LCNumber = @lLCNumber, LCDate = @lLCDate, LCRemark = @lLCRemark, 
      LCConduct = @lLCConduct, LCProgress = @lLCProgress, LeftReason = @lLCReason, UpdatedUserId=@rUserId,UpdatedDateTime=getdate() WHERE StudentId=@1StudentId
      
      UPDATE sStudent.tStudentOther SET DateOfBirth = @lDOB, GenderId = @lGenderId, BloodGroupId = @lBloodGroupId, ReligionId = @lReligionId,
      FamilyCast = @lFamilyCast, FamilySubCast = @lFamilySubCast, CastCategoryId = @lCastCategoryId, BirthPlace = @lBirthPlace, BirthTaluka = @lBirthTaluka,
	  BirthDistrict = @lBirthDistrict, BirthState =@lBirthState, BirthCountry =@lBirthCountry, AdhaarNumber = @lAdhaarNumber, MotherTongue = @lMotherTongue,
	  QuotaId = @lQuotaId, UIDNumber = @lUIDNumber, HouseId = @lHouseId, UpdatedUserId=@rUserId,UpdatedDateTime=getdate() WHERE StudentId = @1StudentId
	  
	  UPDATE sStudent.tStudentCommunication SET PresentStreetOne=@lPresentStreetOne, PresentStreetTwo=@lPresentStreetTwo, PresentStreetThree=@lPresentStreetThree,
	  PresentCountry=@lPresentCountry, PresentState=@lPresentState, PresentCity=@lPresentCity, PresentZipCode=@lPresentZipCode,PresentContactNo=@lPresentContactNo,
	  EmergencyContactNo=@lEmergencyContactNo, ParentContactNo=@lParentContactNo, ParentEmail=@lParentEmail, StudentContactNo=@lStudentContactNo,
	  StudentEmail=@lStudentEmail, UpdatedUserId=@rUserId,UpdatedDateTime=getdate() WHERE StudentId = @1StudentId
      
    
    
      print 'a'
     
    
    	
    
     
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'Altering [sStudent].[pStudentDelete]...';


GO
ALTER PROCEDURE [sStudent].[pStudentDelete]
	 @rId bigint,
	 --@DeletedUserId bigint=0
	 @UserId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	BEGIN TRY
		BEGIN TRANSACTION SD
		        --Maintain Student Master Table Log  
		        
		        DECLARE @UserName nvarchar(100)
		        SET @UserName = (select DisplayTitle FROM sSecurity.tUser where Id=@UserId)
		        
				 CREATE TABLE #tStudentMasterData
				 (
					Id bigint,
					Code nvarchar(20),
					Number bigint,
					FirstName nvarchar(100),
					MiddleName nvarchar(100),
					LastName nvarchar(100),
					OrgId smallint,
					StatusId smallint,
					RecordStatusId smallint,
					CreatedUserId bigint,
					CreatedDateTime DateTime,
					UpdatedUserId bigint,
					UpdatedDateTime DateTime,
					ReferenceSourceId bigint,
					AdmissionCategoryId int,
					RegistrationNumber nvarchar(20),
					IsBlackList bit,
					BlackListReason nvarchar(100),
					SUId nvarchar(50),
					EnrollmentStatusId int,
					StudentUId bigint,
					StudentGroupId int,
					StudentOtherGroupId int,
					DeletededUser nvarchar(100),
					DeletedDateTime DateTime	 			
				  )
				  
				  INSERT INTO #tStudentMasterData
					SELECT Id,Code,Number,FirstName,MiddleName,LastName,OrgId,StatusId,RecordStatusId,CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime,
					ReferenceSourceId,AdmissionCategoryId,RegistrationNumber,IsBlackList,BlackListReason,SUId,EnrollmentStatusId,StudentUId,StudentGroupId,StudentOtherGroupId,@UserName,GETDATE() AS DeletedDateTime
					From sStudent.tStudentMaster WHERE Id=@rId
		          
		        
		          --Maintain Student Master Table Log    
			    
					Delete from sStudent.tStudentAdmission where StudentId=@rId
					Delete from sStudent.tStudentCommunication where StudentId=@rId
					Delete from sStudent.tStudentImages where StudentId=@rId
					Delete from sStudent.tStudentFamily where StudentId=@rId
					Delete from sStudent.tStudentOther where StudentId=@rId
					Delete from sStudent.tStudentHealth where StudentId=@rId

					Delete from sStudent.tStudentAdditional where StudentId=@rId
					Delete from sStudent.tStudentSibling where StudentId=@rId
					Delete from sStudent.tCollegeDetail where StudentId=@rId

					Delete from sSecurity.tDivisionPermission Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003)
					Delete from sSecurity.tUserPreference Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003)
					Delete from sSecurity.tUserProfile Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003)
					Delete from sSecurity.tUserRole Where UserId IN(SELECT Id FROM sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003)			
					Delete from sSecurity.tUser Where SourceId=@rId AND SourceTypeId=2003

					DELETE FROM sStudent.tLinkSibling WHERE StudentId = @rId
					DELETE FROM sStudent.tLinkSibling WHERE LinkedStudentId = @rId
				
	
					----- Start Hostel
					Delete from sHostel.tAssignRoom where SourceId=@rId AND SourceTypeId=2003
					Delete from sHostel.tAssignRoomAsset where SourceId=@rId AND SourceTypeId=2003
					Delete from sHostel.tAttendanceRegister where StudentId=@rId 
					Delete from sHostel.tChangeRoom where SourceId=@rId AND SourceTypeId=2003
					Delete from sHostel.tHostelAdmission where SourceId=@rId AND SourceTypeId=2003
					Delete from sHostel.tAssignRoomAsset where SourceId=@rId AND SourceTypeId=2003
					Delete from sHostel.tAttendanceRegister where StudentId=@rId 
					Delete from sHostel.tHostelDepositAdd where StudentId=@rId 
					Delete from sHostel.tHostelDepositAdjustment where StudentId=@rId 
					Delete from sHostel.tHostelDepositRefund where StudentId=@rId 
					Delete from sHostel.tHostelStudentGatePass where StudentId=@rId 
					Delete from sHostel.tVisitorGatePass where WhomToMeetSourceId=@rId  AND WhomToMeetSourceTypeId=2003
					-- END Hostel
					----- Start Transport
					Delete from sTransport.tAssignRoute where SourceId=@rId AND SourceTypeId=2003
					Delete from sTransport.tAttendanceRegister where SourceId=@rId AND SourceTypeId=2003
					--End Transport
					--Start Library
					--DELETE FROM sLibrary.tBookLog where ReaderSourceTypeId=2003 AND ReaderSourceId=@rId
					-- Update Query added on 24-01-2022 by Jash Gandhi for issue no.: 0017791
					UPDATE sLibrary.tBookLog SET ReaderSourceId = NULL,ReaderSourceTypeId = NULL,UpdatedDateTime = sCommon.fGetDate(),UpdatedUserId = @UserId,StatusId = 521 where ReaderSourceTypeId=2003 AND ReaderSourceId=@rId  
					DELETE FROM sLibrary.tLibraryAttendance WHERE SourceTypeId=2003 AND SourceId=@rId
					--End Library
					--start canteen
					DELETE  cd from sCanteen.tCanteenIssueDetail CD INNER JOIN sCanteen.tCanteenIssue C ON C.Id=CD.CanteenIssueId
					WHERE  C.SourceId=@rId AND C.SourceTypeId=2003
					DELETE FROM sCanteen.tCanteenIssue 	WHERE SourceId=@rId AND SourceTypeId=2003
					--End Canteen
					DELETE FROM  sStudent.tStudentDocument where studentId = @rId
					
					Delete from sStudent.tStudentCustomFieldData where StudentId=@rId
					DELETE FROM sStudent.tStudentCommunicationContactDetail where StudentId=@rId
					--Delete from sStudent.tAcademic where studentId=@rId
					Delete from sStudent.tStudentMaster where Id=@rId
					
					INSERT INTO sStudent.tStudentMasterDelete
					 SELECT *FROM #tStudentMasterData
			
		COMMIT TRANSACTION	SD
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION SD
	END CATCH	
END
GO
PRINT N'Altering [sStudent].[pStudentDocumentClassWiseGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentDocumentClassWiseGet]
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int,
    @rSUId nvarchar(50)='',
    @rUserId bigint=0,
    @rMultiCode nvarchar(max)='',
	@rDocumentId int=0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			--SD.DocumentName
			--ISNULL(STUFF(
			-- (SELECT DISTINCT ',' + SDM.DocumentName
			--  FROM sCommon.tSubmitDocumentMaster SDM
			--  INNER JOIN  sStudent.tStudentDocument SD ON SDM.Id=SD.SubmitDocumentMasterId
			--  INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=SDM.Id AND DS.SourceId = @rClassId
			--  where SD.StudentId=SA.StudentId AND SDM.SubmitDocumentFunctionalityId = 1 AND ((SDM.Id=@rDocumentId)OR(@rDocumentId=0))
			--  FOR XML PATH (''))
			--  , 1, 1, ''),'')  AS DocumentName,
			  ISNULL(sStudent.fStudentDocumentClasswiseget(@rDocumentId,SA.AcademicId),'') AS DocumentName
			
  FROM 
          sStudent.vStudentAcademic SA
		  --LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId=SA.StudentId
		  INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			--SD.DocumentName
			ISNULL(sStudent.fStudentDocumentClasswiseget(@rDocumentId,SA.AcademicId),'') AS DocumentName
			
			
  FROM 
          sStudent.vStudentAcademic SA
		  --LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId=SA.StudentId
          INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)	
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
  
	
END
GO
PRINT N'Altering [sStudent].[pStudentDocumentget]...';


GO
ALTER PROCEDURE [sStudent].[pStudentDocumentget]
	 
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int=0,
	 @rCode nvarchar(20),
	 @rStatusId smallint,
	 @rBatchId int,
	 @rDepartmentId int,
	 @rSUId nvarchar(50)
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rSUId= sCommon.fSearchStringGet(@rSUId)
    DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
	IF (@rClassId = 0)
	BEGIN
    select @cols = STUFF((SELECT ',' + QUOTENAME(DocumentName) 
                    from  sCommon.tSubmitDocumentMaster WHERE  OrgId=@rOrgId  AND SubmitDocumentFunctionalityId=1
                    Order by Id 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
      If(ISNULL(@Cols,'')='')
		 BEGIN
		    SELECT -101 AS Result
		 RETURN
		 END
	END
	ELSE
	BEGIN
	select @cols = ISNULL(STUFF(
	(SELECT DISTINCT ',' + DocumentName FROM (
	SELECT QUOTENAME(DM.DocumentName)  AS DocumentName
                    from  sCommon.tSubmitDocumentMaster DM 
					INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId=DM.Id AND DS.SourceId = @rClassId
					WHERE  OrgId=@rOrgId  AND SubmitDocumentFunctionalityId=1

	UNION ALL

	SELECT QUOTENAME(D.DocumentName) AS DocumentName FROM sCommon.tSubmitDocumentMaster D
			LEFT JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id
			WHERE DS.SubmitDocumentId is null AND D.SubmitDocumentFunctionalityId = 1) AS DocumentName
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,''),'-101')
	END
  set @query = 'SELECT Name,Code,SUID,Class,RollNo,' + @cols + ' from 
             (
               SELECT
               SA.Name,SA.Code,SA.SUID,SA.RollNo,(SA.ClassName+''-''+SA.DivisionName) AS Class,S.DocumentName,CASE WHEN D.SubmitDocumentMasterId IS NULL  THEN ''No'' ELSE ''Yes'' END AS DocumentId
               FROM  sStudent.vStudentAcademic SA 
               LEFT JOIN sStudent.tStudentDocument D ON SA.StudentId=D.StudentId 
               LEFT JOIN sCommon.tSubmitDocumentMaster  S ON S.Id=D.SubmitDocumentMasterId AND SubmitDocumentFunctionalityId=1
		        WHERE 
	          ((SA.OrgId=' + CAST(@rOrgId AS NVARCHAR(50))+'))
	          AND ((SA.BatchId=' + CAST(@rBatchId AS NVARCHAR(50))+'))
	          AND ((SA.DivisionId=' + CAST(@rDivisionId AS NVARCHAR(30))+') OR ('+CAST(@rDivisionId AS NVARCHAR(50))+'= 0))
	          AND ((SA.BatchId=' + CAST(@rBatchId AS NVARCHAR(30))+') OR ('+CAST(@rBatchId AS NVARCHAR(50))+'= 0))
	          AND ((SA.ClassId=' + CAST(@rClassId AS NVARCHAR(30))+') OR ('+CAST(@rClassId AS NVARCHAR(50))+'= 0))
	          AND ((SA.BatchId=' + CAST(@rBatchId AS NVARCHAR(30))+') OR ('+CAST(@rBatchId AS NVARCHAR(50))+'= 0))
	          AND ((SA.DepartmentId=' + CAST(@rDepartmentId AS NVARCHAR(30))+') OR ('+CAST(@rDepartmentId AS NVARCHAR(50))+'= 0))
	          AND ((SA.Code  like  '''+ convert(varchar,@rCode )+''') OR ('''+convert(varchar,@rCode )+'''= ''''))
	          AND ((SA.Suid  like  '''+ ISNULL(@rSUId,'') +''') OR ('''+@rSUId +'''= ''''))
	         AND ((SA.StatusId=' + CAST(@rStatusId AS NVARCHAR(30))+') OR ('+CAST(@rStatusId AS NVARCHAR(50))+'= 0))
              ) x
            pivot 
            (
                MIN(DocumentId)
                for DocumentName in (' + isnull(@cols,0) + ')  
            ) p order by RollNo'
            
  print @query
 execute(@query)
END
GO
PRINT N'Altering [sStudent].[pStudentFullGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentFullGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	@rBatchId int,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rMiddleName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rOrgGroupId int,
	@rOrgGroupBatchId int,
	@rDepartmentId int,
	@rBatchStatusId smallint=0,
	@rSUId nvarchar(50)='',
	@rIsInContext bit=0,
	@rClassStatusId smallint=0
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rMiddleName = sCommon.fSearchStringGet(@rMiddleName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL AND @rIsInContext=1)
	BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.FirstName + ' ' + SF.MiddleName + ' ' + SF.LastName AS Name,
			SF.FirstName,
			SF.MiddleName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			ISNULL(SF.EnrollmentStatusId,0) AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			'' AS Remark,
			'01/01/1900' AS  StatusDate,
			SF.ClassStatusId,
			SF.ClassStatusName
			--SB.Remark,
			--ISNULL(SB.StatusDate,'') AS  StatusDate
			 
	 FROM 
           sStudent.vStudentFull SF
           LEFT JOIN sSetup.tBatchMaster BM
           ON BM.Id=SF.BatchId
           LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
           INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId
           --LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
           LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SF.EnrollmentStatusId
           --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
           --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
           INNER JOIN  sStudent.tStudentMaster  SM ON SM.Id=SF.StudentId 
	 WHERE 
 
		((SF.ClassId=@rClassId)OR(@rClassId=0))
		AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SF.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = ''))
		AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND((OM.Id=@rOrgId)OR(@rOrgId=0))
		AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
		AND ((SF.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
		AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND BM.IsActive=1 
		AND BM.IsInContext= 1
		AND((SF.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		
	ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
	END
	ELSE IF(@rRollNo IS NULL AND @rIsInContext=0)
	BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.FirstName + ' ' + SF.MiddleName + ' ' + SF.LastName AS Name,
			SF.FirstName,
			SF.MiddleName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			ISNULL(SF.EnrollmentStatusId,0) AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			'' AS Remark,
			'01/01/1900' AS  StatusDate,
			SF.ClassStatusId,
			SF.ClassStatusName
			--SB.Remark,
			--ISNULL(SB.StatusDate,'') AS  StatusDate
			 
	FROM 
           sStudent.vStudentFull SF
           LEFT JOIN sSetup.tBatchMaster BM
           ON BM.Id=SF.BatchId
           LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
           INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId
           --LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
           LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SF.EnrollmentStatusId
           --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
           --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
           INNER JOIN  sStudent.tStudentMaster  SM ON SM.Id=SF.StudentId 
	WHERE 
 
		((SF.ClassId=@rClassId)OR(@rClassId=0))
		AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SF.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = '')) 
		AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND((OM.Id=@rOrgId)OR(@rOrgId=0))
		AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
		AND ((SF.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
		AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND((SF.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		 
		 
		
	ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
	END
	
	ELSE
	BEGIN
	if(@rIsInContext=1)
	BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.Name,
			SF.FirstName,
			SF.MiddleName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			ISNULL(SF.EnrollmentStatusId,0) AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			'' Remark,
			'01/01/1900'  AS  StatusDate,
			SF.ClassStatusId,
			SF.ClassStatusName
			--SB.Remark,
			--ISNULL(SB.StatusDate,'') AS  StatusDate 
	  FROM 
			   sStudent.vStudentFull SF
			   LEFT JOIN sSetup.tBatchMaster BM
			   ON BM.Id=SF.BatchId
			   LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId
			   --LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
			   LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SF.EnrollmentStatusId
			   --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
			   --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
			   INNER JOIN  sStudent.tStudentMaster  SM ON SM.Id=SF.StudentId 
	  WHERE 
	 
			((SF.ClassId=@rClassId)OR(@rClassId=0))
			AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SF.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = '')) 
			AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND(SF.RollNo=@rRollNo)	
			AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
			AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
			AND((OM.Id=@rOrgId)OR(@rOrgId=0))
			AND (OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
			AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
			AND ((SF.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
			AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
			AND BM.IsActive = 1 
			AND BM.IsInContext=1 
			AND((SF.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		
	ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
	END
	IF(@rIsInContext=0)
	BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.FirstName + ' ' + SF.MiddleName + ' ' + SF.LastName AS Name,
			SF.FirstName,
			SF.MiddleName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			ISNULL(SF.EnrollmentStatusId,0) AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			'' AS Remark,
			'01/01/1900' AS  StatusDate,
			SF.ClassStatusId,
			SF.ClassStatusName
			--SB.Remark,
			--ISNULL(SB.StatusDate,'') AS  StatusDate
			 
	  FROM 
			   sStudent.vStudentFull SF
			   LEFT JOIN sSetup.tBatchMaster BM
			   ON BM.Id=SF.BatchId
			   LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
			   INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId
			   --LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
			   LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SF.EnrollmentStatusId
			   --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
			   --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
			   INNER JOIN  sStudent.tStudentMaster  SM ON SM.Id=SF.StudentId 
	  WHERE 
	 
			((SF.ClassId=@rClassId)OR(@rClassId=0))
			AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = ''))
			AND((SF.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = ''))  
			AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
			AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
			AND((OM.Id=@rOrgId)OR(@rOrgId=0))
			AND (BM.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
			AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
			AND ((SF.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
			AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
			AND((SF.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
			 
			
	ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
	END
  END
		
END
GO
PRINT N'Altering [sStudent].[pStudentFullWithPhotoGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentFullWithPhotoGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int=0,
	@rBatchId int=0,
	@rCode nvarchar(20)='',
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rMiddleName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rOrgGroupId int =0 ,
	@rOrgGroupBatchId int=0,
	@rDepartmentId int=0,
	@rBatchStatusId smallint=0,	
	@rSUId nvarchar(50)='',
	@rClassStatusId smallint=0
	
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rMiddleName = sCommon.fSearchStringGet(@rMiddleName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.Name,
			SF.FirstName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(SF.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,  
			SB.EnrollmentStatusId AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			SB.Remark,
			ISNULL(SB.StatusDate,'') AS  StatusDate,
			SF.ClassStatusId,
			SF.ClassStatusName
  FROM 
           sStudent.vStudentFull SF
           LEFT JOIN sSetup.tBatchMaster BM
           ON BM.Id=SF.BatchId
           LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
           INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId
           LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
           LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SB.EnrollmentStatusId
           INNER JOIN  sStudent.tStudentMaster  SM ON SM.Id=SF.StudentId 
           --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
           --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
           
  WHERE 
 
		((SF.ClassId=@rClassId)OR(@rClassId=0))
		AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND((OM.Id=@rOrgId)OR(@rOrgId=0))	
		AND (OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
		AND ((SB.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
		AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND((SF.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = ''))
		AND((SF.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		--AND ((SB.BatchStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo
END
ELSE
BEGIN
	SELECT 
			SF.AcademicId,
			SF.StudentId,
			SF.Name,
			SF.FirstName,
			SF.LastName,
			SF.Code,
			SF.BatchId,
			BM.Title AS BatchName,
			SF.ClassId,
			SF.ClassName,
			SF.DivisionId,
			SF.DivisionName,
			SF.Number,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusId,
			SF.StatusName,
			SF.OrgId,
			ISNULL(SF.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(OM.DisplayTitle,'') AS DisplayTitle,
			SB.EnrollmentStatusId AS  BatchStatusId,
			ISNULL(BS.Title,'') AS BatchStatus,
			SB.Remark,
			ISNULL(SB.StatusDate,'') AS  StatusDate,
			SF.ClassStatusId,
			SF.ClassStatusName
  FROM 
           sStudent.vStudentFull SF
           LEFT JOIN sSetup.tBatchMaster BM
           ON BM.Id=SF.BatchId
           LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
           INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id=OM.OrgGroupId AND OGM.Id=@rOrgGroupId 
            LEFT JOIN sStudent.tEnrollmentStatusStudent SB ON SB.AcademicId = SF.AcademicId
           LEFT JOIN sStudent.tEnrollmentStatusMaster BS ON BS.Id = SB.EnrollmentStatusId
           INNER JOIN  sStudent.tStudentMaster  SM ON SM.Id=SF.StudentId 
           --LEFT JOIN sStudent.tStudentBatchStatus SB ON SB.AcademicId = SF.AcademicId
           --LEFT JOIN sStudent.tBatchStatusMaster BS ON BS.Id = SB.BatchStatusId
  WHERE 
 
		((SF.ClassId=@rClassId)OR(@rClassId=0))
		AND((SF.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SF.Code= @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SF.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SF.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SF.RollNo=@rRollNo)	
		AND((SF.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SF.BatchId=@rBatchId)OR(@rBatchId=0))	
		AND((OM.Id=@rOrgId)OR(@rOrgId=0))	
		AND (OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
		AND((SF.DepartmentId=@rDepartmentId)OR(@rDepartmentId=0))
		AND ((SB.EnrollmentStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
		AND((SM.SUId= @rSUId) OR (ISNULL(@rSUId,'') = ''))
		AND((SF.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = ''))
		AND((SF.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		--AND ((SB.BatchStatusId =@rBatchStatusId) OR (@rBatchStatusId=0))
ORDER BY SF.ClassId,SF.DivisionId,SF.RollNo

END
  
		
END
GO
PRINT N'Altering [sStudent].[pStudentGet]...';


GO

 
 
ALTER PROCEDURE [sStudent].[pStudentGet]
	 
	 --@rStudentId bigint
	 @rFirstName nvarchar(50)='',
	 @rLastName nvarchar(50)='',
	 @rSUID nvarchar(50)='',
	 @rID nvarchar(50)='',
	 @rOrgGroupBatch int=0,
	 @rOrgGroupId int=0,
	 @rMiddleName nvarchar(50) = '',
	 @rContactNo nvarchar(50) = '',
	 @rCommonSearch nvarchar(500)='',
	 @rUserId bigint=0
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	Declare @StudentSearchConfig nvarchar(50)=''
	Declare @SUIDConfig nvarchar(50)='',@lIDConfigValue nvarchar(50)=''
	SELECT @SUIDConfig =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 167 AND SourceId = @rOrgGroupId
	
	
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	if(@rUserId !=0)
	Begin
	CREATE TABLE #DivisionTemp
	(
	DivisionId int
	)

	Declare @lTeacherId bigint=0;
	select @lTeacherId=SourceId From sSecurity.tUser Where Id=@rUserId AND SourceTypeId=95 
	SELECT @StudentSearchConfig =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 470 AND SourceId = @rOrgGroupId

	if(@StudentSearchConfig='Class Teacher') 
	BEGIN
		INSERT INTO #DivisionTemp
		SELECT DISTINCT DM.Id AS DivisionId
		FROM sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId 
		WHERE DM.InchargeemployeeID=@lTeacherId   AND OM.OrgGroupId=@rOrgGroupId    
	END
	if(@StudentSearchConfig='Class Teacher Batch')
	BEGIN
		INSERT INTO #DivisionTemp
		SELECT DISTINCT  DM.Id AS DivisionId
		FROM sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id 
		INNER JOIN sSetup.tDivisionInchargeEmployee DIE ON DIE.DivisionId = DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId 
		WHERE DM.InchargeemployeeID=@lTeacherId   AND OM.OrgGroupId=@rOrgGroupId   
	END
	if(@StudentSearchConfig='Academic Setup')
	BEGIN
		INSERT INTO #DivisionTemp
		SELECT DISTINCT DivisionId
		 FROM sAcademic.vTeacherSubjectDivision  TSD INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=TSD.OrgId   
		 WHERE  TSD.EmployeeId= @lTeacherId
	END
	if(@StudentSearchConfig='User Access')
	BEGIN
		INSERT INTO #DivisionTemp
		SELECT DISTINCT DM.Id AS DivisionId
		FROM sSetup.tDivisionMaster DM INNER JOIN sSetup.tClassMaster CM ON CM.Id=DM.ClassId INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id AND U.SourceTypeId= 2005
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=CM.OrgId   WHERE  UserId = @rUserId
	END
	--select * from #DivisionTemp
		select 
		[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			SF.ClassName+'-'+SF.DivisionName As Standard,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusName,
			BM.Title AS BatchName,
			SF.Code,
			OM.DisplayTitle As Organization,
			ISNULL(SM.SUID,'') AS SUID,
			@SUIDConfig AS SUIDConfig,
			@lIDConfigValue As IDConfigValue,
			CASE 
			WHEN RIGHT(REPLACE(([sStudent].[fStudentContactsGet](SF.StudentId))+','+ ISNULL(SC.WhatsAppContactNo,''),' ',''), 1) = ',' 
				THEN reverse(stuff(reverse(REPLACE(([sStudent].[fStudentContactsGet](SF.StudentId))+','+ ISNULL(SC.WhatsAppContactNo,''),' ','')), 1, 1, '')) 
			WHEN LEFT(REPLACE(([sStudent].[fStudentContactsGet](SF.StudentId))+','+ ISNULL(SC.WhatsAppContactNo,''),' ',''), 1) = ',' 
				THEN STUFF(([sStudent].[fStudentContactsGet](SF.StudentId))+','+ ISNULL(SC.WhatsAppContactNo,''),1,1,'')
			ELSE ([sStudent].[fStudentContactsGet](SF.StudentId))+',<br/>'+ ISNULL(SC.WhatsAppContactNo,'') END AS ContactNo,
			--([sStudent].[fStudentContactsGet](SF.StudentId)) AS ContactNo,
			SF.AcademicId,
			SF.StudentId,
			SAS.StudentDataWithMobile,
			SF.OrgId,
			SF.BatchId,
			BM.OrgGroupBatchId,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			ISNULL(SC.ParentEmail,'') AS ParentEmail,
			ISNULL(SI.StudentPhoto,0x) AS StudentPhoto,
			ISNULL(U.Id,0) AS UserId,
			SC.WhatsAppContactNo
			from sStudent.vStudentFull SF
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SF.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
			INNER JOIN sStudent.tStudentMaster SM ON SF.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SF.StudentId	
			LEFT JOIN sStudent.tStudentFamily SFF ON SFF.StudentId = SF.StudentId
			INNER JOIN [sStudent].[vStudentAutoSearch] SAS ON SAS.[AcademicId] = SF.AcademicId AND SAS.BatchId = BM.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SF.StudentId
			LEFT JOIN sSecurity.tUser U ON U.OrgId = OM.Id AND U.SourceId = SF.StudentId AND U.SourceTypeId = 2003
			inner Join #DivisionTemp TempDiv On TempDiv.DivisionId= SF.DivisionId
			
	Where 
		((SF.FirstName like @rFirstName +'%') OR (@rFirstName=''))
		AND ((SF.LastName like @rLastName +'%') OR (@rLastName=''))
		AND ((SM.SUID = @rSUID ) OR (@rSUID=''))
		AND((SF.Code = @rID) OR (@rID=''))
		AND ((BM.OrgGroupBatchId=@rOrgGroupBatch) OR (@rOrgGroupBatch=0))
		AND ((SF.MiddleName like @rMiddleName +'%') OR (@rMiddleName=''))
		AND ((SC.PresentContactNo=@rContactNo) OR (SC.PermanentContactNo=@rContactNo) OR (SC.EmergencyContactNo=@rContactNo) OR (SC.ParentContactNo=@rContactNo) OR (SC.StudentContactNo=@rContactNo) OR (SFF.FatherContactNo=@rContactNo) OR (SFF.MotherContactNo=@rContactNo) OR (@rContactNo=''))
		--AND SF.OrgId=@rOrgId
		AND OM.OrgGroupId=@rOrgGroupId
		AND ((SAS.StudentDataWithMobile like '%'+@rCommonSearch +'%') OR (@rCommonSearch=''))

	DROP TABLE #DivisionTemp

	End
	ELSE
	BEGIN
	 Select 
			 [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			SF.ClassName+'-'+SF.DivisionName As Standard,
			ISNULL(SF.RollNo,0) AS RollNo,
			SF.StatusName,
			BM.Title AS BatchName,
			SF.Code,
			OM.DisplayTitle As Organization,
			ISNULL(SM.SUID,'') AS SUID,
			@SUIDConfig AS SUIDConfig,
			@lIDConfigValue As IDConfigValue,
			CASE 
			WHEN RIGHT(REPLACE(([sStudent].[fStudentContactsGet](SF.StudentId))+','+ ISNULL(SC.WhatsAppContactNo,''),' ',''), 1) = ',' 
				THEN reverse(stuff(reverse(REPLACE(([sStudent].[fStudentContactsGet](SF.StudentId))+','+ ISNULL(SC.WhatsAppContactNo,''),' ','')), 1, 1, '')) 
			WHEN LEFT(REPLACE(([sStudent].[fStudentContactsGet](SF.StudentId))+','+ ISNULL(SC.WhatsAppContactNo,''),' ',''), 1) = ',' 
				THEN STUFF(([sStudent].[fStudentContactsGet](SF.StudentId))+','+ ISNULL(SC.WhatsAppContactNo,''),1,1,'')
			ELSE ([sStudent].[fStudentContactsGet](SF.StudentId))+',<br/>'+ ISNULL(SC.WhatsAppContactNo,'') END AS ContactNo,
			--([sStudent].[fStudentContactsGet](SF.StudentId)) AS ContactNo,
			SF.AcademicId,
			SF.StudentId,
			SAS.StudentDataWithMobile,
			SF.OrgId,
			SF.BatchId,
			BM.OrgGroupBatchId,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			ISNULL(SC.ParentEmail,'') AS ParentEmail,
			ISNULL(SI.StudentPhoto,0x) AS StudentPhoto,
			ISNULL(U.Id,0) AS UserId,
			SC.WhatsAppContactNo
			from sStudent.vStudentFull SF
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=SF.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=SF.OrgId
			INNER JOIN sStudent.tStudentMaster SM ON SF.StudentId=SM.Id
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SF.StudentId	
			LEFT JOIN sStudent.tStudentFamily SFF ON SFF.StudentId = SF.StudentId
			INNER JOIN [sStudent].[vStudentAutoSearch] SAS ON SAS.[AcademicId] = SF.AcademicId AND SAS.BatchId = BM.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SF.StudentId
			LEFT JOIN sSecurity.tUser U ON U.OrgId = OM.Id AND U.SourceId = SF.StudentId AND U.SourceTypeId = 2003
	Where 
		((SF.FirstName like @rFirstName +'%') OR (@rFirstName=''))
		AND ((SF.LastName like @rLastName +'%') OR (@rLastName=''))
		AND ((SM.SUID = @rSUID ) OR (@rSUID=''))
		AND((SF.Code = @rID) OR (@rID=''))
		AND ((BM.OrgGroupBatchId=@rOrgGroupBatch) OR (@rOrgGroupBatch=0))
		AND ((SF.MiddleName like @rMiddleName +'%') OR (@rMiddleName=''))
		AND ((SC.PresentContactNo=@rContactNo) OR (SC.PermanentContactNo=@rContactNo) OR (SC.EmergencyContactNo=@rContactNo) OR (SC.ParentContactNo=@rContactNo) OR (SC.StudentContactNo=@rContactNo) OR (SFF.FatherContactNo=@rContactNo) OR (SFF.MotherContactNo=@rContactNo) OR (@rContactNo=''))
		--AND SF.OrgId=@rOrgId
		AND OM.OrgGroupId=@rOrgGroupId
		AND ((SAS.StudentDataWithMobile like '%'+@rCommonSearch +'%') OR (@rCommonSearch=''))
	END
END
GO
PRINT N'Altering [sStudent].[pStudentLastAcademicGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentLastAcademicGet]
	 
	 @rCode nvarchar(20),
	 @rOrgId int,
	 @rNumber bigint,
	-- @rBatchId int,
	 @rStudentId bigint,
	 @rSUID  nvarchar(50)
	 --@rIsSearch bit
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 

	DECLARE @lAcademicId bigint
	DECLARE @lIsAdmissionCategoryChange bit
	SET @lIsAdmissionCategoryChange=1
	SELECT @lAcademicId=AcademicId FROM sStudent.vStudentLastAcademic SA 
	WHERE 
			((SA.Code=@rCode)OR(ISNULL(@rCode,'')=''))
			AND ((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND SA.OrgId=@rOrgId
			--AND(SA.BatchId=@rBatchId
			
			
	IF(ISNULL(@lAcademicId,0) != 0)
	BEGIN
		IF EXISTS (SELECT 1 FROM sFee.tFeeAllocation WHERE SourceTypeId=2001 AND SourceId=@lAcademicId)
		BEGIN
			SET @lIsAdmissionCategoryChange=0
		END
		ELSE IF EXISTS (SELECT 1 FROM sFee.tFeeOptional WHERE SourceTypeId=2001 AND SourceId=@lAcademicId)
		BEGIN
			SET @lIsAdmissionCategoryChange=0
		END
		ELSE IF EXISTS (SELECT 1 FROM sFee.tReceipt WHERE SourceTypeId=2001 AND SourceId=@lAcademicId)
		BEGIN
			SET @lIsAdmissionCategoryChange=0
		END
	END	
			
	 
	SELECT 
			SA.StudentId AS Id,
			ISNULL(SA.Code,'') AS Code,
			ISNULL(SA.Number,0)AS Number,
			ISNULL(SA.RegistrationNumber,'') AS RegistrationNumber,
			SA.FirstName,
			ISNULL(SA.MiddleName,'')AS MiddleName,
			SA.LastName,
			SA.OrgId,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.StatusId,
			SA.RecordStatusId,
			SA.Name AS Name,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.BatchId,
			--SA.DateOfBirth,
			ISNULL(SO.GenderId,0) AS GenderId,
			SA.ClassName+'-'+SA.DivisionName AS ClassDiv,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			@lIsAdmissionCategoryChange AS IsAdmissionCategoryChange,
			SA.SUId,
			ISNULL(AD.RepeatCount,1) AS RepeatCount
  FROM 
           sStudent.vStudentLastAcademic SA
     LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
     LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicID = SA.AcademicId
  WHERE 
 
			((SA.Code=@rCode)OR(ISNULL(@rCode,'')=''))
			AND ((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.Number=@rNumber) OR (@rNumber=0))
			AND(SA.OrgId=@rOrgId)
			AND ((SA.SUId=@rSUID)OR(ISNULL(@rSUID,'')=''))
			--AND(SA.BatchId=@rBatchId)
END
GO
PRINT N'Altering [sStudent].[pStudentLeaveListingGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentLeaveListingGet]
(  
	@rOrgId int,  
    --@rId bigint = 0, 
	@rAcademicId bigint=0,
    @rStudentId  bigint=0,     
    @rFromDate date='',   
    @rTodate date='',  
    @rOrgGroupBatchId int=0,  
    @rStudentCode nvarchar(100)='',  
    @rStudentName nvarchar(100)='',  
    @rStatusId int = 0,  
	@rClassId int =0,
    @rOrgGroupId int=0,  
    --@rIsSearchLeaveHierarchyWise int = 0,  
    --@rDepartmentId int,	
	@rDivisionId bigint=0,
	@rUserId bigint = 0

 )  
AS  
SET NOCOUNT ON  
IF(@rUserId=0)
BEGIN
 SELECT   
  ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
		L.AcademicId AS AcademicId,  
      SA.[StudentId],  
      L.CreatedDateTime AS ReportDate,  
      L.[LeaveFromDate] AS FromDate,  
      L.[LeaveToDate] AS ToDate,  
     ISNULL(L.LeaveReason,'') as LeaveReason,  
      --EM.EmployeeName,  
	  SA.Name AS StudentName,
      SA.Code AS StudentCode,  
      DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
      ISNULL(L.StatusId,0) AS StatusId,  
      ISNULL(SM.Title,'Pending') AS StatusName,  
      ISNULL(L.StatusReason,'') AS  StatusReason,  
      OM.DisplayTitle AS OrganizationName,  
      ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
      CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
      ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
      OM.Id AS OrgId,  
      SA.BatchId AS BatchId, 
	  SA.DivisionId,
	  SA.DivisionName,
	  SA.ClassId,
	  SA.ClassName, 
      SA.DepartmentId AS DepartmentId,  
      SA.DepartmentName As DepartmentName
	  --US.Id As UserId
  FROM   
      sAttendance.tStudentLeaveRequest L   
      INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
      INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
      LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
     --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
	  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
	 -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017     

  WHERE   
      ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
      AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
	  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
	  AND (SA.ClassId=@rClassId OR @rClassId=0)
	  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
	  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
      AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
      AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
      AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
      AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
      --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
	  AND ISNULL(EMP.IsOtherUser,0)=0 
	  
	 -- AND U.UserId = @rUserId     
  ORDER BY   
      L.CreatedDateTime DESC  
END
ELSE
BEGIN       
  SELECT   
  ROW_NUMBER() OVER(ORDER BY L.CreatedDateTime desc) AS Id,
		L.AcademicId AS AcademicId,  
      SA.[StudentId],  
      L.CreatedDateTime AS ReportDate,  
      L.[LeaveFromDate] AS FromDate,  
      L.[LeaveToDate] AS ToDate,  
     ISNULL(L.LeaveReason,'') as LeaveReason,  
      --EM.EmployeeName,  
	  SA.Name AS StudentName,
      SA.Code AS StudentCode,  
      DATEDIFF(day,L.LeaveFromDate, L.LeaveToDate)+1 AS NoOfLeave,  
      ISNULL(L.StatusId,0) AS StatusId,  
      ISNULL(SM.Title,'Pending') AS StatusName,  
      ISNULL(L.StatusReason,'') AS  StatusReason,  
      OM.DisplayTitle AS OrganizationName,  
      ISNULL(L.ActionByEmployeeId,'') as ActionByEmployeeId,  
      CASE WHEN ISNULL(L.ActionByEmployeeId,0) = 0 AND ISNULL(L.StatusId,549) = 549 THEN '' 	  
      ELSE EMP.FirstName + ' ' + EMP.LastName END AS ActionByEmployee,  
      OM.Id AS OrgId,  
      SA.BatchId AS BatchId, 
	  SA.DivisionId,
	  SA.DivisionName,
	  SA.ClassId,
	  SA.ClassName, 
      SA.DepartmentId AS DepartmentId,  
      SA.DepartmentName As DepartmentName
	  --US.Id As UserId
  FROM   
      sAttendance.tStudentLeaveRequest L   
      INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = L.AcademicId  
      INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId    
      INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId  
      LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId  
      --LEFT JOIN sSecurity.tUser US ON US.Id = L.CreatedUserId 
	  LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = L.ActionByEmployeeId AND ISNULL(EMP.IsOtherUser,0)=0 
	  -- INNER JOIN sSecurity.tUserAccess U ON U.SourceId = EM.DepartmentId AND U.SourceTypeId=2017   
	  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=OM.Id  

  WHERE   
      ((L.LeaveFromDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
      AND ((L.LeaveFromDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))         
      AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
	  AND (SA.DivisionId=@rDivisionId OR @rDivisionId=0)
	  AND (SA.ClassId=@rClassId OR @rClassId=0)
	  AND (SA.[StudentId]=@rStudentId or ISNULL(@rStudentId,0)=0)
	  And(SA.[AcademicId]=@rAcademicId or ISNULL(@rAcademicId,0)=0)
      AND ((SA.OrgId = @rOrgId) OR (@rOrgId = 0))  
      AND (SA.Code = @rStudentCode OR ISNULL(@rStudentCode,'') = '')  
      AND (SA.Name like @rStudentName+'%' OR ISNULL(@rStudentName,'') = '')  
      AND (ISNULL(L.StatusId,0) = @rStatusId OR (@rStatusId = 0 OR (@rStatusId=549 AND  ISNULL(L.StatusId,0)=0))) 
      --AND ((SA.DepartmentId = @rDepartmentId ) OR (@rDepartmentId = 0)) 
	  AND ISNULL(EMP.IsOtherUser,0)=0 
	  AND UO.UserId = @rUserId 
	  
	 -- AND U.UserId = @rUserId     
  ORDER BY   
      L.CreatedDateTime DESC        
END
GO
PRINT N'Altering [sStudent].[pStudentMasterAdd]...';


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

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

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

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

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

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


GO
ALTER PROCEDURE [sStudent].[pStudentSearchGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rMiddleName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rDepartmentId int,
	@rSUId nvarchar(50)='',
	@rUserId bigint=0,
	@rMultiCode nvarchar(max)='',
	@rClassStatusId smallint=0,
	@rContactNo nvarchar(50) = ''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
	BEGIN
		SET @rCode= sCommon.fSearchStringGet(@rCode)
		SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
		SET @rMiddleName = sCommon.fSearchStringGet(@rMiddleName)
		SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	END
 IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.MiddleName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo ,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			ISNULL(SA.SUId,'') AS SUId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.ClassStatusId,
			SA.ClassStatusName
  FROM 
            sStudent.vStudentAcademic SA
            INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
  WHERE 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SA.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = '')) 
			AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
			AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
			AND (OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			AND(SA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
			AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
			AND U.UserId = @rUserId
		    AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='') 
			AND((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
			AND ((SC.PresentContactNo=@rContactNo) OR (SC.PermanentContactNo=@rContactNo) OR (SC.EmergencyContactNo=@rContactNo) OR (SC.ParentContactNo=@rContactNo) OR (SC.StudentContactNo=@rContactNo) OR (SF.FatherContactNo=@rContactNo) OR (SF.MotherContactNo=@rContactNo) OR (@rContactNo=''))
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.MiddleName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			ISNULL(SA.SUId,'') AS SUId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.ClassStatusId,
			SA.ClassStatusName
  FROM 
          sStudent.vStudentAcademic SA             
          INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
		  LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
		  LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
  WHERE 
                    
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.MiddleName like @rMiddleName) OR (ISNULL(@rMiddleName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND ( OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		AND(SA.DepartmentId=@rDepartmentId or @rDepartmentId = 0)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='') 
		AND((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		--AND(SA.BatchId=@rBatchId)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND ((SC.PresentContactNo=@rContactNo) OR (SC.PermanentContactNo=@rContactNo) OR (SC.EmergencyContactNo=@rContactNo) OR (SC.ParentContactno=@rContactNo) OR (SC.StudentContactNo=@rContactNo) OR (SF.FatherContactNo=@rContactNo) OR (SF.MotherContactNo=@rContactNo) OR (@rContactNo=''))

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
		
END
GO
PRINT N'Altering [sStudent].[pStudentSearchWithPhotoGet]...';


GO
ALTER PROCEDURE [sStudent].[pStudentSearchWithPhotoGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int,
    @rSUId nvarchar(50)='',
    @rUserId bigint=0,
	@rClassStatusId smallint = 0,
	@rContactNo nvarchar(50) = ''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			ISNULL(SA.SUId,'') AS SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			SA.ClassStatusId,
			SA.ClassStatusName
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
	   LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
	   LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		--AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		AND ((SC.PresentContactNo=@rContactNo) OR (SC.PermanentContactNo=@rContactNo) OR (SC.EmergencyContactNo=@rContactNo) OR (SC.ParentContactNo=@rContactNo) OR (SC.StudentContactNo=@rContactNo) OR (SF.FatherContactNo=@rContactNo) OR (SF.MotherContactNo=@rContactNo) OR (@rContactNo=''))
ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			ISNULL(SA.SUId,'') AS SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			SA.ClassStatusId,
			SA.ClassStatusName
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
	   LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
	   LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)	
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND((SA.ClassStatusId=@rClassStatusId)OR(@rClassStatusId=0))
		--AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND ((SC.PresentContactNo=@rContactNo) OR (SC.PermanentContactNo=@rContactNo) OR (SC.EmergencyContactNo=@rContactNo) OR (SC.ParentContactno=@rContactNo) OR (SC.StudentContactNo=@rContactNo) OR (SF.FatherContactNo=@rContactNo) OR (SF.MotherContactNo=@rContactNo) OR (@rContactNo=''))

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
  
		
END
GO
PRINT N'Altering [sStudent].[pSUIDGenerationUpdate]...';


GO
ALTER PROCEDURE [sStudent].[pSUIDGenerationUpdate]
	 
	@rStudentId bigint,
	@rSUId nvarchar(50),
	@rCreatedUserId bigint,
	@rOrgGroupId smallint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lSUId nvarchar(50)

	SELECT @lSUId=SUId FROM sStudent.tStudentMaster SM
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId	 
	WHERE SM.SUId=@rSUId AND OM.OrgGroupId=@rOrgGroupId 
	AND SM.Id<>@rStudentId 
	AND SM.Id NOT IN (SELECT ReferenceSourceId FROM sStudent.tStudentMaster S WHERE S.Id = @rStudentId AND ReferenceSourceId IS NOT NULL)
	--AND SM.ReferenceSourceId <> @rStudentId  

	IF @lSUId IS NOT NULL
	BEGIN
		SELECT -103 AS Result,@lSUId AS SUId
		RETURN
	END 
	
	BEGIN TRY
	 BEGIN TRANSACTION	
	 BEGIN
	    UPDATE  sStudent.tStudentMaster
	    SET
		    SUId=@rSUId,
			RecordStatusId = 501,				  
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      WHERE Id = @rStudentId 	   
	 END  
		SELECT 1 AS RESULT
		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS RESULT
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pUploadStudentDocument]...';


GO
ALTER PROCEDURE [sStudent].[pUploadStudentDocument]
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int,
    @rSUId nvarchar(50)='',
    @rUserId bigint=0,
    @rMultiCode nvarchar(max)='',
    @rDocumentMasterId int =0
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			ISNULL(SD.SubmitDocumentMasterId,'') AS DocumentId,
			ISNULL(SD.DocumentName,'') AS DocumentName
			
			
			
  FROM 
          sStudent.vStudentAcademic SA
          LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId = SA.StudentId
      -- LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND((SD.SubmitDocumentMasterId=@rDocumentMasterId)OR(@rDocumentMasterId=0))
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			ISNULL(SD.SubmitDocumentMasterId,'') AS DocumentId,
			ISNULL(DocumentName,'') AS DocumentName
			
  FROM 
          sStudent.vStudentAcademic SA
          LEFT JOIN sStudent.tStudentDocument SD ON SD.StudentId = SA.StudentId
       --LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)	
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND((SD.SubmitDocumentMasterId=@rDocumentMasterId)OR(@rDocumentMasterId=0))
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
  
	
END
GO
PRINT N'Altering [sStudent].[pUploadStudentPhotoClassWise]...';


GO
ALTER PROCEDURE [sStudent].[pUploadStudentPhotoClassWise]
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int,
    @rSUId nvarchar(50)='',
    @rUserId bigint=0,
    @rMultiCode nvarchar(max)=''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		BEGIN
			SET @rCode= sCommon.fSearchStringGet(@rCode)
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
	IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			ISNULL(SA.Number,0) AS Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
			ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
			ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			ISNULL(SI.QRCode, CONVERT(VARBINARY(MAX),0)) AS QRCode
			
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			SA.SUId,
			ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
			ISNULL(SI.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
			ISNULL(SI.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
			ISNULL(SI.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			ISNULL(SI.QRCode, CONVERT(VARBINARY(MAX),0)) AS QRCode
			
  FROM 
          sStudent.vStudentAcademic SA
       LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SA.StudentId
       INNER JOIN sSecurity.tUserAccess U ON U.SourceId = SA.DivisionId AND U.SourceTypeId=2005
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)	
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId)
		AND(SA.BatchId=@rBatchId)
		AND((SA.SUID = @rSUId) OR (ISNULL(@rSUId,'') = '')) 
		AND U.UserId = @rUserId
		AND (ISNULL(SA.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
  
	
END
GO
PRINT N'Altering [sStudent].[pUserControlStudentLastAcademicSearchGet]...';


GO
ALTER PROCEDURE [sStudent].[pUserControlStudentLastAcademicSearchGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rSUId nvarchar(50)=''
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
 IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.BatchId,
			SA.SUId
  FROM 
          sStudent.vStudentLastAcademic SA
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
		AND ( OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))	

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId 
  FROM 
          sStudent.vStudentLastAcademic SA             
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND ( OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND(SA.BatchId=@rBatchId)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
		
END
GO
PRINT N'Altering [sStudent].[pUserControlStudentSearchGet]...';


GO
ALTER PROCEDURE [sStudent].[pUserControlStudentSearchGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rSUId nvarchar(50)=''
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
BEGIN
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
END
	
	DECLARE @lOrgGroupId int=0
	DECLARE @lConfigValue nvarchar(50)
	DECLARE @lIsInContext bit=0

	SELECT @lOrgGroupId = OGBM.OrgGroupId FROM sSetup.tBatchMaster BM INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id = BM.OrgGroupBatchId WHERE BM.Id=@rBatchId
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 480 AND SourceTypeId = 2010 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	SET @lIsInContext = 1
	ELSE
	SET @lIsInContext = 0	

 IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.BatchId,
			SA.SUId,
			ISNULL(So.GenderId,0) AS GenderId,
			ISNULL(SC.ParentContactNo,'') AS ParentContactNo
	
  FROM 
            sStudent.vStudentAcademic SA
            LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND SA.OrgGroupBatchId = BM.OrgGroupBatchId
			LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
  WHERE 
 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
			AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			--AND((SA.Number=@rNumber)OR(@rNumber=0))	
			AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
			AND BM.IsInContext = @lIsInContext

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,
			SA.SUId,
			ISNULL(So.GenderId,0) AS GenderId
			
  FROM 
            sStudent.vStudentAcademic SA    
            LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId       
            INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId AND SA.OrgGroupBatchId = BM.OrgGroupBatchId  
  WHERE 
 
			((SA.ClassId=@rClassId)OR(@rClassId=0))
			AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
			AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
			AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
			AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
			AND(SA.RollNo=@rRollNo)
			AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
			AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
			AND(SA.BatchId=@rBatchId or @rBatchId = 0)
			--AND(SA.BatchId=@rBatchId)
			--AND((SA.Number=@rNumber)OR(@rNumber=0))
			AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 
			AND BM.IsInContext = @lIsInContext

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
		
END
GO
PRINT N'Altering [sStudent].[pValidateImportStudent]...';


GO
ALTER PROCEDURE [sStudent].[pValidateImportStudent]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rOperation int=0,   --1 For Insert,2 For Update
	@rBatchId int=0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
DECLARE @lSUIdActivate nvarchar(50)=''
DECLARE @lIsSurnameAndFatherNameMandatory 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
SELECT @lIsSurnameAndFatherNameMandatory =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 415 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(50),
        @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),
		MiddleName 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(50),
        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,
		MiddleName,
	    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(MiddleName) AS MiddleName,
	    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',
		MiddleName nvarchar(100) '@MiddleName',
        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(50) '@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(@rOperation=2)
   	      BEGIN
   			  DECLARE @lExistingClassId int
   			  DECLARE @lExcelClassId int
   			  SET @lExistingClassId=(SELECT ClassId From sStudent.tAcademic WHERE StudentId=@1StudentId AND BatchId=@rBatchId)
	   		
   			  SET @lExcelClassId=(select Id from sSetup.tClassMaster where Title=@lClass and OrgId=@rOrgId)
	   		  
   			  IF(@lExcelClassId<>@lExistingClassId)
   		       BEGIN
				  SELECT 'Class Id not match/update.' AS StudentCode
			   END
   			
   	      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
		
		ELSE IF (@lIsSurnameAndFatherNameMandatory = 'True' )
		BEGIN
			IF EXISTS(SELECT 1 fROM #tTable1 WHERE MiddleName IS NULL OR MiddleName COLLATE DATABASE_DEFAULT='' COLLATE DATABASE_DEFAULT)
			BEGIN
				SELECT 'FatherName Should not be empty' AS StudentCode
			END
			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 
			BEGIN
				SELECT '' AS StudentCode
			END
						
		END



		END
		END
END
GO
PRINT N'Altering [sStudent].[pValidateImportStudent_New]...';


GO
ALTER PROCEDURE [sStudent].[pValidateImportStudent_New]

	@rOrgGroupId int,
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rOperation int=0,   --1 For Insert,2 For Update
	@rBatchId int=0
	
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(50),
        @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(50),
        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(50) '@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(@rOperation=2)
   	      BEGIN
   			  DECLARE @lExistingClassId int
   			  DECLARE @lExcelClassId int
   			  SET @lExistingClassId=(SELECT ClassId From sStudent.tAcademic WHERE StudentId=@1StudentId AND BatchId=@rBatchId)
	   		
   			  SET @lExcelClassId=(select Id from sSetup.tClassMaster where Title=@lClass and OrgId=@rOrgId)
	   		  
   			  IF(@lExcelClassId<>@lExistingClassId)
   		       BEGIN
				  SELECT 'Class Id not match/update.' AS StudentCode
			   END
   			
   	      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'Altering [sStudent].[pXMLAcademicImportAdd]...';


GO
ALTER PROCEDURE [sStudent].[pXMLAcademicImportAdd]
	
	@rStudentImpXml [nvarchar](max),
	@rToOrgId int,
	@rToBatchId int,
	@rToClassId int,
	@rToDivisionId int,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStudentImpXml
BEGIN

Declare @rOrgGroupId int,@rOrgGroupBatchId int
Select @rOrgGroupId=OrgGroupId from [sSetup].[tOrganizationMaster] Where Id=@rToOrgId

Select @rOrgGroupBatchId= OrgGroupBatchId from [sSetup].[tBatchMaster] Where Id=@rToBatchId

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
				Return
				
			END


DECLARE @lToClassId int 
DECLARE @lToOrgId int
SELECT @lToClassId = ClassId,@lToOrgId = OrgId FROM sSetup.tDivisionMaster WHERE Id = @rToDivisionId
 
 
 IF (@lToOrgId <> @rToOrgId )
 BEGIN
 SELECT 'Org Not Matching, Contact Administrator'
		RETURN
 END
 
 
Declare @lExistCode nvarchar(max)
 
	IF EXISTS(SELECT SM.Code
	from
	(
			SELECT StudentId FROM
			OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
			WITH (
					StudentId bigint)	
	)E
	INNER JOIN sStudent.tStudentMaster SM ON SM.Id=E.StudentId AND SM.OrgId=@rToOrgId
	INNER JOIN sStudent.tAcademic A ON A.StudentId=SM.Id AND A.BatchId=@rToBatchId)
	BEGIN
		SELECT @lExistCode  = COALESCE(@lExistCode ,'') + CONVERT(VARCHAR(15),SM.Code) + ' , ' 
		from
		(
				SELECT StudentId FROM
				OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				WITH (
						StudentId bigint)	
		)E
		INNER JOIN sStudent.tStudentMaster SM ON SM.Id=E.StudentId AND SM.OrgId=@rToOrgId
		INNER JOIN sStudent.tAcademic A ON A.StudentId=SM.Id AND A.BatchId=@rToBatchId
		SELECT @lExistCode
	 	RETURN
	END
	
	BEGIN TRY
	BEGIN TRANSACTION
	DECLARE @lCount INT
	DECLARE @lNextNumber BIGINT 
	
	EXECUTE sCommon.pTableRowIdGet @rToOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output
 
	 INSERT INTO sStudent.tAcademic
		(
			Id,
			StudentId,
			ClassId,
			BatchId,
			DivisionId,
			RollNo,
			OrgId,
			CreatedUserId,
			CreatedDateTime,
			IsCurrent,
			ExemptionTypeId,
			FeeStructureId,
			AdmissionCategoryId,
			ClassStatusId
			)
		SELECT
		
			@lNextNumber+ ROW_NUMBER() OVER(ORDER BY StudentId),
			StudentId,
			@lToClassId,
			@rToBatchId,
			@rToDivisionId,
			ISNULL(RollNo,0),
			@rToOrgId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			1,
			ExemptionTypeId,
			FeeStructureId,
			AdmissionCategoryId,
			1
		FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
		WITH ( 
				StudentId bigint,
				ExemptionTypeId int,
				FeeStructureId int,
				AdmissionCategoryId int,
				RollNo int
			  ) 
			  --B INNER JOIN sStudent.tAcademic A ON B.StudentId = A.StudentId AND A.BatchId = 
		
		SELECT @lCount = COUNT(1) FROM OPENXML (@loDoc, '/Table/StudentImportDetail', 1)
				 WITH ( Id int )
		SET @lNextNumber  = @lCount + @lNextNumber 
		
		EXECUTE sCommon.pTableRowIdModify @rToOrgId, @rTableTitle = 'sStudent.tAcademic', @rCurrentNumber = @lNextNumber 
	    SELECT 1 AS Result
	    
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sTransport].[pAssignRouteGet]...';


GO
ALTER PROCEDURE [sTransport].[pAssignRouteGet]
           
	   @rClassId int = 0,
	   @rDivisionId int = 0,
	   @rBusRouteId int = 0,
	   @rBusRouteDestinationId int = 0,
	   @rBusRouteDestination nvarchar(100) = '',
	   @rOrgId int = 0,
	   @rStudentName nvarchar(100) = '',
	   @rStudentCode nvarchar(100) = '',
	   @rOrgGroupBatchId int,
	   @rStudentId bigint = 0,
	   @rTransportId int = 0,
	   @rSUID nvarchar(50) = '',
	   @rStrStudentCode nvarchar(100) = '',
	   @rOldDropRouteId int = 0 ,
	   @rOldDropDestinationId int  = 0
AS
SET NOCOUNT ON

BEGIN
		SET @rBusRouteDestination = sCommon.fSearchStringGet(@rBusRouteDestination)
SELECT  
		A.StudentId as SourceId,
		A.Code,
		A.Name as Name,
		--SM.FirstName+' '+SM.LastName as Name,
		--[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
		CM.Title+'-'+DM.Title as ClassDivisionName,
		ISNULL(V.BusRouteId,0) AS BusRouteId,
		ISNULL(V.BusRouteDestinationId,0) AS BusRouteDestinationId,
		ISNULL(V.DropRouteId,0) AS DropRouteId,
		ISNULL(V.DropDestinationId,0) AS DropDestinationId,
		O.DisplayTitle AS Organization,
		SC.PresentStreetOne+' '+ SC.PresentStreetTwo+' '+SC.PresentStreetThree+' '+SC.PresentCity AS StudentAddress ,
		ISNULL(A.SUId,'') AS SUId,
		ISNULL(V.Pickuppoint,'') As Pickuppoint,
		Isnull(V.Droppoint,'') As Droppoint,
		ISNULL(V.BusRoute,'') AS BusRoute, 
		A.OrgId,
		REPLACE(V.AdmissionDate,'1900-01-01','')AS AdmissionDate,
		REPLACE(V.LeaveDate,'1900-01-01','') AS LeaveDate,
		ISNULL(V.PickupRoute,'') As PickupRoute,
		Isnull(V.DropRoute,'') As DropRoute
  FROM 
		sStudent.vStudentAcademic A 
		--sStudent.tAcademic A
	 --  INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id AND SM.StatusId=1
	   LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	   INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
       LEFT JOIN 
	  (SElect AR.Sourceid ,ISNULL(BRDM.BusRouteId,0)AS BusRouteId,
			ISNULL(BRDM2.BusRouteId,0)AS DropBusRouteId,
			ISNULL(AR.PickupDestinationId,0) AS BusRouteDestinationId,
			ISNULL(BRDM2.BusRouteId,0)AS DropRouteId,
			ISNULL(AR.DropDestinationId,0) AS DropDestinationId,
			ISNULL(BRM.Title,'') AS PickupRoute,
			ISNULL(BRM2.Title,'') AS DropRoute,
			Isnull(BRDM.Title,'') AS Pickuppoint,
			Isnull(BRDM2.Title,'') AS Droppoint, BRM.Title AS BusRoute,
			ISNULL(AR.AdmissionDate,'')AS AdmissionDate,
			ISNULL(AR.LeaveDate,'')AS LeaveDate FROM sTransport.tAssignRoute AR
			 INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			 INNER JOIN sTransport.tBusRouteMaster BRM On BRm.id=BRDM.BusRouteId AnD BRM.OrgGroupBatchId=@rOrgGroupBatchId
			 LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AR.DropDestinationId	
			 LEFT JOIN sTransport.tBusRouteMaster BRM2 On BRM2.Id=BRDM2.BusRouteId AND BRM2.OrgGroupBatchId=@rOrgGroupBatchId
	 WHERE 
		 ((BRDM.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) OR (BRDM2.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0))
		 AND (BRDM.BusRouteId=@rBusRouteId OR @rBusRouteId=0)

     	AND (BRDM2.Id=@rOldDropDestinationId OR @rOldDropDestinationId=0)
		AND (BRDM2.BusRouteId=@rOldDropRouteId OR @rOldDropRouteId=0)


		--AND (BRDM2.BusRouteId=@rBusRouteId OR @rBusRouteId=0)
		AND (BRDM.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
		AND (BRDM2.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')	
	    AND BRM.TransportId=@rTransportId ) V  ON V.SourceId=A.StudentId 
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId AND BM.OrgGroupBatchId = A.OrgGroupBatchId
	--AND BM.IsActive = 1
	  INNER JOIN sSetup.tOrgGroupBatchMaster OB ON BM.OrgGroupBatchId = ob.iD
	  INNER JOIN sSetup.tOrganizationMaster O ON O.id = BM.OrgId AND O.OrgGroupId = OB.OrgGroupId
	--and bM.OrgGroupBatchId = ob.id
	
  WHERE 
		(A.ClassId=@rClassId OR @rClassId=0)
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	--AND (BRDM.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
	--AND (BRDM2.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0)
	  AND (V.BusRouteId=@rBusRouteId OR @rBusRouteId=0) 
	  AND (V.DropBusRouteId=@rOldDropRouteId OR @rOldDropRouteId=0) 
	--AND (BRDM2.BusRouteId=@rBusRouteId OR @rBusRouteId=0)
	--AND (BRDM.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	--AND (BRDM2.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	
	  AND ((V.BusRouteDestinationId=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
	  OR (V.DropDestinationId=@rBusRouteDestinationId OR @rBusRouteDestinationId=0))

	  AND ((V.DropDestinationId=@rOldDropDestinationId OR @rOldDropDestinationId=0))

	  --AND (V.DropRouteId=@rBusRouteId OR @rBusRouteId=0)
	  AND (V.Pickuppoint Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	  AND (V.Droppoint Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	
	 --AND (A.StudentId = @rStudentId OR ISNULL(@rStudentId,0) = 0)
	 AND (A.Code = @rStudentCode  OR ISNULL(@rStudentCode,'')='')
	--AND ((SM.FirstName + ' ' + SM.LastName) like @rStudentName + '%' OR ISNULL(@rStudentName,'') = '')	
	 AND (A.OrgId = @rOrgId OR @rOrgId = 0)
	--AND (OB.Id=@rOrgGroupBatchId)
	AND(A.OrgId in (select OrgId from sTransport.tAssignTransportOrg where TransportId = @rTransportId))
	AND (A.SUId = @rSUID  OR ISNULL(@rSUID,'')='')
	AND BM.OrgGroupBatchId=@rOrgGroupBatchId
	AND A.StatusId = 1
	AND (A.Code IN (SELECT item from sCommon.fnSplit(@rStrStudentCode,',')) OR @rStrStudentCode = '')
	--AND BM.IsInContext = 1
END
GO
PRINT N'Altering [sTransport].[pPickUpWIseRouteGet]...';


GO
ALTER PROCEDURE [sTransport].[pPickUpWIseRouteGet]
           
	   @rClassId int = 0,
	   @rDivisionId int = 0,
	   @rBusRouteId int = 0,
	   @rBusRouteDestinationId int = 0,
	   @rBusRouteDestination nvarchar(100) = '',
	   @rOrgId int = 0,
	   @rStudentName nvarchar(100) = '',
	   @rStudentCode nvarchar(100) = '',
	   @rOrgGroupBatchId int,
	   @rStudentId bigint = 0,
	   @rTransportId int = 0,
	   @rSUID nvarchar(50) = '',
	   @rStrStudentCode nvarchar(100) = ''
AS
SET NOCOUNT ON

BEGIN
		SET @rBusRouteDestination = sCommon.fSearchStringGet(@rBusRouteDestination)
SELECT  
		A.StudentId as SourceId,
		A.Code,
		A.Name as Name,
		--SM.FirstName+' '+SM.LastName as Name,
		--[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
		CM.Title+'-'+DM.Title as ClassDivisionName,
		ISNULL(V.BusRouteId,0) AS BusRouteId,
		ISNULL(V.BusRouteDestinationId,0) AS BusRouteDestinationId,
		ISNULL(V.DropRouteId,0) AS DropRouteId,
		ISNULL(V.DropDestinationId,0) AS DropDestinationId,
		O.DisplayTitle AS Organization,
		SC.PresentStreetOne+' '+ SC.PresentStreetTwo+' '+SC.PresentStreetThree+' '+SC.PresentCity AS StudentAddress ,
		ISNULL(A.SUId,'') AS SUId,
		ISNULL(V.Pickuppoint,'') As Pickuppoint,
		Isnull(V.Droppoint,'') As Droppoint,
		ISNULL(V.BusRoute,'') AS BusRoute, 
		A.OrgId
		
  FROM 
		sStudent.vStudentAcademic A 
		--sStudent.tAcademic A
	 --  INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id AND SM.StatusId=1
	   LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
	   INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	   INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
       LEFT JOIN 
	  (SElect AR.Sourceid ,ISNULL(BRDM.BusRouteId,0)AS BusRouteId,
			ISNULL(AR.PickupDestinationId,0) AS BusRouteDestinationId,
			ISNULL(BRDM2.BusRouteId,0)AS DropRouteId,
			ISNULL(AR.DropDestinationId,0) AS DropDestinationId,
			Isnull(BRDM.Title,'') AS Pickuppoint,
			Isnull(BRDM2.Title,'') AS Droppoint, BRM.Title AS BusRoute FROM sTransport.tAssignRoute AR
			 INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
			 INNER JOIN sTransport.tBusRouteMaster BRM On BRm.id=BRDM.BusRouteId AnD BRM.OrgGroupBatchId=@rOrgGroupBatchId
			 LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AR.DropDestinationId	
			 LEFT JOIN sTransport.tBusRouteMaster BRM2 On BRM2.Id=BRDM2.BusRouteId AND BRM2.OrgGroupBatchId=@rOrgGroupBatchId
	 WHERE 
		 ((BRDM.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
		OR (BRDM2.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0))
		AND (BRDM.BusRouteId=@rBusRouteId OR @rBusRouteId=0) 
		--AND (BRDM2.BusRouteId=@rBusRouteId OR @rBusRouteId=0)
		AND (BRDM.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
		--AND (BRDM2.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')	
	    AND BRM.TransportId=@rTransportId ) V  ON V.SourceId=A.StudentId 
	   INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId AND BM.OrgGroupBatchId = A.OrgGroupBatchId
	--AND BM.IsActive = 1
	  INNER JOIN sSetup.tOrgGroupBatchMaster OB ON BM.OrgGroupBatchId = ob.iD
	  INNER JOIN sSetup.tOrganizationMaster O ON O.id = BM.OrgId AND O.OrgGroupId = OB.OrgGroupId
	--and bM.OrgGroupBatchId = ob.id
	
  WHERE 
		(A.ClassId=@rClassId OR @rClassId=0)
	AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
	--AND (BRDM.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
	--AND (BRDM2.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0)
	  AND (V.BusRouteId=@rBusRouteId OR @rBusRouteId=0) 
	--AND (BRDM2.BusRouteId=@rBusRouteId OR @rBusRouteId=0)
	--AND (BRDM.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	--AND (BRDM2.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	
	  AND ((V.BusRouteDestinationId=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) 
	  OR (V.DropDestinationId=@rBusRouteDestinationId OR @rBusRouteDestinationId=0))
	  --AND (V.DropRouteId=@rBusRouteId OR @rBusRouteId=0)
	  AND (V.Pickuppoint Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	 -- AND (V.Droppoint Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '')
	
	 --AND (A.StudentId = @rStudentId OR ISNULL(@rStudentId,0) = 0)
	 AND (A.Code = @rStudentCode  OR ISNULL(@rStudentCode,'')='')
	--AND ((SM.FirstName + ' ' + SM.LastName) like @rStudentName + '%' OR ISNULL(@rStudentName,'') = '')	
	 AND (A.OrgId = @rOrgId OR @rOrgId = 0)
	--AND (OB.Id=@rOrgGroupBatchId)
	AND(A.OrgId in (select OrgId from sTransport.tAssignTransportOrg where TransportId = @rTransportId))
	AND (A.SUId = @rSUID  OR ISNULL(@rSUID,'')='')
	AND BM.OrgGroupBatchId=@rOrgGroupBatchId
	AND A.StatusId = 1
	AND (A.Code IN (SELECT item from sCommon.fnSplit(@rStrStudentCode,',')) OR @rStrStudentCode = '')
	AND BM.IsInContext = 1
END
GO
PRINT N'Altering [sTransport].[pTransportStudentList]...';


GO
ALTER PROCEDURE [sTransport].[pTransportStudentList]
           
	 @rOrgId int,	 
	 @rTransportId int,
	 @rBusRouteId int,
	 @rStudentName nvarchar(100),
	 @rStudentCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int,
	 @rSUId nvarchar(max)='',
	 @rBusRouteDestination nvarchar(100) = '',	 
	 @rPickUpId int	 

WITH EXECUTE AS CALLER	 
AS
SET NOCOUNT ON

IF(@rPickUpId!=0 AND @rBusRouteDestination='')
BEGIN
SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS PickUpBusRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint,
				ISnull(SD.SUID,'') AS SUID,							
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				ISNULL(SC.ParentEmail,'') AS EMail,		
				ISNULL(TP.Title,'') AS Transport,
				ISNULL(BM1.Title,'') AS DropBusRoute
				
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 	
				INNER JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId
				LEFT JOIN sTransport.tTransportMaster TP ON TP.OrgGroupId=BM.OrgGroupId AND TP.Id=BM.TransportId			 		
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))				
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 				
				AND (((BDM.Id=@rPickUpId) OR (ISNULL(@rPickUpId,0)=0)))					
				AND BMM.IsInContext = 1				
				order by SD.ClassId,SD.Suid,SD.Code
	
		
			END
			ELSE IF(@rPickUpId=0 AND @rBusRouteDestination!='')
			BEGIN
				SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS PickUpBusRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint,
				ISnull(SD.SUID,'') AS SUID,									
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				ISNULL(SC.ParentEmail,'') AS EMail,		
				ISNULL(TP.Title,'') AS Transport,
				ISNULL(BM1.Title,'') AS DropBusRoute
				
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 	
				INNER JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId
				LEFT JOIN sTransport.tTransportMaster TP ON TP.OrgGroupId=BM.OrgGroupId AND TP.Id=BM.TransportId			 		
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))				
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 				
				AND (((BDM.Title LIKE '%'+@rBusRouteDestination+'%') OR ISNULL(@rBusRouteDestination,'')=''))					
				AND BMM.IsInContext = 1				
				order by SD.ClassId,SD.Suid,SD.Code
			END
			
			ELSE IF(@rPickUpId!=0 AND @rBusRouteDestination!='')
			BEGIN
				SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS PickUpBusRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint,					
				ISnull(SD.SUID,'') AS SUID,				
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				ISNULL(SC.ParentEmail,'') AS EMail,		
				ISNULL(TP.Title,'') AS Transport,
				ISNULL(BM1.Title,'') AS DropBusRoute
				
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 	
				INNER JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId
				LEFT JOIN sTransport.tTransportMaster TP ON TP.OrgGroupId=BM.OrgGroupId AND TP.Id=BM.TransportId			 		
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))				
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 				
				AND (((BDM.Id=@rPickUpId) OR (ISNULL(@rPickUpId,0)=0)))					
				AND BMM.IsInContext = 1				
				--order by SD.ClassId,SD.Suid,SD.Code
				UNION
				SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS PickUpBusRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint,				
				ISnull(SD.SUID,'') AS SUID,				
				ISNULL(SC.ParentContactNo,'') AS ContactNo,	
				ISNULL(SC.ParentEmail,'') AS EMail,	
				ISNULL(TP.Title,'') AS Transport,
				ISNULL(BM1.Title,'') AS DropBusRoute
				
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 
				INNER JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId	
				LEFT JOIN sTransport.tTransportMaster TP ON TP.OrgGroupId=BM.OrgGroupId AND TP.Id=BM.TransportId			 		
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))				
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 				
				AND (((BDM.Title LIKE '%'+@rBusRouteDestination+'%') OR ISNULL(@rBusRouteDestination,'')=''))					
				AND BMM.IsInContext = 1				
				--order by SD.ClassId,SD.Suid,SD.Code
			END
			
			ELSE
			BEGIN
			SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS PickUpBusRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint,					
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint,
				ISnull(SD.SUID,'') AS SUID,				
				ISNULL(SC.ParentContactNo,'') AS ContactNo,	
				ISNULL(SC.ParentEmail,'') AS EMail,	
				ISNULL(TP.Title,'') AS Transport,
				ISNULL(BM1.Title,'') AS DropBusRoute
				
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 	
				INNER JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId
				LEFT JOIN sTransport.tTransportMaster TP ON TP.OrgGroupId=BM.OrgGroupId AND TP.Id=BM.TransportId			 		
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))				
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 				
				AND (((BDM.Id=@rPickUpId) OR (ISNULL(@rPickUpId,0)=0)) 
				AND ((BDM.Title=@rBusRouteDestination) OR ISNULL(@rBusRouteDestination,'')=''))					
				AND BMM.IsInContext = 1				
				order by SD.ClassId,SD.Suid,SD.Code
			END
GO
PRINT N'Altering [sTransport].[pTransportStudentSearchGet]...';


GO
ALTER PROCEDURE [sTransport].[pTransportStudentSearchGet]
	 
	 @rOrgId int,
	 @rTransportId int,
	 @rBusrouteId int,
	 @rStudentName nvarchar(100),
	 @rStudentCode nvarchar(max),
	 @rClassId int,
	 @rDivisionId int,
	 @rOrgGroupBatchId int,
	 @rSUId nvarchar(max)='',
	 @rDepartmentId  int,
	 @rSurName nvarchar(100)='',
	 @rPickUpId int,
	 @rStatusId int = 0,
	 @rIsStudentImage bit = 0
	 	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 
BEGIN 		
			IF(@rIsStudentImage = 0)
			BEGIN
				SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS BusRoute,
				ISNULL(BM1.Title,'') AS DropRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint ,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint ,
				ISnull(SD.SUID,'') AS SUID,
				0x00000000 AS StudentPhoto,
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				ISNULL(SC.ParentEmail,'') AS EMail,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				LEFT JOIN sTransport.tBusRouteMaster BM1 ON BM1.Id = BDM1.BusRouteId 
				--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SD.StudentId
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
				AND ((SD.DepartmentId = @rDepartmentId ) OR (ISNULL(@rDepartmentId,0) = 0))
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
				AND ((SD.Lastname like @rSurName + '%') OR (ISNULL(@rSurName,'') = ''))
				AND ((BDM.Id=@rPickUpId) OR (@rPickUpId=0))
				AND ((SD.StatusId=@rStatusId) OR (@rStatusId=0))
				AND BMM.IsInContext = 1
				order by SD.ClassId,SD.Suid,SD.Code
			END
			IF(@rIsStudentImage = 1)
			BEGIN
				SELECT 		
				SD.OrganizationName AS Organization,
				SD.Code AS StudentCode,
				SD.Name AS StudentName,
				SD.ClassName + ' - ' + SD.DivisionName AS Class,
				SD.DepartmentName AS Department,
				SD.StudentId,
				Sd.OrgId,
				ISNULL(BM.Title,'') AS BusRoute ,
				ISNULL(BM.Title,'') AS DropRoute,
				ISNULL(BDM.Title,'') AS BusRoutePickupPoint ,
				ISNULL(BDM1.Title,'') AS BusRouteDropPoint ,
				ISnull(SD.SUID,'') AS SUID,
				ISNULL(SI.StudentPhoto, CONVERT(VARBINARY(MAX), 0)) AS StudentPhoto,
				ISNULL(SC.ParentContactNo,'') AS ContactNo,
				ISNULL(SC.ParentEmail,'') AS EMail,
				ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
				
				FROM sTransport.tAssignRoute AR 
				INNER JOIN sStudent.vStudentAcademic SD ON SD.StudentId = AR.SourceId AND AR.SourceTypeId = 2003
				INNER JOIN sTransport.tBusRouteDestinationMaster BDM ON BDM.Id = AR.PickupDestinationId 
				LEFT JOIN sTransport.tBusRouteDestinationMaster BDM1 ON BDM1.Id = AR.DropDestinationId 
				INNER JOIN sTransport.tBusRouteMaster BM ON BM.Id = BDM.BusRouteId 
				LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=SD.StudentId
				LEFT JOIN  sStudent.tStudentCommunication SC ON SC.StudentId=SD.StudentId
				INNER JOIN sSetup.tBatchMaster BMM ON BMM.OrgGroupBatchId = SD.OrgGroupBatchId AND BMM.Id = SD.BatchId
				Where 
				SourceTypeId = 2003
				AND (SD.OrgGroupBatchId=@rOrgGroupBatchId)
				AND (BM.OrgGroupBatchId=@rOrgGroupBatchId)
				AND ((SD.OrgId= @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
				AND ((BM.TransportId = @rTransportId) OR (ISNULL(@rTransportId,0) = 0))
				AND ((BM.Id = @rBusRouteId) OR (ISNULL(@rBusRouteId,0) = 0))
				AND ((SD.ClassId = @rClassId) OR (ISNULL(@rClassId,0) = 0))
				AND ((SD.DivisionId = @rDivisionId) OR (ISNULL(@rDivisionId,0) = 0))
				AND ((SD.Name like @rStudentName + '%') OR (ISNULL(@rStudentName,'') = ''))
				AND ((SD.DepartmentId = @rDepartmentId ) OR (ISNULL(@rDepartmentId,0) = 0))
				AND (ISNULL(SD.SUID,'') IN( SELECT cast(item as nvarchar(50)) FROM  sCommon.fnsplit(@rSUId,',')) OR @rSUId='') 
				AND (ISNULL(SD.Code,'') IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rStudentCode,',')) OR @rStudentCode='') 
				AND ((SD.Lastname like @rSurName + '%') OR (ISNULL(@rSurName,'') = ''))
				AND ((BDM.Id=@rPickUpId) OR (@rPickUpId=0))
				AND ((SD.StatusId=@rStatusId) OR (@rStatusId=0))
				AND BMM.IsInContext = 1
				order by SD.ClassId,SD.Suid,SD.Code
			END
END
GO
PRINT N'Altering [sTransport].[pUpdateTransportFeeGet]...';


GO
ALTER PROCEDURE [sTransport].[pUpdateTransportFeeGet]
	   @rClassId int = 0,
	   @rDivisionId int = 0,
	   @rBusRouteId int = 0,
	   @rBusRouteDestinationId int = 0,
	   @rBusRouteDestination nvarchar(100) = '',
	   @rOrgId int = 0,
	   @rStudentCode nvarchar(100) = '',
	   @rOrgGroupBatchId int,
	   @rTransportId int = 0,
	   @rSUID nvarchar(50) = '',
	   @rFeeId int = 0,
	   @rType nvarchar(10)=''
AS
SET NOCOUNT ON

BEGIN
	
	SET @rBusRouteDestination = sCommon.fSearchStringGet(@rBusRouteDestination)
	
	IF(@rType='Assigned')
	BEGIN
		SELECT 
			A.StudentId as SourceId,
			O.DisplayTitle AS Organization,
			ISNULL(A.SUId,'') AS SUId,
			A.Code,
			A.Name as Name,
			CM.Title+' - '+DM.Title as ClassDivisionName,
			
			ISNULL(V.BusRouteId,0) AS BusRouteId,
			ISNULL(V.BusRouteDestinationId,0) AS BusRouteDestinationId,
			
			ISNULL(V.DropRouteId,0) AS DropRouteId,
			ISNULL(V.DropDestinationId,0) AS DropDestinationId,
			
			ISNULL(V.Pickuppoint,'') As PickupPoint,
			Isnull(V.Droppoint,'') As DropPoint,
			FS.Id AS FeeSetupId,
			A.BatchId AS BatchId,
			FM.Title AS FeeName,
			V.Amount,
			V.BusRoute
			
		FROM 
			sStudent.vStudentAcademic A 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.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 
			(
				SELECT 
					AR.Sourceid,
					ISNULL(BRDM.BusRouteId,0)AS BusRouteId,
					ISNULL(AR.PickupDestinationId,0) AS BusRouteDestinationId,
					ISNULL(BRDM2.BusRouteId,0)AS DropRouteId,
					ISNULL(AR.DropDestinationId,0) AS DropDestinationId,
					ISNULL(BRDM.Title,'') AS Pickuppoint,
					ISNULL(BRDM2.Title,'') AS Droppoint,
					ISNULL(BRDM.Amount,0) AS Amount,
					BRM.Title AS BusRoute
				FROM
					sTransport.tAssignRoute AR
					INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster BRM On BRm.id=BRDM.BusRouteId AnD BRM.OrgGroupBatchId=@rOrgGroupBatchId
					LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AR.DropDestinationId	
					LEFT JOIN sTransport.tBusRouteMaster BRM2 On BRM2.Id=BRDM2.BusRouteId AND BRM2.OrgGroupBatchId=@rOrgGroupBatchId
				WHERE
					((BRDM.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) OR (BRDM2.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0))
					AND( (BRDM.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '') OR (BRDM2.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = ''))
					AND (BRDM.BusRouteId=@rBusRouteId OR @rBusRouteId=0) 
					AND BRM.TransportId=@rTransportId
			) 
			V ON V.SourceId=A.StudentId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId AND BM.OrgGroupBatchId = A.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OB ON BM.OrgGroupBatchId = ob.iD
			INNER JOIN sSetup.tOrganizationMaster O ON O.id = BM.OrgId AND O.OrgGroupId = OB.OrgGroupId
			
			INNER JOIN sFee.tFeeSetup FS ON A.ClassId = FS.ClassId AND A.AdmissionCategoryId = FS.AdmissionCategoryId AND FS.BatchId = A.BatchId
			AND FS.IsVariable = 1 AND FS.IsOptional = 1 
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
			INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id AND FHM.Number = 1001
			INNER JOIN sFee.tFeeOptional FO ON FO.SourceId = A.AcademicId AND FO.FeeSetupId = FS.Id AND FO.BatchId = A.BatchId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId = A.AcademicId AND FA.FeeSetupId = FS.Id
		WHERE 
			(A.ClassId=@rClassId OR @rClassId=0)
			AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND (V.BusRouteId=@rBusRouteId OR @rBusRouteId=0) 
			AND ((V.BusRouteDestinationId=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) OR (V.DropDestinationId=@rBusRouteDestinationId OR @rBusRouteDestinationId=0))
			AND ((V.Pickuppoint Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '') OR (V.Droppoint Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = ''))
			AND (A.Code = @rStudentCode  OR ISNULL(@rStudentCode,'')='')
			AND (A.OrgId = @rOrgId OR @rOrgId = 0)
			AND(A.OrgId in (select OrgId from sTransport.tAssignTransportOrg where TransportId = @rTransportId))
			AND (A.SUId = @rSUID  OR ISNULL(@rSUID,'')='')
			AND BM.OrgGroupBatchId=@rOrgGroupBatchId
			AND A.StatusId = 1
			AND BM.IsInContext = 1
			AND (FM.Id = @rFeeId OR @rFeeId=0)
			AND FA.SourceId IS NULL
	END	
	ELSE IF(@rType='Allocated')
	BEGIN
		SELECT 
			A.StudentId as SourceId,
			O.DisplayTitle AS Organization,
			ISNULL(A.SUId,'') AS SUId,
			A.Code,
			A.Name as Name,
			CM.Title+' - '+DM.Title as ClassDivisionName,
			
			ISNULL(V.BusRouteId,0) AS BusRouteId,
			ISNULL(V.BusRouteDestinationId,0) AS BusRouteDestinationId,
			
			ISNULL(V.DropRouteId,0) AS DropRouteId,
			ISNULL(V.DropDestinationId,0) AS DropDestinationId,
			
			ISNULL(V.Pickuppoint,'') As PickupPoint,
			Isnull(V.Droppoint,'') As DropPoint,
			
			FS.Id AS FeeSetupId,
			A.BatchId AS BatchId,
			FM.Title AS FeeName,
			V.Amount,
			V.BusRoute
		FROM 
			sStudent.vStudentAcademic A 
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.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 
			(
				SELECT 
					AR.Sourceid,
					ISNULL(BRDM.BusRouteId,0)AS BusRouteId,
					ISNULL(AR.PickupDestinationId,0) AS BusRouteDestinationId,
					ISNULL(BRDM2.BusRouteId,0)AS DropRouteId,
					ISNULL(AR.DropDestinationId,0) AS DropDestinationId,
					ISNULL(BRDM.Title,'') AS Pickuppoint,
					ISNULL(BRDM2.Title,'') AS Droppoint,
					ISNULL(BRDM.Amount,0) AS Amount,
					BRM.Title AS BusRoute
				FROM
					sTransport.tAssignRoute AR
					INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId
					INNER JOIN sTransport.tBusRouteMaster BRM On BRm.id=BRDM.BusRouteId AnD BRM.OrgGroupBatchId=@rOrgGroupBatchId
					LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON BRDM2.Id=AR.DropDestinationId	
					LEFT JOIN sTransport.tBusRouteMaster BRM2 On BRM2.Id=BRDM2.BusRouteId AND BRM2.OrgGroupBatchId=@rOrgGroupBatchId
				WHERE
					((BRDM.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) OR (BRDM2.Id=@rBusRouteDestinationId OR @rBusRouteDestinationId=0))
					AND ((BRDM.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '') OR (BRDM2.Title Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = ''))
					AND (BRDM.BusRouteId=@rBusRouteId OR @rBusRouteId=0) 
					AND BRM.TransportId=@rTransportId
			) 
			V ON V.SourceId=A.StudentId 
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId AND BM.OrgGroupBatchId = A.OrgGroupBatchId
			INNER JOIN sSetup.tOrgGroupBatchMaster OB ON BM.OrgGroupBatchId = ob.iD
			INNER JOIN sSetup.tOrganizationMaster O ON O.id = BM.OrgId AND O.OrgGroupId = OB.OrgGroupId
			
			INNER JOIN sFee.tFeeSetup FS ON A.ClassId = FS.ClassId AND A.AdmissionCategoryId = FS.AdmissionCategoryId AND FS.BatchId = A.BatchId
			AND FS.IsVariable = 1 AND FS.IsOptional = 1
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId = FM.Id  
			INNER JOIN sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id AND FHM.Number = 1001
			INNER JOIN sFee.tFeeOptional FO ON FO.SourceId = A.AcademicId AND FO.FeeSetupId = FS.Id AND FO.BatchId = A.BatchId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.SourceId = A.AcademicId AND FA.FeeSetupId = FS.Id
		WHERE 
			(A.ClassId=@rClassId OR @rClassId=0)
			AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
			AND (V.BusRouteId=@rBusRouteId OR @rBusRouteId=0) 
			AND ((V.BusRouteDestinationId=@rBusRouteDestinationId OR @rBusRouteDestinationId=0) OR (V.DropDestinationId=@rBusRouteDestinationId OR @rBusRouteDestinationId=0))
			AND ((V.Pickuppoint Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = '') OR (V.Droppoint Like @rBusRouteDestination OR ISNULL(@rBusRouteDestination,'') = ''))
			AND (A.Code = @rStudentCode  OR ISNULL(@rStudentCode,'')='')
			AND (A.OrgId = @rOrgId OR @rOrgId = 0)
			AND(A.OrgId in (select OrgId from sTransport.tAssignTransportOrg where TransportId = @rTransportId))
			AND (A.SUId = @rSUID  OR ISNULL(@rSUID,'')='')
			AND BM.OrgGroupBatchId=@rOrgGroupBatchId
			AND A.StatusId = 1
			AND BM.IsInContext = 1
			AND (FM.Id = @rFeeId OR @rFeeId=0)
			AND FA.SourceId IS NOT NULL
	END
END
GO
PRINT N'Altering [sTransport].[pUserControlStudentSearchGet]...';


GO
ALTER PROCEDURE [sTransport].[pUserControlStudentSearchGet]
	 
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=NULL,
	@rOrgId int,
	--@rNumber bigint,
	@rCode nvarchar(20),
	@rStatusId smallint=0,
	@rFirstName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rBatchId int = 0,
	@rOrgGroupBatchId int = 0,
	@rSUId nvarchar(50)='',
	@rTransportId Int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON			 

BEGIN 	 
		BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rLastName = sCommon.fSearchStringGet(@rLastName)
		END
 IF(@rRollNo IS NULL)
	BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
			SA.BatchId,
			SA.SUId
  FROM 
          sStudent.vStudentAcademic SA
           INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId AND  AR.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId  
	       INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId
		
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SA.OrgId=@rOrgId OR @rOrgId = 0)
		AND (SA. OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))	
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
		AND BRM.TransportId=@rTransportId

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
ELSE
BEGIN
	SELECT 
			SA.AcademicId,
			SA.StudentId,
			SA.FirstName,
			SA.LastName,
			SA.MiddleName,
			SA.Name,
			SA.Code,
			SA.ClassId,
			SA.ClassName,
			SA.DivisionId,
			SA.DivisionName,
			SA.Number,
			SA.RollNo,
			SA.StatusId,
			SA.StatusName,
			SA.OrgId,
			--SA.Age,
			ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId 
  FROM 
          sStudent.vStudentAcademic SA 
          INNER JOIN sTransport.tAssignRoute AR ON AR.SourceId=SA.StudentId AND  AR.SourceTypeId=2003 
          INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR.PickupDestinationId  
	      INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId           
  WHERE 
 
		((SA.ClassId=@rClassId)OR(@rClassId=0))
		AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = '')) 
		AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = '')) 
		AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = '')) 
		AND(SA.RollNo=@rRollNo)
		AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			AND (SA.OrgGroupBatchId = @rOrgGroupBatchId	or @rOrgGroupBatchId = 0)	
		AND(SA.BatchId=@rBatchId or @rBatchId = 0)
		--AND(SA.BatchId=@rBatchId)
		--AND((SA.Number=@rNumber)OR(@rNumber=0))
		AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))
		AND BRM.TransportId=@rTransportId
		

ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
END
		
END
GO
PRINT N'Creating [sAlert].[pEmployeeBiometricAbsentTimeGet]...';


GO


CREATE PROCEDURE [sAlert].[pEmployeeBiometricAbsentTimeGet]
	@rOrgId int,
	@rOrgGroupId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100),
	@rIntervalTime int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
			declare  @lBatchID INT
			SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<=cast([sCommon].[fGetDate]() as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId
				from [sBiometric].[tCloudTransactionData] CDT
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=95 Group by SourceId,SourceTypeId
			END
			
			
			--select * from #tTable
			select EM.MobileNumber AS MobileNo,	
					EM.CompanyEmail AS EmailId,
					replace (
					replace(@rTemplate,'[EmployeeName]',EM.EmployeeName),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MsgText,
					@rSubject AS Subject,
					95 AS ReceiverSourceTypeId,
					EM.EmployeeId AS ReceiverSourceId,
					EM.EmployeeName AS EmployeeName,
					ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
					95 AS SourceTypeId,
					EM.EmployeeId AS SourceId,
					EM.OrgId
				FROM  
					sHrm.vEmployeeCommonDetail EM 
					Inner Join  [sHrm].[tEmployeeMaster] E on EM.EmployeeId=E.Id
					INNER JOIN #tShift tempshift ON tempshift.ShiftCode=E.ShiftId
					LEFT JOIN #tTable temp ON  temp.SourceId=EM.EmployeeId
					LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.EmployeeId
					LEFT JOIN sSetup.tOrganizationMaster OM ON EM.OrgID = OM.Id
				where 
				EM.OrgID =@rOrgId
				AND temp.In_Out_Time is null
				AND ( [sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<>'W')
				AND ( [sHrm].[fWeekHOffGetBio](EM.EmployeeId , YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),@lBatchID ,OrganizationDepartmentId ,@rOrgId )<> 'H')
			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sAlert].[pLeaveHierarchyListingGet]...';


GO

CREATE PROCEDURE [sAlert].[pLeaveHierarchyListingGet]
	
	 	 @rLeaveId bigint,
		 @rOrgId int,
		 @rEmployeeId bigint,
		 @rStatusId int,
	 	 @rTemplate nvarchar(max),
		 @rSubject nvarchar(100)=''
		 --@rHierarchyLevelCount int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

DECLARE @lLeaveCount int,@lEmployeeId bigint, @lLeaveFromDate date, @lLeaveToDate date, @lLeaveReason nvarchar(200),
@lLeaveStatus nvarchar(100),@lEmployeeName nvarchar(100),@lActionByEmployeeName nvarchar(200), @lHierarchyLevelCount int
	
	SELECT @lLeaveCount = COUNT(AutoId) FROM [sHrm].[tLeaveHierarchyLevel] WHERE LeaveId = @rLeaveId
	
	SELECT @lHierarchyLevelCount = ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 485 AND SourceId = @rOrgId
	--SELECT @lLeaveCount,@lHierarchyLevelCount
IF(@lHierarchyLevelCount > 1)
BEGIN
	SELECT 
	 @lLeaveFromDate = FromDate,
	 @lLeaveToDate = ToDate,
	 @lLeaveReason = LeaveReason,
	 @lLeaveStatus = (CASE WHEN @rStatusId = 549 THEN 'Pending' 
						   WHEN @rStatusId = 550 THEN 'Approved'
						   ELSE 'Rejected' END),
	@lEmployeeName = ECD.EmployeeName
	from sHrm.tLeave L 
	INNER JOIN sHrm.vEmployeeCommonDetail ECD  ON L.EmployeeId = ECD.EmployeeId
	 WHERE L.Id = @rLeaveId AND L.OrgId = @rOrgId


	IF(@lHierarchyLevelCount <> @lLeaveCount)
	BEGIN
		SELECT @lEmployeeId = EmployeeManagerId from sHrm.tEmployeeJobDetail WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId
		SELECT @lActionByEmployeeName = EmployeeName from sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId 

		--Select @lEmployeeId , @lActionByEmployeeName
	END

ELSE
--on last approval send alert to employee (Who enter leave)
BEGIN
Select @lEmployeeId = EmployeeId from sHrm.tLeave WHERE Id = @rLeaveId AND OrgId = @rOrgId
SELECT @lActionByEmployeeName = EmployeeName from sHrm.vEmployeeCommonDetail WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId 
END

Select 
		EM.Id AS EmployeeId,
		EM.Code,
		ECD.EmployeeName,
		EC.MobileNumber AS MobileNo,	
		EC.CompanyEmail AS EmailId,
		replace (
		replace (
		replace (
		replace (
		replace (
		replace(@rTemplate,'[EmployeeName]',ISNULL(@lEmployeeName,'')),
		'[LeaveFromDate]',ISNULL(@lLeaveFromDate,'')),
		'[LeaveToDate]',ISNULL(@lLeaveToDate,'')),
		'[LeaveReason]',ISNULL(@lLeaveReason,'')),
		'[LeaveStatus]',ISNULL(@lLeaveStatus,'')),
		'[ActionByEmployeeName]',ISNULL(@lActionByEmployeeName,''))
			AS MsgText,
		@rSubject AS Subject,
		95 AS ReceiverSourceTypeId,
		EM.Id AS ReceiverSourceId,
		ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
		ECD.EmployeeName AS Name,
		EM.OrgId,
		OM.OrgGroupId

FROM 
		sHrm.tEmployeeMaster EM
		INNER JOIN sHrm.vEmployeeCommonDetail ECD ON EM.Id = ECD.EmployeeId
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EC.EmployeeId = EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON EM.OrgId = OM.Id	

		WHERE 
		EM.Id = @lEmployeeId 
		AND EM.OrgId = @rOrgId

END
END
GO
PRINT N'Creating [sAlert].[pQueryCategoryCreate]...';


GO

CREATE PROCEDURE [sAlert].[pQueryCategoryCreate]
	 @rOrgGroupId int,
	 @rQueryCategoryId bigint,
	 @rTemplate nvarchar(max) = '',
	 @rSubject nvarchar(100)= ''
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 		

SELECT 
		    replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SA.StudentId AS ReceiverSourceId,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			OM.OrgGroupId,
			SA.OrgId AS OrgId, 
			2003 AS SourceTypeId,
			SA.StudentId AS SourceId,
			SC.WhatsAppContactNo
	FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN sSetup.tOrganizationMaster OM ON QCS.SourceId = OM.Id 
		INNER JOIN sStudent.vStudentAcademic SA ON OM.Id = SA.OrgId AND SA.StatusId = 1 AND SA.IsActiveBatch = 1
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
	WHERE 
		  QCS.SourceTypeId = 2021 AND QCS.AssigneeToId = 2 
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId

UNION

SELECT 
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			ISNULL(ECS.CompanyEmail,'') AS EmailId,
			ISNULL(ECS.MobileNumber,'') AS MobileNo,
			QCM.OrgGroupId,
			EC.OrgId AS OrgId, 
			95 AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			ECS.WhatsAppContactNo
	FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN sSetup.tOrganizationMaster OM ON QCS.SourceId = OM.Id 
		--INNER JOIN sStudent.vStudentAcademic SA ON OM.Id = SA.OrgId AND SA.StatusId = 1 AND SA.IsActiveBatch = 1
		INNER JOIN sHrm.vEmployeeCommonDetail EC ON  OM.Id = EC.OrgId AND EC.EmployeeStatusId = 7 
		LEFT JOIN sHrm.tEmployeeCommunications ECS ON EC.EmployeeId = ECS.EmployeeId
	WHERE 
		  QCS.SourceTypeId = 2021 AND QCS.AssigneeToId = 3 
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId


UNION

Select 
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SA.StudentId AS ReceiverSourceId,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			QCM.OrgGroupId,
			SA.OrgId AS OrgId, 
			2003 AS SourceTypeId,
			SA.StudentId AS SourceId,
			SC.WhatsAppContactNo

FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN sSetup.tDepartmentMaster DM ON QCS.SourceId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id 
		INNER JOIN sStudent.vStudentAcademic SA ON DM.Id = SA.DepartmentId AND SA.StatusId = 1 AND SA.IsActiveBatch = 1 
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
		WHERE 
		  QCS.SourceTypeId = 2017 AND QCS.AssigneeToId = 2
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId


UNION


Select 
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			ISNULL(ECS.CompanyEmail,'') AS EmailId,
			ISNULL(ECS.MobileNumber,'') AS MobileNo,
			QCM.OrgGroupId,
			EC.OrgId AS OrgId, 
			95 AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			ECS.WhatsAppContactNo

FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN sSetup.tDepartmentMaster DM ON QCS.SourceId=DM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON DM.OrgId=OM.Id  
		INNER JOIN sHrm.vEmployeeCommonDetail EC ON  QCS.SourceId = EC.DepartmentId AND EC.EmployeeStatusId = 7 AND EC.OrgId = OM.Id
		
		LEFT JOIN sHrm.tEmployeeCommunications ECS ON EC.EmployeeId = ECS.EmployeeId
		WHERE 
		  QCS.SourceTypeId = 2017 AND QCS.AssigneeToId = 3
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId


UNION

Select 
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SA.StudentId AS ReceiverSourceId,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			OM.OrgGroupId,
			SA.OrgId AS OrgId, 
			2003 AS SourceTypeId,
			SA.StudentId AS SourceId,
			SC.WhatsAppContactNo
FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN  sSetup.tClassMaster CM ON QCS.SourceId=CM.Id
		INNER JOIN sStudent.vStudentAcademic SA ON CM.Id = SA.ClassId AND SA.StatusId = 1 AND SA.IsActiveBatch = 1
		INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id		
		INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
		WHERE 
		  QCS.SourceTypeId = 2016
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId


UNION

Select 
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SA.StudentId AS ReceiverSourceId,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			OM.OrgGroupId,
			SA.OrgId AS OrgId, 
			2003 AS SourceTypeId,
			SA.StudentId AS SourceId,
			SC.WhatsAppContactNo
FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN   sSetup.tDivisionMaster DM ON QCS.SourceId=DM.Id
		INNER JOIN 	sSetup.tClassMaster CM ON DM.ClassId=CM.Id	
		INNER JOIN sStudent.vStudentAcademic SA ON DM.Id = SA.DivisionId AND SA.StatusId = 1 AND SA.IsActiveBatch = 1
		INNER JOIN sSetup.tDepartmentMaster DMast ON CM.DepartmentId =DMast.Id		
		INNER JOIN sSetup.tOrganizationMaster OM ON DMast.OrgId=OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
		WHERE 
		  QCS.SourceTypeId = 2005
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId


UNION

Select
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			2003 AS ReceiverSourceTypeId,
			SA.StudentId AS ReceiverSourceId,
			ISNULL(SC.ParentEmail,'') AS EmailId,
			ISNULL(SC.ParentContactNo,'') AS MobileNo,
			OM.OrgGroupId,
			SA.OrgId AS OrgId, 
			2003 AS SourceTypeId,
			SA.StudentId AS SourceId,
			SC.WhatsAppContactNo


FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN sStudent.vStudentAcademic SA ON QCS.SourceId=SA.StudentId AND SA.StatusId = 1 AND SA.IsActiveBatch = 1
		INNER JOIN sSetup.tOrganizationMaster OM ON SA.OrgId=OM.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
		WHERE 
		  QCS.SourceTypeId = 2003
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId

UNION

Select
			replace (@rTemplate, '[QueryTitle]',QCM.Title)AS MsgText,
			@rSubject AS Subject,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			ISNULL(ECS.CompanyEmail,'') AS EmailId,
			ISNULL(ECS.MobileNumber,'') AS MobileNo,
			OM.OrgGroupId,
			EC.OrgId AS OrgId, 
			95 AS SourceTypeId,
			EC.EmployeeId AS SourceId,
			ECS.WhatsAppContactNo
FROM 
		sCommunication.tQueryCategoryMaster QCM
		INNER JOIN sCommunication.tQueryCategoryScope QCS ON QCM.Id = QCS.QueryCategoryId
		INNER JOIN sHrm.vEmployeeCommonDetail EC ON  QCS.SourceId = EC.EmployeeId AND EC.EmployeeStatusId = 7 
		INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId=OM.Id 
		LEFT JOIN sHrm.tEmployeeCommunications ECS ON EC.EmployeeId = ECS.EmployeeId

		WHERE 
		  QCS.SourceTypeId = 95
		  AND QCM.Id = @rQueryCategoryId AND QCM.OrgGroupId = @rOrgGroupId
END
GO
PRINT N'Creating [sAlert].[pStudentBiometricAbsentTimeGet]...';


GO

CREATE PROCEDURE [sAlert].[pStudentBiometricAbsentTimeGet]
	 @rOrgId int,
	@rOrgGroupId int,
	@rTemplate nvarchar(max),
	@rSubject nvarchar(100)='',
	@rIntervalTime int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	BEGIN TRY	
		BEGIN TRANSACTION 
		declare  @lBatchID INT
		SELECT @lBatchID = Id from sSetup.tBatchMaster Where OrgId = @rOrgId AND IsActive = 1
			
			if object_id('tempdb..#tShift') is not null
			BEGIN
				DROP TABLE #tShift
			END
			CREATE TABLE #tShift(
					ShiftCode int NOT NULL
				)

			insert #tShift
			Select 
				ShiftCode
			FROM sBiometric.tShiftMasterCloud
			where  ((OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId=0))  
			--AND IsOutTimeAlertTime=1
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)<=cast([sCommon].[fGetDate]() as Time)
			AND CAST(DATEADD(MINUTE,AlterGraceTime,StartTime) AS Time)>=cast(DATEADD(MINUTE,-@rIntervalTime,[sCommon].[fGetDate]()) as Time)

			--select * from #tShift
			declare @lcount int=(SELECT COUNT(ShiftCode) FROM #tShift)

			if object_id('tempdb..#tTable') is not null
			BEGIN
				DROP TABLE #tTable
			END
			CREATE TABLE #tTable(
						SourceId bigint NOT NULL,
						In_Out_Time [datetime] NOT NULL,
						SourceTypeId int NOT NULL
					)

			if(@lcount>0)
			BEGIN
				insert into #tTable
				select SourceId,MIN(In_Out_Time),SourceTypeId
				from [sBiometric].[tCloudTransactionData] CDT
				inner join #tShift tempShift ON tempShift.ShiftCode=CDT.ShiftCode 
				WHERE Attn_Dt=CONVERT(date,[sCommon].[fGetDate]())  AND SourceTypeId=2003 Group by SourceId,SourceTypeId
			END
			
			
			--select * from #tTable
			select SC.ParentContactNo AS MobileNo,	
					SC.ParentEmail AS EmailId,
					replace (
					replace(@rTemplate,'[StudentName]',SC.Name),
					'[AbsentDate]',ISNULL(Convert(varchar,[sCommon].[fGetDate](),103),''))
					 AS MsgText,
					@rSubject AS Subject,
					2003 AS ReceiverSourceTypeId,
					SC.StudentId AS ReceiverSourceId,
					SC.Name AS StudentName,
					ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo,
					2003 AS SourceTypeId,
					SC.StudentId AS SourceId,
					SC.OrgId,
					OM.OrgGroupId
				FROM  
					sStudent.vStudentCommunication SC 
					Inner Join  [sStudent].[tStudentMaster] SM on SM.Id=SC.StudentId
					INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgID = OM.Id
					INNER JOIN #tShift tempshift ON tempshift.ShiftCode=SM.ShiftId
					LEFT JOIN #tTable temp ON  temp.SourceId=SC.StudentId 
				where 
					SC.OrgID =@rOrgId
					AND SC.IsActiveBatch=1
					AND SC.StatusId = 1
					AND temp.In_Out_Time is null
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'W')
					AND ([sAttendance].[fWeekHOffGet](YEAR([sCommon].[fGetDate]()) ,MONTH([sCommon].[fGetDate]()) ,DAY([sCommon].[fGetDate]()),SC.BatchId,SC.ClassId,SC.DivisionId, '',@rOrgId)<>'H')

			DROP TABLE #tTable
			DROP TABLE #tShift
		COMMIT TRANSACTION
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH
END
GO
PRINT N'Creating [sAssessment].[pRptSubjectwisePassFailAndAbsentAnalysis]...';


GO


CREATE PROCEDURE [sAssessment].[pRptSubjectwisePassFailAndAbsentAnalysis]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rOrgId int=0,
	 --@rClass nvarchar(MAX)='',
	 @rGroupByid int=0,
 	 @rSubject nvarchar(max)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 
		 
	 select 
		@rBuilder1 AS Builder1,
		Cm.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
		CS.Id AS ClassSubjectId,
		SM.Id AS SubjectId,
		SM.Code AS SubjectName,
		Sm.OrderIndex As SubjectOrderIndex,
		DM.OrderIndex AS DivisionOrderIndex,
		CM.OrderIndex AS ClassOrderIndex,
		case when @rGroupByid=1 THEN Dm.Id
		when @rGroupByid=2 THEN CM.Classid
		when @rGroupByid=3 THEN CM.DepartmentId
	    when @rGroupByid=4 THEN OM.Id
		ELSE 0  END  AS HeadId,
		case when @rGroupByid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle   
		when @rGroupByid=2 THEN ' Class : ' + CM.ClassName 
		when @rGroupByid=3 THEN 'Department: ' + DP.Title 
		WHen @rGroupByid=4 THen  'Organization : '+Om.Title END  AS HeadName,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
		WHEN @rGroupByid=2  THEN CM.OrderIndex
		WHEN @rGroupByid=3  THEN DP.Id
		WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex,
		

	  (select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	  INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   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  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId 
	  AND CS.SubjectId=SM.Id AND RD.Obtain>=ED.Minimum) AS PassStudent,
  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   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  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.Obtain<ED.Minimum) AS FailStudent,
	  
	  
	(select COUNT(RD.Id) from  sAssessment.tResultDetail RD 
	INNER JOIN  sAssessment.tResult R ON RD.ResultId = R.Id  
	INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	   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  
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND 
	  EM.BatchId = @rBatchId AND CS.SubjectId=SM.Id AND RD.IsPresent = 0) AS AbsentStudent  
	  
	  
	-- from
	-- ssetup.tDivisionMaster DM
	-- INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	--INNER JOIN sSetup.tClassSubject CS ON CS.ClassId=CM.ClassId	
	--INNER JOIN sSetup.tSubjectMaster   SM ON SM.Id = CS.SubjectId
	--INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	-- INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
 --   INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId

	--	WHERE 
	--		((DM.ID=@rDivisionId) or (@rDivisionId=0))
	--		AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
	--		AND CM.BatchId=@rBatchId
	--		AND EM.ExamSubGroupId = @rExamSubGroupId
	--		AND EM.BatchId = @rBatchId
	--		AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
	
	from		
		sAssessment.tExamMaster EM 
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=CS.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = CS.ClassId AND CM.BatchId = @rBatchId
		INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON CLM.OrgId = OM.Id

	WHERE 		
		
		EM.BatchId = @rBatchId 
		AND  ((@rClassId > 0 AND cs.ClassId=@rClassId)
		AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
		AND	CM.BatchId = @rBatchId
		AND EM.ExamSubGroupId = @rExamSubGroupId
		AND EM.BatchId = @rBatchId
		AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject=''))
	
  UNION ALL
  
  
  	 select 
		@rBuilder1 AS Builder1,
		DM.Classid As ClassId,
		Dm.id As DivisionId,
		Cm.ClassName As Classname,
		DM.DisplayTitle As DivisionName,
	0 AS ClassSubjectId,
		0 AS SubjectId,
		'Over All' AS SubjectName,
		0 As SubjectOrderIndex,
		0 AS DivisionOrderIndex,
		0 AS ClassOrderIndex,
		case when @rGroupByid=1 THEN Dm.Id
		when @rGroupByid=2 THEN CM.Classid
		when @rGroupByid=3 THEN CM.DepartmentId
	    when @rGroupByid=4 THEN OM.Id
		ELSE 0    END  AS HeadId,
		case when @rGroupByid=1 THEN ' Division : ' +CM.ClassName+ ' / '+Dm.DisplayTitle  
		when @rGroupByid=2 THEN ' Class : ' + CM.ClassName  
		when @rGroupByid=3 THEN 'Department: ' + DP.Title 
		WHen @rGroupByid=4 THEN  'Organization : '+OM.Title
		END  AS HeadName,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
				WHEN @rGroupByid=2  THEN CM.OrderIndex
				WHEN @rGroupByid=3  THEN DP.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex,
	 

 (select COUNT(R.AcademicId) from   sAssessment.tResult R  INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId  AND R.ResultStatus='PASS') AS PassStudent,
	  
	  (select COUNT(R.AcademicId) from   sAssessment.tResult R   INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
	    
	  	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
		 
	  where 
	  A.DivisionId = DM.Id AND EM.ExamSubGroupId = @rExamSubGroupId AND EM.BatchId = @rBatchId AND R.ResultStatus='FAIL') AS FailStudent,
	  
	 0 AS AbsentStudent  
	  
    
	 --from
	 --ssetup.tDivisionMaster DM
	 --INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = DM.ClassId
	 --INNER JOIN sAssessment.tExamMaster EM ON EM.ClassId = CM.ClassId
	 --INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
  --  INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=DP.OrgId
		--WHERE 
		--	((DM.ID=@rDivisionId) or (@rDivisionId=0))
		--	AND ((Dm.ClassId=@rClassId) or (@rClassId=0))
		--	AND CM.BatchId=@rBatchId
		--	AND EM.ExamSubGroupId = @rExamSubGroupId
		--	AND EM.BatchId = @rBatchId
		
	FROM		
		sAssessment.tExamMaster EM 
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
		INNER JOIN sSetup.tClassMaster CLM ON CLM.Id=CS.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId=CS.ClassId
		INNER JOIN sSetup.vBatchClass CM ON CM.ClassId = CS.ClassId AND CM.BatchId = @rBatchId
		INNER JOIN sSetup.tDepartmentMaster DP ON DP.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON CLM.OrgId = OM.Id

	WHERE 		
		
		EM.BatchId = @rBatchId 
		AND  ((@rClassId > 0 AND cs.ClassId=@rClassId)
		AND (DM.Id=@rDivisionId OR @rDivisionId=0)			
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))
		AND	CM.BatchId = @rBatchId
		AND EM.ExamSubGroupId = @rExamSubGroupId
		AND EM.BatchId = @rBatchId
		AND (ISNULL(SM.Id,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject=''))
			
			--AND (ISNULL(ClassSubjectId,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
END
GO
PRINT N'Creating [sAssessment].[pWrongExamMarkEntryGet]...';


GO
CREATE PROCEDURE [sAssessment].[pWrongExamMarkEntryGet]
    @rWrongExamId int
AS
BEGIN
	SELECT
		RD.*,V.SubjectName
	FROM 
	sAssessment.tResultDetail RD 
	INNER JOIN sAssessment.tResult R ON RD.ResultId = R.Id
	INNER JOIN sAssessment.tExamDetail ED ON RD.ExamDetailId = ED.Id 
	INNER JOIN sSetup.vClassSubject V ON V.ClassSubjectId = Ed.ClassSubjectId  	
	WHERE R.ExamId=@rWrongExamId AND RD.ExamDetailId NOT IN(SELECT Id from sAssessment.tExamDetail WHERE ExamId = @rWrongExamId)
END
GO
PRINT N'Creating [sBiometric].[pRptEmployeeWiseMonthlySummaryGet]...';


GO

CREATE PROCEDURE [sBiometric].[pRptEmployeeWiseMonthlySummaryGet] 
     @rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int ,
	@rDeptId int ,
	@rForYear int,
	@rForMonth int,	 
	@rEmployeeStatusId int,
	@rEmployeeId bigint,
	@rOrgGroupId int
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN   
  
declare @Days int
Declare @lFromDate datetime
Declare @lToDate datetime


CREATE TABLE #TempMonthTrans  
 (  
 Id int ,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 LateBy nvarchar(20),   
 EarlyBy nvarchar(20), 
 ) 
 select @Days=sCommon.fGetDaysInMonth(@rForMonth,@rForYear)
 set @lFromDate=CONVERT(nvarchar(20), @rForYear)+ '-' +  CONVERT(nvarchar(20), @rForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @lToDate=CONVERT(nvarchar(20), @rForYear)+ '-' +  CONVERT(nvarchar(20), @rForMonth) + '-' + CONVERT(nvarchar(20), @Days)
 --select @lFromDate,@lToDate
  INSERT INTO #TempMonthTrans 
  select Id,EmployeeId ,Attn_Date,PresentStatus ,LateBy, EarlyBy 
   from [sBiometric].[fBiometricTempMonthTransGet](@rOrgId ,@rDeptId ,@lFromDate,@lToDate,@rEmployeeId)

  SELECT
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		MT.EmployeeId,
		MT.EmpCode,
		EM.FirstName + ' ' + EM.LastName AS EmployeeName,  
		OM.Id AS OrganizationId,
		OM.DisplayTitle AS OrganizationTitle,
		OM.OrderIndex AS OrganizationOrderIndex,
		EM.Number AS EmployeeNumber,
		DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays,
		MT.Count_Late AS Count_Late,
		isnull(Absent.TotAbsent,0.00) AS TotalAbsentDays,
		isnull(WeekOff.TotWeekOff,0.00) AS TotalWeekOffs,
		isnull(Holidays.TotHoliday,0.00) AS TotalHolidays,
		isnull(Present.TotPresent,0.00) AS TotalPresentDays,
		isnull(HalfDay.TotHalfDay,0.00) AS TotalHalfDays,
		isnull(ErrorCase.TotalErrorCase,0.00) AS TotalErrorCase,
		ISNULL(EA.PaidLeave,0.00)  as PaidLeave,
		Isnull(EA.LWP,0.00)  AS UnPaidLeave,
		IsNull(MT.TotalHour,'00:00') as TotalHour,
		Isnull(MT.Tot_Early,'00:00') as Tot_Early,
		Isnull(MT.Tot_OT,'00:00') as Tot_OT,
		Isnull(MT.Tot_Late,'00:00') as Tot_Late,
		DM.Displaytitle AS DeptName,
		DM.Id As DeptId
	FROM
	sBiometric.tMonthTrans MT
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId AND (SourceTypeId = 95 OR SourceTypeId=0)
	left join [sHrm].[tEmployeeAttendance] EA ON EA.EmployeeId=Mt.EmployeeId AND EA.ForYear=@rForYear AND EA.ForMonth=@rForMonth
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
	LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
	LEFT Join (Select COUNT(*) AS TotPresent,EmployeeId from #TempMonthTrans Where PresentStatus IN ('P','PW','PH') group by EmployeeId,PresentStatus) Present ON Present.EmployeeId = MT.employeeID
	LEFT Join (Select COUNT(*) AS TotAbsent,EmployeeId from #TempMonthTrans Where PresentStatus Like 'A' group by EmployeeId,PresentStatus) Absent ON Absent.EmployeeId = MT.employeeID
	LEFT Join (Select COUNT(*) AS TotWeekOff,EmployeeId from #TempMonthTrans Where PresentStatus IN ('W','PW','PHW') group by EmployeeId) WeekOff ON WeekOff.EmployeeId = MT.employeeID
	LEFT Join (Select COUNT(*) AS TotHalfDay,EmployeeId from #TempMonthTrans Where PresentStatus Like 'HD' group by EmployeeId,PresentStatus) HalfDay ON HalfDay.EmployeeId = MT.employeeID
    LEFT Join (Select COUNT(*) AS TotHoliday,EmployeeId from #TempMonthTrans Where PresentStatus Like 'H' group by EmployeeId,PresentStatus) Holidays ON Holidays.EmployeeId = MT.employeeID	
	LEFT Join (Select COUNT(*) AS TotalErrorCase,EmployeeId from #TempMonthTrans Where PresentStatus Like 'E' group by EmployeeId,PresentStatus) ErrorCase ON ErrorCase.EmployeeId = MT.employeeID	

	WHERE
	(EM.OrgId = @rOrgId OR @rOrgId = 0)
	AND YEAR(MT.Attn_Dt) = @rForYear
	AND (MONTH(MT.Attn_dt) = @rForMonth )
	AND (EJD.OrganizationDepartmentId = @rDeptId OR @rDeptId = 0)		 	
	AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
	AND ISNULL(EM.IsOtherUser,0) = 0 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	AND (OM.OrgGroupId = @rOrgGroupId)
	order by MT.EmpCode

	DROP Table #TempMonthTrans	
 --select 
 --@rBuilder1 AS Builder1,
	--	@rBuilder2 AS Builder2,
	--	CAST(0 AS bigint) AS EmployeeId,
	--	0 AS EmpCode,
	--	'' AS EmployeeName,  
	--	0 AS OrganizationId,
	--	'' AS OrganizationTitle,
	--	0 AS OrganizationOrderIndex,
	--	CAST(0 AS bigint) AS EmployeeNumber,
	--	DAY(DATEADD(MONTH, @rForMonth, DATEADD(YEAR, @rForYear - 1900, -1))) AS TotalDays,
	--	0.00 AS Count_Late,
	--	0.00 AS TotalAbsentDays,
	--	0.00 AS TotalWeekOffs,
	--	0.00 AS TotalHolidays,
	--	0.00 AS TotalPresentDays,
	--	0.00 AS TotalHalfDays,
	--	0.00 AS TotalErrorCase,
	--	0.00  as PaidLeave,
	--	0.00  AS UnPaidLeave,
	--	'00:00' as TotalHour,
	--	'00:00' as Tot_Early,
	--	'00:00' as Tot_OT,
	--	'00:00' as Tot_Late,
	--	'' AS DeptName,
	--	0 As DeptId

end
GO
PRINT N'Creating [sBiometric].[pRptMonthlyLateInSummaryGet]...';


GO

CREATE PROCEDURE [sBiometric].[pRptMonthlyLateInSummaryGet]
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rOrgId int ,
	@rOrganizationDepartmentId int ,
	@rFromDate Datetime,
	@rToDate Datetime,	 
	@rEmployeeStatusId int,
	@rEmployeeId bigint,
	@rOrgGroupId int,
	@rGradeId nvarchar(max)= '0',
	@rOrgGroupDepartmentId int =0,
	@rTimeSheetStatus nvarchar(50) ='0',
	@rOrderBy smallint = 0

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN  
	CREATE TABLE #TempMonthTrans  
	 (  
	 Id int ,  
	 EmployeeId bigint,   
	 Attn_Date DateTime,  
	 PresentStatus nvarchar(15),  
	 LateBy nvarchar(20),   
	 EarlyBy nvarchar(20), 
	 FirstIn nvarchar(20),
	 ShiftName nvarchar(25) ,
	 Duration nvarchar(20),
	  LastOut nvarchar(20)
	 ) 
 
 
	  INSERT INTO #TempMonthTrans 
	  select Id,EmployeeId ,Attn_Date,PresentStatus ,LateBy, EarlyBy,FirstIn,ShiftName,Duration, LastOut
	  from [sBiometric].[fBiometricTempMonthTransGet](@rOrgId ,@rOrganizationDepartmentId ,@rFromDate,@rToDate,@rEmployeeId)
	 -- select * from #TempMonthTrans 
	SELECT
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			MT.EmployeeId,
			MT.EmpCode,
			EM.FirstName + ' ' + EM.LastName AS EmployeeName,  
			OM.Id AS OrganizationId,
			OM.DisplayTitle AS OrganizationTitle,
			OM.OrderIndex AS OrganizationOrderIndex,
			EM.Number AS EmployeeNumber,
			IsNull(MT.TotalHour,'00:00') as TotalHour,
			Isnull(MT.Tot_Early,'00:00') as Tot_Early,
			Isnull(MT.Tot_OT,'00:00') as Tot_OT,
			Isnull(MT.Tot_Late,'00:00') as Tot_Late,
			Isnull(Mt.Count_Late, 0) as Count_Late,
			OM.Id AS OrgId,
			OM.Title AS OrganizationTitle,
			TM.Attn_Date as Attn_Date,
			TM.FirstIn as FirstIn,
			TM.LateBy AS LateBy,
			TM.PresentStatus as PresentStatus,
			TM.EarlyBy AS EarlyBy,
			TM.ShiftName AS ShiftName,
			DM.Displaytitle AS DeptName,
			DM.Id As DeptId,
			@rOrderBy AS OrderBy,
			TM.LastOut AS LastOut
		FROM #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = MT.EmployeeId AND (SourceTypeId = 95 OR SourceTypeId=0)
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
		LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJD.OrganizationDepartmentId
	
		WHERE
		(EM.OrgId = @rOrgId OR @rOrgId = 0)
		 and TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate   
		 and  MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
		AND (EJD.OrganizationDepartmentId = @rOrganizationDepartmentId OR @rOrganizationDepartmentId = 0)		 	
		AND (EM.StatusId = @rEmployeeStatusId OR ISNULL(@rEmployeeStatusId,0)=0)
		AND ISNULL(EM.IsOtherUser,0) = 0 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		AND (MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		AND (OM.OrgGroupId = @rOrgGroupId)
		AND (EmployeeGradeId in ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGradeId,',')) OR @rGradeId=0) 
		AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
		AND  ((PresentStatus in ( SELECT cast(item as nvarchar) FROM  sCommon.fnsplit(@rTimeSheetStatus,','))) OR (@rTimeSheetStatus='0')) 


		DROP Table #TempMonthTrans	

		--select
		--	@rBuilder1 AS Builder1,
		--	@rBuilder2 AS Builder2,
		--	CAST(0 AS bigint) AS EmployeeId,
		--	'' as EmpCode,
		--	'' AS EmployeeName,  
		--	'' AS OrganizationId,
		--	'' AS OrganizationTitle,
		--	0 AS OrganizationOrderIndex,
		--	CAST(0 AS bigint) AS EmployeeNumber,
		--	'' as TotalHour,
		--	'' as Tot_Early,
		--	'' as Tot_OT,
		--	'' as Tot_Late,
		--	0 as Count_Late,
		--	0 AS OrgId,
		--	'' AS OrganizationTitle,
		--	CAST('1999-01-01 00:00:00' AS datetime) as Attn_Date,
		--	'' as FirstIn,
		--	'' AS LateBy,
		--	'' as PresentStatus,
		--	'' AS EarlyBy,
		--	'' AS ShiftName,
		--	'' AS DeptName,
		--	0 As DeptId,
		--	@rOrderBy AS OrderBy,
		-- '' as LastOut


End
GO
PRINT N'Creating [sBiometric].[pRptTimeSheetListGet]...';


GO
CREATE PROCEDURE [sBiometric].[pRptTimeSheetListGet]
  @rBuilder1 nvarchar(max)='',
  @rBuilder2 nvarchar(max)='',
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,  
  @rTimeSheetStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rOrgGroupId int,
  @rEmployeeStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @rOrgGroupDepartmentId int = 0,
  @rGradeId nvarchar(max)= '0'

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
BEGIN 

CREATE TABLE #TempMonthTrans  
 (  
 Id int,  
 EmployeeId bigint,   
 Attn_Date DateTime,  
 PresentStatus nvarchar(15),  
 FirstIn nvarchar(20),  
 LastOut nvarchar(20),  
 OverTime nvarchar(20),  
 LateBy nvarchar(20),  
 Duration nvarchar(20),   
 EarlyBy nvarchar(20),
 ShiftName nvarchar(25)  
 )  
    Declare @ldate datetime,@lDays int
		declare @Days int
		Declare @Firstdate datetime
		Declare @Lastdate datetime
		DECLARE @lBatchID int
		DECLARE @lForYear nvarchar(20),@lForMonth nvarchar(20)
		Set @lForYear = Year(@rFromDate)
		
		Set @lForMonth = Month(@rFromDate)
		
		Set @ldate= CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		Select @lDays=day(dateadd(mm,DateDiff(mm, -1, @ldate),0) -1) 
		select @Days=sCommon.fGetDaysInMonth(@lForMonth,@lForYear)
		
		set @Firstdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), 01)
		set @Lastdate=CONVERT(nvarchar(20), @lForYear)+ '-' +  CONVERT(nvarchar(20), @lForMonth) + '-' + CONVERT(nvarchar(20), @Days)

 INSERT INTO #TempMonthTrans 
  select *
   from [sBiometric].[fBiometricTempMonthTransGet](@rOrgId ,@rOrganizationDepartmentId ,@rFromDate,@rToDate,@rEmployeeId)  
 

		
	 SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 as Builder2,
		TM.Id,
		TM.EmployeeId,
		TM.Attn_Date,
		OGD.Title AS [OrganizationGroupDepartment],
		TM.PresentStatus as PresentStatus,
		TM.FirstIn,
		TM.LastOut,
		TM.OverTime,
		TM.LateBy,
		TM.Duration,
		TM.EarlyBy,
		TM.ShiftName,
		 MT.Tot_Attn,
		 EM.FirstName + ' ' + EM.LastName As ShortName,
		 EM.Code as EmpCode ,   
		[sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,  
		ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
		ISNULL(SM.Id,0) AS StatusId,  
		ISNULL(SM.Title,'') AS Status  
	 FROM #TempMonthTrans TM   
	 INNER JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0)  
	 INNER JOIN sHRM.tEmployeeMaster EM ON EM.Id=TM.EmployeeId  
	 LEFT JOIN sBiometric.tEmployeeLateStatus ELS ON ELS.EmployeeId = TM.EmployeeId AND CONVERT(date,TM.Attn_Date) = CONVERT(date,ELS.LateDate)  
	 LEFT JOIN sCommon.tStatusMaster SM ON SM.Id = ELS.StatusId  
	 INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.Id AND (TM.ATTN_DATE >= ISNULL(cast(rtrim(YEAR(EJD.DateOfJoining) *10000+ Month(EJD.DateOfJoining) *100+ 01) as datetime),'1900/01/01'))
	 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
	 LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
	 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = EM.OrgId
	 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 (( @rTimeSheetStatus = '1' AND (TM.Duration < '09:30')) OR ( @rTimeSheetStatus != '1' AND ((PresentStatus = @rTimeSheetStatus OR @rTimeSheetStatus='0'))))
	 AND (EM.OrgId = @rOrgId OR @rOrgId = 0)
	 AND (OM.OrgGroupId = @rOrgGroupId)
	 AND ((EM.StatusId = @rEmployeeStatusId) OR (@rEmployeeStatusId = 0))
	 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
	 AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
	 AND  ISNULL(EM.IsOtherUser,0) = 0
	 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
	 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	 AND (EmployeeGradeId in ( SELECT cast(item as int) FROM  sCommon.fnsplit(@rGradeId,',')) OR @rGradeId=0) 
	 Order By TM.EmployeeId,TM.Attn_Date

 --SELECT  @rBuilder1 AS Builder1,
	--@rBuilder2 as Builder2,
	--0 as Id,
	--CAST(0 AS bigint) AS EmployeeId,
	--CAST('1999-01-01 00:00:00' AS datetime) as Attn_Date,
	--'' AS OldPresentStatus,
	--'' AS [OrganizationGroupDepartment],
	--'' as PresentStatus,
	--'' as FirstIn,
	--'' AS LastOut,
	--'' as OverTime,
	--'' as LateBy,
	--'' as Duration,
	--'' as EarlyBy,
	--'' as ShiftName, 
	--'' As ShortName,
	--'' as EmpCode ,
	--'' AS LeaveStatus , 
	--'' AS LeavePendingStatus, 
	--'' AS EmployeeTravel,
	--0 AS EmployeeLateStatusId, 
	--0 AS StatusId, 
	--'' AS Status  

 end
GO
PRINT N'Creating [sConfig].[pWebNotificationConfigGet]...';


GO
 
CREATE PROCEDURE [sConfig].[pWebNotificationConfigGet]
	@rOrgGroupId int
	
AS
BEGIN
CREATE TABLE #tmp
(
apiKey nvarchar(max),
authDomain nvarchar(max),
projectId nvarchar(max),
storageBucket nvarchar(max),
messagingSenderId nvarchar(max),
appId nvarchar(max),
measurementId nvarchar(max)
)

INSERT INTO #tmp
(apiKey,authDomain,projectId,storageBucket,messagingSenderId,appId,measurementId)
VALUES
(
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (499) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId),
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (500) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId),
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (501) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId),
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (502) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId),
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (503) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId),
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (504) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId),
	(Select ItemValue From sConfig.tConfigurationSetup
		Where ConfigurationId In (505) AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId)
)
SELECT * FROM #tmp
DROP TABLE #tmp
END
GO
PRINT N'Creating [sFee].[pChargeReceiptDashBoardGet]...';


GO
CREATE PROCEDURE [sFee].[pChargeReceiptDashBoardGet]
	
	@rOrgId int  =0,
	@rOrgGroupId int=0,
	@rOrgGroupBatchId bigint  =0,
	@rCommonOrgGroupBatchId int=0,
	@rFromDate varchar(10)='',
	@rToDate varchar(10)='',
	@rChargeType nvarchar(100)='',
	@rChargeReceiptBookId int=0,
	@rUserId Bigint=0

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY 
	IF OBJECT_ID('tempdb..#tempReceiptOrganizationSync') IS NOT NULL DROP TABLE #tempReceiptOrganizationSync
	IF OBJECT_ID('tempdb..#tempReceiptOrgSync') IS NOT NULL DROP TABLE #tempReceiptOrgSync
	IF OBJECT_ID('tempdb..#tempReceiptUserSync') IS NOT NULL DROP TABLE #tempReceiptUserSync
	IF OBJECT_ID('tempdb..#tempReceiptBookWise') IS NOT NULL DROP TABLE #tempReceiptBookWise
	IF OBJECT_ID('tempdb..#tempReceiptUserWise') IS NOT NULL DROP TABLE #tempReceiptUserWise
	IF OBJECT_ID('tempdb..#tempReceiptOrgWise') IS NOT NULL DROP TABLE #tempReceiptOrgWise
	IF OBJECT_ID('tempdb..#tempReceiptOrgCountWise') IS NOT NULL DROP TABLE #tempReceiptOrgCountWise
	IF OBJECT_ID('tempdb..#tempReceiptOrgwiseSync') IS NOT NULL DROP TABLE #tempReceiptOrgwiseSync
	
	IF(@rChargeType='ReceiptBookwise' OR @rChargeType='ReceiptCountwise' OR @rChargeType='ReceiptAmountwise' OR @rChargeType='ReceiptCancelAmountwise')
	BEGIN
		CREATE TABLE #tempReceiptOrganizationSync
		(
			OrgGroupId int,
			OrgGroupName nvarchar(500),
			ReceiptId bigint,
			TotalReceiptAmount DECIMAL(12,2),
			IsObsolete bit,
			ChargeReceiptBookId int,
			ReceiptBookName nvarchar(100)
		)
		
		INSERT INTO #tempReceiptOrganizationSync
		SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,CR.Id AS ReceiptId,CR.ReceiptAmount,CR.IsObsolete
			  ,CR.ChargeReceiptBookId,RBM.Title As ReceiptBookName
		FROM  sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE COGBM.Id=@rCommonOrgGroupBatchId AND CR.SourceTypeId = 2001
			  AND ( (O.Id= @rOrgGroupId) OR  (@rOrgGroupId=0) )
			  AND ( (OM.Id= @rOrgId) OR  (@rOrgId=0) )
			  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			  AND (COGBM.Id=@rCommonOrgGroupBatchId ) AND ISNULL(O.IsObsolete,0) = 0 
			  AND (CR.ReceiptDate between @rFromDate and @rToDate)    

		CREATE TABLE #tempReceiptBookWise
		(
			OrgGroupId smallint,
			OrgGroupName nvarchar(100),
			ReceiptCount int,
			TotalReceiptAmount DECIMAL(12,2),
			CancelAmount DECIMAL(12,2),
			ReceiptDate datetime,
			CommonOrgGroupBatchId int,
			UpdateDate datetime,
			ChargeReceiptBookId int,
			ReceiptBookName nvarchar(100)
		)

		INSERT INTO #tempReceiptBookWise
		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(),T.ChargeReceiptBookId,T.ReceiptBookName
		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,T.ChargeReceiptBookId,T.ReceiptBookName
		ORDER BY OrgGroupId

		SELECT TR.OrgGroupId,TR.OrgGroupName,TR.ReceiptCount,TR.TotalReceiptAmount AS ReceiptAmount,TR.CancelAmount,TR.ReceiptDate 
			  ,TR.CommonOrgGroupBatchId,TR.UpdateDate ,TR.ChargeReceiptBookId,TR.ReceiptBookName  
		FROM #tempReceiptBookWise TR
		WHERE TR.CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((TR.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			  AND ((TR.ChargeReceiptBookId=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
	END	

	ELSE IF(@rChargeType='Userwise' OR @rChargeType='UserReceiptCountwise' OR @rChargeType='UserReceiptAmountwise' OR @rChargeType='UserReceiptCancelAmountwise')
	BEGIN
		CREATE TABLE #tempReceiptUserSync
		(
			OrgGroupId int,
			OrgGroupName nvarchar(500),
			ReceiptId bigint,
			TotalReceiptAmount DECIMAL(12,2),
			IsObsolete bit,
			CreatedUserId Bigint,
			UserId Bigint,
			UserName nvarchar(50)
		)
		
		INSERT INTO #tempReceiptUserSync
		SELECT OMM.Id AS OrgGroupId,OMM.Title AS OrgGroupName,CR.Id AS ReceiptId,CR.ReceiptAmount,CR.IsObsolete
			  ,CR.CreatedUserId,U.Id As UserId,U.DisplayTitle AS UserName
		FROM  sFee.tChargeReceipt CR		
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = SA.BatchId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=CR.CreatedUserId
		WHERE CR.SourceTypeId = 2001 AND (COGBM.Id=@rCommonOrgGroupBatchId )
			  AND ((OMM.Id= @rOrgGroupId) OR (@rOrgGroupId=0) )
			  AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			  AND ((OM.Id= @rOrgId) OR (@rOrgId=0)) AND ISNULL(OMM.IsObsolete,0) = 0 
			  AND (CR.ReceiptDate between @rFromDate AND @rToDate)    

		CREATE TABLE #tempReceiptUserWise
		(
			OrgGroupId smallint,
			OrgGroupName nvarchar(100),
			ReceiptCount int,
			TotalReceiptAmount DECIMAL(12,2),
			CancelAmount DECIMAL(12,2),
			ReceiptDate datetime,
			CommonOrgGroupBatchId int,
			UpdateDate datetime,
			UserId Bigint,
			UserName nvarchar(50)
		)
		INSERT INTO #tempReceiptUserWise
		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(),T.UserId,T.UserName
		FROM #tempReceiptUserSync T  
		LEFT JOIN (
		SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptUserSync WHERE IsObsolete = 1
		GROUP BY OrgGroupId,OrgGroupName
		) A ON A.OrgGroupId=t.OrgGroupId
		WHERE IsObsolete = 0
		GROUP BY T.OrgGroupId,T.OrgGroupName,A.CancelReceiptCount,T.CreatedUserId,T.UserId,T.UserName
		ORDER BY OrgGroupId

		SELECT TR.OrgGroupId,TR.OrgGroupName, TR.ReceiptCount,TR.TotalReceiptAmount AS ReceiptAmount,TR.CancelAmount,
			   TR.ReceiptDate,TR.CommonOrgGroupBatchId,TR.UpdateDate,TR.UserId,TR.UserName 
		FROM #tempReceiptUserWise TR
		WHERE TR.CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((TR.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
			AND ((TR.UserId=@rUserId) OR (@rUserId=0))
	END

	ELSE IF(@rChargeType='Organizationwise')
	BEGIN
		CREATE TABLE #tempReceiptOrgSync
		(
			OrgGroupId smallint,
			OrgGroupName nvarchar(100),
			ReceiptId bigint,
			TotalReceiptAmount DECIMAL(12,2),
			IsObsolete bit
		)
		
		INSERT INTO #tempReceiptOrgSync
		SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,CR.Id AS ReceiptId,CR.ReceiptAmount AS TotalReceiptAmount,CR.IsObsolete
		FROM  sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster CRBM ON CRBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OM.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		WHERE CR.SourceTypeId = 2001
			  AND ((O.Id= @rOrgGroupId) OR (@rOrgGroupId=0) )
			  AND ((OM.Id= @rOrgId) OR (@rOrgId=0) )
			  AND ((OGBM.Id = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			  AND (COGBM.Id=@rCommonOrgGroupBatchId) AND ISNULL(O.IsObsolete,0) = 0 
			  AND (CR.ReceiptDate between @rFromDate AND @rToDate)    

		CREATE TABLE #tempReceiptOrgWise
		(
			OrgGroupId smallint,
			OrgGroupName nvarchar(100),
			ReceiptCount int,
			TotalReceiptAmount DECIMAL(12,2),
			CancelAmount DECIMAL(12,2),
			ReceiptDate datetime,
			CommonOrgGroupBatchId int,
			UpdateDate datetime
		)
		INSERT INTO #tempReceiptOrgWise
		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 #tempReceiptOrgSync T  
		LEFT JOIN (
		SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrgSync 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 TR.OrgGroupId AS OrgGroupId,TR.OrgGroupName AS OrgGroupName, TR.ReceiptCount,TR.TotalReceiptAmount AS ReceiptAmount,
			   TR.CancelAmount,TR.ReceiptDate,TR.CommonOrgGroupBatchId,TR.UpdateDate
		FROM #tempReceiptOrgWise TR
		WHERE TR.CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((TR.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		GROUP BY TR.OrgGroupId,TR.OrgGroupName,TR.ReceiptCount,TR.TotalReceiptAmount,TR.CancelAmount ,
			TR.ReceiptDate ,TR.CommonOrgGroupBatchId ,TR.UpdateDate
	END

	ELSE IF(@rChargeType='OrganizationCountwise' OR @rChargeType='OrganizationAmountwise' OR @rChargeType='OrganizationCancelAmountwise')
	BEGIN
		CREATE TABLE #tempReceiptOrgwiseSync
		(
			OrgGroupId smallint,
			OrgGroupName nvarchar(100),
			ReceiptId bigint,
			TotalReceiptAmount DECIMAL(12,2),
			IsObsolete bit
		)
		
		INSERT INTO #tempReceiptOrgwiseSync
		SELECT O.Id AS OrgGroupId ,O.Title AS OrgGroupName,CR.Id AS ReceiptId,CR.ReceiptAmount AS TotalReceiptAmount,CR.IsObsolete
		FROM  sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster CRBM ON CRBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster O ON O.Id =  OM.OrgGroupId
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId	
		WHERE CR.SourceTypeId = 2001
			  AND ((O.Id= @rOrgGroupId) OR (@rOrgGroupId=0) )
			  AND ((OM.Id= @rOrgId) OR (@rOrgId=0) )
			  AND ((OGBM.Id = @rOrgGroupBatchId) OR (@rOrgGroupBatchId=0))
			  AND (COGBM.Id=@rCommonOrgGroupBatchId) AND ISNULL(O.IsObsolete,0) = 0 
			  AND (CR.ReceiptDate between @rFromDate AND @rToDate)    

		CREATE TABLE #tempReceiptOrgCountWise
		(
			OrgGroupId smallint,
			OrgGroupName nvarchar(100),
			ReceiptCount int,
			TotalReceiptAmount DECIMAL(12,2),
			CancelAmount DECIMAL(12,2),
			ReceiptDate datetime,
			CommonOrgGroupBatchId int,
			UpdateDate datetime
		)
		INSERT INTO #tempReceiptOrgCountWise
		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 #tempReceiptOrgwiseSync T  
		LEFT JOIN (
		SELECT  OrgGroupId,OrgGroupName,SUM(TotalReceiptAmount) AS CancelReceiptCount  FROM #tempReceiptOrgwiseSync 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 TR.OrgGroupId AS OrgGroupId,TR.OrgGroupName AS OrgGroupName, TR.ReceiptCount,TR.TotalReceiptAmount AS ReceiptAmount,
			   TR.CancelAmount,TR.ReceiptDate,TR.CommonOrgGroupBatchId,TR.UpdateDate
		FROM #tempReceiptOrgCountWise TR
		WHERE TR.CommonOrgGroupBatchId = @rCommonOrgGroupBatchId AND ((TR.OrgGroupId = @rOrgGroupId)OR(@rOrgGroupId=0))
		GROUP BY TR.OrgGroupId,TR.OrgGroupName,TR.ReceiptCount,TR.TotalReceiptAmount,TR.CancelAmount ,
			TR.ReceiptDate ,TR.CommonOrgGroupBatchId ,TR.UpdateDate
	END

	ELSE IF(@rChargeType='OrganizationReceiptAmountwise' OR @rChargeType='OrganizationReceiptCountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE   COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 					 
				AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
				AND ((OM.Id= @rOrgId) OR (@rOrgId=0) )AND OMM.IsObsolete = 0
				AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
				AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
				AND ((CR.ChargeReceiptBookId=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
		Order By CR.ReceiptNumber
	END

	ELSE IF(@rChargeType='OrganizationReceiptCancelAmountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount AS CancelAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 					 
			  AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
			  AND ((OM.Id= @rOrgId) OR (@rOrgId=0) ) AND OMM.IsObsolete = 1
			  AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
			  AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
	END
	
	ELSE IF(@rChargeType='ReceiptBookAmountwise' OR @rChargeType='ReceiptBookCountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 					 
			 AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
			 AND ((OM.Id= @rOrgId) OR (@rOrgId=0)) AND OMM.IsObsolete = 0
			 AND ((RBM.Id=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
			 AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
			 AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
	END

	ELSE IF(@rChargeType='ReceiptBookCancelAmountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount AS CancelAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 					 
			   AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
			   AND ((RBM.Id=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
			   AND ((OM.Id= @rOrgId) OR (@rOrgId=0)) AND OMM.IsObsolete = 1
			   AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
			   AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
	END

	ELSE IF(@rChargeType='UserAmountwise' OR @rChargeType='UserCountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=CR.CreatedUserId
		WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 					 
			   AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
			   AND ((U.Id=@rUserId) OR (@rUserId=0))
			   AND ((OM.Id= @rOrgId) OR (@rOrgId=0)) AND OMM.IsObsolete = 0
			   AND ((RBM.Id=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
			   AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
			   AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
	END

	ELSE IF(@rChargeType='UserCancelAmountwise')
	BEGIN
		SELECT  CR.ReceiptNumber AS ReceiptNumber,CR.ReceiptDate AS ReceiptDate,SA.Code AS Code, SA.Name AS Name
				,CR.ReceiptAmount AS CancelAmount
		FROM sFee.tChargeReceipt CR
		INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=CR.SourceId 
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=CR.PayTypeId
		INNER JOIN sFee.tChargeReceiptBookMaster RBM ON RBM.Id=CR.ChargeReceiptBookId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SA.OrgId
		INNER JOIN sSetup.tOrgGroupMaster OMM ON OMM.Id = OM.OrgGroupId 
		INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.ID=SA.OrgGroupBatchId
		INNER JOIN sSetup.tCommonOrgGroupBatchMaster COGBM ON COGBM.Id=OGBM.CommonOrgGroupBatchId
		LEFT JOIN sSecurity.tUser U ON U.Id=CR.CreatedUserId
		WHERE  COGBM.Id= @rCommonOrgGroupBatchId  AND CR.SourceTypeId = 2001 					 
			   AND((OMM.Id=@rOrgGroupId) OR (@rOrgGroupId=0))
			   AND ((U.Id=@rUserId) OR (@rUserId=0))
			   AND ((OM.Id= @rOrgId) OR (@rOrgId=0)) AND OMM.IsObsolete = 1
			   AND ((RBM.Id=@rChargeReceiptBookId) OR (@rChargeReceiptBookId=0))
			   AND ((CONVERT(DATE, CR.ReceiptDate,102) >= @rFromDate) OR (@rFromDate=''))
			   AND ((CONVERT(DATE, CR.ReceiptDate,102) <= @rToDate) OR (@rToDate=''))
	END

	END TRY 

	BEGIN CATCH
	SELECT -1 AS Result,ERROR_LINE(),ERROR_MESSAGE()
	END CATCH
END
GO
PRINT N'Creating [sStudent].[pUserControlAllStudentSearchGet]...';


GO
CREATE PROCEDURE [sStudent].[pUserControlAllStudentSearchGet]  
    
 @rClassId int=0,  
 @rDivisionId int=0,  
 @rRollNo int=NULL,  
 @rOrgId int,  
 --@rNumber bigint,  
 @rCode nvarchar(20),  
 @rStatusId smallint=0,  
 @rFirstName nvarchar(100)='',  
 @rLastName nvarchar(100)='',  
 @rBatchId int = 0,  
 @rOrgGroupBatchId int = 0,  
 @rSUId nvarchar(50)=''  
   
   
WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON      
  
BEGIN     
  BEGIN  
   SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)  
   SET @rLastName = sCommon.fSearchStringGet(@rLastName)  
  END  
 IF(@rRollNo IS NULL)  
 BEGIN  
 SELECT   
   SA.AcademicId,  
   SA.StudentId,  
   SA.FirstName,  
   SA.LastName,  
   SA.MiddleName,  
   SA.Name,  
   SA.Code,  
   SA.ClassId,  
   SA.ClassName,  
   SA.DivisionId,  
   SA.DivisionName,  
   SA.Number,  
   SA.RollNo,  
   SA.StatusId,  
   SA.StatusName,  
   SA.OrgId,  
   --SA.Age,  
   ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,  
   SA.BatchId,  
   SA.SUId,  
   ISNULL(So.GenderId,0) AS GenderId  
  FROM   
          sStudent.vStudentAcademic SA  
           LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId  
  WHERE   
   
  ((SA.ClassId=@rClassId)OR(@rClassId=0))  
  AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))  
  AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = ''))   
  AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = ''))   
  AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = ''))   
  AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))   
  AND(SA.OrgId=@rOrgId OR @rOrgId = 0)  
  AND ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
  AND(SA.BatchId=@rBatchId or @rBatchId = 0)  
  --AND((SA.Number=@rNumber)OR(@rNumber=0))   
  AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))  
  
ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
END  
ELSE  
BEGIN  
 SELECT   
   SA.AcademicId,  
   SA.StudentId,  
   SA.FirstName,  
   SA.LastName,  
   SA.MiddleName,  
   SA.Name,  
   SA.Code,  
   SA.ClassId,  
   SA.ClassName,  
   SA.DivisionId,  
   SA.DivisionName,  
   SA.Number,  
   SA.RollNo,  
   SA.StatusId,  
   SA.StatusName,  
   SA.OrgId,  
   --SA.Age,  
   ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,  
   SA.SUId,  
   ISNULL(So.GenderId,0) AS GenderId  
  FROM   
          sStudent.vStudentAcademic SA      
           LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId           
  WHERE   
   
  ((SA.ClassId=@rClassId)OR(@rClassId=0))  
  AND((SA.DivisionId=@rDivisionId)OR(@rDivisionId=0))  
  AND((SA.Code=@rCode) OR (ISNULL(@rCode,'') = ''))   
  AND((SA.FirstName like @rFirstName) OR (ISNULL(@rFirstName,'') = ''))   
  AND((SA.LastName like @rLastName) OR (ISNULL(@rLastName,'') = ''))   
  AND(SA.RollNo=@rRollNo)  
  AND((SA.StatusId=@rStatusId)OR(@rStatusId=0))   
  AND((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
   AND ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
  AND(SA.BatchId=@rBatchId or @rBatchId = 0)  
  --AND(SA.BatchId=@rBatchId)  
  --AND((SA.Number=@rNumber)OR(@rNumber=0))  
  AND((SA.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))    
  
ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
END  
    
END
GO

 
  
  

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