

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




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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [ResultIndicator]   NVARCHAR (50) NULL,
        [IsResultIndicator] BIT           NULL;


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


GO
ALTER TABLE [sStudent].[tStudentMaster]
    ADD [PENNumber] BIGINT NULL;


GO

PRINT N'Creating Table [sSecurity].[tForgotPasswordFailureLog]...';


GO
CREATE TABLE [sSecurity].[tForgotPasswordFailureLog] (
    [AutoId]              BIGINT          IDENTITY (1, 1) NOT NULL,
    [OrgId]               SMALLINT        NOT NULL,
    [Username]            NVARCHAR (100)  NOT NULL,
    [Code]                NVARCHAR (20)   NOT NULL,
    [EmailId]             NVARCHAR (100)  NULL,
    [MobileNumber]        NVARCHAR (20)   NULL,
    [SourceId]            BIGINT          NOT NULL,
    [SourceTypeId]        SMALLINT        NULL,
    [IsSendAlert]         BIT             NULL,
    [IsResetPassword]     BIT             NULL,
    [ExceptionType]       NVARCHAR (1000) NULL,
    [ExceptionMessage]    NVARCHAR (MAX)  NOT NULL,
    [ExceptionSource]     NVARCHAR (MAX)  NULL,
    [ExceptionStackTrace] NVARCHAR (MAX)  NULL,
    [ExceptionDetail]     NVARCHAR (MAX)  NULL,
    [UserId]              BIGINT          NOT NULL,
    [CreatedDateTime]     DATETIME        NOT NULL,
    [UpdatedDateTime]     DATETIME        NULL,
    [OsTypeId]            SMALLINT        NOT NULL
);


GO

GO
PRINT N'Altering View [sStudent].[vStudentAcademic]...';


GO
ALTER VIEW sStudent.vStudentAcademic
AS
SELECT        A.Id AS AcademicId, A.ClassId, A.DivisionId, A.RollNo, A.OrgId, A.BatchId, SM.Id AS StudentId, SM.Code, ISNULL(SM.Number, 0) AS Number, SM.RegistrationNumber, SM.FirstName, SM.MiddleName, SM.LastName, 
                         sStudent.fStudentNameGet(SM.FirstName, SM.MiddleName, SM.LastName, OM.StudentNameFormatId) AS Name, CONVERT(Nvarchar(20), A.RollNo) + '-' + SM.FirstName + ' ' + SM.LastName AS RollNoName, SM.StatusId, 
                         CM.DisplayTitle AS ClassName, DM.DisplayTitle AS DivisionName, STM.Title AS StatusName, SM.RecordStatusId, DM.InchargeEmployeeId, BM.OrgGroupBatchId, ISNULL(A.AdmissionCategoryId, 0) AS AdmissionCategoryId, 
                         DM.OrderIndex AS DivisionOrder, BM.IsActive AS IsActiveBatch, BM.Title AS BatchName, ISNULL(DeptM.Id, 0) AS DepartmentId, ISNULL(DeptM.Title, '') AS DepartmentName, SM.IsBlackList, SM.BlackListReason, 
                         CM.OrderIndex AS ClassOrderIndex, ISNULL(A.ExemptionTypeId, 0) AS ExemptionTypeId, ISNULL(OM.DisplayTitle, '') AS OrganizationName, OM.StreetOne, OM.StreetTwo, OM.StreetThree, OM.ZipCode, ISNULL(SM.SUId, '') 
                         AS SUId, ISNULL(OM.ReportOrgGroupTitle, '') AS ReportOrgGroupTitle, ISNULL(OM.ReportOrgTitle, '') AS ReportOrgTitle, ISNULL(A.FeeStructureId, 0) AS FeeStructureId, SM.ReferenceSourceId, SM.StudentGroupId, 
                         SM.StudentOtherGroupId, A.BatchStatusId, A.ClassStatusId, STM1.Title AS ClassStatusName, ISNULL(SO.GenderId, 0) AS GenderId, ISNULL(A.FeesRemark, '') AS FeesRemark,
						 --Mantis Start -0031338  
						 ISNULL(SM.PENNumber, 0) AS PENNumber 
						 --Mantis End -0031338 
FROM            sStudent.tAcademic AS A INNER JOIN
                         sStudent.tStudentMaster AS SM ON A.StudentId = SM.Id INNER JOIN
                         sSetup.tClassMaster AS CM ON CM.Id = A.ClassId INNER JOIN
                         sSetup.tDivisionMaster AS DM ON DM.Id = A.DivisionId INNER JOIN
                         sSetup.tBatchMaster AS BM ON BM.Id = A.BatchId INNER JOIN
                         sStudent.tStatusMaster AS STM ON STM.Id = SM.StatusId INNER JOIN
                         sSetup.tDepartmentMaster AS DeptM ON DeptM.Id = CM.DepartmentId INNER JOIN
                         sSetup.tOrganizationMaster AS OM ON A.OrgId = OM.Id INNER JOIN
                         sStudent.tStatusMaster AS STM1 ON STM1.Id = A.ClassStatusId LEFT OUTER JOIN
                         sStudent.tStudentOther AS SO ON SO.StudentId = SM.Id
GO

GO
PRINT N'Altering Procedure [sAssessment].[pRptSubjectResultListFloating]...';


GO
ALTER PROCEDURE [sAssessment].[pRptSubjectResultListFloating]
	 
	 @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,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	@rIsShowWithDetail bit =0,
	@rFilterId int=0,
	@rOrgGroupBatchId int=0,
	@rClassStatusId int=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 --Select * from dbo.Float
 --Select
 --           ''  AS AcademicIdText,
	--		'' AS ExamIdText,
	--		'' AS IsDisplayMonthlyAttendanceText,
	--		'' AS Exam,
	--		'' AS Builder1,
	--		'' Code,
	--		'' AS Name,
	--		0 RollNo,
	--		Convert(BigInt ,0) AS AcademicId,			
	--		'' ResultStatus,
	--		'' AS Class,
	--		'' AS Division,
	--		Convert(decimal , 0) TotalMarks,
	--		Convert(decimal , 0) TotalObtain,
	--		Convert(decimal , 0) Percentage,
	--		0 RankNumber,
	--		'' ResultGrade,
	--		Convert(decimal , 0) Percentile,			
	--		Convert(BigInt ,0) AS ResultDetailId,		
	--		Convert(bit, 0) IsDisplayInMarksheet,
	--		Convert(bit, 0) IsShowSubjectGrade,
	--		Convert(bit, 0) IsIncludeInTotal,
	--		Convert(decimal , 0) AS SubjectObtain,
	--		Convert(decimal , 0) AS SubjectMinimum,
	--		Convert(decimal , 0) AS SubjectMaximum,			
	--		'' AS SubjectCode,
	--		'' AS SubjectName,
	--		0 AS SubjectOrderIndex,
	--		Convert(BigInt ,0) AS ResultId,
	--		0 AS SubjectId,			 	
	--		Convert(bit, 0) IsMarksInDecimal,
			
	--		 '' AS Remark1,
	--		'' AS Remark2,
	--		'' AS Remark3,
	--		'' DisplayTitle,
	--		Convert(bit, 0) IsRankNo, 
	--		Convert(bit, 0) IsGrade,
	--		Convert(bit, 0) IsPercentile,
	--		Convert(bit, 0) IsPercentage,
	--		Convert(bit, 0) IsSubjectPercentile,
	--		Convert(bit, 0) IsProcessResult,
			 
	--		Convert(bit, 0) IsNegativeMarks,
	--		Convert(bit, 0) IsIncludeCoScholastic,
	--		Convert(bit, 0) IsOnPrePrinted,
	--		Convert(bit, 0) IsDisplayPhoto,
	--		Convert(bit, 0) IsDisplayBirthDate,
	--		Convert(bit, 0) IsLockForEdit,
	--		Convert(bit, 0) IsDisplaySchoolName,			
	--		Convert(bit, 0) IsDisplayAttendance,
	--		Convert(bit, 0) IsDisplayHeightWeight,
	--		Convert(bit, 0) IsResultStatus,
	--		'' AS FooterAdjustmentText,
	--		'' AS DetailAdjustmentText,
	--		0 FooterAdjustment,
	--		0 DetailAdjustment,
		 		 
	--		0 TermScopeId,
		 
	--		Convert(bit, 0) IsPresent,
	--		'' AS GradeString,
	--		Convert(bit, 0) IsDisplayGradeString,
	--		Convert(decimal , 0) HighestDivisionMark,
	--		 ''  AS HighestDivisionGrade,			
	--		'' SmallAddress1,
	--		Convert(bit, 0) IsDisplayParentName,
			 
	--		Convert(bit, 0) AS IsShowSubjectMark,
			
	--		Convert(bit, 0) IsDisplayTeacherSign,
	--		Convert(bit, 0) IsDisplayPrincipalSign,
		 
	--		Convert(bit, 0) AS IsDisplayMonthlyAttendance,
			 
	--		Convert(bit, 0) AS IsImageHeader,
			 
	--		0 SubExamId,
	--		0 ExamOrderIndex,
	--		0 AnnualExamId ,
	--		'' DecimalFormat,
	--		0 TermExamId,
	--		'' AS ExamNAme, 			 
	--		'' AS AnnualSubjectGrade,
	--		Convert(decimal , 0) As AnnualSubjectObtain,
	--		'' AS TermSubjectGrade,
	--		Convert(decimal , 0) As TermSubjectObtain ,
	--		'' AS SubjectGrade,
	--      '' AS Remark,
	--      Convert(decimal , 0) AS ExamMaximum,
	--	  Convert(bit, 0) IsAbsentRemark,
	--	  '' AS AbsentRemark,
	--		0 TermExamOrderIndex
	  
			
 
 
 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int, @lOrgId int, @lAbsentRemarkConfig nvarchar(20) = ''
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  
SELECT @lOrgId=OrgId FROM sSetup.tBatchMaster WHERE Id=@rBatchId
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId

CREATE TABLE #TempExam
(
	SubExamId int, 
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int, 
	Exam nvarchar(50),
	ExamMaximum decimal(6,2),
	TermExamOrderIndex int		-- MantisId : 0031760
)
--INSERT INTO #TempExam
--(
--	SubExamId,	 
--	ExamOrderIndex,
--	ExamId,
--	Exam 
--)
--Select 
	 
--	EC.SubExamId,
--	EC.ExamOrder,
--	EM.Id As ExamId,
--	ES.Title AS Exam
--	from sAssessment.tExamMaster EM 
--	INNER JOIN sAssessment.tExamCombine EC ON EC.ExamId = EM.Id 
--	INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = EM.ExamSubGroupId 
--	WHERE EM.Id=@rExamId 
Declare @lExamMaximum decimal(6,2)
Select @lExamMaximum = ExamMaximum from sAssessment.tExamMaster Where Id = @rExamId
INSERT INTO #TempExam
(
	 SubExamId,
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam,
	 ExamMaximum,
	 TermExamOrderIndex		-- Mantis Id : 0031760
)
Select  
	EC.SubExamId,
	EC.ExamOrder,
	EC.ExamId AS TermExamId,
	@rExamId AS AnnualExamId,
	ES.Title AS Exam,
	@lExamMaximum,
	SE.ExamOrder AS TermExamOrderIndex		-- Mantis Id : 0031760

	from  sAssessment.tExamCombine EC 
	INNER JOIN sAssessment.tExamMaster EM  ON EC.ExamId = EM.Id 
	 INNER JOIN sAssessment.tExamSubGroupMaster ES ON ES.Id = EM.ExamSubGroupId
	 INNER JOIN (select SubExamId, ExamOrder from sAssessment.tExamCombine where examId = @rExamId) AS SE
	 ON EC.ExamId = SE.SubExamId  
	--WHere EC.ExamId  in  (select SubExamId from sAssessment.tExamCombine where examId = @rExamId  )
	--Select * from #TempExam
	
 
		
	
	
	
--INSERT INTO #TempExam
--(
--	ExamId, 
--	ExamOrderIndex
--)
--Select 
	 
--	@rExamId,
--	999 
	 --Select * from #TempExam
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			 @rBuilder1 AS Builder1,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			 
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
		 		 
			EM.TermScopeId,
		 
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
		 
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			 
			EC.SubExamId,
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			EM.DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamNAme, 			 
			ARD.SubjectGrade AS AnnualSubjectGrade,
			ARD.Obtain As AnnualSubjectObtain,
			TRD.SubjectGrade AS TermSubjectGrade,
			TRD.Obtain As TermSubjectObtain ,
			RD.SubjectGrade AS SubjectGrade,
			ISNULL(ARD.Remark,'')  AS Remark,
			EC.ExamMaximum,
			CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,
			ISNULL(RD.AbsentRemark,'') AS AbsentRemark,
			EC.TermExamOrderIndex								-- Mantis Id : 0031760
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.SubExamId = EM.Id 	
			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 BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			INNER JOIN sAssessment.tResult AR ON AR.AcademicId = A.Id AND AR.ExamId = EC.AnnualExamId 
			INNER JOIN sAssessment.tResultDetail ARD ON AR.Id = ARD.ResultId 
			INNER JOIN sAssessment.tExamDetail AED ON ARD.EXamDetailId = AED.Id 
			INNER JOIN sSetup.tClassSubject ACS ON AED.ClassSubjectId = ACS.Id AND ACS.SubjectId = @rSubjectId  
			INNER JOIN sAssessment.tResult TR ON TR.AcademicId = A.Id AND TR.ExamId = EC.TermExamId 
			INNER JOIN sAssessment.tResultDetail TRD ON TR.Id = TRD.ResultId 
			INNER JOIN sAssessment.tExamDetail TED ON TRD.EXamDetailId = TED.Id 
			INNER JOIN sSetup.tClassSubject TCS ON TED.ClassSubjectId = TCS.Id AND TCS.SubjectId = @rSubjectId 
			
			
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.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 
				
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			--LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
			--LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
			--LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			--LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
			--LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
			--LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
			--LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		--AND (R.ExamId = @rExamId)
	 
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		--order by A.RollNo,CS.OrderIndex 
		
	 drop table #TempExam
		
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardGet]...';


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

BEGIN 

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

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

--add for 28663 mantis start
DECLARE @lAbsentRemarkConfig nvarchar(20) = ''
SELECT @lAbsentRemarkConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 515 AND SourceTypeId = 1016 AND SourceId = @lOrgId
--add for 28663 mantis end
 
	SELECT 
	R.examId,
		Convert(nvarchar(20),A.Id) AS AcademicIdText,
		Convert(nvarchar(20),@rExamId) AS ExamIdText,
		Convert(nvarchar(20),EM.CoScholasticScopeId) AS CoScholasticScopeIdText,
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
		Convert(nvarchar(20),@rBatchId) AS BatchIdText,
		ESGM.Title AS Exam,
		StuM.Code,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		R.AcademicId,			
		R.ResultStatus,
		CM.DisplayTitle AS Class,
		DM.DisplayTitle AS Division,
		R.TotalMarks,
		R.TotalObtain,
		R.Percentage,
		R.RankNumber,
		R.ResultGrade,
		R.Percentile,			
		RD.Id AS ResultDetailId,		
		ED.IsDisplayInMarksheet,
		ED.IsShowSubjectGrade,
		ED.IsIncludeInTotal,
		RD.Obtain AS SubjectObtain,
		ED.Minimum AS SubjectMinimum,
		ED.Maximum AS SubjectMaximum,
		RD.SubjectGrade,
		SM.Code AS SubjectCode,
		SM.Title AS SubjectName,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		R.Id AS ResultId,
		CS.Id AS SubjectId,			 	
		EM.IsMarksInDecimal,
		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsMarksInDecimal,
		EM.IsNegativeMarks,
		EM.IsIncludeCoScholastic,
		EM.IsOnPrePrinted,
		EM.IsDisplayPhoto,
		EM.IsDisplayBirthDate,
		EM.IsLockForEdit,
		EM.IsDisplaySchoolName,			
		EM.IsDisplayAttendance,
		EM.IsDisplayHeightWeight,
		EM.IsResultStatus,
		REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
		REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
		EM.FooterAdjustment,
		EM.DetailAdjustment,
		--ISNULL(R.ResultRemark,'') AS ResultRemark,
		SO.DateOfBirth,
		EM.TermScopeId,
		(CASE EM.IsDisplayPhoto WHEN 1 THEN
			SI.StudentPhoto
		ELSE NULL END) AS StudentPhoto,
		RD.IsPresent,
		CASE @GradeStringRemark WHEN '' THEN @GradeString  ELSE @GradeStringRemark END AS GradeString,
		EM.IsDisplayGradeString,
		(CASE EM.IsDisplayHighestDivisionMark
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
		ELSE 0 END) AS HighestDivisionMark,
		(CASE EM.IsDisplayHighestDivisionGrade
		WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
		ELSE '' END) AS HighestDivisionGrade,			
		OM.SmallAddress1,
		EM.IsDisplayParentName,
		SF.FatherName,
		SF.MotherName,
		ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
		
		EM.IsDisplayTeacherSign,
		Em.IsDisplayPrincipalSign,
		(CASE 	EM.IsDisplayTeacherSign WHEN 1 THEN
			EI.EmployeeSign
		ELSE NULL END)AS EmployeeSign,
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		--(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
		--	OI.CertificateHeaderA4 
		--ELSE 
		--	NULL END) AS MarksheetHeaderA4,
		(CASE EM.IsDisplayImageHeader WHEN 1 THEN 
			OI.MarksheetHeaderA4 
		ELSE 
			NULL END) AS MarksheetHeaderA4,
		ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
		
		SR.StudentHeight,
		SR.StudentWeight,		
		SR.PresentDays,			
		SR.TotalDays,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.Resultremark3,
		ISNULL(SR.MyGoal,'') AS MyGoal,
		ISNULL(SR.AreaOfInterest,'') AS AreaOfInterest,
		ISNULL(SR.Responsibility,'') AS Responsibility,
		ISNULL(SR.MyInterestHobby,'') AS MyInterestHobby,
		ISNULL(SR.MyStrength,'') AS MyStrength,
		ISNULL(SR.Achievements,'') AS Achievements,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.DentalHygiene,'') AS DentalHygiene,
		ISNULL(SR.VisionLeft,'') AS VisionLeft,
		ISNULL(SR.VisionRight,'') AS VisionRight,
		ISNULL(SR.ImprovementArea,'') As ImprovementArea,
		ISNULL(SR.ProgressArea,'') AS ProgressArea,
		ISNULL(SR.GeneralRemark,'') As GeneralRemark,
		ISNULL(SR.MyActivity,'') AS MyActivity,
		ISNULL(SR.ClassTeacherRemark,'') As ClassTeacherRemark,
		ISNULL(SR.HouseRemark,'') As HouseRemark,
		ISNULL(Emp.FirstName,'') +' ' + ISNULL(EMp.LastName,'') AS ClassTeacherName,
		BM.Title AS BatchName,
		Em.DecimalFormat,
		RD.GraceMark,
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		ISNULL(SG.Title,'')AS SubjectGroupTitle,
		ISNULL(SG.Code,'') AS SubjectGroupCode,
		@lGradeStringText AS GradeStringText,
		ISNULL(HM.Title,'') AS House,
		ISNULL(EM.TeacherSignCaption,'') As TeacherSignCaption,
		ISNULL(EM.PrincipalSignCaption,'') As PrincipalSignCaption,
		ISNULL(EM.ParentSignCaption,'') As ParentSignCaption,
		ISNULL(BGM.Title,'') AS BloodGroup,
		GS.GradeTitle,
		GS.GradePoint,
		RAD.SubjectHighestDivisionGrade,
		RAD.SubjectHighestDivisionMark,
		GM.Title AS Gender,
		RD.KrupaMark,
		RD.Remark AS OtherDetailRemark,
		ISNULL(SO.AdhaarNumber,'') AS AdharNumber,
		ISNULL(SO.UIDNumber,'') AS UIDNumber,
		ISNULL(SC.PresentStreetOne,'')+' '+ISNULL(SC.PresentStreetTwo,'')+' '+ISNULL(SC.PresentStreetThree,'')+' '+ISNULL(SC.PresentCity,'')+' '+ISNULL(SC.PresentState,'') AS PresentAddress,
		ISNULL(SC.ParentContactNo,'') AS ContactNo,
		(CASE  When EM.IsDisplayAbsentCount=1 then ([sAssessment].[fGetAbsentCount](@rExamId,R.AcademicId, CS.Id)) ELSE 0 END) AS AbsentCount,
		(CASE  When EM.CoordinatorEmployeeId IS NOT NULL AND EM.CoordinatorEmployeeId !=0 then EICoordinator.EmployeeSign ELSE NULL END) AS CoordinatorEmployeeSign,
		ISNULL((SELECT ISNULL(Template,'') FROM sCommon.tReportTemplate WHERE ReportId = 20438 AND OrgId=A.OrgId),0) AS ReportTemplate,
		StuM.SUId As SUID,
		ISNULL(SO.MotherTongue,'') as MotherTongue,
		CONVERT(bit,@DecimalConfigid) AS IsDecimal,
		ISNULL(Stum.RegistrationNumber,'') as RegistrationNumber,
		EM.IsDisplayHighestDivisionMark,
		EM.ResultSheetAdditionalTitle,
		SR.ExamSeatNo,
		ISNULL(R.ResultIndicator,'') AS ResultIndicator,
		CONVERT(bit,@lAbsentRemarkConfig) AS IsAbsentRemark,	--add for 28663 mantis
		ISNULL(RD.AbsentRemark,'') AS AbsentRemark				--add for 28663 mantis

	FROM 
		sAssessment.tResultDetail RD
		INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
		INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId			
		INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
		LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
		INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
		LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = SO.GenderId
		LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=StuM.Id
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		LEFT JOIN sHrm.tEmployeeMaster Emp ON Emp.Id=DM.InchargeEmployeeId AND ISNULL(EMP.IsOtherUser,0) = 0
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = Dm.InchargeEmployeeId
		INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
		LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId
		LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.batchId
		LEFT JOIN sActivity.tHouseMaster HM ON HM.Id=SO.HouseId
		LEFT JOIN 	sCommon.tBloodGroupMaster BGM ON BGM.Id=So.BloodGroupId
		LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId  and RD.SubjectGrade = GS.GradeCode
		LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
		LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=A.StudentId
		LEFT JOIN sHrm.tEmployeeImages EICoordinator ON EICoordinator.EmployeeId = EM.CoordinatorEmployeeId
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND (R.ExamId = @rExamId)
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0)) 
		--AND  ISNULL(EMP.IsOtherUser,0) = 0
		AND (ISNULL(StuM.Code,0) IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
		order by A.RollNo,ED.DisplayOrder
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptResultSheetStandardMultiExamGet]...';


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

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

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

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

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


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

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

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

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


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

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

					 ObtainedMaximum' + convert(nvarchar(15),@lCount)+ '= CASE WHEN EM.IsDisplayHighestDivisionMark = 1
									THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
									ELSE 0  END							
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId AND R.ExamId = ED.ExamId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId	
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 									
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
--print(@query)
	 execute(@query)
	
						
			set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.ExamSubGroupDisplayTitle,
					Exam' + convert(nvarchar(15),@lCount)+ 'Code=ESGM.Code,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=ISNULL(EM.ExamMaximum,0)
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		execute(@query)
		
		Declare @lCombineExamId int
			SELECT @lCombineExamId = EC.ExamId  FROM [sAssessment].[tExamMaster] EM 
										INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId  
										INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId in (SELECT SubExamId  FROM sAssessment.tExamCombine WHERE examid=@rExamId) 
										WHERE   (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId AND EM.Id = @lSubExamId
			--SELECT @lSubCombineExamName
		set @query ='update T set 
					 Exam' + convert(nvarchar(15),@lCount)+ 'CombineExamName =  EM.DisplayTitle
					  From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lCombineExamId) 
				
				--Print @query		
		execute(@query)
		
	set @lCount = @lCount -1
	end
	

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

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

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


GO

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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
 begin
 	

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

Declare @lDecimalConfig nvarchar(20)=''
SELECT @lDecimalConfig =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 496 AND SourceTypeId = 1016 AND SourceId = @rOrgId
 
--#TempAllExam
	CREATE TABLE #TempAllExam
	(
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		
		ResultStatus Nvarchar(50),	
		
		ClassName NVarchar(100),
				
		Division NVarchar(100),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		--MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		--Obtain1 decimal(8,2),
		--ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2),
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2),
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2),
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2),
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2),
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2),
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2),
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	

		SubjectGrade9 NVarchar(50),
		IsPresent9 bit,

		SubjectGrade10 NVarchar(50),
		IsPresent10 bit,

		SubjectGrade11 NVarchar(50),
		IsPresent11 bit,

		SubjectGrade12 NVarchar(50),
		IsPresent12 bit,

		SubjectGrade13 NVarchar(50),
		IsPresent13 bit,
		
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(1000),
		
		Remark2 nvarchar(300),
		Remark3 nvarchar(300),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		IsIncludeCoScholastic bit,
		IsOnPrePrinted bit,
		IsDisplayPhoto bit,
		IsDisplayBirthDate bit,
		IsLockForEdit bit,
		IsDisplaySchoolName bit,			
		IsDisplayAttendance bit,
		IsDisplayHeightWeight bit,
		IsResultStatus bit,
		FooterAdjustmentText nvarchar(max),
		DetailAdjustmentText nvarchar(max),
		FooterAdjustment smallint,
		DetailAdjustment smallint,
		ResultRemark nvarchar(200),
		DateOfBirth date,
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TermScopeId tinyint,		 
		StudentPhoto varbinary(max),
		GradeString nvarchar(1000),
		IsDisplayGradeString bit,		 
		IsDisplayInMarksheet bit,
		IsShowSubjectGrade bit,
		IsIncludeInTotal bit,
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		SubActivityGrade1 nvarchar(50),
		ActivityGrade1 nvarchar(50),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		SubActivityGrade2 nvarchar(50),
		ActivityGrade2 nvarchar(50),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		SubActivityGrade3 nvarchar(50),
		ActivityGrade3 nvarchar(50),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		SubActivityGrade4 nvarchar(50),
		ActivityGrade4 nvarchar(50),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		SubActivityGrade5 nvarchar(50),
		ActivityGrade5 nvarchar(50),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		SubActivityGrade6 nvarchar(50),
		ActivityGrade6 nvarchar(50),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		SubActivityGrade7 nvarchar(50),
		ActivityGrade7 nvarchar(50),
		
		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),

		SubActivityGrade8 nvarchar(50),
		ActivityGrade8 nvarchar(50),

		Exam9Name Nvarchar(150),
		Exam10Name Nvarchar(150),
		Exam11Name Nvarchar(150),
		Exam12Name Nvarchar(150),
		Exam13Name Nvarchar(150),

		SubActivityGrade9 nvarchar(50),
		ActivityGrade9 nvarchar(50),

		SubActivityGrade10 nvarchar(50),
		ActivityGrade10 nvarchar(50),

		SubActivityGrade11 nvarchar(50),
		ActivityGrade11 nvarchar(50),

		SubActivityGrade12 nvarchar(50),
		ActivityGrade12 nvarchar(50),

		SubActivityGrade13 nvarchar(50),
		ActivityGrade13 nvarchar(50),

		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		TotalDays decimal(6, 2),
		PresentDays decimal(6, 2),
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		IsDisplayParentName bit,
		
		FatherName nvarchar(100),
		MotherName nvarchar(100),
		IsShowSubjectMark bit, 
		IsOptionalSubject bit,
		CoScholasticScopeId tinyint,
		IsDisplayPrincipalSign bit,
		IsDisplayTeacherSign bit,
		EmployeeSign varbinary(max),
		
		ActivityName nvarchar(200),
		SubActivityName nvarchar(200),
		SubActivityId int,
		ActivityId Int,
		 SubActivityGrade nvarchar(50),
		 ActivityGrade nvarchar(50),
		SubActivityGradeIndicator nvarchar(50),
		SubActivityDescriptiveIndicator nvarchar(200),
		SubjectActivityOrderIndex Smallint,
		SubActivityOrderIndex smallint,
		ColumnSubjectCount SmallInt,
		MarksheetHeaderA4 varbinary(max),
		IsImageHeader bit,
		Height1 decimal(6,2),
		Height2 decimal(6,2),
		Height3 decimal(6,2),
		Height4 decimal(6,2),
		Height5 decimal(6,2),
		Height6 decimal(6,2),
		Height7 decimal(6,2),
		Height8 decimal(6,2),
		Height9 decimal(6,2),
		Height10 decimal(6,2),
		Height11 decimal(6,2),
		Height12 decimal(6,2),
		Height13 decimal(6,2),
		Weight1 decimal(6,2),
		Weight2 decimal(6,2),
		Weight3 decimal(6,2),
		Weight4 decimal(6,2),
		Weight5 decimal(6,2),
		Weight6 decimal(6,2),
		Weight7 decimal(6,2),
		Weight8 decimal(6,2),
		Weight9 decimal(6,2),
		Weight10 decimal(6,2),
		Weight11 decimal(6,2),
		Weight12 decimal(6,2),
		Weight13 decimal(6,2),
		TotalDays1 decimal(6, 2),
		PresentDays1 decimal(6, 2),
		TotalDays2 decimal(6, 2),
		PresentDays2 decimal(6, 2),
		TotalDays3 decimal(6, 2),
		PresentDays3 decimal(6, 2),
		TotalDays4 decimal(6, 2),
		PresentDays4 decimal(6, 2),
		TotalDays5 decimal(6, 2),
		PresentDays5 decimal(6, 2),
		TotalDays6 decimal(6, 2),
		PresentDays6 decimal(6, 2),
		TotalDays7 decimal(6, 2),
		PresentDays7 decimal(6, 2),
		TotalDays8 decimal(6, 2),
		PresentDays8 decimal(6, 2),
		TotalDays9 decimal(6, 2),
		PresentDays9 decimal(6, 2),
		TotalDays10 decimal(6, 2),
		PresentDays10 decimal(6, 2),
		TotalDays11 decimal(6, 2),
		PresentDays11 decimal(6, 2),
		TotalDays12 decimal(6, 2),
		PresentDays12 decimal(6, 2),
		TotalDays13 decimal(6, 2),
		PresentDays13 decimal(6, 2),
		MyActivity1 nvarchar(200),
		MyActivity2 nvarchar(200),
		MyActivity3 nvarchar(200),
		MyActivity4 nvarchar(200),
		MyActivity5 nvarchar(200),
		MyActivity6 nvarchar(200),
		MyActivity7 nvarchar(200),
		MyActivity8 nvarchar(200),
		MyActivity9 nvarchar(200),
		MyActivity10 nvarchar(200),
		MyActivity11 nvarchar(200),
		MyActivity12 nvarchar(200),
		MyActivity13 nvarchar(200),
		GeneralRemark1 nvarchar(200),
		GeneralRemark2 nvarchar(200),
		GeneralRemark3 nvarchar(200),
		GeneralRemark4 nvarchar(200),
		GeneralRemark5 nvarchar(200),
		GeneralRemark6 nvarchar(200),
		GeneralRemark7 nvarchar(200),
		GeneralRemark8 nvarchar(200),
		GeneralRemark9 nvarchar(200),
		GeneralRemark10 nvarchar(200),
		GeneralRemar11 nvarchar(200),
		GeneralRemark12 nvarchar(200),
		GeneralRemark13 nvarchar(200),
		PresentAddress nvarchar(500) ,
		MobileNo nvarchar(50),
		House nvarchar(100),
		 
		AttendanceTerm1 decimal(6, 2) ,
		AttendanceTerm2 decimal(6, 2),
		WorkingDaysTerm1 decimal(6, 2),
		WorkingDaysTerm2 decimal(6, 2),
		
		BloodGroup nvarchar(20),
		GradeSetIdText nvarchar(50),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		DentalHygiene nvarchar(200),
		VisionLeft nvarchar(50),
		VisionRight nvarchar(50),
		TeacherSignCaption nvarchar(100),
		PrincipalSignCaption nvarchar(100),
		ParentSignCaption nvarchar(100),
		ParentEmail nvarchar(500),
		MyGoal nvarchar(200),
		MyStrength nvarchar(200),
		MyInterestHobby nvarchar(200),
		AreaOfInterest nvarchar(200),
		Responsibility nvarchar(200),
		Achievements nvarchar(1000),
		ImprovementArea nvarchar(200),
		ProgressArea nvarchar(200),
		MyActivity nvarchar(200),
		ClassTeacherRemark nvarchar(1000),
		ClassTeacherName Nvarchar(100),
		HouseRemark nvarchar(1000),
		GeneralRemark nvarchar(1000),
		FatherContactNo nvarchar(50),
		MotherContactNo nvarchar(50),
		FatherMail nvarchar(max),
		MotherMail nvarchar(max),
		IsDecimal bit,
		Name nvarchar(150),
		--mantis 0029914
		PermanentStreetOne nvarchar(150),
		PermanentStreetTwo nvarchar(150),
		PermanentStreetThree nvarchar(150),
		AdmissionNo nvarchar(50),
		StudentContactNo nvarchar(50),
		DescriptiveIndicator nvarchar(200),
		DescriptiveIndicator1 nvarchar(200),
		DescriptiveIndicator2 nvarchar(200),
		DescriptiveIndicator3 nvarchar(200),
		DescriptiveIndicator4 nvarchar(200),
		DescriptiveIndicator5 nvarchar(200),
		DescriptiveIndicator6 nvarchar(200),
		DescriptiveIndicator7 nvarchar(200),
		DescriptiveIndicator8 nvarchar(200),
		DescriptiveIndicator9 nvarchar(200),
		DescriptiveIndicator10 nvarchar(200),
		DescriptiveIndicator11 nvarchar(200),
		DescriptiveIndicator12 nvarchar(200),
		DescriptiveIndicator13 nvarchar(200)

	)	
	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

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


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

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

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


						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
 
  set @query ='update T SET
					
					  ActivityGrade' + convert(nvarchar(15),@lCount)+ '=SAS.Grade	
					 						
					 From
						sAssessment.tCCESubjectActivityExamScore SAS				
						inner JOIN 	#TempAllExam  T ON T.ActivityId = SAS.SubjectActivityId And T.AcademicId = SAS.AcademicId	 					
						WHERE SAS.ExamId =' + convert(nvarchar(15), @lSubExamId)  
						
	
 --PRINT(@QUERY)	
   EXECUTE(@query)
	-- set @query ='update T SET
					
	--				 Height' + convert(nvarchar(15),@lCount)+ '=SR.StudentHeight,
	--				 Weight' + convert(nvarchar(15),@lCount)+ '=SR.StudentWeight,				
	--				 TotalDays'+convert(nvarchar(15),@lCount)+'=SR.TotalDays,
	--				 PresentDays'+convert(nvarchar(15),@lCount)+'=SR.PresentDays,
	--				 MyActivity'+convert(nvarchar(15),@lCount)+'=SR.MyActivity,
	--				 GeneralRemark'+convert(nvarchar(15),@lCount)+'=SR.GeneralRemark
	--				 From
	--					sAssessment.tCCESubjectSubActivityExamScore SSA
						
	--					inner JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.Id = SSA.SubjectSubActivityId
	--					inner JOIN sAssessment.tCCESubjectActivityMaster SAM ON SAM.Id = SSAM.SubjectActivityId
	--					INNER JOIN sAssessment.tExamMaster EM ON EM.Id=SSA.ExamId
	--					inner JOIN 	#TempAllExam  T ON T.SubActivityId = SSA.SubjectSubActivityId And T.AcademicId = SSA.AcademicId	
	--					LEFT JOIN sAssessment.tStudentRemark SR ON SR.ExamId = EM.Id AND T.AcademicId = SR.AcademicId 					
	--					WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	
 ----PRINT(@QUERY)	
 --  EXECUTE(@query)
	
						
		/*	set @query ='update T set 
				    TotalMarks' + convert(nvarchar(15),@lCount)+ '=R.TotalMarks,
					TotalObtain' + convert(nvarchar(15),@lCount)+ '=R.TotalObtain,
					Percentage' + convert(nvarchar(15),@lCount)+ '=R.Percentage,
					RankNumber' + convert(nvarchar(15),@lCount)+'=R.RankNumber,
					ResultGrade' + convert(nvarchar(15),@lCount)+'=R.ResultGrade,
					Percentile' + convert(nvarchar(15),@lCount)+'=R.Percentile,
					ResultStatus' + convert(nvarchar(15),@lCount)+'=R.ResultStatus,
					Exam' + convert(nvarchar(15),@lCount)+ 'Name=ESGM.Title,
					ExamMaximum' + convert(nvarchar(15),@lCount)+'=EM.ExamMaximum
					 From						
						sAssessment.tResult R						
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
	execute(@query)*/
		
		
	set @lCount = @lCount -1
	end
	SELECT @rBuilder1 , T.*
	FROM #TempAllExam T
	
	
		
	drop table #tempcombineExam
	Drop table #TempAllExam

	--Select 
	-- '' As AcademicIdText,
	--	'' As ExamIdText,
	--	'' As CoScholasticScopeIdText ,
		
	--	CONVERT(bigint , 0) As AcademicId,
	--	'' As ExamName,
	--	'' As StudCode,
	--	'' As StudentName ,
	--	0 As RollNo,
	--	'' As ResultStatus ,	
	--	'' As ClassName ,		
	--	'' As Division ,
	--	CONVERT(decimal , 0) As TotalMark ,
	--	CONVERT(decimal , 0) As TotalObtain,
	--	CONVERT(decimal , 0) As Percentage ,
	--	0 As RankNumber ,
	--	'' As ResultGrade ,
		
	--	--MaximumMark1 decimal(8,2),		
	--	'' As SubjectGrade1 ,
	--	--Obtain1 decimal(8,2),
	--	--ExamMaximum1 decimal(8,2),
	--	CONVERT(bit , 0) As IsPresent1,
						
	--	CONVERT(decimal , 0) As MaximumMark2 ,	
	--	'' As SubjectGrade2 ,
	--	CONVERT(decimal , 0) As Obtain2 ,
	--	CONVERT(decimal , 0) As ExamMaximum2 ,
	--	CONVERT(bit , 0) As IsPresent2,
				
	--	CONVERT(decimal , 0) As MaximumMark3 ,
	--	'' As SubjectGrade3 ,
	--	CONVERT(decimal , 0) As Obtain3 ,
	--	CONVERT(decimal , 0) As ExamMaximum3 ,
	--	CONVERT(bit , 0) As IsPresent3 ,		
		
	--	CONVERT(decimal , 0) As MaximumMark4 ,	
	--	'' As SubjectGrade4 ,
	--	CONVERT(decimal , 0) As Obtain4 ,
	--	CONVERT(decimal , 0) As ExamMaximum4 ,
	--	CONVERT(bit , 0) As IsPresent4 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark5 ,		
	--	'' As SubjectGrade5 ,
	--	CONVERT(decimal , 0) As Obtain5 ,
	--	CONVERT(decimal , 0) As ExamMaximum5 ,
	--	CONVERT(bit , 0) As IsPresent5 ,	
				
	--	CONVERT(decimal , 0) As MaximumMark6 ,		
	--	'' As SubjectGrade6,
	--	CONVERT(decimal , 0) As Obtain6 ,
	--	CONVERT(decimal , 0) As ExamMaximum6 ,
	--	CONVERT(bit , 0) As IsPresent6 ,	
		
	--	CONVERT(decimal , 0) As MaximumMark7 ,		
	--	'' As SubjectGrade7,
	--	CONVERT(decimal , 0) As Obtain7 ,
	--	CONVERT(decimal , 0) As ExamMaximum7 ,
	--	CONVERT(bit , 0) As IsPresent7 ,	
	
	--	CONVERT(decimal , 0) As MaximumMark8 ,	
	--	'' As SubjectGrade8,
	--	CONVERT(decimal , 0) As Obtain8 ,
	--	CONVERT(decimal , 0) As ExamMaximum8 ,
	--	CONVERT(bit , 0) As IsPresent8 ,	
		
	--	'' As SubjectGrade9,
	--	CONVERT(bit , 0) As IsPresent9 ,

	--	'' As SubjectGrade10,
	--	CONVERT(bit , 0) As IsPresent10 ,

	--	'' As SubjectGrade11,
	--	CONVERT(bit , 0) As IsPresent11 ,

	--	'' As SubjectGrade12,
	--	CONVERT(bit , 0) As IsPresent12 ,

	--	'' As SubjectGrade13,
	--	CONVERT(bit , 0) As IsPresent13 ,

	--	'' As SubjectGradeTerm1,
	--	'' As SubjectGradeTerm2 ,
	--	CONVERT(bit , 0) As IsMarksInDecimal ,
	--	CONVERT(bit , 0) As column_visible ,
	--	--Obtain decimal(5,2),
	--	CONVERT(decimal , 0) As Percentile,
	--	--ClassSubject nvarchar(100),
	--	CONVERT(bigint , 0) As ResultDetailId ,
	--	CONVERT(bigint , 0) As ResultId ,	
	--	'' As Remark1 ,
	--	'' As Remark2 ,
	--	'' As Remark3 ,
	--	'' As DisplayTitle ,		
	--	CONVERT(bit , 0) As IsRankNo , 
	--	CONVERT(bit , 0) As IsGrade ,
	--	CONVERT(bit , 0) As IsPercentile ,
	--	CONVERT(bit , 0) As IsPercentage ,
	--	CONVERT(bit , 0) As IsSubjectPercentile ,
	--	CONVERT(bit , 0) As IsProcessResult ,
	--	CONVERT(bit , 0) As IsNegativeMarks ,
	--	CONVERT(bit , 0) As IsIncludeCoScholastic ,
	--	CONVERT(bit,0) As IsOnPrePrinted ,
	--	CONVERT(bit , 0) As IsDisplayPhoto ,
	--	CONVERT(bit , 0) As IsDisplayBirthDate ,
	--	CONVERT(bit , 0) As IsLockForEdit ,
	--	CONVERT(bit , 0) As IsDisplaySchoolName ,			
	--	CONVERT(bit , 0) As IsDisplayAttendance ,
	--	CONVERT(bit , 0) As IsDisplayHeightWeight ,
	--	CONVERT(bit , 0) As IsResultStatus ,
	--	'' As FooterAdjustmentText ,
	--	'' As DetailAdjustmentText ,
	--	0 As FooterAdjustment ,
	--	0 As DetailAdjustment ,
	--	'' As ResultRemark ,
	--	CONVERT(Date , null) As DateOfBirth ,
	--	CONVERT(decimal , 0) As HeightTerm1 ,
	--	CONVERT(decimal , 0) As WeightTerm1 ,
	--	CONVERT(decimal , 0) As HeightTerm2,
	--	CONVERT(decimal , 0) As WeightTerm2 ,
	--	CONVERT(decimal , 0) As HeightAnnual ,
	--	CONVERT(decimal , 0) As WeightAnnual ,
	--	0 As PresentDaysTerm1,
	--	0 As PresentDaysTerm2 ,
	--	0 As PresentDaysAnnual ,
	--	0 As TotalDaysTerm1 ,
	--	0 As TotalDaysTerm2 ,
	--	0 As TotalDaysAnnual ,
	--	CONVERT(decimal , 0) As TotalMarkTerm1 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm1 ,
	--	CONVERT(decimal , 0) As PercentageTerm1,
	--	0 As RankNumberTerm1 ,
	--	'' As ResultGradeTerm1,
	--	CONVERT(decimal , 0) As PercentileTerm1 ,
	--	'' As ResultStatusTerm1,		   
	--	CONVERT(decimal , 0) As TotalMarkTerm2 ,
	--	CONVERT(decimal , 0) As TotalObtainTerm2 ,
	--	CONVERT(decimal , 0) As PercentageTerm2 ,
	--	0 As RankNumberTerm2 ,
	--	'' As ResultGradeTerm2 ,
	--	CONVERT(decimal , 0) As PercentileTerm2 ,
	--	'' As ResultStatusTerm2 , 
	--	CONVERT(tinyInt , 0) As TermScopeId ,		 
	--	Convert (varbinary(max) , '') As StudentPhoto ,
	--	'' As GradeString,
	--	CONVERT(bit , 0) As IsDisplayGradeString ,		 
	--	CONVERT(bit , 0) As IsDisplayInMarksheet ,
	--	CONVERT(bit , 0) As IsShowSubjectGrade ,
	--	CONVERT(bit , 0) As IsIncludeInTotal ,
	--	0 As ClassSubjectID ,
	--	0 As SubjectId ,
	--	--Maximum decimal(5,2),
	--	0 As SubjectOrderIndex ,
	--	'' As SubjectGrade ,
	--	'' As SubjectName ,
	--	'' As SubjectCode ,	
	--	CONVERT(decimal , 0) As SubjectMinimum ,		
	--	CONVERT(decimal , 0) As SubjectMaximum ,
	--	CONVERT(decimal , 0) As SubjectObtain ,
		
	--	'' As Exam1Name ,		
	--	CONVERT(decimal , 0) As TotalMarks1 ,		
	--	CONVERT(decimal , 0) As TotalObtain1 ,
	--	CONVERT(decimal , 0) As Percentage1 ,
	--	0 As RankNumber1 ,
	--	'' As ResultGrade1,
	--	CONVERT(decimal , 0) As Percentile1 ,
	--	'' As ResultStatus1 ,
		
	--	'' As SubActivityGrade1,
	--	'' As ActivityGrade1,
		
	--	'' As Exam2Name ,	
	--	CONVERT(decimal , 0) As TotalMarks2 ,
	--	CONVERT(decimal , 0) As TotalObtain2 ,
	--	CONVERT(decimal , 0) As Percentage2 ,
	--	0 As RankNumber2 ,
	--	'' As ResultGrade2 ,
	--	CONVERT(decimal , 0) As Percentile2 ,
	--	'' As ResultStatus2 ,
		
	--	'' As SubActivityGrade2,
	--	'' As ActivityGrade2 ,
		
	--	'' As Exam3Name ,	
	--	CONVERT(decimal , 0) As TotalMarks3 ,
	--	CONVERT(decimal , 0) As TotalObtain3 ,
	--	CONVERT(decimal , 0) As Percentage3 ,
	--	0 As RankNumber3 ,
	--	'' As ResultGrade3 ,
	--	CONVERT(decimal , 0) As Percentile3 ,		
	--	'' As ResultStatus3,
		
	--	'' As SubActivityGrade3 ,
	--	'' As ActivityGrade3 ,
		
	--	'' As Exam4Name ,	
	--	CONVERT(decimal , 0) As TotalMarks4 ,
	--	CONVERT(decimal , 0) As TotalObtain4,
	--	CONVERT(decimal , 0) As Percentage4 ,
	--	0 As RankNumber4 ,
	--	'' As ResultGrade4 ,
	--	CONVERT(decimal , 0) As Percentile4 ,
	--	'' As ResultStatus4 ,
		
	--	'' As SubActivityGrade4,
	--	'' As ActivityGrade4 ,
		
	--	'' As Exam5Name ,		
	--	CONVERT(decimal , 0) As TotalMarks5 ,
	--	CONVERT(decimal , 0) As TotalObtain5 ,
	--	CONVERT(decimal , 0) As Percentage5 ,
	--	0 As RankNumber5 ,
	--	'' As ResultGrade5 ,
	--	CONVERT(decimal , 0) As Percentile5 ,
	--	'' As ResultStatus5 ,
		
	--	'' As SubActivityGrade5 ,
	--	'' As ActivityGrade5 ,
		
	--	'' As Exam6Name ,	
	--	CONVERT(decimal , 0) As TotalMarks6 ,
	--	CONVERT(decimal , 0) As TotalObtain6,
	--	CONVERT(decimal , 0) As Percentage6 ,
	--	0 As RankNumber6 ,
	--	'' As ResultGrade6 ,
	--	CONVERT(decimal , 0) As Percentile6 ,
	--	'' As ResultStatus6 ,
		
	--	'' As SubActivityGrade6 ,
	--	'' As ActivityGrade6 ,
		
	--	'' As Exam7Name ,		
	--	CONVERT(decimal , 0) As TotalMarks7 ,
	--	CONVERT(decimal , 0) As TotalObtain7,
	--	CONVERT(decimal , 0) As Percentage7 ,
	--	0 As RankNumber7 ,
	--	'' As ResultGrade7,
	--	CONVERT(decimal , 0) As Percentile7 ,
	--	'' As ResultStatus7 ,
		
	--	--SubActivityGrade7 nvarchar(10),
		
	--	'' As Exam8Name,
	--	CONVERT(decimal , 0) As TotalMarks8 ,
	--	CONVERT(decimal , 0) As TotalObtain8 ,
	--	CONVERT(decimal , 0) As Percentage8,
	--	0 As RankNumber8 ,
	--	'' As ResultGrade8 ,
	--	CONVERT(decimal , 0) As Percentile8,
	--	'' As ResultStatus8,

	--	'' As Exam9Name,
	--	'' As Exam10Name,
	--	'' As Exam11Name,
	--	'' As Exam12Name,
	--	'' As Exam13Name,

	--	'' As ResultRemark1 ,
	--	'' As ResultRemark2,
	--	CONVERT(decimal , 0) As TotalDays ,
	--	CONVERT(decimal , 0) As PresentDays ,
	--	CONVERT(decimal , 0) As StudentHeight,
	--	CONVERT(decimal , 0) As StudentWeight ,
	--	'' As ExamSeatNo ,
	--	0 As ExamId ,
	--	CONVERT(bit , 0) As IsDisplayParentName ,
	--	'' As FatherName ,
	--	'' As MotherName ,
	--	CONVERT(bit , 0) As IsShowSubjectMark , 
	--	CONVERT(bit , 0) As IsOptionalSubject ,
	--	CONVERT(tinyInt , 0) As CoScholasticScopeId ,
	--	CONVERT(bit , 0) As IsDisplayPrincipalSign ,
	--	CONVERT(bit , 0) As IsDisplayTeacherSign ,
	--	Convert (varbinary(max) , '') As EmployeeSign,
		
	--	'' As ActivityName ,
	--	'' As SubActivityName ,
	--	0 As SubActivityId ,
	--	0 As ActivityId ,
	--	 '' As SubActivityGrade,
	--	 '' As ActivityGrade ,
	--	'' As SubActivityGradeIndicator ,
	--	'' As SubActivityDescriptiveIndicator,
	--	0 As SubjectActivityOrderIndex ,
	--	0 As SubActivityOrderIndex ,
	--	0 As ColumnSubjectCount ,
	--	Convert (varbinary(max) , '') As MarksheetHeaderA4 ,
	--	CONVERT(bit,0) As IsImageHeader ,
	--	CONVERT(decimal , 0) As Height1 ,
	--	CONVERT(decimal , 0) As Height2 ,
	--	CONVERT(decimal , 0) As Height3,
	--	CONVERT(decimal , 0) As Height4 ,
	--	CONVERT(decimal , 0) As Height5,
	--	CONVERT(decimal , 0) As Height6 ,
	--	CONVERT(decimal , 0) As Height7 ,
	--	CONVERT(decimal , 0) As Height8 ,
	--	CONVERT(decimal , 0) As Height9,
	--	CONVERT(decimal , 0) As Height10 ,
	--	CONVERT(decimal , 0) As Height11,
	--	CONVERT(decimal , 0) As Height12 ,
	--	CONVERT(decimal , 0) As Height13 ,

	--	CONVERT(decimal , 0) As Weight1 ,
	--	CONVERT(decimal , 0) As Weight2 ,
	--	CONVERT(decimal , 0) As Weight3 ,
	--	CONVERT(decimal , 0) As Weight4,
	--	CONVERT(decimal , 0) As Weight5 ,
	--	CONVERT(decimal , 0) As Weight6 ,
	--	CONVERT(decimal , 0) As Weight7 ,
	--	CONVERT(decimal , 0) As Weight8 ,
	--	CONVERT(decimal , 0) As Weight9 ,
	--	CONVERT(decimal , 0) As Weight10,
	--	CONVERT(decimal , 0) As Weight11 ,
	--	CONVERT(decimal , 0) As Weight12 ,
	--	CONVERT(decimal , 0) As Weight13 ,

	--	CONVERT(decimal , 0) As TotalDays1 ,
	--	CONVERT(decimal , 0) As PresentDays1 ,
	--	CONVERT(decimal , 0) As TotalDays2 ,
	--	CONVERT(decimal , 0) As PresentDays2 ,
	--	CONVERT(decimal , 0) As TotalDays3 ,
	--	CONVERT(decimal , 0) As PresentDays3 ,
	--	CONVERT(decimal , 0) As TotalDays4 ,
	--	CONVERT(decimal , 0) As PresentDays4 ,
	--	CONVERT(decimal , 0) As TotalDays5 ,
	--	CONVERT(decimal , 0) As PresentDays5 ,
	--	CONVERT(decimal , 0) As TotalDays6 ,
	--	CONVERT(decimal , 0) As PresentDays6 ,
	--	CONVERT(decimal , 0) As TotalDays7 ,
	--	CONVERT(decimal , 0) As PresentDays7 ,
	--	CONVERT(decimal , 0) As TotalDays8 ,
	--	CONVERT(decimal , 0) As PresentDays8 ,
	--	CONVERT(decimal , 0) As TotalDays9 ,
	--	CONVERT(decimal , 0) As PresentDays9 ,
	--	CONVERT(decimal , 0) As TotalDays10 ,
	--	CONVERT(decimal , 0) As PresentDays10 ,
	--	CONVERT(decimal , 0) As TotalDays11 ,
	--	CONVERT(decimal , 0) As PresentDays11 ,
	--	CONVERT(decimal , 0) As TotalDays12 ,
	--	CONVERT(decimal , 0) As PresentDays12 ,
	--	CONVERT(decimal , 0) As TotalDays13 ,
	--	CONVERT(decimal , 0) As PresentDays13 ,

	--	'' As MyActivity1,
	--	'' As MyActivity2 ,
	--	'' As MyActivity3,
	--	'' As MyActivity4 ,
	--	'' As MyActivity5,
	--	'' As MyActivity6,
	--	'' As MyActivity7,
	--	'' As MyActivity8 ,
	--	'' As MyActivity9,
	--	'' As MyActivity10 ,
	--	'' As MyActivity11,
	--	'' As MyActivity12,
	--	'' As MyActivity13,

	--	'' As GeneralRemark1,
	--	'' As GeneralRemark2 ,
	--	'' As GeneralRemark3 ,
	--	'' As GeneralRemark4,
	--	'' As GeneralRemark5,
	--	'' As GeneralRemark6,
	--	'' As GeneralRemark7,
	--	'' As GeneralRemark8 ,
	--	'' As GeneralRemark9 ,
	--	'' As GeneralRemark10,
	--	'' As GeneralRemark11,
	--	'' As GeneralRemark12,
	--	'' As GeneralRemark13,

	--	'' As PresentAddress ,
	--	'' As  MobileNo,
	--	'' As House ,
		 
	--	CONVERT(decimal , 0) As AttendanceTerm1  ,
	--	CONVERT(decimal , 0) As AttendanceTerm2 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm1 ,
	--	CONVERT(decimal , 0) As WorkingDaysTerm2 ,
	--	  '' As BloodGroup ,
	--	  '' As GradeSetIdText ,
	--	  '' As IsDisplayMonthlyAttendanceText ,
	--	  '' As DentalHygiene ,
	--	'' As VisionLeft ,
	--	'' As VisionRight ,
	--	'' As TeacherSignCaption ,
	--	'' As PrincipalSignCaption ,
	--	'' As ParentSignCaption ,
	--	'' As ParentEmail ,
	--  '' AS MyGoal,
	--	'' AS MyStrength,
	--	'' AS MyInterestHobby,
	--	'' AS AreaOfInterest,
	--	'' AS Responsibility,
	--	'' AS Achievements,
	--	'' As ImprovementArea,
	--	'' AS ProgressArea,
	--	'' AS MyActivity,
	--	'' As ClassTeacherRemark,
	--	'' AS ClassTeacherName,
	--	'' As HouseRemark,
	--	'' As GeneralRemark,
	--	'' AS FatherContactNo,
	--	'' AS MotherContactNo,
	--	'' AS FatherMail,
	--	'' AS MotherMail,
	--  CONVERT(bit , 0) As IsDecimal,
	--  '' As Name,
	--'' AS PermanentStreetOne,
	--'' AS PermanentStreetTwo,
	--'' AS PermanentStreetThree,
	--'' AS AdmissionNo,
	--'' AS StudentContactNo,
	--'' AS DescriptiveIndicator ,
	--'' AS DescriptiveIndicator1,
	--'' AS DescriptiveIndicator2,
	--'' AS DescriptiveIndicator3,
	--'' AS DescriptiveIndicator4,
	--'' AS DescriptiveIndicator5,
	--'' AS DescriptiveIndicator6,
	--'' AS DescriptiveIndicator7,
	--'' AS DescriptiveIndicator8,
	--'' AS DescriptiveIndicator9,
	--'' AS DescriptiveIndicator10,
	--'' AS DescriptiveIndicator11,
	--'' AS DescriptiveIndicator12,
	--'' AS DescriptiveIndicator13

	


end
/*
 MaximumMark' + convert(nvarchar(15),@lCount)+ '=ED.Maximum,
Obtain' + convert(nvarchar(15),@lCount)+'=RD.Obtain,
					
					--sAssessment.tCCESubjectActivityMaster SAM 	
	--		INNER JOIN sAssessment.tCCESubjectSubActivityMaster SSAM ON SSAM.SubjectActivityId=SAM.Id  
	--		INNER JOIN sAssessment.vCCEExamClassSubject CS ON CS.ClassSubjectId=SAM.ClassSubjectId
	--		INNER JOIN sSetup.tClassMaster CMM ON CMM.Id=CS.ClassId 
	--		 INNER JOIN sStudent.vStudentAcademic  A ON   A.ClassId = CS.ClassId AND  A.StatusId = 1
	--		 LEFT JOIN sAssessment.tCCESubjectSubActivityExamScore SSA ON SSA.AcademicId = A.AcademicId AND SSA.SubjectSubActivityId= SSAM.Id  	
			  */
GO
PRINT N'Altering Procedure [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 @lPENNumberActive nvarchar(50)='' --Mantis- 0031338	
DECLARE @lIsActivateUniquePENNumber bit = 0 --Mantis- 0031338	
DECLARE @lIsSurnameAndFatherNameMandatory nvarchar(50)=''
DECLARE @lIsActivateUniqueId bit = 0
DECLARE @lOrgGroupId int = 0
DECLARE @lIsStudentUIDNumberUnique nvarchar(50)=''		--add
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 @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId --Mantis- 0031338	
SELECT @lIsSurnameAndFatherNameMandatory =  ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 415 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId	
SELECT @lIsStudentUIDNumberUnique = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 534 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId		--add
IF (@lSUIdActivate = '') OR (@lSUIdActivate = 'False')
	SET @lIsActivateUniqueId = 0
ELSE
	SET @lIsActivateUniqueId = 1	

	
--Mantis Start- 0031338	
IF (ISNULL(@lPENNumberActive, '') = '') OR (@lPENNumberActive = 'False')
	SET @lIsActivateUniquePENNumber = 0
ELSE
	SET @lIsActivateUniquePENNumber = 1	
--Mantis End- 0031338	

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,
		@lPENNumber BIGINT = 0, --Mantis- 0031338	
		@1ExistPENNumber nvarchar(max) = '',--Mantis- 0031338	
		@1DuplicatePENNumber nvarchar(max) = '' --Mantis - 0031338	

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
		PENNumber BIGINT --Mantis- 0031338	
 
  )
  INSERT INTO #tTable1
	(
	    Code,
	    RegistrationNumber, 
	    FirstName,
		MiddleName,
	    LastName,
	    Class,
	    Division,
	    AdmissionStandard,
	    AdmissionDate,
	    DOB,
	    Gender,
	    --AdmissionCategory,
	    Religion,
	    CastCategory,
	    SUId,
	    LeftDate,
        LCDate,
        LeftStandard,
        StatusId,
        AdhaarNumber,
        UIDNumber,
		PENNumber --Mantis- 0031338	
    ) 
   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,
		PENNumber --Mantis- 0031338	
   
   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',
		PENNumber BIGINT '@PENNumber'--Mantis- 0031338	
   )   
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,
		 @lPENNumber = PENNumber --Mantis- 0031338	
        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 + ','    
   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	 
--Mantis Start- 0031338	 
	IF(@lPENNumber > 0)
	BEGIN
		IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where CAST(SM.PENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT = CAST(@lPENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId))         
        BEGIN
  		    SET @1ExistPENNumber = @1ExistPENNumber + CAST(@lPENNumber AS NVARCHAR(200)) + ','
	    END	       
	END
--Mantis Start- 0031338	        
	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(@lIsStudentUIDNumberUnique='True')	--add
		BEGIN
			IF(ISNULL(@lUIDNumber,'')!='')
			BEGIN
                
  				SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
			END 
		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	
--Mantis Start- 0031338	
	IF(@lPENNumber > 0)
	BEGIN 
		IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where CAST(SM.PENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT = CAST(@lPENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT AND OM.OrgGroupId = @rOrgGroupId AND SM.Id<>@1StudentId))         
        BEGIN
  		    SET @1ExistPENNumber = @1ExistPENNumber + CAST(@lPENNumber AS NVARCHAR(200)) + ','
	    END	       
	END
--Mantis Start- 0031338	          
	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(@lIsStudentUIDNumberUnique='True')		--add
		BEGIN  
			IF(ISNULL(@lUIDNumber,'')!='')
			BEGIN
                
  				SET @1DuplicateUIDNumber = @1DuplicateUIDNumber + @lUIDNumber + ',' 
  			                 
			END 
		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
--Mantis Start- 0031338	

	SELECT @1DuplicatePENNumber=COALESCE(@1DuplicatePENNumber ,'') + CAST(PENNumber AS nvarchar(30))+ ',' FROM #tTable1 GROUP BY PENNumber HAVING ( COUNT(PENNumber) > 1 )	
			IF(@1DuplicatePENNumber IS NOT NULL AND @1DuplicatePENNumber != '' AND @lIsActivateUniquePENNumber=1)
				BEGIN
					SET @1DuplicatePENNumber = 'Duplicate PENNumber ' + @1DuplicatePENNumber
					SELECT @1DuplicatePENNumber AS StudentCode
				END
--Mantis end- 0031338	

			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 AND @lIsStudentUIDNumberUnique='True') --add
		BEGIN
			SET @1DuplicateUIDNumber = 'Exist UID Number ' + @1DuplicateUIDNumber
			Select @1DuplicateUIDNumber AS StudentCode
		END
		--Mantis Start- 0031338
		ELSE IF (@1ExistPENNumber IS NOT NULL AND @1ExistPENNumber != '' AND @lIsActivateUniquePENNumber=1)
		BEGIN
			SET @1ExistPENNumber = 'Exist PENNumber ' + @1ExistPENNumber
			Select @1ExistPENNumber AS StudentCode
		END
		--Mantis End- 0031338	
		
		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 Procedure [sAssessment].[pRptStudentMultiSubjectAnalysisGet]...';


GO

ALTER PROCEDURE [sAssessment].[pRptStudentMultiSubjectAnalysisGet]
	 
	  
     @rClassId int=0,
	 @rDivisionId int=0,
	 --@rExamSubGroupId int=0,
	 @rExamId int,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 --@rGroupByid int=0,

	 --@rOrgId  int=0,
	 --@rSubject nvarchar(MAX)=''
	 @rCode nvarchar(20)='' --mentis : 0031596
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
DECLARE @lExamIds nvarchar(500)

select @lExamIds = 
STUFF(
(SELECT ', ' + convert(nvarchar(500), EM.Id, 120)
FROM [sAssessment].[tExamMaster] EM 
INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId 
INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id 
where  EC.ExamId =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId
FOR XML PATH (''))
, 1, 1, '')
--Select @lExamIds
	SELECT
		--0 AS GradeCount,
		(Select Title from vExamSubGroupMaster Where ExamId =@rExamId) AS Builder1,
		A.Id As AcademicId ,
		A.StudentId As StudentId ,
		A.RollNo As RollNo ,
		STM.FirstName As StudentName ,
		STM.MiddleName As FatherName ,
		STM.LastName As SurName,
		STM.FirstName+' '+STM.MiddleName+' '+STM.LastName AS Name ,
		--EM.DisplayTitle As ExamName ,
		ESGM.Title AS ExamName,
		CM.Id As ClassId, 
		CM.Title As Class ,
		CM.DisplayTitle As ClassName ,
		DM.Id As DivisionId, 
		DM.Title As Division ,
		DM.DisplayTitle As DivisionName ,
		SM.Title AS SubjectName,
		RD.Obtain AS ObtainMarks,
		SM.OrderIndex AS SubjectOrderIndex
		--GD.GradeSetId AS GradeSetId,	
	from 
		sAssessment.tResultDetail  RD
		INNER JOIN sAssessment.tResult R ON R.Id=Rd.ResultId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId
		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.tStudentMaster StuM ON StuM.Id=A.StudentId
		--LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		--GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		--INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	where 
		--EM.ExamSubGroupId=@rExamSubGroupId
		(EM.Id IN( SELECT cast(item as nvarchar(20)) FROM  sCommon.fnsplit(@lExamIds,',')) OR @lExamIds='')
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
	order by 
		A.RollNo

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


GO

ALTER PROCEDURE [sAssessment].[pRptStudentSingleSubjectAnalysisGet]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 --@rGroupByid int=0,
	 --@rOrgId  int=0,
	 --@rSubject nvarchar(MAX)=''
	 @rCode nvarchar(20)='' --mentis : 0031596
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 

	SELECT
		--0 AS GradeCount,
		(Select Title from SASSESSMENT.TEXAMSUBGROUPmASTER Where Id =@rExamSubGroupId) AS Builder1,
		A.Id As AcademicId ,
		A.StudentId As StudentId ,
		A.RollNo As RollNo ,
		STM.FirstName As StudentName ,
		STM.MiddleName As FatherName ,
		STM.LastName As SurName,
		STM.FirstName+' '+STM.MiddleName+' '+STM.LastName AS Name ,
		EM.DisplayTitle As ExamName ,
		CM.Id As ClassId, 
		CM.Title As Class ,
		CM.DisplayTitle As ClassName ,
		DM.Id As DivisionId, 
		DM.Title As Division ,
		DM.DisplayTitle As DivisionName ,
		SM.Title AS SubjectName,
		RD.Obtain AS ObtainMarks,
		SM.OrderIndex AS SubjectOrderIndex
		--GD.GradeSetId AS GradeSetId,	
	from 
		sAssessment.tResultDetail  RD
		INNER JOIN sAssessment.tResult R ON R.Id=Rd.ResultId
		INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sStudent.tStudentMaster STM ON STM.Id = A.StudentId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
		--LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		--GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		--INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
	where 
		EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((StuM.Code=@rCode) OR (@rCode=''))
	order by 
		A.RollNo
	
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAddValidate]...';


GO
ALTER PROCEDURE [sFee].[pReceiptAddValidate]
 
		 @rAcademicId bigint,
		 @rFeeSetupIds nvarchar(max) = '',
		 @rReceiptDetailXml [nvarchar](max),
		 @rPayTypeId tinyint,
		 @rPaymentTransactionId bigint = 0,
		 @rIsCreated int OUTPUT
	    
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 

DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rReceiptDetailXml
	 
create table #temptable (FeeId int,Id int,Amount decimal(12,2), AcademicId bigint ) 
INSERT INTO #temptable (FeeId,Id ,Amount , AcademicId)
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			 
			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 sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
			WHERE 
			    (FS1.IsOptional=0)
			    AND SA1.Id = @rAcademicId				
				AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				
				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				
			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 sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId 
				AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId

		WHERE
				  (FS1.IsOptional=1)
				   AND SA1.Id = @rAcademicId	
				  	
				AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='') 

create table #temptable1 (PaidAmount decimal(12,2),FeeSetupId int, SourceId bigint ) 
INSERT INTO #temptable1 (PaidAmount ,FeeSetupId , SourceId )
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 AND R.SourceTypeId = 2001
				INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
				INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
				
			WHERE	
			
			(R.SourceTypeId = 2001)
				 AND R.SourceId = @rAcademicId				
				AND (R.IsObsolete = 0) 
				AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
				GROUP BY FeeSetupId,R.SourceId	


	
	IF EXISTS(	
	SELECT 1
	FROM 
		sStudent.tAcademic SA
		INNER JOIN #temptable
		--(
		--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			 
		--	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 sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
		--	WHERE 
		--	    (FS1.IsOptional=0)
		--	    AND SA1.Id = @rAcademicId				
		--		AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
			
		--		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				
		--	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 sFee.tFeeHeadMaster FHM ON FM.FeeHeadId = FHM.Id 
		--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=FO.SourceId 
		--		AND SA1.BatchId = FS1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId

		--WHERE
		--		  (FS1.IsOptional=1)
		--		   AND SA1.Id = @rAcademicId	
			  	
		--		AND (ISNULL(FS1.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='') 
		--)
		 FS ON FS.AcademicId=SA.Id
		LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.Id
		LEFT JOIN #temptable1
		--(
		--	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 AND R.SourceTypeId = 2001
		--		INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
		--		INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
			
		--	WHERE	
		
		--	(R.SourceTypeId = 2001)
		--		 AND R.SourceId = @rAcademicId				
		--		AND (R.IsObsolete = 0) 
		--		AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
		--		GROUP BY FeeSetupId,R.SourceId	
		--)
		R ON R.FeeSetupId = FS.Id AND SA.Id = R.SourceId			
		LEFT JOIN
		(
			SELECT 	    
			FeeSetupId,
			Amount
			FROM OPENXML (@loDoc, '/Table/ReceiptDetail', 1)
			WITH ( 
					FeeSetupId int,
					Amount decimal(12,2)
				  ) 
		 ) AS RD ON RD.FeeSetupId = FS.Id			
		 WHERE 
		 SA.Id =   @rAcademicId         
		 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) - RD.Amount < 0)			
	)
	BEGIN
		SELECT @rIsCreated = 1
	END 
	ELSE
	BEGIN
		--Start for mantis 0031290 By Foram
		IF(@rPayTypeId = 8)
		BEGIN
			IF EXISTS (SELECT 1
				FROM
					sFee.tReceipt R 
					INNER JOIN sFee.tReceiptDetail RD ON RD.ReceiptId = R.Id AND R.SourceTypeId = 2001
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					INNER JOIN sStudent.tAcademic SA1 ON SA1.Id=R.SourceId AND SA1.AdmissionCategoryId = FS.AdmissionCategoryId	 
				WHERE	
					(R.SourceTypeId = 2001)
					AND R.SourceId = @rAcademicId				
					AND (R.IsObsolete = 0) 
					AND (ISNULL(FS.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeSetupIds,','))OR @rFeeSetupIds='')
					AND R.PaymentTransactionId = @rPaymentTransactionId
					AND R.PayTypeId = 8
				)
			BEGIN
				SELECT @rIsCreated = 1
			END
			ELSE
			BEGIN
				SELECT @rIsCreated = 0
			END
		END
		--end for mantis 0031290 By Foram
		ELSE
		BEGIN
			SELECT @rIsCreated = 0
		END
 END 
 
 	EXEC sp_xml_removedocument @loDoc
END
GO
PRINT N'Altering Procedure [sStudent].[pDigitalFormFieldApprove]...';


GO



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

	BEGIN
	BEGIN TRY
	
	BEGIN TRANSACTION

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

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

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

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

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

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

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

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

			Declare @Sql nvarchar(max)

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

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

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

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

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

				DROP TABLE ListofData
				SET @lResult = 1;
				--SELECT 1 AS StatusCode
			END
			ELSE
			BEGIN
			CREATE TABLE ListofData(Id bigint,StudentId bigint,SubCategory nvarchar(150),UpdatedUserId bigint,IsExist bit);
			insert into ListofData VALUES (@rId,@lStudentId,@rNewValue,@rActionUserId,0)
			
			IF(@lSubFunctionality = 'Communication')  ----Communication
				BEGIN
			UPDATE ListofData SET IsExist=1 WHERE StudentId NOT IN(SELECT StudentId FROM sStudent.tStudentCommunication)
				set @sql='INSERT INTO sStudent.tStudentCommunication 
							(StudentId,'+@lUpdateField+',CreatedUserId,CreatedDateTime)
							SELECT
								LD.StudentId,Ld.SubCategory,LD.UpdatedUserId,sCommon.fGetDate()
							FROM
								ListofData LD WHERE LD.IsExist=1'
					
				print @sql		
				Exec sp_executesql @sql
				set @sql='UPDATE sStudent.tStudentCommunication set '+@lUpdateField+' = LD.SubCategory,
							UpdatedUserId=LD.UpdatedUserId,
							UpdatedDateTime=sCommon.fGetDate()  
							from sStudent.tStudentCommunication SC 
							INNER JOIN ListofData LD ON SC.StudentId=LD.StudentId AND IsExist=0'
		
				Exec sp_executesql @sql
	
		
				Drop Table ListofData
					 SET @lResult = 1;
				END

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

						Exec sp_executesql @sql
					  
						 Drop Table ListofData
							 SET @lResult = 1;
					END
			   Else IF(@lSubFunctionality = 'AcademicDetail')	   ----------General
					 BEGIN
					 UPDATE ListofData SET IsExist=1 WHERE Id NOT IN(SELECT AcademicId FROM sStudent.tAcademicDetail) 
						set @sql='INSERT INTO sStudent.tAcademicDetail 
								(AcademicId,'+@lUpdateField+')
								SELECT
									LD.Id,Ld.SubCategory
								FROM
									ListofData LD WHERE LD.IsExist=1'				
					Exec sp_executesql @sql
		
					set @sql='UPDATE sStudent.tAcademicDetail set '+@lUpdateField+' = LD.SubCategory
								from sStudent.tAcademicDetail AD 
								INNER JOIN ListofData LD ON AD.AcademicId=LD.Id AND IsExist=0'
		
					Exec sp_executesql @sql
		
					IF(@lUpdateField = 'BatchAdmissionDate' )
					BEGIN
					SET @sql='UPDATE sStudent.tAcademicDetail SET '+@lUpdateField+' = NULL WHERE BatchAdmissionDate=''1900-01-01'''
						Exec sp_executesql @sql
					END
					Drop Table ListofData
						 SET @lResult = 1;
					END	
			  Else IF(@lSubFunctionality = 'General')	   ----------General
					 BEGIN
					 IF(@lUpdateField = 'AdmissionCategoryId')
						BEGIN
							set @sql='UPDATE sStudent.tAcademic set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sStudent.tAcademic A 
										INNER JOIN ListofData LD ON A.Id=LD.Id AND IsExist=0'
			
							Exec sp_executesql @sql
							Drop Table ListofData
		
						END
						--Added for mantis : 31451
					  ELSE IF(@lUpdateField = 'FeesRemark')
						BEGIN
							set @sql='UPDATE sStudent.tAcademic set '+@lUpdateField+' = LD.SubCategory,
										UpdatedUserId=LD.UpdatedUserId,
										UpdatedDateTime=sCommon.fGetDate()  
										from sStudent.tAcademic A 
										INNER JOIN ListofData LD ON A.Id=LD.Id AND IsExist=0'
			
							Exec sp_executesql @sql
							Drop Table ListofData
		
						END					 

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

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


GO

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

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

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


	--Mantis Start- 0031338	
	DECLARE @lPENNumberActive nvarchar(50)=''
	SELECT @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	--Mantis END- 0031338	
	begin

		UPDATE sStudent.tStudentMaster
		SET 
		FirstName = case when isnull(@rFirstName,'') <> '' then @rFirstName else FirstName end
		,MiddleName   = case when isnull(@rMiddleName,'') <> '' then @rMiddleName else MiddleName end
		,LastName     = case when isnull(@rLastName,'') <> '' then @rLastName else LastName end
		--,StatusId     = case when isnull(@statusid,0) <> 0 then @statusid else StatusId end
		 ,UpdatedUserId = @rCreatedUserId
		,UpdatedDateTime = sCommon.fGetDate()
		WHERE Id = @StudentId and OrgId = @rOrgId
		--Mantis Start- 0031338	
		
		IF (@lPENNumberActive = 'True')
		Begin
			UPDATE sStudent.tStudentMaster
			SET 
			PENNumber =case when isnull(@rPENNumber,0) <> 0 then  @rPENNumber else PENNumber END--Mantis - 0031338
			WHERE Id = @StudentId and OrgId = @rOrgId
		END
--Mantis End- 0031338	

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

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

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

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

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

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

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

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

		UPDATE sStudent.tStudentAdditional
		SET
			BankBranch = case when isnull(@rBranch,'') <> '' then @rBranch else BankBranch end 
		  ,BankAccountNumber = case when isnull(@rAccountNumber,'') <> '' then @rAccountNumber else BankAccountNumber end 
		  ,BankName = case when isnull(@rBankName,'') <> '' then @rBankName else BankName end 
		  ,BankIFSCCode = case when isnull(@rBankIFSCCode,'') <> '' then @rBankIFSCCode else BankIFSCCode end 
		  
		where StudentId=@StudentId
		
	end	
end
GO
PRINT N'Altering Procedure [sStudent].[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) = '',
	@rPENNumber bigint = 0, --Mantis - 0031338
	@rOrgGroupId int = 0,
	@rMobileNo nvarchar(50)='',
	@rStudentGroupId int=0,
	@rStudentOtherGroupId int=0,
	@rDateOfBirth Date=NULL,
    @rGenderId int=0,
    @rAcademicId bigint = 0,
	@rBirthDateInWord nvarchar(150)='',
	@rTransportModeId int = 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 
			--Mantis Start - 0031338
			ELSE IF(@rPENNumber > 0)
			BEGIN
				IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
						   WHERE SM.PENNumber=@rPENNumber AND OM.OrgGroupId=@rOrgGroupId)
				BEGIN
					SELECT -400 AS RESULT, '' AS Code, 0 AS Id 
					RETURN
				END 
			END
			--Mantis End - 0031338
		
		--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 
		--Mantis Start - 0031338
		ELSE IF(@rPENNumber > 0)
		BEGIN
			IF EXISTS (SELECT SM.Id FROM sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
					   WHERE SM.PENNumber=@rPENNumber AND OM.OrgGroupId=@rOrgGroupId AND SM.Id!=@rId)
			BEGIN
				SELECT -400 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		END
		--Mantis End - 0031338
	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,
			PENNumber --Mantis - 0031338
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rNumber,
			@rRegistrationNumber,
			@rFirstName,
			@rMiddleName,
			@rLastName,
			@rOrgId,
			--@rDepartmentId,
			@rAdmissionCategoryId,
			@rStatusId,
			@rRecordStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rSUId,
			@rStudentGroupId ,
			@rStudentOtherGroupId ,
			@rPENNumber --Mantis - 0031338
		)
		
		INSERT INTO sStudent.tStudentOther
		(
			StudentId,
			DateOfBirth,
			GenderId,
			CreatedUserId,
			CreatedDateTime,
			BirthDateInWord,
			TransportModeId
		)
		VALUES
		(
			@lNextNumber,
			@rDateOfBirth,
			@rGenderId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rBirthDateInWord,
			@rTransportModeId
		)
		----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,
			PENNumber=@rPENNumber --Mantis - 0031338
	      
	      WHERE Id = @rId 
	      
	    UPDATE  sStudent.tStudentOther
		SET
			DateOfBirth=@rDateOfBirth,
			GenderId=@rGenderId,
	        UpdatedUserId=@rUpdatedUserId,
	        UpdatedDateTime=sCommon.fGetDate(),
			BirthDateInWord = @rBirthDateInWord,
			TransportModeId = @rTransportModeId
	      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 Procedure [sStudent].[pValidateStudentBulkDateUpdate]...';


GO
ALTER PROCEDURE [sStudent].[pValidateStudentBulkDateUpdate]

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


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

		 IF (@rSubCategoryType='PENNumber')
        BEGIN
			--Mantis Start- 0031338	
			DECLARE @lPENNumberActive nvarchar(50)=''
			SELECT @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
			--Mantis END- 0031338	
			IF (@lPENNumberActive = 'True')
			Begin
				IF(ISNULL(@lSubCategory, '') <> '' AND CAST(@lSubCategory AS bigint) > 0)
				BEGIN
					IF Exists ((select 1 from sStudent.tStudentMaster SM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where CAST(SM.PENNumber AS NVARCHAR(200)) COLLATE DATABASE_DEFAULT = @lSubCategory COLLATE DATABASE_DEFAULT AND SM.Id <> @lStudentId AND OM.OrgGroupId = @rOrgGroupId))         
					BEGIN
						IF(ISNULL(@lSubCategory,'')!='')
						BEGIN
  							SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ','
  						END
					END	
				END
			END
	     END  
	     
	      --   IF (@rSubCategoryType='AdmissionDate')
   --     BEGIN
			--IF Exists ((select * from sStudent.tStudentAdmission SA INNER JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId 
			--INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId
			--INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId
			--where 
			--SA.AdmissionDate = @lSubCategory 
			--AND SA.StudentId <> @lStudentId AND SM.OrgId=@rOrgId
			--AND SA.AdmissionDate=SO.DateOfBirth
			--AND SA.AdmissionDate<=SO.DateOfBirth))         
			--  BEGIN
			--		IF(ISNULL(@lSubCategory,'')!='')
			--		BEGIN
	                    
  	--					SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ','
	  			        
  	--				END
			--   END	
	  --   END 
	     
	     
	     
	      
	    --IF Exists ((select * from sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = SM.OrgId where SO.UIDNumber COLLATE DATABASE_DEFAULT = @lSubCategory COLLATE DATABASE_DEFAULT))         
     --     BEGIN
     --           IF(ISNULL(@lSubCategory,'')!='')
     --           BEGIN
  			--        SET @1DuplicateCode = @1DuplicateCode + @lSubCategory + ',' 
  			       	        
  			--    END    
	    --   END
	       
	       
  SET @lCount = @lCount - 1		               
  END       
 
--select * from sStudent.tStudentOther SO where AdhaarNumber='8327'



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


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


GO
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailsGet]
						
			@rReportId int=0,
			@rReceiptId bigint = 0,
			@rOrgGroupId int = 0,
			@rReceiptBookId int = 0,
			@rFromReceiptNo int=0,
			@rToReceiptNo int=0,
			@rOrgId int = 0,
			@rBatchId int = 0,
			@rReceiptDate Date='',
			@rClassId int = 0,
			@rOrgIds nvarchar(max) = '',
			@rReceiptPrintGroupId nvarchar(100)='',
			@rDivisionId int = 0,
			@rAdmissionCategoryId int = 0

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	
	
	DECLARE @lOrgGroupId int = 0
	DECLARE @lAmountInWord nvarchar(500) = ''
	DECLARE @lReceiptAmount Decimal(12,2) = 0.0
	DECLARE @lCurrencyCode nvarchar(20) = ''
	DECLARE @lCurrencyTitle nvarchar(100) = ''
	Declare @lIDConfigValue nvarchar(50)='',@lOrgGroup_Id int=0
	Select @lOrgGroup_Id = OrgGroupId From  sSetup.tOrganizationMaster Where Id = @rOrgId
	 
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId
	
	IF(@rOrgGroupId=0)
	BEGIN
		SELECT @lOrgGroupId = OrgGroupId ,@lReceiptAmount = R.ReceiptAmount  FROM sFee.tReceipt R 
		INNER JOIN sSetup.tOrgGroupBatchMaster OB ON R.OrgGroupBatchId = OB.Id 
		WHERE R.Id = @rReceiptId

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

	IF(@rOrgGroupId=0) SET @rOrgGroupId=@lOrgGroupId

	SELECT 
			FRD.ReceiptId,
			FR.ReceiptNumber,
			FR.ReceiptDate,			
			SA.AcademicId,
			--SA.FirstName+' '+SA.MiddleName+' '+SA.LastName AS Name,
			SA.Name AS Name,
			SA.Code,
			SA.RollNo,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			FM.FeeHeadId,
			FHM.Title AS FeeHead,
			FM.Id AS FeeId,
			FM.Title AS FeeName,
			FRD.Amount AS PaidAmount,
			PTM.Id AS PayTypeId,
			PTM.Title AS PayType,			
			--changes by Jash on 06/11/2020--%
			CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo ELSE CONVERT(nvarchar(20),ISNULL(FR.PaymentTransactionId,''))  END AS ChequeNo,
			--CASE WHEN ISNULL(FR.ChequeNo,'') != '' THEN FR.ChequeNo
			--	WHEN ISNULL(PT.BankTransactionId,'') = '' THEN  CONVERT(nvarchar(20),FR.PaymentTransactionId)
			--	ELSE CONVERT(nvarchar(20),FR.PaymentTransactionId) +' - '+ CONVERT(nvarchar(20),PT.BankTransactionId) END AS ChequeNo,
			--%ISNULL(FR.ChequeNo,'') AS ChequeNo,
			ISNULL(FR.BankName,'') AS BankName,
			ISNULL(RBM.Address1,'') AS Address1,
			ISNULL(RBM.Address2,'') AS Address2,
			ISNULL(RBM.FullTitle,'') AS FullTitle,
			ISNULL(FR.TotalReceiptAmount,0.00) AS TotalReceiptAmount,
			ISNULL(FR.ReceiptAmount,0.00) AS ReceiptAmount,					
			(CASE WHEN @rOrgGroupId = 0 -- For Single Receipt
					THEN '' 
				  WHEN @rOrgGroupId != 0 -- For Bulk Receipt
					THEN sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(FR.ReceiptAmount,0.00),1,2,@rOrgGroupId)
			END) AS ReceiptAmountInWords,			
			ISNULL(FR.DiscountAmount,0.00) AS DiscountAmount,
			FR.Remark,
			(CASE WHEN  ISNULL(FR.PaymentTransactionId,0) > 0 
			  THEN -- Navrachana
				'Online Generated'
				ELSE ISNULL(U.DisplayTitle,'') END) AS UserName,
			--ISNULL(U.DisplayTitle,'') AS UserName,
			OM.OrgLogo,
			RBM.Remark1,
			RBM.Remark2,			 
			ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
			ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
			ISNULL(RBM.IsDisplaySchoolName,0) AS IsDisplaySchoolName,
			RBM.ReportId,
			OM.Title AS OrganizationName,
			--(CASE  WHEN (RBM.ReportId = 20775 OR RBM.ReportId = 20777 OR RBM.ReportId = 20874 OR RBM.ReportId =20427 OR RBM.ReportId =20890 OR RBM.ReportId =20901 OR RBM.ReportId =20902) AND ISNULL(RBM.IsMonthDetailOnly,0) = 0 THEN 
			--	[sFee].[fFeeHeadMonthDetailGet](FR.ID,FHM.Id) -- Fee name in detail	 			  
			(CASE WHEN  RBM.ReportId = 20576
			      THEN -- HM patel report
				  [sFee].[fReceiptMonthDetailGet](FR.ID,0)
			      WHEN RBM.ReportId = 30457 
			      THEN
				  [sFee].[fReceiptMonthDetailGet](FR.ID,1)		
			      WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
				  [sFee].[fFeeHeadMonthNameGet](FR.ID,FHM.Id) -- Head wise Month name in detail
				  WHEN ISNULL(RBM.IsMonthDetailOnly,0) = 1  AND ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN				
				  [sFee].[fFeeMonthNameGet](FR.ID,FM.Id) -- Fee wise Month name in detail
			ELSE '' END) 
			AS MonthDetail,    			
			(CASE WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 1
			      THEN				
					 Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
					sFee.tReceipt FR1				
					INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
					INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
					INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
					INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
					INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
					Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
					AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
					Order By FS1.StartDate
					FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' )    -- Fee Head wise Fee Duration
				  WHEN ISNULL(RBM.IsFeeInvoiceHeadwise,0) = 0
			      THEN
					FS.FeeDuration -- Fee wise Fee Duration
				 ELSE '' END) AS FeeDuration,			
			--Stuff((SELECT  N', ' +  FS1.FeeDuration FROM 
			--sFee.tReceipt FR1				
			--INNER JOIN sFee.tReceiptDetail FRD1	ON FR1.Id=FRD1.ReceiptId AND FR1.SourceTypeId=2001				
			--INNER JOIN sFee.tFeeSetup FS1 ON FRD1.FeeSetupId = FS1.Id
			--INNER JOIN sFee.tFeeMaster FM1 ON FS1.FeeId=FM1.Id						
			--INNER JOIN sFee.tFeeHeadMaster FHM1 ON FHM1.Id=FM1.FeeHeadId 
			--INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.AcademicId = FR1.SourceId
			----Where FM1.FeeHeadId = FM.FeeHeadId AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--Where FM1.Id = FM.Id AND FS.ClassId = FS1.ClassId AND FR1.Id = @rReceiptId
			--AND (ISNULL(SA1.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
			-- Order By FS.StartDate
			--FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'' ) AS FeeDuration,			
			DM.Title AS DepartmentName,
			FM.OrderIndex AS FeeOrderIndex,
			FHM.OrderIndex AS FeeHeadOrderIndex,
			FR.IsObsolete AS IsCancelReceipt,
			@lCurrencyCode AS CurrencyCode,
			@lCurrencyTitle AS CurrencyTitle,
			BM.Title AS Batch,
			FR.ChequeDate AS ChequeDate,
			ISNULL(RBM.IsMonthDetailOnly,0) AS IsMonthDetailOnly,
	        ISNULL(RBM.IsFeeInvoiceHeadwise,0) AS IsFeeInvoiceHeadwise,
	        ISNULL(RBM.GroupTitle,'') AS GroupTitle,
	        ISNULL(RBM.IsSuppressFeeDetail,0) AS IsSuppressFeeDetail,
	        ISNULL(CGM.Title,'') AS CollectionGroupName,
	        ISNULL(FI.InvoiceNumber,0) AS InvoiceNumber,
	        SA.SUID,
	        CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.HeaderDisplayId,1)
				END AS HeaderDisplayId,
	        RBM.ReceiptBookHeader,
	        RBM.ServiceTaxPercentage,
	        ISNULL(FR.AmountAfterDiscount,0) AS AmountAfterDiscount,
	        (CASE WHEN  FR.CGSTPercentage IS NULL THEN RBM.CGSTPercentage ELSE FR.CGSTPercentage END) AS CGSTPercentage,
	        (CASE WHEN  FR.SGSTPercentage IS NULL THEN RBM.SGSTPercentage ELSE FR.SGSTPercentage END) AS SGSTPercentage,
	        ISNULL(FR.CGSTAmount,0) AS CGSTAmount,
	        ISNULL(FR.SGSTAmount,0) AS SGSTAmount,
			ISNULL(OOM.GSTINNo,'') AS GSTINNo,
	        ISNULL(OOM.HSNSACCode,'') AS HSNSACCode,
	        @lIDConfigValue AS ItemValue ,
	        SF.FatherName,
	        SF.MotherName,
	        ISNULL(FA.DiscountAmount,0) AS ExemptionAmount,
			ISNULL(FA.Remark,'') AS ExemptionRemark,
			EI.EmployeeSign,
			ISNULL(SC.PresentCity,'') AS PresentCity,
			(ISNULL((CASE WHEN SC.PresentStreetOne IS NOT NULL AND SC.PresentStreetOne!='' THEN ''+ SC.PresentStreetOne END),'')+
			ISNULL((CASE WHEN SC.PresentStreetTwo IS NOT NULL AND SC.PresentStreetTwo!=''  THEN ', '+ SC.PresentStreetTwo END),'')+
			ISNULL((CASE WHEN SC.PresentStreetThree IS NOT NULL AND SC.PresentStreetThree!=''  THEN ', '+ SC.PresentStreetThree END),'')+
			ISNULL((CASE WHEN SC.PresentCity IS NOT NULL AND SC.PresentCity!=''  THEN ', ' + SC.PresentCity  END),'')+
			ISNULL((CASE WHEN SC.PresentState IS NOT NULL AND SC.PresentState!=''  THEN  ', '+ SC.PresentState END),'')+
			ISNULL((CASE WHEN SC.PresentZipCode IS NOT NULL AND SC.PresentZipCode!=''  THEN  ', '+ SC.PresentZipCode  END),''))
			 AS PresentAdress,
			--ISNULL(SC.PresentStreetOne +','+ SC.PresentStreetTwo +','+ SC.PresentStreetThree +','+ SC.PresentCity +','+ SC.PresentState +'-'+ SC.PresentZipCode ,'') AS PresentAdress,
			SC.ParentContactNo,			
			ISNULL(RBM.IsDisplayPendingFeeAmount,0) AS IsDisplayPendingFeeAmount,
			CASE WHEN @rOrgGroupId = 1134 OR @rOrgGroupId = 1742 THEN
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,RBM.Id),0) END)
			ELSE 
			(CASE WHEN  ISNULL(RBM.IsDisplayPendingFeeAmount,0) = 0 THEN 0 ELSE ISNULL([sFee].[fPendingFeeAmountReceiptBookwiseGet](FR.SourceId,0),0) END) END AS PendingFeeAmount,
			SA.FirstName,
			SA.LastName,
			ISNULL([sFee].[fFeeAmountSumGet](FR.SourceId),0) AS FeeAmount,
			ISNULL([sFee].[fFeeReceiptDiscountSumGet](FR.SourceId),0) AS ExemptionAmountSum,
			[sFee].[fTransportBusRouteGet](SA.StudentId,FR.OrgGroupBatchId) AS TransportBusRoute,
			ISNULL(RBM.BankAccountNumber,'') AS BankAccountNumber,
			ISNULL(FHM.Number,0) AS FeeHeadNumber,
			ISNULL(FM.Number,0) AS FeeNumber,
			ISNULL(RBM.DigitalSignature,0x) AS DigitalSignature,
			ISNULL(FR.CancelStatusRemark,'') AS CancelStatusRemark,
			FS.Amount AS FeeSetupAmount,
			FR.CreatedDateTime ,
			ISNULL(FR.PaymentTransactionId,0) As PaymentTransactionId,
			SA.MiddleName,
			CONVERT(char(5),FR.CreatedDateTime,108) AS CreatedTime,
			--by megha - 0026430
			(CASE WHEN ISNULL(FA.VariableAmount,0) > 0 Then FA.VariableAmount 
			      When ISNULL(FS.Amount,0) > 0 Then FS.Amount END) + ISNULL(FA.AdditionalAmount,0) - ISNULL(FA.DiscountAmount,0) - ISNULL(FA.NotApplicableAmount,0) As TotalPayableAmount,
			OGM.Title AS OrgGroupTitle,
			 NID.CollectionGroupName AS NextInstallmentName --Mantis End- 0031305
 	FROM 
	
			sFee.tReceipt FR				
			INNER JOIN sFee.tReceiptDetail FRD ON FR.Id=FRD.ReceiptId AND FR.SourceTypeId=2001				
			INNER JOIN sFee.tFeeSetup FS ON FRD.FeeSetupId = FS.Id				
			INNER JOIN sFee.tFeeMaster FM ON FS.FeeId=FM.Id						
			INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
			INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId = FR.SourceId
			INNER JOIN sStudent.tStudentCommunication SC ON SC.StudentId = SA.StudentId
			INNER JOIn sFinanceCommon.tPayTypeMaster PTM ON PTM.Id=FR.PayTypeId
			LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS.Id AND FA.SourceId=SA.AcademicId
			INNER JOIN sFee.tReceiptBookMaster RBM  ON RBM.Id=FR.ReceiptBookId
			LEFT JOIN sSecurity.tUser U ON U.Id=FR.CreatedUserId
			INNER JOIN sSetup.tDepartmentMaster DM ON SA.DepartmentId =DM.Id
			LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=DM.OrgId
			LEFT JOIN sSetup.tOrganizationOtherDetail OOM ON OM.Id=OOM.OrgId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = FR.BatchId 
			LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id=FR.CollectionGroupId 
			LEFT JOIN sFee.tFeeInvoice FI ON FI.Id=FR.FeeInvoiceId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = U.SourceId AND U.SourceTypeId=95
			LEFT JOIN sOp.tPaymentTransaction PT ON PT.Id = FR.PaymentTransactionId
			INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = OM.OrgGroupId  -- Mantis : 0029314
			LEFT JOIN (SELECT * FROM [sFee].[fNextInstallmentDetailsGet](@rReceiptBookId, @rReceiptId)) NID -- Mantis Start - 0031305
			ON NID.SourceId = FR.SourceId AND NID.SourceTypeId = FR.SourcetypeId -- Mantis End - 0031305
	WHERE 
			((FR.Id=@rReceiptId) OR (@rReceiptId = 0))
			AND ((RBM.OrgGroupId = @rOrgGroupId) OR (@rOrgGroupId = 0))
			AND ((FR.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
			AND ((FR.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))
			AND ((FR.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))
			AND ((FR.BatchId = @rBatchId) OR (@rBatchId = 0))
			AND ((BM.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((FR.ReceiptDate = @rReceiptDate) OR (ISNULL(@rReceiptDate,'') = ''))
			AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
			AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
			AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')			
			AND ((ISNULL(FR.ReceiptPrintGroupId,'')=@rReceiptPrintGroupId) OR (ISNULL(@rReceiptPrintGroupId,'') = ''))
			AND ((FS.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0) )
    ORDER BY 
            FS.StartDate,FHM.OrderIndex,FM.OrderIndex ASC 
END

--BEGIN
--SELECT
-- CAST(0 AS bigint) AS ReceiptId,
-- 0	AS ReceiptNumber,
-- CAST('' AS date) AS ReceiptDate,
-- CAST(0 AS bigint) AS AcademicId,
-- ''	AS Name,
--''	AS Code,
-- 0	AS RollNo,
--0	AS ClassId,
--0	AS DivisionId,
--''	AS ClassName,
--''	AS DivisionName,
--''	AS ClassDivision,
--0	AS FeeHeadId,
--''	AS FeeHead,
--0	AS FeeId,
--''	AS FeeName,
--CAST(0.0 AS decimal(12,2)) AS PaidAmount,
--CAST(0 AS tinyint) AS PayTypeId,
--''	AS PayType,
--''	AS ChequeNo,	
--''	AS BankName,
--''	AS Address1,
--''	AS Address2,
--''	AS FullTitle,
--CAST(0.0 AS decimal(12,2)) AS TotalReceiptAmount,
--CAST(0.0 AS decimal(12,2)) AS ReceiptAmount,					
--''	AS ReceiptAmountInWords,		
--CAST(0.0 AS decimal(12,2)) AS DiscountAmount,
--''	AS Remark,
--''	AS UserName,		
--0x  AS OrgLogo,
--''	AS Remark1,
--''	AS Remark2,			 
--CAST(0 AS bit) AS IsOnPrePrinted,
--CAST(0 AS bit) AS IsSupressLogo,
--CAST(0 AS bit) AS IsDisplaySchoolName,
--0	AS ReportId,
--''	AS OrganizationName,		  
--''	AS MonthDetail,    			
--''	AS FeeDuration,		
--''	AS DepartmentName,
-- 0	AS FeeOrderIndex,
--CAST(0 AS smallint)	AS FeeHeadOrderIndex,
--CAST(0 AS bit) AS IsCancelReceipt,
--''	AS CurrencyCode,
--''	AS CurrencyTitle,
--''	AS Batch,
--CAST('' AS date) AS ChequeDate,
--CAST(0 AS bit) AS IsMonthDetailOnly,
--CAST(0 AS bit) AS IsFeeInvoiceHeadwise,
--''	AS GroupTitle,
--CAST(0 AS bit) AS IsSuppressFeeDetail,
--''	AS CollectionGroupName,
--0	AS InvoiceNumber,
--''	AS SUID,
--CAST(0 AS tinyint) AS HeaderDisplayId,
--0x  AS ReceiptBookHeader,
--CAST(0.0 AS decimal(6,2)) AS ServiceTaxPercentage,
--CAST(0.0 AS decimal(12,2)) AS AmountAfterDiscount,
--CAST(0.0 AS decimal(5,2)) AS CGSTPercentage,
--CAST(0.0 AS decimal(5,2)) AS SGSTPercentage,
--CAST(0.0 AS decimal(12,2)) AS CGSTAmount,
--CAST(0.0 AS decimal(12,2))	AS SGSTAmount,
--''	AS GSTINNo,
--''	AS HSNSACCode,
--''	AS ItemValue ,
--''	AS FatherName,
--''	AS MotherName,
--CAST(0.0 AS decimal(12,2)) AS ExemptionAmount,
--''	AS ExemptionRemark,
--0x AS EmployeeSign,
--''	AS PresentCity,
--''	AS PresentAdress,
--''	AS ParentContactNo,	
--CAST(0 AS bit) AS IsDisplayPendingFeeAmount,
--CAST(0.0 AS decimal(12,0)) AS PendingFeeAmount,
--''	AS FirstName,
--''	AS LastName,
--CAST(0.0 AS decimal(12,0))	AS FeeAmount,
--CAST(0.0 AS decimal(12,0)) AS ExemptionAmountSum,
--''	AS TransportBusRoute,
--''	AS BankAccountNumber,
--0	AS FeeHeadNumber,
--0	AS FeeNumber,
--0x AS DigitalSignature,
--''	AS CancelStatusRemark,
--CAST(0.0 AS decimal(12,2))	AS FeeSetupAmount,
--''	AS CreatedDateTime ,
--CAST(0 AS bigint)	AS PaymentTransactionId,
--''	AS MiddleName,
--'' AS CreatedTime,
-- 0 AS TotalPayableAmount,
-- '' AS OrgGroupTitle,
-- '' AS NextInstallmentName
--END
GO
PRINT N'Altering Procedure [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,
	 @rIsAbsentRemark bit = 0	--mantis: 30947
	 
	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,		
			SA.FirstName,
			SA.MiddleName,
			SA.LastName,
			(case when @rIsAbsentRemark =0 then sAttendance.fAttendanceGet(SA.AcademicId,@rAttendanceTypeId,@rSubjectId,@rFromDate,@rToDate)	-- remove for mantis: 30947
			else sAttendance.fAttendanceWithRemarkGet(SA.AcademicId,@rAttendanceTypeId,@rSubjectId,@rFromDate,@rToDate) end) AS AttendanceDate,	-- add for mantis: 30947
			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.FirstName,SA.MiddleName,SA.LastName,SA.DivisionOrder,SC.ParentContactNo,SR.AttendanceRemark;

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


GO
ALTER PROCEDURE [sFee].[pRptDepositAddGet]
          
		   @rOrgId int,          
           @rDepositHeadId int,
           @rFromAmount decimal(12,2),
           @rToAmount decimal(12,2),
           @rFromDepositDate date,
           @rToDepositDate date,
           @rBatchId int,
           @rCode nvarchar(20),
           @rOrgGroupBatchId int=0
           
AS
SET NOCOUNT ON 

BEGIN
	Declare @lOrgId int = 0
	DECLARE @lOrgGroupId int = 0
Declare @lIDConfigValue nvarchar(50)=''
if(@rOrgGroupBatchId > 0)
		begin 
			SELECT @lOrgId = OrgId FROM sSetup.tBatchMaster where ID = 110100110
			seT @rOrgId = @lOrgId
			
			--select @rOrgId 
			--RETURN;
		end
	SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup WHERE ConfigurationId = 308 AND SourceId = @lOrgGroupId

SELECT  
		DHM.Title AS DepositHeadName,
		DA.Id,
		DA.DepositHeadId,
		--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,
		OI.CertificateHeaderA4  AS DepositHeaderA4,
		@lIDConfigValue AS DepositConfigValue,
		DA.DepositNumber AS DepositNumber --Mantis 0031422
  FROM 		
		sStudent.vStudentAcademic vSA
		INNER JOIN sFee.tDepositAdd DA ON DA.AcademicId = vSA.AcademicId
		INNER JOIN sFee.tDepositHeadMaster DHM ON DHM.Id = DA.DepositHeadId 
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=vSA.OrgId
		LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
  WHERE  
		--vSA.BatchId = @rBatchId 
		(vSA.OrgId=@rOrgId OR @rOrgId=0)
		AND (DA.DepositHeadId=@rDepositHeadId OR @rDepositHeadId=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.OrgGRoupBatchId=@rOrgGroupBatchId
		AND vSA.OrgGRoupBatchId=@rOrgGroupBatchId
		Order By DA.DepositDate
END
GO
PRINT N'Altering Procedure [sFee].[pRptPendingFee100PercentGet]...';


GO

ALTER PROCEDURE [sFee].[pRptPendingFee100PercentGet]

 @rOrgId int = 0,
 @rBatchId int = 0,
 @rOrgGroupBatchId int = 0,
 @rClassId int = 0,
 @rDivisionId int = 0,
 @rReceiptBookId int = 0,
 @rDepartmentId int = 0,
 @rCommonBatch nvarchar(100) = '',
 @rAdmissionCategoryId int = 0,
 @rClassStatusId int = 0,
 @rIsDisplayOrgGroup bit=0,
 @rIsFilter bit=0,
 @rBuilder1 nvarchar(max) = '',
 @rBuilder2 nvarchar(max) = ''
	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	IF object_id('tempdb..#tTable') IS NOT NULL
	BEGIN
		DROP TABLE #tTable
	END
CREATE TABLE #tTable(
	AcademicId BIGINT NOT NULL,
	AdmissionCategoryId int,
	ReceiptBookId int
)
INSERT INTO #tTable
	SELECT SA.AcademicId, FS.AdmissionCategoryId, FS.ReceiptBookId
	FROM sFee.tFeeSetup FS
	INNER JOIN sStudent.vStudentAcademic SA ON SA.ClassId=FS.ClassId AND FS.BatchId = SA.BatchId AND SA.AdmissionCategoryId = FS.AdmissionCategoryId
	--INNER JOIN sSetup.tBatchMaster BM ON FS.BatchId = BM.Id 
	AND (SA.OrgGroupBatchId = @rOrgGroupBatchId OR @rOrgGroupBatchId = 0)
	WHERE 
	((SA.OrgId = @rOrgId)OR(@rOrgId = 0)) 
	AND ((SA.BatchId = @rBatchId) OR (@rBatchId = 0))
	AND (SA.BatchName = @rCommonBatch OR @rCommonBatch = '') 
	AND (SA.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	AND (SA.ClassStatusId = @rClassStatusId OR @rClassStatusId = 0)
	AND (SA.ClassId = @rClassId OR @rClassId = 0)
	AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
	AND (FS.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
	AND (FS.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
	GROUP BY FS.ClassId,SA.AcademicId,FS.AdmissionCategoryId, FS.ReceiptBookId


SELECT F.AcademicId, F.RollNo, F.Name, F.Code, F.ClassName , F.DivisionName , @rIsFilter AS IsFilter ,
	 @rIsDisplayOrgGroup AS IsDisplayOrgGroup, F.ClassOrderIndex, F.DivisionOrder AS DivisionOrderIndex,
	 @rBuilder1 AS Builder1, @rBuilder2 AS Builder2, 
	 --Mantis Start-0031251
	   F.ParentContactNo
	 --Mantis End 
	FROM
		(

		SELECT 
			SA.AcademicId, SA.RollNo,SA.Name,SA.Code, ISNULL(T.AcademicId,0) AS Pending, ISNULL(PS.AcademicId,0) AS [Partial]
			,SA.ClassName , SA.DivisionName , SA.ClassOrderIndex , SA.DivisionOrder
			,(
				SELECT (SUM(FS1.Amount)+Sum(FA1.VariableAmount)+ SUM(FA1.AdditionalAmount)) - (SUM(FA1.DiscountAmount)+ SUM(FA1.NotApplicableAmount)) 
				FROM sFee.tFeeAllocation FA1
				INNER JOIN sFee.tFeeSetup FS1 ON FS1.BatchId = SA.BatchId AND FS1.ClassId = SA.ClassId AND FS1.AdmissionCategoryId = SA.AdmissionCategoryId AND FA1.FeeSetupId = FS1.Id
				WHERE FA1.SourceId = SA.AcademicId 
					AND (FS1.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
					AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
			) AS IsFeePayAmount, 
			--Mantis Start-0031251
			ISNULL(SC.ParentContactNo, '') AS ParentContactNo
			--Mantis End
		FROM sStudent.vStudentAcademic SA 
		INNER JOIN #tTable FS  on  FS.AcademicId = SA.AcademicId
		LEFT JOIN(
			SELECT COUNT(R.Id)as PaidCount,R.SourceId AS AcademicId--, SA.Code,SA.Name 
			FROM sFee.tReceipt R
			--INNER JOIN sStudent.vStudentAcademic SA ON SA.AcademicId=R.SourceId 
			WHERE R.SourceTypeId = 2001 --AND((SA.OrgId = @rOrgId) OR (@rOrgId = 0))
			AND ((R.BatchId = @rBatchId) OR (@rBatchId = 0)) AND (R.IsObsolete = 0)
			AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0) 
			GROUP BY R.SourceId--, SA.Code,SA.Name
			)T ON T.AcademicId = SA.AcademicId
		LEFT JOIN 
			(
				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
					(
					SELECT 
						SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
					Group By R.SourceId,FS.Id
					) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
					(
					SELECT Distinct SourceId 
					FROM sFee.tReceipt 
					) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 0
					AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
					AND (FS1.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
					AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
							
				UNION 

				SELECT 
					SA1.AcademicId 
				FROM sFee.tFeeSetup FS1
				INNER JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS1.Id 
				INNER JOIN sStudent.vStudentAcademic SA1 ON SA1.ClassId=FS1.ClassId AND FS1.BatchId = SA1.BatchId AND SA1.AdmissionCategoryId = FS1.AdmissionCategoryId AND SA1.AcademicId=FO.SourceId
				LEFT JOIN sFee.tFeeAllocation FA ON FA.FeeSetupId=FS1.Id AND FA.SourceId=SA1.AcademicId
				LEFT JOIN 
				(
					SELECT SUM(RD.Amount) as Amount,R.SourceId,FS.Id AS FeeSetupId
					FROM sFee.tReceiptDetail RD
					INNER JOIN sFee.tReceipt R ON RD.ReceiptId = R.Id
					INNER JOIN sFee.tFeeSetup FS ON RD.FeeSetupId = FS.Id
					WHERE R.SourceTypeId = 2001
					AND (R.IsObsolete = 0) 
					AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))
					AND (R.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
					Group By R.SourceId,FS.Id
					) R ON R.SourceId = SA1.AcademicId AND R.FeeSetupId = FS1.Id
				INNER JOIN 
				(
					SELECT Distinct SourceId 
					FROM sFee.tReceipt 
				) RE ON RE.SourceId = SA1.AcademicId
				WHERE 
					((SA1.OrgId=@rOrgId) OR (@rOrgId=0))
					AND ((SA1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND ((FS1.BatchId=@rBatchId) OR (@rBatchId=0))
					AND SA1.StatusId =1
					AND FS1.IsOptional = 1
					AND ISNULL(FS1.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.Amount,0.00) > 0
					AND (FS1.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)
					AND (FS1.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)

			) PS ON PS.AcademicId=SA.AcademicId
			--Mantis Start-0031251
			LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId =SA.StudentId 
			--Mantis End

		WHERE 
			
		((SA.OrgId = @rOrgId)OR(@rOrgId = 0)) 
		AND SA.StatusId =1
		AND ((SA.BatchId = @rBatchId) OR (@rBatchId = 0))
		AND (SA.BatchName = @rCommonBatch OR @rCommonBatch = '') 
		AND (SA.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND (SA.ClassStatusId = @rClassStatusId OR @rClassStatusId = 0)
		AND (SA.ClassId = @rClassId OR @rClassId = 0)
		AND (SA.DivisionId = @rDivisionId OR @rDivisionId = 0)
		AND (FS.ReceiptBookId = @rReceiptBookId OR @rReceiptBookId = 0)
		AND (FS.AdmissionCategoryId = @rAdmissionCategoryId OR @rAdmissionCategoryId = 0)	
		) 
		AS F 
		
	WHERE ISNULL(F.IsFeePayAmount,1) <> 0 AND F.Pending = 0 AND F.Partial = 0


	--For Dataset Drag and Drop
	--SELECT
	--CONVERT(BigInt,0) AS AcademicId,
	--0 AS RollNo,
	--'' AS Name,
	--'' AS Code,
	--'' AS ClassName,
	--'' AS DivisionName,
	--CONVERT(bit,0) AS IsFilter,
	--CONVERT(bit,0) AS IsDisplayOrgGroup,
	--0 AS ClassOrderIndex,
	--0 AS DivisionOrderIndex,
	--'' AS Builder1,
	--'' AS Builder2,
	--'' AS ParentContactNo --Mantis 0031251

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


GO
ALTER PROCEDURE [sStudent].[pStudentDetailUpdateGet]

	 @rCategoryId int,
	 @rSubCategory nvarchar(100),
	 @rOrgId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rBatchId int,
	 --@rIsBlank bit,
	 @rStatusId int,
	 @rOrderBy int,
	 @rFromCode nvarchar(20)='',
	 @rToCode nvarchar(20)='',
	 @rMultiCode nvarchar(max)=''

AS
SET NOCOUNT ON

BEGIN
	 	DECLARE @lDataTypeId nvarchar(1)
		SELECT @lDataTypeId=DataTypeId FROM sCommon.tUpdateFieldMaster WHERE Field=@rSubCategory

		--mantis: 31316, change the sequence of "Number" field at the end of the SELECT
		IF @rCategoryId=1
		BEGIN-- Communication
			IF @rSubCategory ='Present Address'
			BEGIN
				IF @rOrderBY=1
				BEGIN
					SELECT  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,--SA.Number,
							PresentStreetOne,
							PresentStreetTwo,
							PresentStreetThree,
							PresentCountry,
							PresentState,
							PresentCity,
							PresentZipCode,
							PresentContactNo
							,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
						AND (ISNULL(SA.Code,0) IN( SELECT cast(item AS nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')
					ORDER BY SA.RollNo
				END
				ELSE
				BEGIN
					SELECT  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,--SA.Number,
						PresentStreetOne,
						PresentStreetTwo,
						PresentStreetThree,
						PresentCountry,
						PresentState,
						PresentCity,
						PresentZipCode,
						PresentContactNo
						,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
						AND (ISNULL(SA.Code,0) IN( SELECT cast(item AS nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')

					ORDER BY SA.Number		--add
				END
			END
			IF @rSubCategory ='Permanent Address'
			BEGIN
				IF @rOrderBY=1
				BEGIN
					SELECT  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,--SA.Number,
							PermanentStreetOne As PresentStreetOne,
							PermanentStreetTwo AS PresentStreetTwo,
							PermanentStreetThree AS PresentStreetThree,
							PermanentCountry AS PresentCountry,
							PermanentState AS PresentState,
							PermanentCity As PresentCity,
							PermanentZipCode As PresentZipCode,
							PermanentContactNo AS PresentContactNo
							,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
						AND (ISNULL(SA.Code,0) IN( SELECT cast(item AS nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')

					ORDER BY Sa.RollNo
				END
				ELSE
				BEGIN
					SELECT  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,--SA.Number,
							PermanentStreetOne As PresentStreetOne,
							PermanentStreetTwo AS PresentStreetTwo,
							PermanentStreetThree AS PresentStreetThree,
							PermanentCountry AS PresentCountry,
							PermanentState AS PresentState,
							PermanentCity As PresentCity,
							PermanentZipCode As PresentZipCode,
							PermanentContactNo AS PresentContactNo
							,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
						AND (ISNULL(SA.Code,0) IN( SELECT cast(item AS nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')

					ORDER BY SA.Number		--add
				END
			END
			IF @rSubCategory ='Emergency Address'
			BEGIN
				IF @rOrderBY=1
				BEGIN
					SELECT  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,--SA.Number,
							EmergencyStreetOne AS PresentStreetOne,
							EmergencyStreetTwo As PresentStreetTwo,
							EmergencyStreetThree As PresentStreetThree,
							EmergencyCountry As PresentCountry,
							EmergencyState As PresentState,
							EmergencyCity AS PresentCity,
							EmergencyZipCode As PresentZipCode,
							EmergencyContactNo  AS PresentContactNo
							,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
						AND (ISNULL(SA.Code,0) IN( SELECT cast(item AS nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')

					ORDER BY SA.RollNo
				END
				ELSE
				BEGIN
					SELECT  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,--SA.Number,
						EmergencyStreetOne AS PresentStreetOne,
						EmergencyStreetTwo As PresentStreetTwo,
						EmergencyStreetThree As PresentStreetThree,
						EmergencyCountry As PresentCountry,
						EmergencyState As PresentState,
						EmergencyCity AS PresentCity,
						EmergencyZipCode As PresentZipCode,
						EmergencyContactNo  AS PresentContactNo
						,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentCommunication SC ON SC.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
						AND (ISNULL(SA.Code,0) IN( SELECT cast(item AS nvarchar(20)) FROM  sCommon.fnsplit(@rMultiCode,',')) OR @rMultiCode='')

					ORDER BY SA.Number		--add
				END
			END
		END
		IF @rCategoryId= 4
		BEGIN --Family
			IF @rSubCategory ='Father'
			BEGIN
				IF @rOrderBY=1
				BEGIN
					SELECT  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,--SA.Number,
							FatherName,FatherDateOfBirth,FatherOccupation,FatherQualification,FatherContactNo,FatherMail,
							FatherOfficeAddress,FatherIncome,FatherOfficeContactNo,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY SA.RollNo
				END
				ELSE
				BEGIN
					SELECT  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,--SA.Number,
							FatherName,FatherDateOfBirth,FatherOccupation,FatherQualification,FatherContactNo,FatherMail,
							FatherOfficeAddress,FatherIncome,FatherOfficeContactNo,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY SA.Number	--add
				END
			END
			IF @rSubCategory ='Mother'
			BEGIN
				IF @rOrderBY=1
				BEGIN
					SELECT  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,--SA.Number,
							MotherName,MotherDateOfBirth,MotherOccupation,MotherQualification,MotherContactNo,MotherMail,
							MotherOfficeAddress,MotherIncome,MotherOfficeContactNo,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))
				
					ORDER BY SA.ROllNO
				END
				ELSE
				BEGIN
					SELECT  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,--SA.Number,
							MotherName,MotherDateOfBirth,MotherOccupation,MotherQualification,MotherContactNo,MotherMail,
							MotherOfficeAddress,MotherIncome,MotherOfficeContactNo,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY SA.Number	--add
				END
			END
			IF @rSubCategory ='Relative'
			BEGIN
				IF @rOrderBY=1
				BEGIN
					SELECT  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,--SA.Number,
							RelativeName,RelativeDateOfBirth,RelativeOccupation,RelativeQualification,RelativeContactNo,RelativeMail,
							RelativeOfficeAddress,RelativeIncome,RelationshipName,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY SA.ROllNo
				END
				ELSE
				BEGIN
					SELECT  SA.StudentId,SA.AcademicId,SA.Name,SA.ClassName+' - '+SA.DivisionName AS ClassDivision,SA.RollNo,SA.Code,--SA.Number,
							RelativeName,RelativeDateOfBirth,RelativeOccupation,RelativeQualification,RelativeContactNo,RelativeMail,
							RelativeOfficeAddress,RelativeIncome,RelationshipName,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentFamily SC ON SC.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY SA.Number		--add
				END
			END
		END
		IF @rCategoryId= 10
		BEGIN
			IF @rSubCategory ='Academic'
			BEGIN
				IF @rOrderBY=1
				 BEGIN
					 SELECT
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,--SA.Number,
						SA.DivisionName,convert(date,SO.DateOfBirth) As DateOfBirth,AD.AdmissionDate,AD.AdmissionStandardId,SA.Name,Sa.RollNo,SO.GenderId,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						INNER JOIN sStudent.tStudentOther SO
									ON SO.StudentId=SA.StudentId
						LEFT JOIN sStudent.tStudentAdmission AD
									ON AD.StudentID = SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY RollNo
				END
				ELSE
				BEGIN
					SELECT
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,--SA.Number,
						SA.DivisionName,convert(date,SO.DateOfBirth) DateOfBirth,AD.AdmissionDate,AD.AdmissionStandardId,SA.Name,Sa.RollNo,SO.GenderId,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						INNER JOIN sStudent.tStudentOther SO
									ON SO.StudentId=SA.StudentId
						LEFT JOIN sStudent.tStudentAdmission AD
									ON AD.StudentID = SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY SA.Number--add
				END
			END
			IF @rSubCategory ='Main Group'
			BEGIN
				IF @rOrderBY=1
				 BEGIN
					SELECT
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,--SA.Number,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') AS groupCode,ISNULl(AD.Title,'') AS Title,SA.Name,Sa.RollNo,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentGroupMaster AD
									ON AD.Id = SA.StudentGroupId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY RollNo
				END
				ELSE
				BEGIN
					SELECT
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,--SA.Number,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') AS groupCode,ISNULl(AD.Title,'') As Title,SA.Name,Sa.RollNo,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentGroupMaster AD
									ON AD.Id = SA.StudentGroupId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY SA.Number		--add
				END
			END
			IF @rSubCategory ='Other Group'
			BEGIN
				IF @rOrderBY=1
				BEGIN
					SELECT
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,--SA.Number,
						SA.DivisionName,AD.Id,ISNULl(AD.Code,'') As groupCode,ISNULl(AD.Title,'') AS Title,SA.Name,Sa.RollNo,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentOtherGroupMaster AD
									ON AD.Id = SA.StudentOtherGroupId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY RollNo
				END
				ELSE
				BEGIN
					SELECT
						SA.StudentId,SA.Code,SA.FirstName,SA.MiddleName,SA.LastName,SA.ClassName,SA.ClassId,SA.DivisionID,--SA.Number,
						SA.DivisionName,Ad.Id,ISNULl(AD.Code,'') As groupCode,ISNULl(AD.Title,'') As Title,SA.Name,Sa.RollNo,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentOtherGroupMaster AD
									ON AD.Id = SA.StudentOtherGroupId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY SA.Number	--add
				END
			END
			IF @rSubCategory ='Demographic'
			BEGIN
				IF @rOrderBY=1
				 BEGIN
					SELECT
						SA.StudentId,SA.Code,SA.Name,Sa.RollNo,SO.ReligionId,SO.FamilyCast,SO.FamilySubCast,SO.CastCategoryId,SO.NationalityId,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentOther SO
									ON SO.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY RollNo
				END
				ELSE
				BEGIN
					SELECT
						SA.StudentId,SA.Code,SA.Name,Sa.RollNo,SO.ReligionId,SO.FamilyCast,SO.FamilySubCast,SO.CastCategoryId,SO.NationalityId,SA.Number
					FROM
						sStudent.vStudentAcademic SA
						LEFT JOIN sStudent.tStudentOther SO
									ON SO.StudentId=SA.StudentId
					WHERE SA.OrgId=@rOrgId
						AND ((SA.ClassId=@rClassId) OR (@rClassId =0))
						AND ((SA.DivisionId=@rDivisionId) OR  (@rDivisionId=0))
						AND ((SA.StatusId= @rStatusId ) OR  (@rStatusId  =0))
						AND ((SA.BatchId= @rBatchId ))
						AND((SA.Code >= @rFromCode) OR (ISNULL(@rFromCode,'') = ''))
						AND((SA.Code <= @rToCode) OR (ISNULL(@rToCode,'') = ''))

					ORDER BY SA.Number		--add
				END
			END
		END
END
GO
PRINT N'Altering Procedure [sStudent].[pStudentMasterGet]...';


GO

ALTER PROCEDURE [sStudent].[pStudentMasterGet]
	 
	 @rCode nvarchar(20),
	 @rOrgId int,
	 @rNumber bigint,
	 @rBatchId int,
	 @rStudentId bigint,
	 @rOrgGroupBatchId int=0
	 --@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.vStudentAcademic 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	
			
	 --IF(@rIsSearch=1)
		--BEGIN
		--	SET @rCode = sCommon.fSearchStringGet(@rCode)
		--	SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		--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.FirstName+' '+SA.LastName AS Name,
			SA.Name,
			@lAcademicId AS AcademicId,
			SA.ClassId,
			SA.DivisionId,
			ISNULL(SA.RollNo,0) AS RollNo,
			SA.BatchId,
			ISNULL(SO.DateOfBirth,'') AS 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,
			ISNULL(SA.DepartmentId,0) AS DepartmentId,
			ISNULL(RM.HostelId,0) AS HostelId,
			ISNULL(AR.RoomId,0) AS RoomId,
			ISNULL(A.TransportId,0) AS TransportId,
			ISNULL(A.BusRouteId,0) AS BusRouteId,
			ISNULL(A.PickupDestinationId,0) AS PickupDestinationId,
			ISNULL(SA.StudentGroupId,0) AS StudentGroupId,
			ISNULL(SA.StudentOtherGroupId,0) AS StudentOtherGroupId,
			ISNULL(SA.ClassStatusId,0) AS ClassStatusId,
			ISNULL(SA.FeesRemark,'') AS FeesRemark,
			ISNULL(SO.TransportModeId,0) AS TransportModeId,
			ISNULL(SO.BirthDateInWord, '') AS BirthDateInWord,
			ISNULL(SM.PENNumber,0) AS PENNumber --Mantis- 0031338
			
  FROM 
           sStudent.vStudentAcademic SA
     LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId
     LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicID = SA.AcademicId
     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
     (SELECT ATR.SourceId,ISNULL(ATR.PickupDestinationId,0) AS PickupDestinationId,	ISNULL(BRM.TransportId,0) AS TransportId,ISNULL(BRM.Id,0) AS BusRouteId FROM sTransport.tAssignRoute ATR 
     INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=ATR.PickupDestinationId
     INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId  AND BRM.OrgGroupBatchId=@rOrgGroupBatchId   AND ATR.SourceTypeId = 2003 ) A ON A.SourceId = SA.StudentId AND SA.OrgGroupBatchId=@rOrgGroupBatchId
     LEFT JOIN  sStudent.tStudentGroupMaster GM ON GM.Id=SA.StudentGroupId
     LEFT JOIN sStudent.tStudentOtherGroupMaster OGM  ON OGM.Id=SA.StudentOtherGroupId
	 LEFT JOIN sStudent.tStudentMaster SM ON SM.Id = SA.StudentId --Mantis- 0031338
  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.BatchId=@rBatchId)
  ORDER BY SA.Code
END
GO
PRINT N'Altering Procedure [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), @lIsStudentCommonSearchBatchWise nvarchar(50)
	DECLARE @lIsInContext bit=0

	SELECT @lIsStudentCommonSearchBatchWise = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 508 AND SourceTypeId = 2010 AND SourceId = @rOrgId

	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 (@lIsStudentCommonSearchBatchWise = 'True')
	BEGIN
		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,  
			  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,  
			  SA.BatchId,  
			  SA.SUId,  
			  ISNULL(So.GenderId,0) AS GenderId,
			  ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
			  SA.FeesRemark
			  --Mantis - 0031307
			   
			 FROM   
			         sStudent.vStudentAcademic SA  
			          LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId  
					  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 ( OrgGroupBatchId = @rOrgGroupBatchId or @rOrgGroupBatchId = 0)   
			 AND(SA.BatchId=@rBatchId or @rBatchId = 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,
			  ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId ,  
			  SA.SUId,  
			  ISNULL(So.GenderId,0) AS GenderId,
			  ISNULL(SC.ParentContactNo,'') AS ParentContactNo, 
			  SA.FeesRemark --Mantis - 0031307

			 FROM   
			         sStudent.vStudentAcademic SA      
			          LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=SA.StudentId           
					  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.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.SUId=@rSUId) OR (ISNULL(@rSUId,'') = ''))    
			 
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo  
		END  
	END

	ELSE
	BEGIN
		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,
				ISNULL(SA.AdmissionCategoryId,0) AS AdmissionCategoryId,
				SA.BatchId,
				SA.SUId,
				ISNULL(So.GenderId,0) AS GenderId,
				ISNULL(SC.ParentContactNo,'') AS ParentContactNo,
				SA.FeesRemark --Mantis - 0031307
		
			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.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,
					SA.FeesRemark --Mantis - 0031307
					
			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.SUId=@rSUId) OR (ISNULL(@rSUId,'') = '')) 
					AND BM.IsInContext = @lIsInContext
			ORDER BY SA.ClassId,SA.DivisionId,SA.RollNo
		END
	END
END
GO
PRINT N'Altering Procedure [sAlert].[pSubjectwiseStudentAttendanceStatusGet]...';


GO
ALTER PROCEDURE [sAlert].[pSubjectwiseStudentAttendanceStatusGet]
	 	 
	 	 @rBatchId int,
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rOrgId int,
	 	 @rTemplate nvarchar(max),
	 	 @rAttendanceTypeId tinyint,
	 	 --@rSubjectId int,
	 	 @rFromDate date,
	 	 @rToDate date,
	 	 --@rIsPresent bit,
	 	 @rMailSubject nvarchar(500)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

--SET @rToDate = dateadd(d,1,@rToDate)
	CREATE TABLE #TMP 
	(
	AcademicId bigint,
	Code nvarchar(20),
	Name nvarchar(300),
	MobileNo nvarchar(50),
	EmailId nvarchar(50),
	SubjectId bigint,
	AttendanceDate Date,
	DivisionName nvarchar(100),
	WhatsAppContactNo nvarchar(20)
	)
	INSERT INTO #TMP
	Select 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			SR.SubjectId,
			SR.AttendanceDate,
			DM.Code
			,SC.WhatsAppContactNo
	From 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	LEFT JOIN sAttendance.tAbsentReasonMaster AR ON SR.AbsentReasonId = AR.Id
	INNER JOIN sSetup.tSubjectMaster SM ON SR.SubjectId=SM.Id 
	INNER JOIN sSetup.tDivisionMaster DM ON SC.DivisionId=DM.Id
			
	WHERE
		((SC.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SC.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND (SC.OrgId=@rOrgId)
		AND (SC.BatchId=@rBatchId)
		AND (SC.StatusId=1)
		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 = @rIsPresent)
		AND	SC.AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tStudentLeaveRequest WHERE LeaveFromDate = @rFromDate AND LeaveToDate=@rToDate)
		AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
		GROUP BY SC.AcademicId,SC.Code,SC.Name,SC.ParentContactNo,	SC.ParentEmail,SR.SubjectId,SR.AttendanceDate,DM.Code,SC.WhatsAppContactNo
   --ORDER BY SC.ClassOrderIndex,SC.DivisionOrderIndex,SC.Rollno
   --Select * from #TMP
   Select 
   			AcademicId,
			Code,
			Name,
			MobileNo,	
			EmailId,
			AttendanceDate,
			replace (
			replace (
			replace(@rTemplate,'[Name]',tmp.Name),
			--'[Class]',ClassName),
			'[Division]',tmp.DivisionName),
			--'[AbsentDates]',SR.AttendanceDate),
			'[SubjectLectureStatusReason]', CHAR(13) +[sAlert].[fPeriodWiseAttendanceGet](tmp.AcademicId,STUFF(
                 (SELECT ',' + CONVERT(VARCHAR,tmp1.SubjectId) FROM #TMP tmp1
				  WHERE tmp1.AcademicId=tmp.AcademicId 
				  FOR XML PATH ('')), 1, 1, ''
               ),AttendanceDate,@rOrgId))
			AS MsgText,
			[sAlert].[fPeriodWiseAttendanceGet](tmp.AcademicId,STUFF(
                 (SELECT ',' + CONVERT(VARCHAR,tmp1.SubjectId) FROM #TMP tmp1
				  WHERE tmp1.AcademicId=tmp.AcademicId 
				  FOR XML PATH ('')), 1, 1, ''
               ),AttendanceDate,@rOrgId),
			@rMailSubject AS Subject,			   
			ISNULL(tmp.WhatsAppContactNo,'') AS WhatsAppContactNo
		
    from #TMP tmp
	GROUP BY AcademicId,Code,Name,MobileNo,EmailId,AttendanceDate,DivisionName,WhatsAppContactNo

	DROP TABLE #TMP
END
GO
PRINT N'Altering Procedure [sAlert].[pAlumniStudentBirthdayWishGet]...';


GO
ALTER PROCEDURE [sAlert].[pAlumniStudentBirthdayWishGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN	
	SELECT
		R.Id As RegistrationId,
		R.FirstName,
		R.LastName,
		R.MappedStudentId As AcademicId,
		SC.StudentId,
		SC.Name As StudentName,
		replace(
		replace(
		replace (					
		replace (
		@rTemplate,'[Name]',SC.Name)
		,'[Class]',SC.ClassName)
		,'[Division]',SC.DivisionName)
		,'[SchoolName]',OM.Title)
		AS MsgText,
		@rMailSubject AS Subject,
		OM.OrgGroupId AS OrgGroupId,
		OM.Id As OrgId,
		OM.Title As SchoolName,
		BM.Id AS BatchId,
		SC.StudentId AS SourceId,
		2003 AS SourceTypeId,
		SC.StudentId AS ReceiverSourceId,
		2003 AS ReceiverSourceTypeId,
		ISNULL(CM.DisplayTitle,'') AS Class,
		ISNULL(SC.Code,'') as Code,
		ISNULL(SC.ClassName +'-'+ SC.DivisionName,'') as ClassDivision,
		ISNULL(Sc.ParentContactNo,'') AS MobileNo,
		ISNULL(SC.ParentEmail,'') As EmailId,
		ISNULL(SC.WhatsAppContactNo,'') AS WhatsAppContactNo
		FROM  [sStudent].[vStudentCommunication]  SC
		INNER JOIN sAlumni.tRegistration R ON SC.AcademicId = R.MappedStudentId
		INNER JOIN sSetup.tClassMaster CM ON CM.Id=R.PassingClassId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=R.OrgId
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = R.PassingBatchId
		
	WHERE R.MappedStudentId <> 0
		AND (DAY(SC.DateOfBirth) = DAY(sCommon.fGetDate()))
		AND (MONTH(SC.DateOfBirth) = MONTH(sCommon.fGetDate()))
		--AND (SC.StatusId=1)
		AND (SC.OrgId=@rOrgId) AND SC.IsBlockAllAlert=0
END
GO
PRINT N'Altering Procedure [sAttendance].[pMonthlyRegisterStudentviewGet]...';


GO


ALTER PROCEDURE [sAttendance].[pMonthlyRegisterStudentviewGet]
	 	 
	 	 @rBatchId int,
	 	 @rAcademicId bigint,
	 	 @rAttendanceTypeId tinyint
	 	
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
declare @lAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid nvarchar(max)=''
declare @lCuurentMonthAttedanceGrid1 nvarchar(max)=''
Declare @lAttendanceGridTotal nvarchar(max)=''
CREATE TABLE #AttedanceGridTable (AttendanceCount int,PresentCount int,AbsentCount int,AvreragePresence Decimal(10,2));

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

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

		SET @YearNumber =Year(GETDATE())



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

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


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

		IF(@AttendanceCount = 0) BEGIN SET @AveragePresence = 0 END ELSE BEGIN
		SET @AveragePresence= (@PresentCount/@AttendanceCount)*100 
		END

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

		ORDER BY AcademicId,AttendanceDate -- Added AttendanceDate in order by for mantis id : 29551
		FOR XML PATH('')),2,200000) AS CSV
)
END


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


	Select 
	@lAttedanceGrid = @lAttedanceGrid + '<tr>
	<td align="left" scope="col">' + Isnull(MY.MonthTitle,'')  + '</td>
	<td align="left" scope="col">' +convert(varchar,isnull( MY.YearNumber,0))+ '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AttendanceCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.PresentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AbsentCount,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar,isnull(MR.AveragePresence,0)) + '</td>
	<td align="left" scope="col">' + convert(varchar(max),isnull(MR.AbsentDays,0),103) + '</td>  
	</tr>'
	--Change datatype to varchar(max) for AbsentDays for mantis 29551
		From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND MR.AttendanceTypeId=@rAttendanceTypeId
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	WHERE
		SN.AcademicId=@rAcademicId	
	ORDER BY MY.YearNumber,MY.MonthNumber;


INSERT INTO #AttedanceGridTable (AttendanceCount,
								 PresentCount,
								 AbsentCount,
								 AvreragePresence)
				SELECT @AttendanceCount,@PresentCount,@AbsentCount,@AveragePresence;

INSERT INTO #AttedanceGridTable (AttendanceCount,
								 PresentCount,
								 AbsentCount,
								 AvreragePresence)
				SELECT MR.AttendanceCount, MR.PresentCount, MR.AbsentCount,MR.AveragePresence

	From sStudent.vStudentName SN 
	INNER JOIN sSetup.fMonthYearForBatchGET(@rBatchId) AS MY ON MY.BatchId=SN.BatchId AND SN.AcademicId=@rAcademicId 
	INNER JOIN sAttendance.tMonthlyRegister MR ON MR.AcademicId=SN.AcademicId 
		AND MR.AttendanceTypeId=@rAttendanceTypeId
		AND MR.ForMonth=MY.MonthNumber AND MR.ForYear=MY.YearNumber
	WHERE
		SN.AcademicId=@rAcademicId	
	ORDER BY MY.YearNumber,MY.MonthNumber;
 	
	--add for 28718 mantis, change the attendance formula for percentage
	-- Added NULLIF(CAST((Sum(ISNULL( AGT.AttendanceCount,0))) instead of (CAST((Sum(ISNULL( AGT.AttendanceCount,0))) for mantis : 31548
	select 
	@lAttendanceGridTotal = @lAttendanceGridTotal + '<tr>
	<td align="left" scope="col"></td>
	<td align="left" scope="col"></td>
	<td align="left" scope="col">' + convert(varchar, Sum(isnull( AGT.AttendanceCount,0))) + '</td>
	<td align="left" scope="col">' + convert(varchar, Sum(isnull(AGT.PresentCount,0))) + '</td>
	<td align="left" scope="col">' + convert(varchar, Sum(isnull(AGT.AbsentCount,0))) + '</td>
	<td align="left" scope="col">' + convert(varchar, CAST((CAST((Sum(ISNULL(AGT.PresentCount,0))*100) AS decimal(10,2))/NULLIF(CAST((Sum(ISNULL( AGT.AttendanceCount,0))) AS decimal(10,2)),0)) AS decimal(10,2))) + '</td>
	<td align="left" scope="col"></td>
	</tr>'
		 From #AttedanceGridTable AGT;
	 
	SELECT  isnull(@lAttedanceGrid ,'') + isnull(@lCuurentMonthAttedanceGrid ,'') + isnull(@lAttendanceGridTotal ,'') AS AttedanceGrid		
	
	SELECT * FROM #AttedanceGridTable
	DROP TABLE #AttedanceGridTable;	
END
GO
PRINT N'Altering Procedure [sFee].[pReceiptAdd]...';


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

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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

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

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

	 IF @lConfigValue = ''
		SET @lConfigValue = 'ReceiptBookWise'

	IF @rChequeDate = '1900-01-01'
		SET @rChequeDate = NULL

-- Mantis - 0030695
	 DECLARE @lConfigValue1 nvarchar(50)=''
	 SELECT @lConfigValue1 = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 543 AND SourceTypeId = 2010 AND SourceId = LEFT(@rOrgGroupBatchId,4)
-- Mantis - 0030695	 

	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@rId = 0)--ID Condition Added by dhruv for issue no.0013266	
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			ELSE IF(@lConfigValue='PayTypeWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695
			IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ChequeNo=@rChequeNo)
				BEGIN
					SELECT -103 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695
		END
		ELSE
		BEGIN
			IF(@lConfigValue='ReceiptBookWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			ELSE IF(@lConfigValue='PayTypeWise')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId AND Id != @rId)
				BEGIN
					SELECT -102 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695
			IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ChequeNo=@rChequeNo AND Id != @rId)
				BEGIN
					SELECT -103 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695
		END 
	END
	ELSE
	BEGIN
		SET @rReceiptNumber = sFee.fReceiptNumberGet(@rReceiptBookId,@rOrgGroupBatchId,@rPayTypeId,@lConfigValue)
	END	

	EXECUTE [sFee].[pReceiptAddValidate] @rSourceId,'',@rReceiptDetailXml,@rPayTypeId,@rPaymentTransactionId,@rIsCreated = @lIsCreated OUTPUT -- Added ,@rPayTypeId,@rPaymentTransactionId for mantis 0031290 By Foram	

	IF(@lIsCreated = 1)
 		BEGIN
			SELECT -501 AS Result
			RETURN
		END
 
	 BEGIN TRANSACTION	
 IF(@rId = 0)	
BEGIN

	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sFee.tReceipt', 0, 1, 1,@outNextNumber = @lNextNumber output
	
--IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
--			BEGIN
--				SELECT -102 AS Result
--				RETURN	
--			END

		--Added By Dhruv
			IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		--Added By Dhruv
		-- Mantis - 0030695
		IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ChequeNo=@rChequeNo)
			BEGIN
				SELECT -103 AS Result
				RETURN	
			END
		END
		-- Mantis - 0030695

	Declare @lSourceTypeId int 
	SET @lSourceTypeId =(select ISNULL(SourceTypeId,0) from sSecurity.tUser where Id = @rCreatedUserId)

	DECLARE @lCreatedUserId bigint
	IF(@lSourceTypeId = 2001 OR @lSourceTypeId = 2003 OR @rCreatedUserId = 3)
		SET @lCreatedUserId=(Select [sCommon].[fGetBigIntIdForOrg](4,LEFT(@rOrgGroupBatchId,4)))
	ELSE
		SET @lCreatedUserId = @rCreatedUserId 

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

		EXEC [sFee].[pFeeProcessGeneratePaidFeeAdd] @rOrgId,@rBatchId,@rSourceId,@lNextNumber,@lCreatedUserId
		
 END 
	ELSE
	
	IF EXISTS(SELECT 1 FROM sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND Id = @rId)
	BEGIN
		UPDATE sFee.tReceipt SET
			ReceiptDate=@rReceiptDate,
			PayTypeId=@rPayTypeId,
			ChequeDate=@rChequeDate,
		    ChequeNo=@rChequeNo,
		    BankName=@rBankName,
		    Remark=@rRemark
		WHERE Id=@rId
		
	SELECT @rId AS RESULT
	END 
	ELSE
	IF(@rReceiptNumber <> 0)
	BEGIN
		IF(@lConfigValue='ReceiptBookWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		ELSE IF(@lConfigValue='PayTypeWise')
		BEGIN
			IF EXISTS(SELECT 1 from sFee.tReceipt where ReceiptNumber=@rReceiptNumber AND ReceiptBookId=@rReceiptBookId AND  PayTypeId=@rPayTypeId AND OrgGroupBatchId = @rOrgGroupBatchId)
			BEGIN
				SELECT -102 AS Result
				RETURN	
			END
		END
		-- Mantis - 0030695
			IF(@rChequeNo <> '' AND @lConfigValue1 = 'True')
			BEGIN
				IF EXISTS(SELECT 1 from sFee.tReceipt where ChequeNo=@rChequeNo AND Id != @rId)
				BEGIN
					SELECT -103 AS Result
					RETURN	
				END
			END
			-- Mantis - 0030695

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


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

BEGIN 
	
	IF(@rIsGivenAdmissionForm=1)
		SET @rIsGivenAdmissionForm = 1
  	IF(@rIsGivenAdmissionForm=2)
		SET @rIsGivenAdmissionForm =0
	 
	SET @rToDate = DATEADD(d,1,@rToDate)
	BEGIN
		SET @rFirstName= sCommon.fSearchStringGet(@rFirstName)
		SET @rLastName= sCommon.fSearchStringGet(@rLastName)
		SET @rHandledBy= sCommon.fSearchStringGet(@rHandledBy)
	END

DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

-- CTE for Admission Form custom Field
;WITH AdmissionInquiryCriteriaFormCTE AS (SELECT DISTINCT (AIF.FieldGroup+' - '+AIF.FieldRemark) AS FieldRemark FROM sAdmission.tAdmissionInquiryForm AIF 
	LEFT JOIN sAdmission.tAdmissionInquiryField AI ON AI.AdmissionInquiryFormId = AIF.Id 
	WHERE (ClassId = @rForClassId  OR @rForClassId=0)
	AND (AI.AdmissionInquiryFormId = @rId  OR @rId = 0)
	AND (BatchId = @rForBatchId OR @rForBatchId=0) 
)

SELECT @cols = STUFF((SELECT  ',' + QUOTENAME(FieldRemark) FROM AdmissionInquiryCriteriaFormCTE GROUP BY FieldRemark
ORDER BY FieldRemark FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')

IF object_id('tempdb..##tempAdmissionInquiryCustomField') IS NOT NULL 
BEGIN
   DROP TABLE ##tempAdmissionInquiryCustomField 
END

IF(@cols IS NOT NULL)
BEGIN 
	SET @query = N'SELECT DISTINCT AdmissionInquiryId,' + @cols + N' INTO ##tempAdmissionInquiryCustomField FROM 
	(
		SELECT DISTINCT  AI.AdmissionInquiryId,AI.AdmissionInquiryFieldResponse, (AIF.FieldGroup+'' - ''+AIF.FieldRemark) AS FieldRemark
		FROM sAdmission.tAdmissionInquiryForm AIF
		LEFT JOIN sAdmission.tAdmissionInquiryField AI ON AI.AdmissionInquiryFormId = AIF.Id
		WHERE (AIF.ClassId = '+CONVERT(nvarchar(10),@rForClassId)+'  OR '+CONVERT(nvarchar(10),@rForClassId)+'=0)
		AND (AIF.BatchId = '+CONVERT(nvarchar(10),@rForBatchId)+' OR '+CONVERT(nvarchar(10),@rForBatchId)+'=0)
	) x
	PIVOT
	(
		MAX(AdmissionInquiryFieldResponse)
		FOR FieldRemark IN (' + @cols + N')
	) p'

	exec sp_executesql @query
	
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CASE WHEN @rAdmissionInquiryIdText = 0 THEN AI.Number ELSE @rAdmissionInquiryIdText END AS AdmissionInquiryIdText
		,AI.Id
		,AI.ForBatchId
		,AI.ForClassId
		,AI.StatusId
		,ISNULL(SM.Id,0) AS InquiryStatusMasterId
		,ISNULL(AI.GenderId,0) AS GenderId
		,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
		,ISNULL(IMM.Title,'') AS InquiryMode
		,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		,AI.OrgId
		,ISNULL(AI.Number,0) AS InquiryNumber
		,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		,OM.DisplayTitle AS OrgName
		,BM.Title AS ForBatch
		,ISNULL(CM.Title,'') AS ClassName	
		,AI.FirstName
		,AI.MiddleName
		,AI.LastName
		,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
		,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
		,ISNULL(AI.DateOfBirth,'') As DateOfBirth
		,ISNULL(GM.Title,'') As Gender			
		,AI.ContactNo
		,AI.ContactEmail			
		,AI.StreetOne
		,AI.StreetTwo
		,AI.StreetThree
		,AI.Country
		,AI.State
		,AI.City
		,AI.ZipCode
		,ISNULL(AI.Remark,'') AS Remark						
		,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
		,ISNULL(AI.MeritMarks,0) AS MeritMarks
		,ISNULL(AI.MeritGrade,'') AS MeritGrade
		,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
		,SM.Title as StatusName	
		,ISNULL(AI.FollowupDate,'') As FollowupDate
		,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
		,ISNULL(IRM.Title ,'') AS InquiryReference	
		,ISNULL(SCM.Title,'') AS AdmissionCategory		
		,ISNULL(AI.HandledBy,'') AS HandledBy
		,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
		,ISNULL(AI.StudentId,0) AS StudentId,
		ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
		ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
		ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
		CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
		ISNULL(SM.HighlightColor,'') AS HighlightColor,
		ISNULL(SA.PreviousStandard,'') As PreviousStandard,
		AI.AlternateContactNo,
		AI.AlternateContactEmail
		,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
		ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
		ISNULL(AI.MotherName,'') AS MotherName,
		CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode 
		,ISNULL(AI.MinorityStatusId,0) As MinorityStatusId
		,ISNULL(AI.LiveWithId,0) AS LiveWithId
		,ISNULL(AI.AdhaarNumber,'') AS AdhaarNumber 
		,ISNULL(AI.BloodGroupId,0) AS BloodGroupId
		,ISNULL(AI.FatherName,'') AS FatherName
		,ISNULL(AI.FatherOccupation,'') AS FatherOccupation 
		,ISNULL(AI.FatherIncome,0) AS FatherIncome 
		,ISNULL(AI.FatherContactNo,'') AS FatherContactNo
		,ISNULL(AI.FatherMail,'') AS FatherMail
		,ISNULL(AI.FatherQualification,'') AS FatherQualification
		,ISNULL(AI.MotherOccupation,'') As MotherOccupation
		,ISNULL(AI.MotherIncome,0) AS MotherIncome
		,ISNULL(AI.MotherContactNo,'') AS MotherContactNo 
		,ISNULL(AI.MotherMail,'') AS MotherMail 
		,ISNULL(AI.MotherQualification,'') AS  MotherQualification
		,ISNULL(AI.Stream,'') AS Stream
		,ISNULL(AI.Board,'') AS Board
		,ISNULL(CCM.Title,'') AS CasteCategory
		,ISNULL(AI.InquiryReferenceRemark,'') AS InquiryReferenceRemark
		,ISNULL(AI.WhatsAppContactNo,'') AS WhatsAppContactNo
		,tempACF.*
  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId  
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId 
			LEFT JOIN  scommon.tCastCategoryMaster CCM on CCM.Id = AI.CastCategoryId
			LEFT JOIN sAdmission.tAdmissionInquiryField AIF ON AIF.AdmissionInquiryFormId = AI.Id 
			LEFT JOIN sAdmission.tAdmissionInquiryForm AIF1 ON AIF.AdmissionInquiryFormId = AIF1.Id   
			LEFT JOIN ##tempAdmissionInquiryCustomField tempACF ON tempACF.AdmissionInquiryId = AI.Number
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1 END)
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1 END)
	 AND ((AI.ContactNo = @rContactNo) OR (ISNULL(@rContactNo, '')=''))
	 AND ((AI.HandledBy like @rHandledBy) OR (ISNULL(@rHandledBy, '')=''))
	 AND ((GM.Id = @rGenderId) OR (@rGenderId = 0))
	 Order by Case @rOrderBy When 1 then AI.MeritMarks END desc, Case @rOrderBy when 0 then AI.Number Else AI.Number END desc  
END	
ELSE 
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		CASE WHEN @rAdmissionInquiryIdText = 0 THEN AI.Number ELSE @rAdmissionInquiryIdText END AS AdmissionInquiryIdText,
		 AI.Id
		,AI.ForBatchId
		,AI.ForClassId
		,AI.StatusId
		,ISNULL(SM.Id,0) AS InquiryStatusMasterId
		,ISNULL(AI.GenderId,0) AS GenderId
		,ISNULL(AI.InquiryModeId,0) AS InquiryModeId
		,ISNULL(IMM.Title,'') AS InquiryMode
		,ISNULL(AI.InquiryReferenceId,0) AS InquiryReferenceId		
		,ISNULL(AI.AdmissionCategoryId,0) AS AdmissionCategoryId
		,AI.OrgId
		,ISNULL(AI.Number,0) AS InquiryNumber
		,ISNULL(AI.InquiryDate,'') AS AdmissionInquiryDate 		    
		,OM.DisplayTitle AS OrgName
		,BM.Title AS ForBatch
		,ISNULL(CM.Title,'') AS ClassName	
		,AI.FirstName
		,AI.MiddleName
		,AI.LastName
		,[sStudent].[fStudentNameGet](AI.FirstName , ISNULL(AI.MiddleName,'') , AI.LastName,OM.StudentNameFormatId ) AS StudentName
		,AI.LastName +' ' +AI.FirstName+' '+AI.MiddleName as Name				
		,ISNULL(AI.DateOfBirth,'') As DateOfBirth
		,ISNULL(GM.Title,'') As Gender			
		,AI.ContactNo
		,AI.ContactEmail			
		,AI.StreetOne
		,AI.StreetTwo
		,AI.StreetThree
		,AI.Country
		,AI.State
		,AI.City
		,AI.ZipCode
		,ISNULL(AI.Remark,'') AS Remark						
		,ISNULL(AI.PreviousSchool,'') as PreviousSchool			
		,ISNULL(AI.MeritMarks,0) AS MeritMarks
		,ISNULL(AI.MeritGrade,'') AS MeritGrade
		,ISNULL(AI.MeritMarksBreakup,'') AS MeritMarksBreakup
		,SM.Title as StatusName
		,ISNULL(AI.FollowupDate,'') As FollowupDate
		,ISNULL(AI.FollowupRemark,'') As FollowupRemark			
		,ISNULL(IRM.Title ,'') AS InquiryReference	
		,ISNULL(SCM.Title,'') AS AdmissionCategory		
		,ISNULL(AI.HandledBy,'') AS HandledBy
		,ISNULL(AI.CreatedDateTime,'') As CreatedDateTime
		,ISNULL(AI.StudentId,0) AS StudentId,
		ISNULL(AI.CastCategoryId,0) AS CastCategoryId,
		ISNULL(AI.IsTransportRequired,0) AS IsTransportRequired,
		ISNULL(AI.IsHostelRequired,0) AS IsHostelRequired,
		CONVERT(int,ISNULL(AI.IsGivenAdmissionForm,0)) AS IsGivenAdmissionForm,
		ISNULL(SM.HighlightColor,'') AS HighlightColor,
		ISNULL(SA.PreviousStandard,'') As PreviousStandard,
		AI.AlternateContactNo,
		AI.AlternateContactEmail
		,CASE WHEN AI.FollowupDate IS NULL THEN '' ELSE  CONVERT(VARCHAR(10), AI.FollowupDate, 103) END AS FollowupDateString,
		ISNULL(AIC.AgeCutOffDate,'') AS AgeCutOffDate,
		ISNULL(AI.MotherName,'') AS MotherName,
		CASE WHEN AI.DataEntryModeId = 561 THEN 'Online' ELSE 'Offline' END DataEntryMode 
		,ISNULL(AI.MinorityStatusId,0) As MinorityStatusId
		,ISNULL(AI.LiveWithId,0) AS LiveWithId
		,ISNULL(AI.AdhaarNumber,'') AS AdhaarNumber 
		,ISNULL(AI.BloodGroupId,0) AS BloodGroupId
		,ISNULL(AI.FatherName,'') AS FatherName
		,ISNULL(AI.FatherOccupation,'') AS FatherOccupation 
		,ISNULL(AI.FatherIncome,0) AS FatherIncome 
		,ISNULL(AI.FatherContactNo,'') AS FatherContactNo
		,ISNULL(AI.FatherMail,'') AS FatherMail
		,ISNULL(AI.FatherQualification,'') AS FatherQualification
		,ISNULL(AI.MotherOccupation,'') As MotherOccupation
		,ISNULL(AI.MotherIncome,0) AS MotherIncome
		,ISNULL(AI.MotherContactNo,'') AS MotherContactNo 
		,ISNULL(AI.MotherMail,'') AS MotherMail 
		,ISNULL(AI.MotherQualification,'') AS  MotherQualification
		,ISNULL(AI.Stream,'') AS Stream
		,ISNULL(AI.Board,'') AS Board
		,ISNULL(CCM.Title,'') AS CasteCategory
		,ISNULL(AI.InquiryReferenceRemark,'') AS InquiryReferenceRemark
		,ISNULL(AI.WhatsAppContactNo,'') AS WhatsAppContactNo
		,0 AS AdmissionInquiryId
  FROM 
            sAdmission.tAdmissionInquiry AI
            LEFT JOIN sAdmission.tInquiryModeMaster IMM ON IMM.Id = AI.InquiryModeId
            INNER JOIN sAdmission.tInquiryStatusMaster SM ON SM.Id=AI.InquiryStatusId 
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=AI.ForClassId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=AI.OrgId
			INNER JOIN sSetup.tBatchMaster BM ON AI.ForBatchId = BM.Id
			LEFT JOIN sAdmission.tInquiryReferenceMaster IRM ON IRM.Id=AI.InquiryReferenceId
			LEFT JOIN sStudent.tAdmissionCategoryMaster SCM ON SCM.Id=AI.AdmissionCategoryId
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id=AI.GenderId  
			LEFT JOIN sStudent.tStudentAdmission SA oN SA.StudentId=AI.StudentID
			LEFT JOIN sAdmission.tAdmissionInquiryCriteria AIC ON AIC.ClassId=AI.ForClassId AND AIC.BatchId=AI.ForBatchId 
			LEFT JOIN  scommon.tCastCategoryMaster CCM on CCM.Id = AI.CastCategoryId 
  WHERE  
      ((AI.Id = @rId) OR (@rId = 0))
      AND ((AI.FirstName like @rFirstName) OR (@rFirstName=''))
      AND ((AI.LastName like @rLastName) OR (@rLastName=''))
      AND ((AI.InquiryDate>= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
      AND ((AI.InquiryDate < @rToDate) OR (ISNULL(@rToDate,'')=''))
	  AND ((AI.ForClassId=@rForClassId) OR (@rForClassId=0)) 
	  AND ((SM.Id=@rInquiryStatusMasterId) OR (@rInquiryStatusMasterId=0))
	  AND (AI.OrgId=@rOrgId OR @rOrgId=0)
	  AND ((AI.ForBatchId=@rForBatchId) OR (@rForBatchId=0))
	  AND ((CM.DepartmentId=@rDepartmentId) or (@rDepartmentId = 0))
	  AND ((AI.MeritMarks >= @rFromMeritMarks) OR (@rFromMeritMarks=0))
	  AND ((AI.MeritMarks <= @rToMeritMarks) OR (@rToMeritMarks=0))
	  AND ((AI.InquiryModeId=@rInquiryModeId) OR (@rInquiryModeId=0))
	  AND ((AI.InquiryReferenceId=@rInquiryReferenceId) OR (@rInquiryReferenceId=0))
	  AND ((AI.Number=@rNumber) OR (@rNumber=0))
	  AND (BM.OrgGroupBatchid=@rOrgGroupBatchId OR @rOrgGroupBatchId=0)
	  AND ((AI.FollowUpdate=@rFollowupdate) OR (ISNULL(@rFollowUpdate,'')=''))
	  AND ((ISNULL(AI.IsGivenAdmissionForm,0)=@rIsGivenAdmissionForm) OR (@rIsGivenAdmissionForm=-1))
	  AND (AI.IsTransportRequired = CASE @rIsTransportRequired
                              WHEN 0 THEN ISNULL(AI.IsTransportRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1  END)
	  AND (AI.IsHostelRequired = CASE @rIsHostelRequired
                              WHEN 0 THEN ISNULL(AI.IsHostelRequired,0)
                              WHEN 2 THEN 0
                              WHEN 1 THEN 1 END)
	 AND ((AI.ContactNo = @rContactNo) OR (ISNULL(@rContactNo, '')=''))
	 AND ((AI.HandledBy like @rHandledBy) OR (ISNULL(@rHandledBy, '')=''))
	 AND ((GM.Id = @rGenderId) OR (@rGenderId = 0))
	 Order by Case @rOrderBy When 1 then AI.MeritMarks END desc, Case @rOrderBy when 0 then AI.Number Else  AI.Number END desc  
END		    
END
GO
PRINT N'Altering Procedure [sAssessment].[pRptGraphicalStudentGradeAnalysisSubjectWise]...';


GO


ALTER PROCEDURE [sAssessment].[pRptGraphicalStudentGradeAnalysisSubjectWise]
	 
	  
	 @rClassId int=0,
	 @rDivisionId int=0,
	 
	 @rExamSubGroupId int=0,
	 @rBuilder1 nvarchar(MAX)='',
	 @rBatchId int,
	 @rGroupByid int=0,
	 @rOrgId  int=0,
	 @rSubject nvarchar(MAX)='',
	 @rStatusId int=0,			-- #Start MantisId : 0031568
	 @rClassStatusId int=0		-- #End MantisId : 0031568
		 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
CREATE TABLE #TempCradeCount
(Id Int Identity (1,1),
 HEADID int,
 Subjectid int, 
 TotalCount int
)
INSERT INTO  #TempCradeCount
SELECT 
CASE WHEN @rGroupByid=1 THEN DM.Id 
				WHEN @rGroupByid=2 THEN CM.Id 
				WHEN @rGroupByid =3 THEN Dept.Id 
				WHEn @rGroupByid =4 THEN OM.Id
				ELSE 0 END AS HeadId,
				SM.Id AS  Subjectid,
					COUNT(R.Id) AS total_count
					FROm sAssessment.tResultDetail  RD
		  INNER JOIN sAssessment.tResult R ON R.Id=Rd.ResultId
		 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		 INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		--LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		--GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId		-- MantisId : 0031568
		where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))						-- #Start MantisId : 0031568
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))		-- #End MantisId : 0031568
		GROUP BY CASE WHEN @rGroupByid=1 THEN DM.Id 
				WHEN @rGroupByid=2 THEN CM.Id 
				WHEN @rGroupByid =3 THEN Dept.Id 
				WHEn @rGroupByid =4 THEN OM.Id
				ELSE 0 END,
				SM.Id
				
				
SELECT ISNULL(A.GradeCount,0) AS GradeCount, A.Builder1,A.SubjectGrade,A.SubjectName,A.HeadId,A.HeadName,T.Subjectid,ISNULL(T.TotalCount,0) AS TotalCount,A.OrderIndex FROM(
				
SElect
		COUNT(RD.Id) AS GradeCount,
		@rBuilder1 AS Builder1,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		SM.Id AS SubjectId,
		SM.OrderIndex AS SubjectOrderIndex,
		GD.GradeSetId AS GradeSetId,
		CASE WHEN @rGroupByid=1 THEN DM.Id 
				WHEN @rGroupByid=2 THEN CM.Id 
				WHEN @rGroupByid =3 THEN Dept.Id 
				WHEn @rGroupByid =4 THEN OM.Id
				ELSE 0
				 END AS HeadId,CS.IsOptional ,
				
			case when @rGroupByid=1 THEN ' Division : ' +CM.Title+ ' / '+Dm.DisplayTitle  
		when @rGroupByid=2 THEN ' Class : ' + CM.Title  
		when @rGroupByid=3 THEN 'Department: ' + Dept.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 Dept.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END AS OrderIndex
		from sAssessment.tResultDetail  RD
		  INNER JOIN sAssessment.tResult R ON R.Id=Rd.ResultId
		 INNER JOIN sStudent.tAcademic A ON R.AcademicId = A.Id 
		 INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
		 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
		
		INNER JOIN sAssessment.tExamDetail ED ON ED.ID=RD.ExamDetailId
		INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
		INNER JOIN  sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
		LEFT JOIN  sAssessment.tGradeSetDetail GD ON
		GD.GradeSetId = ED.GradeSetId AND RD.SubjectGrade = GD.GradeCode
		INNER JOIN sSetup.tDepartmentMaster Dept ON Dept.Id=CM.DepartmentId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=Dept.OrgId
		INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId		-- MantisId : 0031568
	where 
		  EM.ExamSubGroupId=@rExamSubGroupId
		and EM.BatchId=@rBatchId
		and ((CM.Id=@rClassId)  OR (@rClassId=0))
		AND ((DM.ID=@rDivisionId) OR (@rDivisionId=0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))						-- #Start MantisId : 0031568
		AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))		-- #End MantisId : 0031568
		
		Group by RD.SubjectGrade,SM.Title
		 ,GD.GradeSetId,
		 	CASE WHEN @rGroupByid=1 THEN DM.Id 
				WHEN @rGroupByid=2 THEN CM.Id 
				WHEN @rGroupByid =3 THEN Dept.Id 
				WHEn @rGroupByid =4 THEN OM.Id ELSE 0 END ,	SM.Id,
		case when @rGroupByid=1 THEN ' Division : ' +CM.Title+ ' / '+Dm.DisplayTitle 
		when @rGroupByid=2 THEN ' Class : ' + CM.Title    
		when @rGroupByid=3 THEN 'Department: ' + Dept.Title 
		WHen @rGroupByid=4 THEN  'Organization : '+OM.Title END,
		SM.OrderIndex,CS.IsOptional ,
		CASE WHEN @rGroupByid=1 THEN DM.OrderIndex
				WHEN @rGroupByid=2  THEN CM.OrderIndex
				WHEN @rGroupByid=3  THEN Dept.Id
				WHen @rGroupByid=4 THen OM.OrderIndex  END 
		) A 
		INNER JOIN #TempCradeCount T ON T.HEADID=A.HeadId 
		AND T.Subjectid=A.Subjectid
		AND (ISNULL(T.Subjectid,0) IN( SELECT item FROM  sCommon.fnsplit(@rSubject,','))OR @rSubject='')
		
			
	
END
GO
PRINT N'Altering Procedure [sCommunication].[pFeedbackAdd]...';


GO

ALTER PROCEDURE [sCommunication].[pFeedbackAdd]
	 
	 	@rOrgGroupBatchId  int,
        @rId bigint=0,
        @rTitle nvarchar(200), 
		@rCreatedUserId bigint ,
		@rIsPublish bit,
		@rIsClose bit,
		@rFeedbackTemplateId bigint ,
		@rOrgGroupId int
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 
	 DECLARE @lNextNumber BIGINT 

	 
	
	IF(@rId = 0)	
	BEGIN
		if exists(Select 1 from sCommunication.tFeedback where Title=@rTitle AND FeedbackTemplateId=@rFeedbackTemplateId  AND OrgGroupBatchId =@rOrgGroupBatchId )
	BEGIn
		Select -101 As Result
		Return
	END  
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sCommunication.tFeedback', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	INSERT INTO sCommunication.tFeedback
		(
			Id,
			Title,
			FeedbackTemplateId ,
			IsPublish,
			IsClose,			
			OrgGroupBatchId,
			CreatedUserId,
			CreatedDateTime 
			 
		)
	VALUES
		(
			@lNextNumber,
			@rTitle, 
			@rFeedbackTemplateId,
			@rIsPublish,
			@rIsClose,
			@rOrgGroupBatchId,
			@rCreatedUserId,
			sCommon.fGetDate() 
		)
		    SELECT @lNextNumber AS Result
	END	 

ELSE
	 BEGIN
	 --SET @lNextNumber = @rId
	    UPDATE  sCommunication.tFeedback
	    SET 
			Title = @rTitle, -- Added field for mantis : 31215
			IsPublish=@rIsPublish,
			IsClose=@rIsClose,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      
	      WHERE Id = @rId
	      SELECT @rId AS Result
	 END  	

 
		
END
GO
PRINT N'Altering Procedure [sHrm].[pRptEmployeeAttendanceGet]...';


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

BEGIN 
       SELECT 
			 @rBuilder1 AS Builder1,
			 @rBuilder2 AS Builder2, 
			 EM.Code AS EmployeeCode,
			 EM.EmployeeName,   
			 EM.EmployeeId,
			 EM.DepartmentName,
			 EM.EmployeeGrade,     
			 ISNULL(WD.TotalDays,ISNULL(AT.TotalWorkingDays,0)) As TotalDays,
			 ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays, 
			 ISNULL(AT.LWP,0) AS LWP,
			-- CONVERT(INT,(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0))) AS PresentDays,
			 (ISNULL(AT.TotalWorkingDays,0) - (ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0))) AS PresentDays,
			 MM.Title AS MonthName,
			 AT.ForYear As YearName,			
			 --L.LeaveReason,
			 --L.NoOfLeave,
			 --L.ReportDate,
			 --L.FromDate,
			 --L.ToDate,
			 --LPM.Title As LeavePeriod,
			 --LTM.Title As LeaveType,
			 --LTM.IsCarryForward,
			 --LTM.IsLWP
			  EM.EmployeeDesignation As Designation, -- Mantis 0030721
			  [sHrm].[fEmployeeNameGet](EM.FirstName, EM.MiddleName, Em.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise --Mantis 0031250
        FROM 
			sHrm.vEmployeeCommonDetail EM 
			LEFT JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId
			LEFT JOIN sCommon.tMonthMaster MM ON MM.Id=AT.ForMonth
			LEFT JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId
			AND WD.ForMonth=@rForMonth AND WD.ForYear=@rForYear AND WD.BatchId = @rBatchId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId
			--INNER JOIN sHrm.tLeave L ON L.EmployeeId = EM.EmployeeId
			--INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id=L.LeavePeriodId
			--INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id=L.LeaveTypeId
    	WHERE 
    			EM.OrgID = @rOrgId 
    		AND (AT.BatchId=@rBatchId)
    		AND ((AT.ForMonth=@rForMonth) OR (@rForMonth=0))
    		AND ((AT.ForYear=@rForYear) OR (@rForYear=0))
    		AND ((EM.EmployeeGradeId=@rEmployeeGradeId) OR (@rEmployeeGradeId=0))
    		AND ((EM.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
    		AND ((EM.Code like @rEmployeeCode) OR (@rEmployeeCode=''))
    		AND ((EM.EmployeeName like @rEmployeeName) OR (@rEmployeeName=''))
    		AND ((EM.EmployeeId=@rEmployeeId) OR (@rEmployeeId=0))
    		AND ((EM.EmployeeStatusId=@rEmployeeStatusId) OR (@rEmployeeStatusId=0))
    		--AND ((L.FromDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
    		--AND ((L.ToDate>=@rToDate) OR (ISNULL(@rToDate,'')=''))
    		AND EM.IsOtherUser = 0
    		ORDER BY EM.Number
    		
END
GO
PRINT N'Altering Procedure [sPayroll].[pRptEmployeeSalaryDetail]...';


GO

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

BEGIN  
	
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	
	--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


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

	SELECT
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2, 
		EM.EmployeeId, 
		PP.ID As PayProcessId,
		PPE.ID AS PayProcessEmployeeId,
		PP.SalaryMonth,
		PP.SalaryYear,
		tEM.FirstName +' '+tEM.MiddleName+' '+tEm.LastName AS EmployeeName,
		EM.Code AS EmployeeCode,
		EM.EmployeeDesignation,
		EM.EmployeeGrade,
		ESO.EPFNumber,
		ESO.PanNumber,
		PPE.TotalEarning,		
		PPE.TotalDeduction,
		PPE.NetAmount,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeductionTotal,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
		PE.Amount As PPEAmount,
		P.Title AS PayElementTitle,
		P.ID AS PayElementId,
		P.PayElementTypeId,
		ISNULL(ESO.BankName,'') AS BankName,
		ISNULL(ESO.AccountNumber,'') AS AccountNumber, 
		MM.Title AS MonthName,
		P.Title AS PayElementName,
		P.Code AS PayElementCode,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.WorkingDays,@lMonthDay) else 0 END) AS WorkingDays,
		--ISNULL(EWD.WorkingDays,@lMonthDay) AS WorkingDays,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.Lwp else 0 END) AS Lwp,
		(CASE WHEN PayElementId = @lBasicPayElementId then ISNULL(PPE.PaidLeave,0) else 0 END) AS PaidLeave,
		P.SortOrder,
		PY.Title AS PayrollYearName,
		PGM.Id AS PayrollGroupId,
		PGM.Title AS PayrollGroupName,
		PPE.GrossBasic,
		P.PayElementDefaultId,
		ISNULL(EPD.Qualification,'') AS Qualification,
		EJD.DateOfJoining AS DateOfAppointment,
		ISNULL(ESO.PayScale,'') AS PayScale,
		EPD.DateOfBirth,
		ISNULL(ROG.SelectableField,'') AS SelectableField,
		RGO.SchoolRequiredSignature ,
		RGO.SchoolRemark1,
		ISNULL(ESO.BasicPay,0) AS BasicPay,
		DAY(DATEADD(DD,-1,DATEADD(mm, DATEDIFF(mm, 0, CONVERT(DATE,CONVERT(nvarchar,PP.SalaryMonth) +'/01/'+CONVERT(nvarchar,PP.SalaryYear)) ) + 1, 0))) AS MonthDay,
		ESO.UAN,
		EPD.GenderId,
		ISNULL(PPR.Remark,'') AS PayProcessEmployeeRemark,
		tEM.FirstName,
		tEm.LastName,
		EM.DateOfJoining,
		OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
		ISNULL(REPLACE(REPLACE(
		(SELECT STUFF(
		(
		  SELECT  ' ' + Leave FROM -- create comma separated values
			(
					Select '<br>'+('<b>'+ LTM.Code +'</b>' +' - '+ CAST(SUM(CAST(L.NoOfLeave AS FLOAT)) AS varchar(50)) ) + '</br>'AS Leave 
					from 
					sHrm.tLeaveTypeMaster LTM  
					INNER JOIN sHrm.tLeave L ON  EM.EmployeeId = L.EmployeeId 
					INNER JOIN sCommon.tStatusMaster SM ON SM.Id=L.StatusId
					Where EM.EmployeeId=EM.EmployeeId AND LTM.OrgId=EM.OrgId AND LTM.IsObsolete = 0 
					AND LTM.Id = L.LeaveTypeId AND SM.Id=550
					AND (YEAR(L.FromDate) = @rForYear OR @rForYear=0) 
					AND (MONTH(L.FromDate) = @rForMonth OR @rForMonth=0) 
					GROUP BY LTM.Code
					)AS T FOR XML PATH('')
		)
		,1,1,'')),'&lt;','<'),'&gt;','>')
		,'') AS LeaveCount,
		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.IFSCNumber,'') AS IFSCNumber,
		ISNULL(EPD.AdhaarNumber,'') AS AdhaarNumber,
		EM.DepartmentName, --Mantis : 0029371
		ESO.ESINumber,
		--(SELECT PS.Amount FROM sPayroll.tPaySetup PS WHERE PS.PayElementId = P.Id 
		--	AND PS.SourceId = tEM.Id AND PS.PayrollYearId = PP.PayrollYearId) AS PaySetupAmount,
		CASE 
			WHEN ISNULL(P.IsEmployeeSpecific,0) = 1
			THEN
				(SELECT PS.Amount 
					FROM sPayroll.tPaySetup PS 
					WHERE PS.PayElementId = P.Id 
					AND (PS.SourceId = tEM.Id AND PS.SourceTypeId = 95) 
					AND PS.PayrollYearId = PP.PayrollYearId)
			ELSE
				(SELECT PS.Amount 
					FROM sPayroll.tPaySetup PS 
					WHERE PS.PayElementId = P.Id 
					AND (PS.SourceId = PPE.PayrollGroupId AND PS.SourceTypeId = 2020) 
					AND PS.PayrollYearId = PP.PayrollYearId) 
			END AS PaySetupAmount,					--MantisId = 0030726
			tEM.CreatedDateTime AS CreatedDateTime, --mantis - 0030732
			[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise,	--MantisId = 0030726
			ISNULL(PPR.ChequeNo,'') ChequeNo,	--#Start Mantis Id : 0031036
			PPR.PayDate,
			CASE WHEN ISNULL(PPR.PayTypeId,0) = 0 THEN ISNULL(ESO.PayTypeId,0)
				ELSE ISNULL(PPR.PayTypeId,0) END AS PayTypeId,
			CASE WHEN ISNULL(PPR.PayTypeId,0) = 0 THEN ISNULL(PTM2.Title,'')
				ELSE ISNULL(PTM.Title,'') END AS PayTypeName,	--#End Mantis Id : 0031036
	       ESO.RetirementDate AS RetirementDate --Mantis - 0031406
	FROM 
	sPayroll.tPayProcess PP 
	INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId = PP.ID 
	INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId 
	INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id = PPE.EmployeeId 
	INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
	INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID AND P.IsIncludeInPaySlip = 1
	LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=PPE.EmployeeId	
	LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=PPE.EmployeeId	
	INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
	INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
	INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
	LEFT JOIN sCommon.tReportOrgGroup ROG ON ROG.OrgGroupId=PY.OrgGroupId AND (ROG.ReportId = @rReportId OR @rReportId = 0) 
	LEFT JOIN sCommon.tReportRemarkGroupOrg RGO ON RGO.OrgId = tEM.OrgID AND RGO.ReportRemarkGroupId =  4
	LEFT JOIN sPayroll.tPayProcessEmployeeRemark PPR ON PPR.SalaryMonth = PP.SalaryMonth
	AND PPR.SalaryYear = PP.SalaryYear AND PPR.PayrollYearId = PP.PayrollYearId AND  PPR.EmployeeId = PPE.EmployeeId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
	LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
	INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
	LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PPR.PayTypeId		--#Start Mantis Id : 0031036
	LEFT JOIN sFinanceCommon.tPayTypeMaster PTM2 ON PTM2.Id = ESO.PayTypeId		--#End Mantis Id : 0031036
	
	--LEFT JOIN sHrm.tEmployeeWorkingDays EWD ON tEM.Id = EWD.EmployeeId AND PP.SalaryMonth=EWD.ForMonth AND PP.SalaryYear=EWD.ForYear
where 
      (EM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
      AND (P.IsObsolete=0)
      AND ((EM.Code Like '%' +  @rEmployeeCode + '%' ) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like '%' + @rEmployeeName  + '%') OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  AND ((EJD.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering Procedure [sPayroll].[pRptPayElementwiseSummaryDetail]...';


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

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

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

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

	SELECT 
	@rOrderByField AS OrderByField,
	@rBuilder1 AS Builder1,
	@rBuilder2 AS Builder2,	
	PE.Amount,
	P.Id AS PayElementId, 
	P.Title AS PayElementName,
	P.Code AS PayElementCode,
	EM.EmployeeId,
	tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
	EM.Code,
	EM.EmployeeDesignation,
	PP.SalaryMonth,
	PP.SalaryYear,
	MM.Title AS MonthName,
	PY.Title AS PayrollYearName,
	P.SortOrder,
	P.PayElementTypeId,
	@rPayElementTypeId AS IsPayElementTypeIdZero,
	@rPayElementId AS IsPayElementIdZero, 
	PPE.TotalEarning,		
	PPE.TotalDeduction,
	PPE.NetAmount,
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarningTotal,
	(CASE WHEN (PayElementId = @lBasicPayElementId And @rPayElementTypeId <> 2) 
	 THEN PPE.TotalDeduction WHEN PayElementId = @lProfessionalTaxPayElementId And @rPayElementTypeId = 2 
	 THEN PPE.TotalDeduction ELSE 0 END) AS TotalDeductionTotal,	 
	(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmountTotal,
	PGM.Id AS PayrollGroupId,
	PGM.Title AS PayrollGroupName,
	PPE.GrossBasic ,
	P.PayElementDefaultId,
	ISNULL(PPE.WorkingDays,0) AS WorkingDays,
	ISNULL(PPE.Lwp,0) AS Lwp,
	EM.FirstName,
	EM.LastName,
	tEM.Number,
	OM.Id AS OrganizationId,
	OM.Title AS OrganizationTitle,
	OM.Code AS OrganizationCode,
	OM.OrderIndex AS OrganizationOrderIndex,
	@rIsDetail AS IsDetail,
	EM.DateOfBirth,
	EM.DateOfJoining,
	--@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,
	tEM.CreatedDateTime as CreatedDateTime,
	[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise	 ---30737
		
	FROM sPayroll.tPayProcessEmployee PPE
		INNER JOIN sPayroll.tPayProcess PP ON PPE.PayProcessId=PP.ID
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON P.ID=PE.PayElementId AND P.IsObsolete = 0
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId=PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=PPE.EmployeeId	
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id 
		INNER JOIN sPayroll.tPayrollGroupMaster PGM ON PGM.Id = PPE.PayrollGroupId
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = tEM.OrgId
		--LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = tEM.OrgID
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
WHERE 
      (PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
      AND ((P.ID=@rPayElementId) OR (@rPayElementId=0))
      AND ((EM.Code Like  @rEmployeeCode) OR (@rEmployeeCode = ''))
	  AND ((EM.EmployeeName Like @rEmployeeName ) OR (@rEmployeeName = ''))
	  AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
	  AND (PP.SalaryMonth = @rForMonth OR @rForMonth = 0)
	  AND (PP.SalaryYear = @rForYear OR @rForYear = 0)
	  AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
	  AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
	  AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
	  AND (P.PayElementTypeId = @rPayElementTypeId OR @rPayElementTypeId = 0) 
	  AND (PP.SalaryMonth IN(SELECT cast(item as int) FROM  sCommon.fnsplit(@rMonths,',')) OR @rMonths='')
	  AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
	  AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
	  --AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '')
   --   AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '')
	  AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering Procedure [sPayroll].[pRptPayStatementGet]...';


GO

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

BEGIN 
	DECLARE @lMonthDay int=0
	SELECT @lMonthDay=[sCommon].[fGetDaysInMonth] (@rForMonth,@rForYear)
	DECLARE @lBasicPayElementId int
	SELECT @lBasicPayElementId = Id FROM sPayroll.tPayElement WHERE PayrollId = @rPayrollId AND PayElementDefaultId = 1

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

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


	SELECT 
		@rOrderByField AS OrderByField,
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,	
		ISNULL(ESO.EPFNumber,'') AS PFNumber,
		EM.EmployeeId,
		tEM.FirstName +' '+tEM.MiddleName+' '+ tEM.LastName AS EmployeeName,
		[sHrm].[fEmployeeNameGet](tEM.FirstName, tEM.MiddleName, tEm.LastName, OM.EmployeeNameFormatId) AS EmployeeNameFormatWise,
		EM.Code AS EmployeeCode,
		ISNULL(PPE.GrossBasic,0) AS GrossBasic,
		PY.Title AS PayrollYearName,
		PP.SalaryMonth,
		PP.SalaryYear,
	    MM.Title AS MonthName,
	    ISNULL(ESO.UAN,'') AS UAN,
	    (CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalEarning else 0 END) AS TotalEarning,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.TotalDeduction else 0 END) AS TotalDeduction,
		(CASE WHEN PayElementId = @lBasicPayElementId then PPE.NetAmount else 0 END) AS NetAmount,
	    EM.FirstName,
		EM.LastName,
		tEM.Number,
		(CASE WHEN ISNULL(PM.HeaderDisplayId,1) = 3 THEN ISNULL(PM.PayrollHeader,0x) ELSE NULL END) AS PayrollHeader,
		ISNULL(PM.HeaderDisplayId,1)AS HeaderDisplayId,
		EM.DateOfLeaving,
		tEM.CreatedDateTime,
		ISNULL(PPE.WorkingDays,@lMonthDay) WorkingDays,
		PPE.Lwp,
		ISNULL(PPE.PaidLeave,0) PaidLeave,
		ISNULL(PER.ChequeNo,'') ChequeNo,
		PER.PayDate,
		CASE WHEN ISNULL(PER.PayTypeId,0) = 0 THEN ISNULL(ESO.PayTypeId,0)
			ELSE ISNULL(PER.PayTypeId,0) END AS PayTypeId,
		CASE WHEN ISNULL(PER.PayTypeId,0) = 0 THEN ISNULL(PTM2.Title,'')
			ELSE ISNULL(PTM.Title,'') END AS PayTypeName


	FROM 
		sPayroll.tPayProcess PP 
		INNER JOIN sPayroll.tPayProcessEmployee PPE ON PPE.PayProcessId=PP.ID
		INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = PPE.EmployeeId
		INNER JOIN sHrm.tEmployeeMaster tEM ON tEM.Id=PPE.EmployeeId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId=EM.EmployeeId
		INNER JOIN sPayroll.tPayProcessElement PE ON PE.PayProcessEmployeeId=PPE.ID
		INNER JOIN sPayroll.tPayElement P ON PE.PayElementId=P.ID 
		INNER JOIN sPayroll.tPayrollYearMaster PY ON PP.PayrollYearId = PY.Id
		INNER JOIN sCommon.tMonthMaster MM ON MM.Id=PP.SalaryMonth
		INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND ((AT.ForMonth = @rForMonth) OR (@rForMonth = 0))  AND ((AT.ForYear = @rForYear) OR (@rForYear = 0)) 
		INNER JOIN sPayroll.tPayrollMaster PM ON PY.PayrollId = PM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=tEM.OrgId
		LEFT JOIN sPayroll.tPayProcessEmployeeRemark PER ON
			PER.SalaryMonth=@rForMonth AND PER.SalaryYear=@rForYear	AND PER.PayrollYearId=@rPayrollYearId AND EM.EmployeeId = PER.EmployeeId
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = PER.PayTypeId
		LEFT JOIN sFinanceCommon.tPayTypeMaster PTM2 ON PTM2.Id = ESO.PayTypeId
WHERE 
		(PPE.EmployeeId = @rEmployeeId OR @rEmployeeId = 0) 
		AND ((EM.Code Like @rEmployeeCode) OR (@rEmployeeCode = ''))
		AND ((EM.EmployeeName Like @rEmployeeName) OR (@rEmployeeName = ''))
		AND ((PP.SalaryMonth = @rForMonth) OR (@rForMonth = 0))
	    AND ((PP.SalaryYear = @rForYear) OR (@rForYear = 0))
		AND ((PY.PayrollId=@rPayrollId) OR (@rPayrollId=0))
		AND (PPE.PayrollGroupId = @rPayrollGroupId OR @rPayrollGroupId = 0) 
		AND (PP.PayrollYearId = @rPayrollYearId OR @rPayrollYearId = 0) 
		AND ((EM.DateOfleaving >= @lFirstDate) OR ISNULL(EM.DateOfleaving,'') = '' OR ISNULL(@lFirstDate,'')='')
        AND ((EM.DateOfJoining <= @lLasteDate) OR ISNULL(EM.DateOfJoining,'') = '' OR ISNULL(@lLasteDate,'')='')
		AND ((tEM.OrgID = @rOrgId) OR (@rOrgId = 0))
		AND (EM.DepartmentId = @rDepartmentId OR @rDepartmentId = 0)
		AND ((tEM.StatusId = @rStatusId) OR (@rStatusId = 0))
		AND ((EM.EmployeeGroupId = @rEmployeeGroupId) OR (@rEmployeeGroupId = 0))
END
GO
PRINT N'Altering Procedure [sPayroll].[pRptPFDetail]...';


GO

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

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

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

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

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

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


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


GO
ALTER PROCEDURE [sSecurity].[pMobValidateUser]

    @rOrgId int = 0,
    @rUserTitle nvarchar(100)='',
    @rUserMobileNumber nvarchar(50)=''
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		DECLARE @rUserSourceId bigint=0
		DECLARE @rUserId bigint=0
		DECLARE @rUserSourceTypeId smallint=0
		DECLARE @newpwd VARCHAR(100)
		SELECT @rUserId=Id,@rUserSourceId = SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserTitle) AND OrgId = @rOrgId
		
		IF(@rUserSourceTypeId = 95)
		BEGIN
			IF EXISTS (SELECT 1 FROM sHrm.tEmployeeCommunications WHERE MobileNumber = @rUserMobileNumber and EmployeeId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId

					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP
			END	
		END
		IF(@rUserSourceTypeId = 2003)
		BEGIN
			IF EXISTS (SELECT 1 FROM sStudent.tStudentCommunication WHERE ParentContactNo = @rUserMobileNumber and StudentId = @rUserSourceId)
			BEGIN
				IF EXISTS (SELECT 1 FROM sSecurity.tUser WHERE Id = @rUserId AND OrgId = @rOrgId)
				BEGIN				
					EXEC [sSecurity].[pNumericOTPGenerate] @len=6, @min=48, @range=9, @exclude='', @output=@newpwd OUT
					UPDATE sSecurity.tUser
					SET	TempPasswordCode=@newpwd,CreatedDateTime=sCommon.fGetDate(),OTPExpiryDate=DATEADD(SECOND,120,GETDATE())				
					WHERE Id = @rUserId AND OrgId = @rOrgId
					SELECT 1 AS Result,'' AS [Message],TempPasswordCode AS OTP FROM sSecurity.tUser WHERE Id = @rUserId  AND OrgId = @rOrgId					
				END
				ELSE
				BEGIN
					SELECT -101 AS Result,'User does not exist' AS [Message],'' AS OTP
				END
			END
			ELSE
			BEGIN
				SELECT -102 AS Result,'Mobile number is wrong' AS [Message],'' AS OTP
			END		
		END
END
GO
PRINT N'Altering Procedure [sTool].[pDeleteStaticData]...';


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

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


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

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

DELETE FROM sAdmission.tInquiryModeMaster

DELETE FROM sFee.tFeeMainGroupMaster

DELETE FROM sPayroll.tPayElementDefault

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


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

DELETE FROM sCommon.tRangeGroupMaster

DELETE FROM sHostel.tLogStatusMaster

DELETE FROM sSetup.tStudentNameFormatMaster

DELETE FROM sCommon.tMainCastCategoryMaster

DELETE FROM sOp.tFunctionalityMaster
DELETE FROM sOp.tPaymentGatewayMaster

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

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

DELETE FROM sActivity.tEventMainTypeMaster
DELETE FROM sAlert.tOSType

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

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

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

DELETE FROM sAssessment.tStaticCCECSMaster
DELETE FROM sAssessment.tStaticCCECSGroupMaster

DELETE FROM siTax.tStaticIncomeTaxGroup
DELETE FROM siTax.tStaticIncomeTaxSubGroup

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

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

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

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

DELETE FROM sSystem.tStaticVersion

DELETE FROM sCommunication.tFeedBackAnswerGroupMaster

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

DELETE FROM sSystem.tTimeZone
DELETE FROM sTool.tTestCaseTypeMaster

DELETE FROM sAlumni.tEmployeementType

DELETE FROM sErp.tCampusTypeMaster

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

DELETE FROM sSecurity.tScreenHelp
DELETE FROM sSystem.tSettingInfo

DELETE FROM sProcurement.tOtherLocationSourceTypeMaster

DELETE FROM sCommon.tFieldTypeMaster
DELETE FROM sErp.tLeadInfrastructureMaster

DELETE FROM sHostel.tHostelEventMainTypeMaster

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

DELETE FROM sAcademic.tHomeworkCheckStatusMaster
DELETE FROM sAssessment.tExamTypeMaster

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

DELETE FROM sAudit.tOperationMaster

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

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


DELETE FROM sErp.tPlugInMaster
DELETE FROM sErp.tTagMaster

DELETE FROM sErp.tIssueTypeMaster

DELETE FROM sErp.tScreenFunctionalityMaster

DELETE FROM sHrm.tChangeTypeMaster


DELETE FROM sCommon.tDataMaster
DELETE FROM sCommon.tDataTypeMaster

DELETE FROM siTax.tStaticIncomeTaxSubSubGroup

DELETE FROM sCommunication.tStudentDocumentTypeMaster

DELETE FROM sCommon.tUploadFunctionalityMaster
DELETE FROM sCommunication.tEmployeeDocumentTypeMaster

DELETE FROM sErp.tCustomerMessageTypeMaster

DELETE FROM sActivity.tActivityMainTypeMaster
DELETE FROM sSecurity.tTraceabilityMaster
DELETE FROM sSecurity.tTraceabilityTrack

DELETE FROM sSecurity.tScreenScopeDetails
DELETE FROM sBiometric.tEmployeeConfigurationMaster
DELETE FROM sSetup.tEmployeeNameFormatMaster
DELETE FROM sStudent.tOnlineRegistrationDisplayFieldMaster

DELETE FROM sSetup.tFormTypeMaster
DELETE FROM sSetup.tFormButtonMaster

DELETE FROM sSecurity.tSysSuperScreen
DELETE FROM sAppraisal.tKPAStatus
--DELETE FROM sAttendance.tPeriodNoMaster

DELETE FROM sPurchase.tPurchaseReportTemplateMaster
DELETE FROM sWf.tWfStatusMaster
DELETE FROM sWf.tWfFunctionalityMaster
DELETE FROM sWf.tWfTypeMaster

END
GO

PRINT N'Creating Procedure [sBiometric].[pNewTimeSheetListGet]...';


GO
CREATE PROCEDURE [sBiometric].[pNewTimeSheetListGet]
  @rEmployeeId bigint=0,  
  @rFromDate DateTime,  
  @rToDate DateTime,  
  @rStatus nvarchar(10) = '0',  
  @rOrgId int = 0  ,
  @rEmployeeName nvarchar(50) = '',
  @rStatusId int = 0,
  @rOrganizationDepartmentId int=0,
  @rOrgGroupDepartmentId int = 0

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  BEGIN  

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

		SELECT @lBatchID = Id FROM sSetup.tBatchMaster WHERE OrgId = @rOrgId AND IsActive = 1

 INSERT INTO #TempNewMonthTrans  
   
	SELECT	EM.Id as EmployeeId,
			--MT.EmployeeId,
			isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(Mt.attn_dt) *100+ 01) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)),
			D01,D01_IN,D01_OUT,D01_O,D01_L,D01_T,D01_E,D01_S 
	FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId
			AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
			AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
	WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		--AND EJD.DateOfJoining<=cast(rtrim(YEAR('2024-01-01 00:00:00') *10000+ Month('2024-01-01 00:00:00') *100+ 01) as datetime) 
		AND (EJD.DateOfJoining<= @Lastdate)
		--AND (ejd.dateofleaving>=cast(rtrim(YEAR('2024-01-01 00:00:00') *10000+ Month('2024-01-01 00:00:00') *100+ 01) as datetime) or ejd.dateofleaving is null)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
		--AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 1
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 02) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 02) as datetime)),
	D02,D02_IN,D02_OUT,D02_O,D02_L,D02_T,D02_E,D02_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId 
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) 
		--AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 2
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 03) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 03) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 03) as datetime)),
	D03,D03_IN,D03_OUT,D03_O,D03_L,D03_T,D03_E,D03_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 3
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 04) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 04) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 04) as datetime)),
	D04,D04_IN,D04_OUT,D04_O,D04_L,D04_T,D04_E,D04_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 4
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 05) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 05) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 05) as datetime)),
	D05,D05_IN,D05_OUT,D05_O,D05_L,D05_T,D05_E,D05_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	--	(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 5
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 06) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 06) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 06) as datetime)),
	D06,D06_IN,D06_OUT,D06_O,D06_L,D06_T,D06_E,D06_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	--	(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 6
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 07) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 07) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 07) as datetime)),
	D07,D07_IN,D07_OUT,D07_O,D07_L,D07_T,D07_E,D07_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	--	(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 7
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 08) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 08) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 08) as datetime)),
	D08,D08_IN,D08_OUT,D08_O,D08_L,D08_T,D08_E,D08_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
	--	(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 8
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 09) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 09) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 09) as datetime)),
	D09,D09_IN,D09_OUT,D09_O,D09_L,D09_T,D09_E,D09_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 9
	UNION ALL

	SELECT EM.Id as EmployeeId,
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 10) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 10) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 10) as datetime)),
	D10,D10_IN,D10_OUT,D10_O,D10_L,D10_T,D10_E,D10_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 10

	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 11) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 11) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 11) as datetime)),
	D11,D11_IN,D11_OUT,D11_O,D11_L,D11_T,D11_E,D11_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 11

	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 12) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 12) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 12) as datetime)),
	D12,D12_IN,D12_OUT,D12_O,D12_L,D12_T,D12_E,D12_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 12
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 13) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 13) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 13) as datetime)),
	D13,D13_IN,D13_OUT,D13_O,D13_L,D13_T,D13_E,D13_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 13
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 14) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 14) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 14) as datetime)),
	D14,D14_IN,D14_OUT,D14_O,D14_L,D14_T,D14_E,D14_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 14
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 15) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 15) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 15) as datetime)),
	D15,D15_IN,D15_OUT,D15_O,D15_L,D15_T,D15_E,D15_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 15
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 16) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 16) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 16) as datetime)),
	D16,D16_IN,D16_OUT,D16_O,D16_L,D16_T,D16_E,D16_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 16
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 17) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 17) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 17) as datetime)),
	D17,D17_IN,D17_OUT,D17_O,D17_L,D17_T,D17_E,D17_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 17
	UNION ALL

	SELECT EM.Id as EmployeeId,
	-- MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 18) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 18) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 18) as datetime)),
	D18,D18_IN,D18_OUT,D18_O,D18_L,D18_T,D18_E,D18_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 18
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 19) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 19) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 19) as datetime)),
	D19,D19_IN,D19_OUT,D19_O,D19_L,D19_T,D19_E,D19_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 19
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 20) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 20) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 20) as datetime)),
	D20,D20_IN,D20_OUT,D20_O,D20_L,D20_T,D20_E,D20_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 20
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 21) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 21) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 21) as datetime)),
	D21,D21_IN,D21_OUT,D21_O,D21_L,D21_T,D21_E,D21_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 21
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 22) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 22) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 22) as datetime)),
	D22,D22_IN,D22_OUT,D22_O,D22_L,D22_T,D22_E,D22_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 22
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 23) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 23) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 23) as datetime)),
	D23,D23_IN,D23_OUT,D23_O,D23_L,D23_T,D23_E,D23_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 23
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 24) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 24) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 24) as datetime)),
	D24,D24_IN,D24_OUT,D24_O,D24_L,D24_T,D24_E,D24_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 24
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 25) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 25) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 25) as datetime)),
	D25,D25_IN,D25_OUT,D25_O,D25_L,D25_T,D25_E,D25_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 25
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 26) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 26) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 26) as datetime)),
	D26,D26_IN,D26_OUT,D26_O,D26_L,D26_T,D26_E,D26_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 26
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 27) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 27) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 27) as datetime)),
	D27,D27_IN,D27_OUT,D27_O,D27_L,D27_T,D27_E,D27_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 27
	UNION ALL

	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 28) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 28) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 28) as datetime)),
	D28,D28_IN,D28_OUT,D28_O,D28_L,D28_T,D28_E,D28_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 28

	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 #TempNewMonthTrans
		SELECT EM.Id as EmployeeId, 
		--MT.EmployeeId,
		--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 29) as datetime),
		isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 29) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 29) as datetime)),
		D29,D29_IN,D29_OUT,D29_O,D29_L,D29_T,D29_E,D29_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 29
	END
	
	IF Month(@rFromDate) <> 2
	BEGIN
	INSERT INTO #TempNewMonthTrans
	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 30) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 30) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 30) as datetime)),
	D30,D30_IN,D30_OUT,D30_O,D30_L,D30_T,D30_E,D30_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT >= cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) AND MT.ATTN_DT <= cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 30
	END
	--Mantis Id:28837 Start to check from amd to date month contain 31 days
	IF Month(@rFromDate) NOT IN (2,4,6,9,11)
	BEGIN
	INSERT INTO #TempNewMonthTrans
	SELECT EM.Id as EmployeeId, 
	--MT.EmployeeId,
	--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 31) as datetime),
	isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 31) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 31) as datetime)),
	D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND MT.ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 31
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
	--AND MT.ATTN_DT = cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime) 
	AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
	END

	IF NOT EXISTS (SELECT * FROM #TempNewMonthTrans WHERE (EmployeeId = @rEmployeeId OR @rEmployeeId = 0) AND Attn_Date=@rToDate)	--Mantis Id 30042, only "if" condition will be added
	BEGIN
		IF Month(@rToDate) NOT IN (2,4,6,9,11)
		BEGIN
		INSERT INTO #TempNewMonthTrans
		SELECT EM.Id as EmployeeId, 
		--MT.EmployeeId,
		--cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 31) as datetime),
		isnull(cast(rtrim(YEAR(MT.attn_dt) *10000+ Month(MT.attn_dt) *100+ 31) as datetime),cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 31) as datetime)),
		D31,D31_IN,D31_OUT,D31_O,D31_L,D31_T,D31_E,D31_S FROM sHRM.tEmployeeMaster EM
		INNER JOIN sHrm.tEmployeeJobDetail EJD ON EM.Id=EJD.EmployeeId
		LEFT JOIN sBiometric.tMonthTrans MT ON EM.Id=MT.EmployeeId AND  MT.ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		WHERE (EM.Id = @rEmployeeId OR @rEmployeeId = 0)
		AND EM.OrgId = @rOrgId
		AND (EJD.DateOfJoining<= @Lastdate)
		AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
		--AND (DATEDIFF(DAY, @rFromDate, @rToDate) + 1) >= 31
		--(MT.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)
		--AND  MT.ATTN_DT = cast(rtrim(YEAR(@rToDate) *10000+ Month(@rToDate) *100+ 01) as datetime) 
		AND (ISNULL(MT.SourceTypeId,95) = 95 OR MT.SourceTypeId = 0)
		END
	END

--select * from #TempNewMonthTrans

SELECT TM.Id,TM.EmployeeId,TM.Attn_Date,isnull(TM.PresentStatus,'XX') AS OldPresentStatus,OGD.Title AS [Organization Group Department],
 
 isnull(CASE 
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn !='00:00'))  then 'PH'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='H') AND (TM.FirstIn='00:00')) THEN 'H'  
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn !='00:00'))  then 'PW'
 When (([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )='W') AND (TM.FirstIn ='00:00'))  then 'W'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='PW')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn !='00:00'))  then 'P'
 When ((TM.PresentStatus='W')AND ([sHrm].[fWeekHOffGetBio](TM.EmployeeId , YEAR(Attn_Date) ,MONTH(TM.Attn_Date) ,DAY(TM.Attn_Date) ,@lBatchID ,ODM.Id ,@rOrgId )!='W') AND (TM.FirstIn ='00:00'))  then 'A'
 WHEN ((TM.PresentStatus='W') AND (TM.FirstIn !='00:00')) THEN 'PW'
  When ((TM.PresentStatus='XX')AND (Cast(TM.Attn_Date as date)<GETDATE()) And (cast(EJD.DateOfJoining as date)<= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfJoining,'')='')AND (EJD.DateOfleaving>= Cast(TM.Attn_Date as date) OR ISNULL(EJD.DateOfleaving,'')='') AND (TM.FirstIn ='00:00'))  then 'A'
 ELSE
 TM.PresentStatus END,'A') as PresentStatus,

 isnull(TM.FirstIn,'00:00') as FirstIn ,isnull(TM.LastOut,'00:00') as LastOut,isnull(TM.OverTime,'00:00') as OverTime,isnull(TM.LateBy,'00:00') as LateBy, isnull(TM.Duration,'00:00') as Duration,isnull(TM.EarlyBy,'00:00') as EarlyBy,isnull(TM.ShiftName,'') as ShiftName, MT.Tot_Attn,
 MT.Tot_Attn + Tot_WeekOff + Tot_Holiday  AS TotalPresent,Tot_Abs AS TotalAbsent,Tot_WeekOff AS TotalWeekOff,  
 Tot_Holiday AS Totalholiday,Tot_Leave AS TotalLeave,EM.FirstName + ' ' + EM.LastName As ShortName,EM.Code as EmpCode ,   
 [sBiometric].[fEmployeeLeaveTypeGet] (TM.ATTN_DATE,TM.EmployeeId) AS LeaveStatus ,   
 [sBiometric].[fEmployeeLeaveTypePendingGet](TM.ATTN_DATE,TM.EmployeeId) AS LeavePendingStatus,   
 [sBiometric].[fEmployeeTravelGet](TM.ATTN_DATE,TM.EmployeeId) AS EmployeeTravel,  
 ISNULL(ELS.Id,0) AS EmployeeLateStatusId, 
 ISNULL(SM.Id,0) AS StatusId,  
 ISNULL(SM.Title,'') AS Status  
 FROM #TempNewMonthTrans TM   
 LEFT JOIN sBiometric.tMonthTrans MT ON MT.EmployeeId=TM.EmployeeId AND (ISNULL(SourceTypeId,95) = 95 OR SourceTypeId = 0) AND MT.Attn_dt=cast(rtrim(YEAR(@rFromDate) *10000+ Month(@rFromDate) *100+ 01) as datetime)
 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') or TM.ATTN_DATE is null)
 INNER JOIN sSetup.tDepartmentMaster ODM ON EJD.OrganizationDepartmentId = ODM.Id 
 LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGD ON  EJD.OrgGroupDepartmentId=OGD.Id
 WHERE   
 ((TM.ATTN_DATE >= @rFromDate AND TM.ATTN_DATE <=@rToDate) or TM.ATTN_DATE is null)
 AND (TM.EmployeeId = @rEmployeeId OR @rEmployeeId = 0)   
 AND (( @rStatus = '1' AND (TM.Duration < '09:30')) OR ( @rStatus != '1' AND ((PresentStatus = @rStatus OR @rStatus='0'))))
 AND EM.OrgId = @rOrgId 
 AND ((EM.StatusId = @rStatusId) OR (@rStatusId = 0))
 AND((EJD.OrganizationDepartmentId=@rOrganizationDepartmentId) OR (@rOrganizationDepartmentId=0))
 AND ((EJD.OrgGroupDepartmentId = @rOrgGroupDepartmentId) OR (@rOrgGroupDepartmentId=0)) 
 AND (EM.FirstName + ' ' + EM.LastName like '%' + @rEmployeeName + '%' or @rEmployeeName = '')
 AND  ISNULL(EM.IsOtherUser,0) = 0
 AND (EJD.DateOfJoining<= @Lastdate OR ISNULL(EJD.DateOfJoining,'')='')
 AND (EJD.DateOfleaving>= @Firstdate OR ISNULL(EJD.DateOfleaving,'')='')
 Order By TM.EmployeeId,TM.Attn_Date


 
 --Drop table #TempNewMonthTrans

 END
GO
PRINT N'Creating Procedure [sMis].[pRptAppStudentUserSummaryGet]...';


GO

CREATE PROCEDURE [sMis].[pRptAppStudentUserSummaryGet]
(
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='', 
	@rOrgGroupId int = 0 ,
	@rOrgGroupBatchId int = 0,
	@rOrgMainGroupId int = 0,
	@rOrgSubGroupId int = 0,
	@rOrgId int = 0
 )
AS
SET NOCOUNT ON

BEGIN
		 SELECT 
				@rBuilder1 AS Builder1,
				@rBuilder2 AS Builder2,
				OM2.ID AS OrgId,
				OM2.DisplayTitle AS OrgName,
				OM2.Code, 
				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId 
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND OM.Id = OM2.Id  AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003),0) AS 'StudentCreatedUser',
 
				ISNULL((SELECT COUNT(DISTINCT(RU.UserId)) FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				AND(OM1.Id !=1) AND OM1.Id = OM2.Id AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0)) LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId
				WHERE U1.IsObsolete = 0 AND U1.SourceTypeId = 2003 AND ((SC.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND SC.StatusId = 1),0) AS 'StudentRegister',

				ISNULL((SELECT COUNT(U1.Id) FROM sSecurity.tUser U1 INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = U1.OrgId LEFT JOIN (SELECT DISTINCT UserId FROM sCommunication.tRegisteredUsers) AS A ON A.UserId = U1.Id
				LEFT JOIN sStudent.vStudentCommunication SC ON SC.StudentId = U1.SourceId WHERE U1.IsObsolete = 0 AND OM.Id = OM2.Id AND((OM.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM.Id !=1) AND ((SC.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) AND SC.StatusId = 1 AND U1.SourceTypeId=2003 AND A.UserId IS NULL),0) AS 'StudentNotRegister'
				 
				FROM
				 
				sSecurity.tUser U
				INNER JOIN sSetup.tOrganizationMaster OM2 ON OM2.Id = U.OrgId
				INNER JOIN sSetup.tOrgSubGroupMaster OSGM2 ON OSGM2.Id = OM2.OrgSubGroupId
				INNER JOIN sSetup.tOrgMainGroupMaster OMGM2 ON OMGM2.Id = OSGM2.OrgMainGroupId
				LEFT JOIN (
				SELECT RU.UserId AS  UserId  
				FROM sCommunication.tRegisteredUsers RU INNER JOIN sSecurity.tUser U1 ON RU.UserId = U1.Id 
				INNER JOIN sSetup.tOrganizationMaster OM1 ON OM1.Id = U1.OrgId 
				INNER JOIN sSetup.tOrgGroupMaster O1 ON O1.Id = OM1.OrgGroupId
				INNER JOIN sSetup.tOrgSubGroupMaster OSGM1 ON OSGM1.Id = OM1.OrgSubGroupId
				INNER JOIN sSetup.tOrgMainGroupMaster OMGM1 ON OMGM1.Id = OSGM1.OrgMainGroupId
				AND(OM1.Id !=1)
				AND ((OM1.Id = @rOrgId) OR (@rOrgId = 0))
				AND((O1.Id =  @rOrgGroupId)OR(@rOrgGroupId=0))
				AND ((OMGM1.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
				AND ((OSGM1.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
				WHERE U1.IsObsolete = 0 GROUP BY RU.UserId ) RU ON RU.UserId = U.Id
				 
				WHERE U.IsObsolete = 0
				AND((OM2.OrgGroupId =  @rOrgGroupId)OR(@rOrgGroupId=0)) 
				AND(OM2.Id !=1)
				AND ((OM2.Id = @rOrgId) OR (@rOrgId = 0))
				AND ((OMGM2.Id=@rOrgMainGroupId) OR (@rOrgMainGroupId=0))
				AND ((OSGM2.Id=@rOrgSubGroupId) OR (@rOrgSubGroupId=0))
				GROUP BY OM2.Id,OM2.DisplayTitle,OM2.Code
END
GO
PRINT N'Creating Procedure [sSecurity].[pForgotPasswordFailureLogAdd]...';


GO
CREATE PROCEDURE [sSecurity].[pForgotPasswordFailureLogAdd]

	@rUserName varchar(255),
	@rMobileNumber nvarchar(50) = '',
	@rEmailId varchar(100)='',
	@rOrgId smallint,
	@rExceptionType nvarchar(1000)=NULL,
	@rExceptionMessage nvarchar(max),
	@rExceptionSource nvarchar(max)=NULL,
	@rExceptionStackTrace nvarchar(max)=NULL,
	@rExceptionDetail nvarchar(max)=NULL,
	@rOsTypeId smallint


WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		DECLARE @lCode VARCHAR(100) ,@lSourceId bigint = 0, @lUserId bigint = 0, @lSourceTypeId int
	
		IF (@rUserName != '')
		BEGIN
			SELECT @lUserId = Id, @lSourceId = SourceId, @lSourceTypeId = SourceTypeId
			FROM  sSecurity.tUser
			WHERE OrgId = @rOrgId AND LoginTitle = @rUserName
		END 

		IF(@lSourceId != 0 AND @lSourceTypeId = 2003)
		BEGIN
			SELECT @lCode=Code
			FROM  sStudent.tStudentMaster WHERE Id=@lSourceId AND OrgId = @rOrgId
		END
		
		IF (@lSourceId != 0 AND @lSourceTypeId = 95) 
		BEGIN
			SELECT @lCode=Code
			FROM  sHrm.tEmployeeMaster WHERE Id=@lSourceId AND OrgId = @rOrgId
		END
		
		IF NOT EXISTS(select 1 from sSecurity.tForgotPasswordFailureLog where OrgId = @rOrgId AND UserName=@rUserName AND UserId = @lUserId AND IsSendAlert = 0)
		BEGIN	
		Insert Into sSecurity.tForgotPasswordFailureLog
		(
			 OrgId
			,UserName
			,Code
			,EmailId
			,MobileNumber
			,SourceId
			,SourceTypeId
			,IsSendAlert
			,IsResetPassword
			,ExceptionType
			,ExceptionMessage
			,ExceptionSource
			,ExceptionStackTrace
			,ExceptionDetail
			,UserId
			,CreatedDateTime
			,OsTypeId
		)
		Values
		(
			 @rOrgId
			,@rUserName
			,@lCode
			,@rEmailId
			,@rMobileNumber
			,@lSourceId
			,@lSourceTypeId
			,0
			,0
			,@rExceptionType
			,@rExceptionMessage
			,@rExceptionSource
			,@rExceptionStackTrace
			,@rExceptionDetail
			,@lUserId
			,sCommon.fGetDate()
			,@rOsTypeId
		)
		END

		ELSE
		BEGIN
			update sSecurity.tForgotPasswordFailureLog
			SET 
				EmailId = @rEmailId, MobileNumber = @rMobileNumber, ExceptionType = @rExceptionType, ExceptionMessage = @rExceptionMessage, 
				ExceptionSource =@rExceptionSource, ExceptionStackTrace = @rExceptionStackTrace, ExceptionDetail = @rExceptionDetail, 
				UpdatedDateTime = sCommon.fGetDate(), OsTypeId = @rOsTypeId
			WHERE OrgId = @rOrgId AND UserName=@rUserName AND UserId = @lUserId AND IsSendAlert = 0
		END
END
GO
PRINT N'Creating Procedure [sSecurity].[pValidateUserMobileDetails]...';


GO
CREATE PROCEDURE sSecurity.pValidateUserMobileDetails
@rUserName VARCHAR(100),
@rMobileNumber VARCHAR(50),
@rOrgId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lRes varchar(2000)='',@lUserId bigint,@lCode varchar(100),@lEmployeeId bigint,@lStudentId bigint=0
	SELECT @lUserId = Id from sSecurity.tUser WHERE UPPER(LoginTitle) = UPPER(@rUserName) AND
	  NumberOfLogonAttempt <= 5000 and IsObsolete = 0 and OrgId = @rOrgId
	
	IF @lUserId > 0
	BEGIN
		UPDATE sSecurity.tUser set TempPasswordCode = newid() WHERE Id = @lUserId
		SELECT @lCode = TempPasswordCode,@lRes = '',@lEmployeeId = SourceId from sSecurity.tUser where Id = @lUserId and SourceTypeId = 95
		SELECT @lCode = TempPasswordCode,@lRes = '', @lStudentId = SourceId from sSecurity.tUser where Id = @lUserId and SourceTypeId = 2003
		
		IF @lEmployeeId > 0
		BEGIN		
			IF exists (SELECT 1 from sHrm.tEmployeeCommunications WHERE EmployeeId = @lEmployeeId and isnull(@rMobileNumber,'') = '')
			BEGIN
				update sHrm.tEmployeeCommunications set MobileNumber = @rMobileNumber WHERE EmployeeId = @lEmployeeId
				SELECT @lRes = ''
			END
			ELSE
			BEGIN
				if exists (SELECT 1 from sHrm.tEmployeeCommunications WHERE EmployeeId = @lEmployeeId and MobileNumber = @rMobileNumber)
				BEGIN
					SELECT @lRes = ''
				END
				else
				BEGIN
					SELECT @lRes = 'Invalid Mobile Number'
				END			
			END
		END
		ELSE IF @lStudentId>0
    	BEGIN
    	IF EXISTS (SELECT 1 from sStudent.tStudentCommunication WHERE StudentId = @lStudentId AND isnull(ParentContactNo,'') = '')
			BEGIN
				UPDATE sStudent.tStudentCommunication set ParentContactNo = @rMobileNumber WHERE StudentId = @lStudentId
				SELECT @lRes = ''
			END
			ELSE
			BEGIN
				if exists (SELECT 1 from sStudent.tStudentCommunication WHERE StudentId = @lStudentId and ParentContactNo = @rMobileNumber)
				BEGIN
					SELECT @lRes = ''
				END
				else
				BEGIN
					SELECT @lRes = 'Invalid Mobile Number'
				END			
			END
    	
		END
		ELSE
		BEGIN
			SELECT @lRes = 'Invalid User Name'
		END
	END
	ELSE
	BEGIN
		SELECT @lRes = 'Invalid User Name'
	END
	SELECT @rMobileNumber as MobileNumber,isnull(@lRes,'') as Res,isnull(@lEmployeeId,0) as EmployeeId,isnull(@lCode,'') as Code
END
GO
PRINT N'Creating Procedure [sStudent].[pConvertLeftStudentToAlumni]...';


GO


CREATE PROCEDURE [sStudent].[pConvertLeftStudentToAlumni]   
	@rAcademicIds nvarchar(max),
	@rUserId bigint,
	@rOrgId int
	
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
 SET @rAcademicIds = REPLACE(@rAcademicIds, '''', '')
 --Select @rAcademicIds
CREATE TABLE #Registration
(
	AutoId int IDENTITY,
	FirstName nvarchar(100) ,
	MiddleName nvarchar(100) ,
	LastName nvarchar(100) ,
	GenderId tinyint ,
	RegistrationDate date ,
	EmailId nvarchar(150) ,
	MobileNo nvarchar(11) ,
	OrgId int ,
	PassingBatchId int ,
	PassingClassId int ,
	MappedStudentId bigint ,
	EmployeementTypeId int ,
	EmployerName nvarchar(150) ,
	Designation nvarchar(150) ,
	EmployeementCountry nvarchar(150) ,
	EmployeementState nvarchar(150) ,
	EmployeementCity nvarchar(150) ,
	SpecialAchievement nvarchar(500) ,
	UniversityName nvarchar(200) ,
	HigherStudyCountry nvarchar(150) ,
	HigherStudyState nvarchar(150) ,
	HigherStudyCity nvarchar(150) ,
	ResidentialCountry nvarchar(150) ,
	ResidentialState nvarchar(150) ,
	ResidentialCity nvarchar(150) ,
	OfficePhone nvarchar(150) ,
	ResidentialPhone nvarchar(150) ,
	CreatedUserId bigint ,
	CreatedDateTime datetime ,
	UpdatedUserId bigint ,
	UpdatedDateTime datetime 
)
	
INSERT INTO #Registration
SELECT 
	ISNULL(SM.FirstName,'') AS FirstName,
	ISNULL(SM.MiddleName,'') AS MiddleName,
	ISNULL(SM.LastName,'') AS LastName,
	SD.GenderId,
	sCommon.fGetDate() AS RegistrationDate,
	SC.ParentEmail AS EmailId,
	SC.ParentContactNo AS MobileNo,
	ISNULL(A.OrgId,0) AS OrgId,
	ISNULL(A.BatchId,0) AS PassingBatchId,
	ISNULL(A.ClassId,0) AS PassingClassId,
	ISNULL(A.Id,0) AS MappedStudentId,
	0 AS EmployeementTypeId,
	'' AS EmployerName,
	'' AS Designation,
	'' AS EmployeementCountry,
	'' AS EmployeementState,
	'' AS EmployeementCity,
	'' AS SpecialAchievement,
	'' AS UniversityName,
	'' AS HigherStudyCountry,
	'' AS HigherStudyState,
	'' AS HigherStudyCity,
	'' AS ResidentialCountry,
	'' AS ResidentialState,
	'' AS ResidentialCity,
	'' AS OfficePhone,
	'' AS ResidentialPhone,
	@rUserId AS CreatedUserId,
	sCommon.fGetDate() AS CreatedDateTime,
	@rUserId AS UpdatedUserId,
	sCommon.fGetDate() AS UpdatedDateTime


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.Id IN (SELECT cast(item as nvarchar(max)) FROM  sCommon.fnsplit(@rAcademicIds,','))

	--Select * from #Registration
	
	DECLARE @lCount int,@lId int,@lFirstName nvarchar(100),@lMiddleName nvarchar(100),@lLastName nvarchar(100),@lEmailId nvarchar(150),@lMobileNo nvarchar(11) 
	SELECT @lCount = COUNT(AutoId) FROM #Registration
	SELECT Top 1 @lId=AutoId FROM #Registration
	

	WHILE @lId <= @lCount 
	BEGIN

		SELECT @lFirstName = FirstName,@lMiddleName = MiddleName , @lLastName = LastName , @lEmailId = EmailId , @lMobileNo = MobileNo FROM #Registration WHERE AutoId = @lId
		--Select @lFirstName, @lMiddleName,@lLastName,@lEmailId,@lMobileNo
		IF EXISTS (Select 1 FROM sAlumni.tRegistration WHERE FirstName = @lFirstName AND MiddleName = @lMiddleName AND LastName = @lLastName AND EmailId = @lEmailId AND MobileNo = @lMobileNo)
		BEGIN
			DELETE FROM sAlumni.tRegistration WHERE FirstName = @lFirstName AND MiddleName = @lMiddleName AND LastName = @lLastName AND EmailId = @lEmailId AND MobileNo = @lMobileNo
		END

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

		INSERT INTO sAlumni.tRegistration
		(
			Id,FirstName,MiddleName,LastName,GenderId,RegistrationDate ,EmailId,MobileNo,OrgId,PassingBatchId,
			PassingClassId,MappedStudentId,EmployeementTypeId,EmployerName,Designation,EmployeementCountry,
			EmployeementState,EmployeementCity,SpecialAchievement,UniversityName,HigherStudyCountry,HigherStudyState,
			HigherStudyCity,ResidentialCountry,ResidentialState,ResidentialCity,OfficePhone,ResidentialPhone,
			CreatedUserId,CreatedDateTime,UpdatedUserId,UpdatedDateTime
		)
		SELECT
			@lNextNumber ,FirstName ,MiddleName ,LastName ,GenderId ,RegistrationDate ,EmailId ,MobileNo ,OrgId ,PassingBatchId ,
			PassingClassId ,MappedStudentId ,EmployeementTypeId ,EmployerName ,Designation ,EmployeementCountry ,
			EmployeementState ,EmployeementCity ,SpecialAchievement ,UniversityName ,HigherStudyCountry ,HigherStudyState ,
			HigherStudyCity ,ResidentialCountry ,ResidentialState ,ResidentialCity ,OfficePhone ,ResidentialPhone ,
			CreatedUserId ,CreatedDateTime ,UpdatedUserId ,UpdatedDateTime 
			FROM #Registration WHERE AutoId = @lId

		SET @lId=@lId+1
	END

	DROP TABLE #Registration

END
GO
PRINT N'Creating Procedure [sStudent].[pLeftStudentListGet]...';


GO

CREATE PROCEDURE [sStudent].[pLeftStudentListGet]   
	@rFirstName nvarchar(100)='',
	@rMiddleName nvarchar(100)='',
	@rLastName nvarchar(100)='',
	@rOrgId int=0,
	@rBatchId int=0,
	@rDepartmentId int=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rSUId nvarchar(50)='',
	@rCode nvarchar(20)=''
	

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN
	
	SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
	SET @rMiddleName = sCommon.fSearchStringGet(@rMiddleName)
	SET @rLastName = sCommon.fSearchStringGet(@rLastName)
	
	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(SC.ParentEmail,'') AS ParentEmail,
	--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,
	--(CASE
	-- WHEN (SELECT ISNULL(R.Id,0) AS Id FROM sAlumni.tRegistration R WHERE R.MappedStudentId = A.Id) = 0 THEN 'Not Converted' ELSE 'Converted' END ) StatusName
	(CASE
        WHEN ISNULL((SELECT TOP 1 1 FROM sAlumni.tRegistration R WHERE R.MappedStudentId = A.Id), 0) = 0 THEN 'Not Converted'
        ELSE 'Converted'
    END )AS StatusName
	--ISNULL(STM.Title,'') AS StatusName

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
	--LEFT JOIN sAlumni.tRegistration R ON A.Id = R.MappedStudentId
WHERE 
	((A.ClassId=@rClassId)OR(@rClassId=0))
	AND((A.DivisionId=@rDivisionId)OR(@rDivisionId=0))
	--AND((SM.Code >= CONVERT(nvarchar(20),@rFromCode)) OR (ISNULL(@rFromCode,0) = 0)) 
	--AND((SM.Code <= CONVERT(nvarchar(20),@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=3)
	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,'') = '')) 
	AND ((SM.Code=@rCode) OR (@rCode=''))
	ORDER BY SM.Number
	--END

END
GO

PRINT N'Altering Procedure [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)
			,@lPreviousLeftDate DATE
			,@lPENNumber BIGINT --Mantis - 0031338
		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)
			,PreviousLeftDate DATE
			,PENNumber BIGINT --Mantis - 0031338
			)

		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
			,PreviousLeftDate
			,PENNumber
			)
		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
			,PreviousLeftDate
			,PENNumber --Mantis - 0031338
		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'
				,PreviousLeftDate DATE '@PreviousLeftDate'
				,PENNumber BIGINT '@PENNumber'--Mantis - 0031338
				)

		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 = ''
			SET @lPreviousLeftDate = ''
			SET @lPENNumber = NULL --Mantis - 0031338

			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
				,@lPreviousLeftDate = CASE 
					WHEN PreviousLeftDate = ''
						THEN NULL
					ELSE PreviousLeftDate
					END
				,@lPENNumber = PENNumber --Mantis - 0031338
			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
						,@lPENNumber --Mantis - 0031338
				ELSE
					EXEC sStudent.pStudentMasterAdd 0
						,@lCode
						,@lRegistrationNumber
						,@lNumber
						,@lFirstName
						,@lMiddleName
						,@lLastName
						,@rOrgId
						,@lAdmissionCategoryId
						,3
						,502
						,@rUserId
						,@rUserId
						,@rOrgGroupBatchId
						,@OutStudentId OUTPUT
						,@lSUId
						,@lPENNumber --Mantis - 0031338

				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
						,NULL
						,@lPreviousLeftDate
				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
						,NULL
						,@lPreviousLeftDate
			END
			ELSE
			BEGIN
				SET @1StudentId = (
						SELECT Id
						FROM sStudent.tStudentMaster
						WHERE Code COLLATE DATABASE_DEFAULT = @lCode COLLATE DATABASE_DEFAULT
							AND OrgId = @rOrgId
						)
	--Mantis Start- 0031338	
	DECLARE @lPENNumberActive nvarchar(50)=''
	SELECT @lPENNumberActive = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 544 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	
	--Mantis END- 0031338	

				UPDATE sStudent.tStudentMaster
				SET RegistrationNumber = @lRegistrationNumber
					,FirstName = @lFirstName
					,MiddleName = @lMiddleName
					,LastName = @lLastName
					,SUId = @lSUId
					,UpdatedUserId = @rUserId
					,UpdatedDateTime = getdate()
				WHERE Id = @1StudentId

--Mantis Start- 0031338		
		IF (@lPENNumberActive = 'True')
		Begin
			UPDATE sStudent.tStudentMaster
			SET 
			PENNumber =case when isnull(@lPENNumber,0) <> 0 then  @lPENNumber else PENNumber END--Mantis - 0031338
			WHERE Id = @1StudentId and OrgId = @rOrgId
		END
--Mantis End- 0031338	

				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
					,PreviousLeftDate = @lPreviousLeftDate
				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

				IF (@lDivisionId IS NOT NULL)
				BEGIN
					UPDATE sStudent.tAcademic
					SET DivisionId = @lDivisionId
						,RollNo = @lRollNo
						,UpdatedUserId = @rUserId
						,UpdatedDateTime = getdate()
					WHERE StudentId = @1StudentId
						AND BatchId = @rBatchId
						AND OrgId = @rOrgId
				END

				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'Update complete.';


GO




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

