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

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


GO
ALTER TABLE [sAssessment].[tTempAllExam]
    ADD [StreamTitle] NVARCHAR (50) NULL;


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


GO
ALTER TABLE [sStudent].[tOnlineRegistrationStudentMaster]
    ADD [StudentPhoto] VARBINARY (MAX) NULL;


GO
PRINT N'Creating [sTransport].[tAssignRouteLog]...';


GO
CREATE TABLE [sTransport].[tAssignRouteLog] (
    [AutoId]                 BIGINT   IDENTITY (1, 1) NOT NULL,
    [SourceTypeId]           SMALLINT NOT NULL,
    [SourceId]               BIGINT   NOT NULL,
    [NewPickupDestinationId] INT      NOT NULL,
    [NewDropDestinationId]   INT      NULL,
    [ChangeDate]             DATE     NOT NULL,
    [StatusId]               INT      NOT NULL,
    [OrgGroupBatchId]        INT      NULL,
    [CreatedUserId]          BIGINT   NOT NULL,
    [CreatedDateTime]        DATETIME NOT NULL
);


GO
PRINT N'Creating PK_tAssignRouteLog...';


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


GO

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


GO
 
ALTER PROCEDURE [sAdmission].[pAPIAdmissionInquiryAdd]

		 @rAdmissionInquiryId bigint
		,@rFirstName nvarchar(100)
		,@rMiddleName nvarchar(100)
		,@rLastName nvarchar(100)
		,@rForClassId int
		,@rForBatchId	int 
		,@rDateOfBirth date
		,@rOrgId smallint
		,@rInquiryStatusMasterId int
		,@rStreetOne nvarchar(50)
		,@rStreetTwo nvarchar(50)
		,@rStreetThree nvarchar(50)
		,@rCountry nvarchar(50)
		,@rState nvarchar(50)
		,@rCity	nvarchar(50)
		,@rZipCode nvarchar(20)
		,@rContactNo nvarchar(20)
		,@rContactEmail	nvarchar(50)
		,@rRemark nvarchar(200)
		,@rInquiryModeId tinyint
		,@rInquiryReferenceId int
		,@rAdmissionCategoryId int
		,@rPreviousSchool nvarchar(200)
		,@rMeritMarks decimal(10,2) 
		,@rMeritGrade nvarchar(20)
		,@rMeritMarksBreakup nvarchar(100)
		,@rGenderId tinyint
		,@rFollowupDate date
		,@rFollowupRemark nvarchar(150)
		,@rCreatedUserId bigint
		,@rInquiryDate date
		,@rNumber bigint 
		,@rHandledBy nvarchar(100) 
		,@rOrgGroupId int,
		@rCastCategoryId int=0,
		@rIsHostelRequired bit=0,
		@rIsTransportRequired bit=0,
		@rIsValidateInquiryAsPerAdmission bit=0,
		@rIsGivenAdmissionForm bit=0,
		@rAlternateContactNo nvarchar(100)='',
		@rAlternateContactEmail	nvarchar(200) = '',
		@rMotherName nvarchar(100)='',
		@rDataEntryModeId smallint = 561
	 
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	DECLARE @lOrgGroupBatchId int=0
	
	SELECT @lOrgGroupBatchId=OrgGroupBatchId FROM sSetup.tBatchMaster BM WHERE BM.Id = @rForBatchId
	
	DECLARE @lConfigValue nvarchar(50)=''
	SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 341 AND SourceTypeId = 2010 AND SourceId = @rOrgGroupId
	 
	
	IF(@lConfigValue='OrgGroupBatch')
	BEGIN
		SELECT @rNumber = (ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry AI
		INNER JOIN sSetup.tBatchMaster BM ON BM.Id = AI.ForbatchId 
		WHERE BM.OrgGroupBatchId = @lOrgGroupBatchId
	END
	ELSE IF(@lConfigValue='Batch')
	BEGIN
		SELECT @rNumber = (ISNULL(MAX(Number),0) + 1) FROM sAdmission.tAdmissionInquiry AI
		WHERE AI.ForBatchId = @rForBatchId
	END
	
	Declare @lStatusId smallint,@lIsValidateBirthdate bit,@lFromDateOfBirth date,@lToDateOfBirth date
	SET @lStatusId= 0
	
	if(@rIsValidateInquiryAsPerAdmission=1)
	Begin
		Select @lIsValidateBirthdate=IsValidateBirthdate,@lFromDateOfBirth=FromDateOfBirth,@lToDateOfBirth=ToDateOfBirth from  sAdmission.tAdmissionCriteria where ClassId=@rForClassId AND BatchID=@rForBatchId
		
		if(@lIsValidateBirthdate=1 AND @rDateOfBirth NOT between @lFromDateOfBirth And @lToDateOfBirth)
		BEGIN
			Select  -101 AS Result
			return
		End
	End
	 
 BEGIN TRANSACTION	
IF(@rAdmissionInquiryId = 0)	
	BEGIN	

 DECLARE @lNextNumber BIGINT 
 EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sAdmission.tAdmissionInquiry', 0, 1, 1,@outNextNumber = @lNextNumber output
	
	SET @rInquiryStatusMasterId = (SELECT ISM.Id FROM [sAdmission].[tInquiryStatusMaster] ISM INNER JOIN [sCommon].[tStatusMaster] SM ON SM.Id=ISM.StatusId WHERE SM.Id=205 AND SM.StatusTypeId=104 AND ISM.OrgGroupId=@rOrgGroupId) 
			
	INSERT INTO sAdmission.tAdmissionInquiry
		(
			 Id
			,FirstName
			,MiddleName
			,LastName
			,ForClassId			 
			,ForBatchId
			,DateOfBirth
			,OrgId
			,StatusId
			,StreetOne
			,StreetTwo
			,StreetThree
			,Country
			,State
			,City
			,ZipCode
			,ContactNo
			,ContactEmail
			,Remark
			,InquiryModeId
			,InquiryReferenceId
			,AdmissionCategoryId
			,PreviousSchool
			,MeritMarks
			,MeritGrade
			,MeritMarksBreakup
			,GenderId
			,FollowupDate
			,FollowupRemark
			,CreatedUserId
			,CreatedDateTime
			,InquiryDate
			,Number
			,HandledBy
			,OrgGroupId
			,InquiryStatusId,
			CastCategoryId,
			IsHostelRequired,
			IsTransportRequired,
			IsGivenAdmissionForm,
			AlternateContactNo,
			AlternateContactEmail,
			MotherName,
			DataEntryModeId
		)
	VALUES
		(
			 @lNextNumber
			,@rFirstName
			,@rMiddleName
			,@rLastName
			,@rForClassId
			,@rForBatchId			 
			,@rDateOfBirth
			,@rOrgId
			,@lStatusId
			,@rStreetOne
			,@rStreetTwo
			,@rStreetThree
			,@rCountry
			,@rState
			,@rCity
			,@rZipCode
			,@rContactNo
			,@rContactEmail
			,@rRemark
			,@rInquiryModeId
			,@rInquiryReferenceId
			,@rAdmissionCategoryId
			,@rPreviousSchool
			,@rMeritMarks
			,@rMeritGrade
			,@rMeritMarksBreakup
			,@rGenderId
			,@rFollowupDate
			,@rFollowupRemark
			,@rCreatedUserId
			,sCommon.fGetDate()
			,@rInquiryDate
			,@rNumber
			,@rHandledBy
			,@rOrgGroupId
			,@rInquiryStatusMasterId,
			@rCastCategoryId,
			@rIsHostelRequired,
			@rIsTransportRequired,
			@rIsGivenAdmissionForm,
			@rAlternateContactNo,
			@rAlternateContactEmail,
			@rMotherName,
			@rDataEntryModeId
		)
		    SELECT @lNextNumber AS Result         
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rAdmissionInquiryId
	    UPDATE  sAdmission.tAdmissionInquiry
	    SET
			 FirstName=@rFirstName
			,MiddleName=@rMiddleName
			,LastName=@rLastName
			,ForClassId=@rForClassId
			,ForBatchId = @rForBatchId		 
			,DateOfBirth=@rDateOfBirth
			,OrgId=@rOrgId
			,StatusId=@lStatusId
			,StreetOne=@rStreetOne
			,StreetTwo=@rStreetTwo
			,StreetThree=@rStreetThree
			,Country=@rCountry
			,State=@rState
			,City=@rCity
			,ZipCode=@rZipCode
			,ContactNo=@rContactNo
			,ContactEmail=@rContactEmail
			,Remark=@rRemark
			,InquiryModeId=@rInquiryModeId
			,InquiryReferenceId=@rInquiryReferenceId 
			,AdmissionCategoryId=@rAdmissionCategoryId
			,PreviousSchool=@rPreviousSchool
			,MeritMarks=@rMeritMarks
			,MeritGrade=@rMeritGrade
			,MeritMarksBreakup=@rMeritMarksBreakup
			,GenderId=@rGenderId
			,FollowupDate=@rFollowupDate
			,FollowupRemark=@rFollowupRemark
			,UpdatedUserId=@rCreatedUserId
			,UpdatedDateTime=sCommon.fGetDate()
			,InquiryDate=@rInquiryDate
			,HandledBy=@rHandledBy
			,InquiryStatusId = @rInquiryStatusMasterId,
			CastCategoryId = @rCastCategoryId,
			IsHostelRequired=@rIsHostelRequired,
			IsTransportRequired=@rIsTransportRequired,
			IsGivenAdmissionForm =@rIsGivenAdmissionForm,
			AlternateContactNo = @rAlternateContactNo,
			AlternateContactEmail = @rAlternateContactEmail,
			MotherName = @rMotherName,
			DataEntryModeId = @rDataEntryModeId
	      WHERE Id = @rAdmissionInquiryId 	   
	      SELECT 11 AS Result      
	      
	 END  
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sAdmission].[pAPIAdmissionInquiryGet]...';


GO
 
 
ALTER PROCEDURE [sAdmission].[pAPIAdmissionInquiryGet]
	

	 @rInquiryStatusId int,
	 @rBatchId int,
	 @rOrgId int,
	 @rOrgGroupId int,
	 @rFromDate DateTime = '',
	 @rToDate DateTime = '' 

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	Select
			AI.Id AS AdmissionInquiryId,
			AI.ForBatchId AS BatchId,
			AI.ForClassId AS ClassId,
			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 BatchName,
			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,
			U.DisplayTitle AS CreatedUser
			
			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
			INNER JOIN sSecurity.tUser U ON AI.CreatedUserId = U.Id
			Where 
			((AI.InquiryStatusId = @rInquiryStatusId) OR (@rInquiryStatusId = 0))
			AND AI.ForBatchId = @rBatchId
			AND AI.OrgId = @rOrgId
			AND AI.OrgGroupId = @rOrgGroupId
			AND ((AI.InquiryDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))
			AND ((AI.InquiryDate <=  @rToDate) OR (ISNULL(@rToDate,'') = ''))

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


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

	DECLARE @lConfigValue int = 0
	IF @rIsPresent=0
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 160 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	ELSE
		SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 161 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	SELECT 
			SC.AcademicId,
			SC.Code,
			SC.Name,
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			AC.AbsentCount,
			AC1.AveragePresence,
			REPLACE
			(REPLACE
			(REPLACE
			(@rTemplate,'[Name]',SC.Name),
			'[AbsentCount]',COUNT(SC.AcademicId)),
			'[AveragePresence]', AC1.AveragePresence)
			AS MsgText,
			@rMailSubject AS Subject,
			SC.WhatsAppContactNo
	FROM 
		sStudent.vStudentCommunication SC
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
	INNER JOIN
	(
		SELECT SC.AcademicId,COUNT(SC.AcademicId) AS AbsentCount
		FROM sStudent.vStudentCommunication SC
			INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
		WHERE 
		SC.OrgId=@rOrgId
		AND SC.BatchId=@rBatchId
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND SR.AttendanceTypeId=1 AND SR.IsPresent=0 AND SC.StatusId=1 AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
		GROUP BY SC.AcademicId
    ) AC ON AC.AcademicId = SC.AcademicId
    INNER JOIN 
    (
		SELECT SC.AcademicId, COUNT(SC.AcademicId) AS AbsentCount1, (CONVERT(DECIMAl(5,2),(CONVERT(DECIMAl(5,2),COUNT(SC.AcademicId))*100)/(CONVERT(DECIMAl(5,2),COUNT(SC.AcademicId)+AC.AbsentCount)))) AS AveragePresence FROM sStudent.vStudentCommunication SC
		INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
		INNER JOIN
		(
			SELECT SC.AcademicId,COUNT(SC.AcademicId) AS AbsentCount
			FROM sStudent.vStudentCommunication SC
				INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SC.AcademicId
			WHERE 
			SC.OrgId=@rOrgId
			AND SC.BatchId=@rBatchId
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND SR.AttendanceTypeId=1 AND SR.IsPresent=1 AND SC.StatusId=1 AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
			GROUP BY SC.AcademicId
		) AC ON AC.AcademicId = SC.AcademicId
	    
		WHERE
			SC.OrgId=@rOrgId
			AND SC.BatchId=@rBatchId
			AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			AND SR.AttendanceTypeId=1 AND SR.IsPresent=@rIsPresent AND SC.StatusId=1 AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
			GROUP BY 
			SC.AcademicId,
			AC.AbsentCount
    )AC1 ON  AC1.AcademicId = SC.AcademicId
	
	WHERE
		SC.OrgId=@rOrgId
		AND SC.BatchId=@rBatchId AND SC.IsBlockAttendanceAlert=0 AND SC.IsBlockAllAlert=0
		AND ((SR.AttendanceDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((SR.AttendanceDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		AND SR.AttendanceTypeId=1 AND SR.IsPresent=@rIsPresent AND SC.StatusId=1
		AND (((@rIsPresent = 0) AND @lConfigValue!=0 AND @lConfigValue <= AC.AbsentCount)
        OR ((@rIsPresent = 1) AND @lConfigValue!=0 AND @lConfigValue >= AC1.AveragePresence))
		GROUP BY 
		SC.AcademicId,
		SC.Code,
		SC.Name,
		SC.ParentContactNo,	
		SC.ParentEmail,
		AC.AbsentCount,
		AC1.AbsentCount1,
		SC.DivisionOrderIndex,
		SC.RollNo,
		AC1.AveragePresence,
		SC.WhatsAppContactNo
	ORDER BY SC.DivisionOrderIndex,SC.RollNo 
END
GO
PRINT N'Altering [sAlert].[pCircularSchedulerGet]...';


GO
 

ALTER PROCEDURE [sAlert].[pCircularSchedulerGet]
	 	 
	 	 @rOrgId smallint
	 	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
 
			A.MobileNumber AS MobileNo,	
			A.EmailId AS EmailId,
			CR.Title AS MsgText,
			CR.Title AS Subject,
			(SELECT OrgGroupId FROM sSetup.tOrganizationMaster where ID=A.OrgId) AS OrgGroupId,
			A.OrgId AS OrgId,
			A.Id AS SourceId,
			A.SourceTypeId AS SourceTypeId,
			A.Id AS ReceiverSourceId,
			A.SourceTypeId AS ReceiverSourceTypeId,
			A.Name,
			A.Code,
			A.WhatsAppContactNo
	From 
			sCommunication.tCircular CR
			INNER JOIN (
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.StudentId = CS.SourceId AND SC.IsActiveBatch = 1
			WHERE 
			    convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 
				AND SC.IsBlockAllAlert=0 AND CS.SourceTypeId = 2003  AND C.IsPublishInFuture = 1

			UNION ALL

			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.AcademicId = CS.SourceId AND SC.IsActiveBatch = 1
			WHERE 
			    convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 AND CS.SourceTypeId = 2001
				AND IsBlockAllAlert=0 AND C.IsPublishInFuture = 1

			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.EmployeeId = CS.SourceId 
			WHERE 
			    convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND vEC.StatusId = 7 AND CS.SourceTypeId = 95
				AND C.IsPublishInFuture = 1 AND vEC.IsOtherUser = 0

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.DepartmentId = CS.SourceId AND SC.IsActiveBatch = 1
				 
			WHERE 
				convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 
				AND  CS.SourceTypeId = 2017 AND CS.AssigneeToId = 2
				AND IsBlockAllAlert=0 AND C.IsPublishInFuture = 1

			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.DepartmentId = CS.SourceId 
			WHERE 
			    convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND vEC.StatusId = 7 
				AND CS.SourceTypeId = 2017 AND CS.AssigneeToId = 3 AND C.IsPublishInFuture = 1 AND vEC.IsOtherUser = 0

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.DepartmentId = CS.SourceId AND SC.IsActiveBatch = 1
				 
			WHERE 
				convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 
				AND  CS.SourceTypeId = 2017 AND CS.AssigneeToId = 2 AND IsBlockAllAlert=0 AND C.IsPublishInFuture = 1

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.ClassId = CS.SourceId AND SC.IsActiveBatch = 1
				 
			WHERE 
				convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 
				AND  CS.SourceTypeId = 2016 AND CS.AssigneeToId = 2 AND IsBlockAllAlert=0 AND C.IsPublishInFuture = 1

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.DivisionId = CS.SourceId AND SC.IsActiveBatch = 1
				 
			WHERE 
				convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 
				AND  CS.SourceTypeId = 2005 AND CS.AssigneeToId = 2 AND IsBlockAllAlert=0 AND C.IsPublishInFuture = 1

			UNION ALL	
																			 			  
			SELECT 
				C.Id as CircularId,
				SC.StudentId As Id,
				SC.Name As Name,
				SC.Code As Code,
				SC.ParentContactNo As MobileNumber,	
				SC.ParentEmail As EmailId,
				SC.OrgId As OrgId,
				2003 As SourceTypeId,
				SC.WhatsAppContactNo
			FROM 
				sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sStudent.vStudentCommunication SC ON SC.OrgId = CS.SourceId AND SC.IsActiveBatch = 1
				 
			WHERE 
				convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND SC.StatusId = 1 
				AND  CS.SourceTypeId = 2021 AND CS.AssigneeToId = 2 AND IsBlockAllAlert=0 AND C.IsPublishInFuture = 1

			UNION ALL

			SELECT 
				C.Id as CircularId,
				vEC.EmployeeId As Id,
				vEC.EmployeeName As Name,
				vEC.Code As Code,
				vEC.MobileNumber As MobileNumber,	
				vEC.CompanyEmail As EmailId,
				vEC.OrgId As OrgId,
				95 As SourceTypeId,
				vEC.WhatsAppContactNo
			FROM 
			    sCommunication.tCircularScope CS 
				INNER JOIN sCommunication.tCircular C ON CS.CircularId = C.Id 
				INNER JOIN sHrm.vEmployeeCommunication vEC ON vEC.OrgID = CS.SourceId 
			WHERE 
			    convert(varchar, C.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND vEC.StatusId = 7 
				AND CS.SourceTypeId = 2021 AND CS.AssigneeToId = 3 AND C.IsPublishInFuture = 1 AND vEC.IsOtherUser = 0
			
		) as A ON A.CircularId = CR.Id 
	WHERE
			convert(varchar, CR.PublishDateTime, 103) = convert(varchar, GetDate(), 103) AND A.OrgId = @rOrgId AND CR.IsPublishInFuture = 1
END
GO
PRINT N'Altering [sAlert].[pEmployeeBirthdayWishSchedulerGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pEmployeeBirthdayWishSchedulerGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
			EC.MobileNumber AS MobileNo,	
			--EC.PersonalEmail AS EmailId,			
			(CASE WHEN ISNULL(EC.PersonalEmail,'')='' THEN EC.CompanyEmail
			ELSE EC.PersonalEmail END) AS EmailId,
			replace(replace(@rTemplate,'[Name]',EC.EmployeeName),'[SchoolName]',OM.Title)
			AS MsgText,
			@rMailSubject AS Subject,
			OM.OrgGroupId AS OrgGroupId,
			OM.Id AS OrgId,
			EC.EmployeeId AS SourceId,
			95 AS SourceTypeId,
			EC.EmployeeId AS ReceiverSourceId,
			95 AS ReceiverSourceTypeId,
			EC.EmployeeName AS [Name],
			OM.Title AS SchoolName,
			EC.WhatsAppContactNo AS WhatsAppContactNo
		
	From 
		sHrm.vEmployeeCommunication EC
		INNER JOIN sSetup.tOrganizationMaster OM ON EC.OrgId = OM.Id
	WHERE
			(DAY(EC.DateOfBirth) = DAY(sCommon.fGetDate()))
		AND (MONTH(EC.DateOfBirth) = MONTH(sCommon.fGetDate()))
		AND (EC.StatusId=7)
		AND (EC.OrgId=@rOrgId)
END
GO
PRINT N'Altering [sAlert].[pStudentBirthdayWishSchedulerGet]...';


GO
 
ALTER PROCEDURE [sAlert].[pStudentBirthdayWishSchedulerGet]
	 	 
	 	 @rOrgId smallint,
	 	 @rTemplate nvarchar(max),
	 	 @rMailSubject nvarchar(100)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	Select 
 
			SC.ParentContactNo AS MobileNo,	
			SC.ParentEmail AS EmailId,
			replace(replace(@rTemplate,'[Name]',SC.Name),'[SchoolName]',OM.Title)
			 AS MsgText,
			@rMailSubject AS Subject,
			OM.OrgGroupId AS OrgGroupId,
			OM.Id AS OrgId,
			SC.StudentId AS SourceId,
			2003 AS SourceTypeId,
			SC.StudentId AS ReceiverSourceId,
			2003 AS ReceiverSourceTypeId,
			SC.Name AS [Name],
			OM.Title AS SchoolName,
			SC.WhatsAppContactNo AS WhatsAppContactNo
			
	From 
		sStudent.vStudentCommunication SC
		INNER JOIN sSetup.tOrganizationMaster OM ON SC.OrgId = OM.Id
	WHERE
			(DAY(SC.DateOfBirth) = DAY(sCommon.fGetDate()))
		AND (MONTH(SC.DateOfBirth) = MONTH(sCommon.fGetDate()))
		AND (SC.StatusId=1)
		AND (SC.OrgId=@rOrgId)
		AND SC.IsActiveBatch = 1 AND SC.IsBlockAllAlert=0
END
GO
PRINT N'Altering [sAssessment].[pExamListGet]...';


GO

ALTER PROC [sAssessment].[pExamListGet]
	
	@rAcademicId bigint=0,
	@rBatchId int=0

AS
BEGIN
	DECLARE @lTotalMarks decimal=0,@lTotalObtain decimal=0,@lResultStatus nvarchar(50)='' ,@lResultGrade nvarchar(10)='',@lRankNumber int=0,@lPercentage decimal=0,@lPercentile decimal=0
	DECLARE @lempgrid NVARCHAR(max)=''
	SELECT  @lempgrid = @lempgrid + '<tr>
	<td align="left" scope="col">' + ISNULL(Cm.DisplayTitle,'')+' - '+isnull(Dm.DisplayTitle,'')+' : '+isnull(E.Name,'') +' '+'<a  class="fa fa-plus-square"  
    onclick="GetExamDetailList(' + convert(varchar,isnull(E.Id,0)) + ','+ convert(varchar,@rAcademicId) +');"></a>'+ '</td>
	<td align="left" scope="col">' + isnull(BM.Title,'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.TotalMarks,0)) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.TotalObtain,'')) + '</td>
	<td align="left" scope="col">' + isnull(R.ResultStatus,'') + '</td>
	<td align="left" scope="col">' + isnull(R.ResultGrade,'') + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.RankNumber,0)) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.Percentage,0)) + '</td>
	<td align="left" scope="col">' +  convert(varchar,isnull(R.Percentile,0)) + '</td>
	  <td scope="col" align="center"><a  class="fa fa-plus-square"  
    onclick="SelectResult(this,' + convert(varchar,isnull(E.Id,0)) + ');"></a></td></tr>'	
 From
 sStudent.tAcademic AD 
 INNER JOIN  sAssessment.vExamMaster E ON E.BatchId = AD.BatchId AND E.ClassId = AD.ClassId
 INNER JOIN sSetup.tBatchMaster BM ON E.BatchId = BM.Id 
 INNER JOIN sSetup.tClassMaster CM ON CM.Id=AD.ClassId
 INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=AD.DivisionId
 INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = E.Id
 
 WHERE ((AD.Id=@rAcademicId) OR (@rAcademicId=0))
	--AND ((AD.BatchId =  @rBatchId) OR (@rBatchId=0))
	 AND IsProcessResult=1
	 ORDER BY DM.OrderIndex DESC
	select isnull(@lempgrid,'') as EmpGrid
END
GO
PRINT N'Altering [sAssessment].[pResultSheetStandardMultiExamGet]...';


GO
ALTER PROCEDURE [sAssessment].[pResultSheetStandardMultiExamGet]	 	 	
	 @rExamId int,	
	 @rAcademicId bigint=0,
	 @rIsUseInStudent360 bit =0		 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
begin
 
  --select * from sAssessment.tTempAllExam
-- --drop table sAssessment.tTempAllExam
 
  
DECLARE @GradeString nvarchar(1000)
DECLARE @GradeStringRemark nvarchar(500),
@GradeSetId int , @IsIncludeSubExam bit,@GradeStringHtml nvarchar(500)
SELECT @GradeSetId = GradesetId,
	   @IsIncludeSubExam = ISNULL(IsIncludeSubExam,0)  FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)

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

--#TempAllExam
	CREATE TABLE #TempAllExam
	(
	    SRNO INT IDENTITY(1,1) PRIMARY KEY, 
		AcademicIdText nvarchar(20),
		ExamIdText nvarchar(20),
		CoScholasticScopeIdText nvarchar(20),
		IsDisplayMonthlyAttendanceText nvarchar(20),
		ClassIdText nvarchar(50),
		AcademicId bigint,
		ExamName Nvarchar(150),
		StudCode NVarchar(20),
		StudentName Nvarchar(150),
		RollNo int,
		ResultStatus Nvarchar(20),	
		ClassName NVarchar(50),		
		Division NVarchar(50),
		TotalMark decimal(8,2),
		TotalObtain decimal(8,2),
		Percentage decimal(8,2),
		RankNumber int,
		ResultGrade NVarchar(50),
		
		MaximumMark1 decimal(8,2),		
		SubjectGrade1 NVarchar(50),
		Obtain1 decimal(8,2) Default 0,
		ExamMaximum1 decimal(8,2),
		IsPresent1 bit,
						
		MaximumMark2 decimal(8,2),	
		SubjectGrade2 NVarchar(50),
		Obtain2 decimal(8,2) Default 0,
		ExamMaximum2 decimal(8,2),
		IsPresent2 bit,
				
		MaximumMark3 decimal(8,2),
		SubjectGrade3 NVarchar(50),
		Obtain3 decimal(8,2) Default 0,
		ExamMaximum3 decimal(8,2),
		IsPresent3 bit,		
		
		MaximumMark4 decimal(8,2),	
		SubjectGrade4 NVarchar(50),
		Obtain4 decimal(8,2) Default 0,
		ExamMaximum4 decimal(8,2),
		IsPresent4 bit,	
				
		MaximumMark5 decimal(8,2),		
		SubjectGrade5 NVarchar(50),
		Obtain5 decimal(8,2) Default 0,
		ExamMaximum5 decimal(8,2),
		IsPresent5 bit,	
				
		MaximumMark6 decimal(8,2),		
		SubjectGrade6 NVarchar(50),
		Obtain6 decimal(8,2) Default 0,
		ExamMaximum6 decimal(8,2),
		IsPresent6 bit,	
		
		MaximumMark7 decimal(8,2),		
		SubjectGrade7 NVarchar(50),
		Obtain7 decimal(8,2) Default 0,
		ExamMaximum7 decimal(8,2),
		IsPresent7 bit,	
		
		MaximumMark8 decimal(8,2),	
		SubjectGrade8 NVarchar(50),
		Obtain8 decimal(8,2) Default 0,
		ExamMaximum8 decimal(8,2),
		IsPresent8 bit,	
		
		MaximumMark9 decimal(8,2),		
		SubjectGrade9 NVarchar(50),
		Obtain9 decimal(8,2) Default 0,
		ExamMaximum9 decimal(8,2),
		IsPresent9 bit,	
		
		
		MaximumMark10 decimal(8,2),		
		SubjectGrade10 NVarchar(50),
		Obtain10 decimal(8,2) Default 0,
		ExamMaximum10 decimal(8,2),
		IsPresent10 bit,	
		
		MaximumMark11 decimal(8,2),		
		SubjectGrade11 NVarchar(50),
		Obtain11 decimal(8,2) Default 0,
		ExamMaximum11 decimal(8,2),
		IsPresent11 bit,
		
		MaximumMark12 decimal(8,2),		
		SubjectGrade12 NVarchar(50),
		Obtain12 decimal(8,2) Default 0,
		ExamMaximum12 decimal(8,2),
		IsPresent12 bit,		
		 
		 
		SubjectGradeTerm1 NVarchar(50),
		SubjectGradeTerm2 NVarchar(50),
		SubjectGradeTerm3 NVarchar(50),
		IsMarksInDecimal bit,
		column_visible bit,
		--Obtain decimal(5,2),
		Percentile decimal(5,2),
		--ClassSubject nvarchar(100),
		ResultDetailId bigint,
		ResultId bigint,	
		Remark1 nvarchar(500),
		Remark2 nvarchar(500),
		Remark3 nvarchar(500),
		DisplayTitle nvarchar(150),		
		IsRankNo bit, 
		IsGrade bit,
		IsPercentile bit,
		IsPercentage bit,
		IsSubjectPercentile bit,
		IsProcessResult bit,
		IsNegativeMarks bit,
		
		
		
		IsResultStatus bit,
		
		ResultRemark nvarchar(200),
	
		HeightTerm1 decimal(5,2),
		WeightTerm1 decimal(5,2),
		HeightTerm2 decimal(5,2),
		WeightTerm2 decimal(5,2),
		HeightAnnual decimal(5,2),
		WeightAnnual decimal(5,2),
		PresentDaysTerm1 smallint,
		PresentDaysTerm2 smallint,
		PresentDaysAnnual smallint,
		TotalDaysTerm1 smallint,
		TotalDaysTerm2 smallint,
		TotalDaysAnnual smallint,
		TotalMarkTerm1 decimal(8,2),
		TotalObtainTerm1 decimal(8,2),
		PercentageTerm1 decimal(8,2),
		RankNumberTerm1 int,
		ResultGradeTerm1 NVarchar(50),
		PercentileTerm1 decimal(8,2),
		ResultStatusTerm1 Nvarchar(20),		   
		TotalMarkTerm2 decimal(8,2),
		TotalObtainTerm2 decimal(8,2),
		PercentageTerm2 decimal(8,2),
		RankNumberTerm2 int,
		ResultGradeTerm2 NVarchar(50),
		PercentileTerm2 decimal(8,2),
		ResultStatusTerm2 Nvarchar(20), 
		TotalMarkTerm3 		decimal(8,2),
		TotalObtainTerm3 decimal(8,2),
		PercentageTerm3 decimal(8,2),
		RankNumberTerm3 int,
		ResultGradeTerm3 NVarchar(50),
		PercentileTerm3 decimal(8,2),
		ResultStatusTerm3 Nvarchar(20), 
		
		
		ClassSubjectID int,
		SubjectId int,
		--Maximum decimal(5,2),
		SubjectOrderIndex smallint,
		SubjectGrade NVarchar(50),
		SubjectName NVarchar(150),
		SubjectCode Nvarchar(50),	
		SubjectMinimum decimal(8,2),		
		SubjectMaximum decimal(8,2),
		SubjectObtain  decimal(8,2),
		
		Exam1Name Nvarchar(150),		
		TotalMarks1 decimal(8,2),		
		TotalObtain1 decimal(8,2),
		Percentage1 decimal(8,2),
		RankNumber1 int,
		ResultGrade1 NVarchar(50),
		Percentile1 decimal(8,2),
		ResultStatus1 Nvarchar(20),
		
		Exam2Name nvarchar(150),	
		TotalMarks2 decimal(8,2),
		TotalObtain2 decimal(8,2),
		Percentage2 decimal(8,2),
		RankNumber2 int,
		ResultGrade2 NVarchar(50),
		Percentile2 decimal(8,2),
		ResultStatus2 Nvarchar(20),
		
		Exam3Name nvarchar(150),	
		TotalMarks3 decimal(8,2),
		TotalObtain3 decimal(8,2),
		Percentage3 decimal(8,2),
		RankNumber3 int,
		ResultGrade3 NVarchar(50),
		Percentile3 decimal(8,2),		
		ResultStatus3 Nvarchar(20),
		
		Exam4Name nvarchar(150),	
		TotalMarks4 decimal(8,2),
		TotalObtain4 decimal(8,2),
		Percentage4 decimal(8,2),
		RankNumber4 int,
		ResultGrade4 NVarchar(50),
		Percentile4 decimal(8,2),
		ResultStatus4 Nvarchar(20),
		
		Exam5Name nvarchar(150),		
		TotalMarks5 decimal(8,2),
		TotalObtain5 decimal(8,2),
		Percentage5 decimal(8,2),
		RankNumber5 int,
		ResultGrade5 NVarchar(50),
		Percentile5 decimal(8,2),
		ResultStatus5 Nvarchar(20),
		
		Exam6Name nvarchar(150),	
		TotalMarks6 decimal(8,2),
		TotalObtain6 decimal(8,2),
		Percentage6 decimal(8,2),
		RankNumber6 int,
		ResultGrade6 NVarchar(50),
		Percentile6 decimal(8,2),
		ResultStatus6 Nvarchar(20),
		
		Exam7Name nvarchar(150),		
		TotalMarks7 decimal(8,2),
		TotalObtain7 decimal(8,2),
		Percentage7 decimal(8,2),
		RankNumber7 int,
		ResultGrade7 NVarchar(50),
		Percentile7 decimal(8,2),
		ResultStatus7 Nvarchar(20),
		
		Exam8Name nvarchar(150),
		TotalMarks8 decimal(8,2),
		TotalObtain8 decimal(8,2),
		Percentage8 decimal(8,2),
		RankNumber8 int,
		ResultGrade8 NVarchar(50),
		Percentile8 decimal(8,2),
		ResultStatus8 Nvarchar(20),
		
		
		Exam9Name nvarchar(150),	
		TotalMarks9 decimal(8,2),
		TotalObtain9 decimal(8,2),
		Percentage9 decimal(8,2),
		RankNumber9 int,
		ResultGrade9 NVarchar(50),
		Percentile9 decimal(8,2),
		ResultStatus9 Nvarchar(20),
		
		Exam10Name nvarchar(150),	
		TotalMarks10 decimal(8,2),
		TotalObtain10 decimal(8,2),
		Percentage10 decimal(8,2),
		RankNumber10 int,
		ResultGrade10 NVarchar(50),
		Percentile10 decimal(8,2),
		ResultStatus10 Nvarchar(20),
		
		Exam11Name nvarchar(150),	
		TotalMarks11 decimal(8,2),
		TotalObtain11 decimal(8,2),
		Percentage11 decimal(8,2),
		RankNumber11 int,
		ResultGrade11 NVarchar(50),
		Percentile11 decimal(8,2),
		ResultStatus11 Nvarchar(20),
		
		Exam12Name nvarchar(150),	
		TotalMarks12 decimal(8,2),
		TotalObtain12 decimal(8,2),
		Percentage12 decimal(8,2),
		RankNumber12 int,
		ResultGrade12 NVarchar(50),
		Percentile12 decimal(8,2),
		ResultStatus12 Nvarchar(20),
		
		ResultRemark1 nvarchar(200),
		ResultRemark2 nvarchar(200),
		
		TotalDays smallint,
		PresentDays smallint,
		StudentHeight decimal(6,2),
		StudentWeight decimal(6,2),
		ExamSeatNo nvarchar(20),
		ExamId int,
		
		ExamCode nvarchar(20),
		Exam1Code nvarchar(20),
		Exam2Code nvarchar(20),
		Exam3Code nvarchar(20),
		Exam4Code nvarchar(20),
		Exam5Code nvarchar(20),
		Exam6Code Nvarchar(20),
		Exam7Code Nvarchar(20),
		Exam8Code nvarchar(20),
		Exam9Code nvarchar(20),
		Exam10Code nvarchar(20),
		Exam11Code nvarchar(20),
		Exam12Code nvarchar(20),
		
		
--		ResultDetailId int,
		ResultDetailId1 bigint,
		ResultDetailId2 bigint,
		ResultDetailId3 bigint,
		ResultDetailId4 bigint,
		ResultDetailId5 bigint,
		ResultDetailId6 bigint,
		ResultDetailId7 bigint,
		ResultDetailId8 bigint,
		ResultDetailId9 bigint,
		ResultDetailId10 bigint,
		ResultDetailId11 bigint,
		ResultDetailId12 bigint,
		
		
	
		Batch nvarchar(100),
		ExamNameTerm1 NVarchar(100),
		ExamNameTerm2 NVarchar(100) ,
		ExamNameTerm3 NVarchar(100),
		ClassTeacherName Nvarchar(100),
		FirstName nvarchar(50),
		LastName nvarchar(50),
		IsDisplayMonthlyAttendance bit,
		
		SubjectGroupId int,
		--SubjectGroupTitle nvarchar(50),
		--SubjectGroupCode nvarchar(50),
		DecimalFormat nvarchar(10),
		SubjectRemark nvarchar(1000),
		GraceMark decimal(5,2),
		KrupaMark decimal(5,2),
		GradeStringHtml nvarchar(500),
		ResultRemark3 nvarchar(200),
		IsDisplayTotalMark bit,
		SubjectObtainTerm1 decimal(8,2),	
		SubjectObtainTerm2 decimal(8,2),
		SubjectObtainTerm3  decimal(8,2),
		SubjectMaxTerm1 decimal(8,2),
		SubjectMaxTerm2 decimal(8,2),
		SubjectMaxTerm3 decimal(8,2),
		
		TotalDays1 smallint,
		PresentDays1 smallint,
		TotalDays2 smallint,
		PresentDays2 Smallint,
		TotalDays3 smallint,
		PresentDays3 smallint,
		TotalDays4 smallint,
		PresentDays4 smallint,
		TotalDays5 smallint,
		PresentDays5 smallint,
		TotalDays6 smallint,
		PresentDays6 smallint,
		TotalDays7 smallint,
		PresentDays7 smallint, 
		TotalDays8 smallint,
		PresentDays8 smallint,
		TotalDays9 smallint,
		PresentDays9 smallint,
		TotalDays10 smallint,
		PresentDays10 smallint,
		TotalDays11 smallint,
		PresentDays11 smallint,
		TotalDays12 smallint,
		PresentDays12 smallint,
		BatchIdText nvarchar(20),
		--IsShowWithDetail bit,
		IsPresent bit,
		GradeTitle nvarchar(50),
		
		
		AchievementsTerm1 nvarchar(200),
		AchievementsTerm2 nvarchar(200),
		GeneralRemarkTerm1 nvarchar(200),
		GeneralRemarkTerm2 nvarchar(200),
		ResultRemark1Term1 nvarchar(200),
		ResultRemark2Term1 nvarchar(200),
		ResultRemark1Term2 nvarchar(200),
		ResultRemark2Term2 nvarchar(200),
		SR_HeightTerm1 decimal(5,2),
		SR_WeightTerm1 decimal(5,2),
		SR_HeightTerm2 decimal(5,2),
		SR_WeightTerm2 decimal(5,2),
		SR_PresentDaysTerm1 smallint,
		SR_PresentDaysTerm2 smallint,
		SR_TotalDaysTerm1 smallint,
		SR_TotalDaysTerm2 smallint
	)	
	 --print 'temp created'    	
	INSERT INTO  #TempAllExam 
	(
	AcademicIdText,
	ExamIdText,
	CoScholasticScopeIdText,
	IsDisplayMonthlyAttendanceText,
	--ClassIdText,
	AcademicId,
	ExamName,
	StudCode,
	StudentName,
	RollNo,
	ResultStatus,
	ClassName,
	Division,
	TotalMark,
	TotalObtain,
	Percentage,
	RankNumber,
	ResultGrade,
	IsMarksInDecimal,
	column_visible,
	--Obtain,
	Percentile,
	--ClassSubject,
	ResultDetailId,
	ResultId,

	Remark1,
	Remark2,
    Remark3,
	DisplayTitle,
	IsRankNo, 
	IsGrade,
	IsPercentile,
	IsPercentage,
	IsSubjectPercentile,
	IsProcessResult,
	IsNegativeMarks,
	
	IsResultStatus,
	
	ResultRemark,
	
	HeightTerm1,
	WeightTerm1,
	HeightTerm2,
	WeightTerm2,
	HeightAnnual,
	WeightAnnual,
	PresentDaysTerm1,
	PresentDaysTerm2,
	PresentDaysAnnual,
	TotalDaysTerm1,
	TotalDaysTerm2,
	TotalDaysAnnual,
	
	
	ClassSubjectID,
	SubjectId,
	--Maximum,
	SubjectOrderIndex,
	SubjectGrade,
	SubjectName,
	SubjectCode,
	SubjectMinimum,
	SubjectMaximum,
	SubjectObtain,
	ResultRemark1,
	ResultRemark2,
	
	TotalDays,
	PresentDays,
	StudentHeight,
	StudentWeight,
	ExamSeatNo,
	ExamId,
	
	ExamCode,
	
	
	Batch,
	ClassTeacherName,
	FirstName,
	LastName,
	IsDisplayMonthlyAttendance,
	
	SubjectGroupId,
	--SubjectGroupTitle,
	--SubjectGroupCode,
	DecimalFormat,
	SubjectRemark,
	GraceMark,
	KrupaMark,
	GradeStringHtml,
	ResultRemark3,
	IsDisplayTotalMark,
	
    IsPresent,
    GradeTitle,
	
	AchievementsTerm1,
	AchievementsTerm2,
	GeneralRemarkTerm1,
	GeneralRemarkTerm2,
	ResultRemark1Term1,
	ResultRemark2Term1,
	ResultRemark1Term2,
	ResultRemark2Term2,
	SR_HeightTerm1,
	SR_WeightTerm1,
	SR_HeightTerm2,
	SR_WeightTerm2,
	SR_PresentDaysTerm1,
	SR_PresentDaysTerm2,
	SR_TotalDaysTerm1,
	SR_TotalDaysTerm2	
	)
	SELECT 
		Convert(nvarchar(20),A.Id),
		Convert(nvarchar(20),@rExamId),
		Convert(nvarchar(20),EM.CoScholasticScopeId),
		Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)),
		--Convert(nvarchar(50),@rClassId),
		A.Id,
		ISNULL(ESGM.Title,'') AS EXAMNAME,
		StuM.Code AS StudCode,
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
		A.RollNo,
		ISNULL(R.ResultStatus,'') AS ResultStatus,
		CM.DisplayTitle AS ClassName,
		DM.DisplayTitle AS Division,
		R.TotalMarks AS TotalMark,
		R.TotalObtain,
		ISNULL(R.Percentage,0) As Percentage,
		R.RankNumber,
		ISNULL(R.ResultGrade,'') AS ResultGrade,
		EM.IsMarksInDecimal,			
		1,
		--RD.Obtain,
		R.Percentile,
		--SM.Title AS ClassSubject,
		RD.Id AS ResultDetailId,
		R.Id AS ResultId,

		ISNULL(EM.Remark1,'') AS Remark1,
		ISNULL(EM.Remark2,'') AS Remark2,
		ISNULL(EM.Remark3,'') AS Remark3,
		EM.DisplayTitle,
		EM.IsRankNo, 
		EM.IsGrade,
		EM.IsPercentile,
		EM.IsPercentage,
		EM.IsSubjectPercentile,
		EM.IsProcessResult,
		EM.IsNegativeMarks,		
		EM.IsResultStatus,		
		ISNULL(R.ResultRemark,'') AS ResultRemark,		
		AD.HeightTerm1,
		AD.WeightTerm1,
		AD.HeightTerm2,
		AD.WeightTerm2,
		AD.HeightAnnual,
		AD.WeightAnnual,
		AD.PresentDaysTerm1,
		AD.PresentDaysTerm2,
		AD.PresentDaysAnnual,
		AD.TotalDaysTerm1,
		AD.TotalDaysTerm2,
		AD.TotalDaysAnnual,
	
	    ED.ClassSubjectId,
		CS.SubjectId AS SubjectId,
		--ED.Maximum,
		(CASE ISNULL(ED.DisplayOrder,0)
		WHEN 0 THEN CS.OrderIndex
		ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
		
		--SM.OrderIndex AS SubjectOrderIndex,
		RD.SubjectGrade,
		SM.Title AS SubjectName,
		ISNULL(SM.Code,'') AS SubjectCode,
		ED.Minimum,
		ED.Maximum,
		RD.Obtain,
		SR.ResultRemark1,
		SR.ResultRemark2,
		SR.TotalDays,
		SR.PresentDays,
		SR.StudentHeight,
		SR.StudentWeight,
		SR.ExamSeatNo,
		@rExamId,
		ISNULL(ESGM.Code,'') AS ExamCode,
		
		
		BM.Title AS Batch,
		EMP.FirstName + ' ' + EMP.LastName AS ClassTeacherName,
		Stum.FirstName,
		Stum.LastName,
		 
		ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
		
		ISNULL(SM.SubjectGroupId,0) AS SubjectGroupId,
		--ISNULL(SG.Title,'')AS SubjectGroupTitle,
		--ISNULL(SG.Code,'') AS SubjectGroupCode,
		ISNULL(EM.DecimalFormat,0) AS DecimalFormat,
		ISNULL(RD.Remark,'') AS SubjectRemark,
		RD.GraceMark,
		RD.KrupaMark,
		@GradeStringHtml,
		SR.ResultRemark3,
		EM.IsDisplayTotalMark,
		
		IsPresent,
		GradeTitle ,
		
		
		'' AS AchievementsTerm1,
		'' AS AchievementsTerm2,
		'' AS GeneralRemarkTerm1,
		'' AS GeneralRemarkTerm2,
		'' AS ResultRemark1Term1,
		'' AS ResultRemark2Term1, 
		'' AS ResultRemark1Term2,
		'' AS ResultRemark2Term2,
		SR.StudentHeight AS SR_HeightTerm1,
		SR.StudentWeight AS SR_WeightTerm1,
		SR.StudentHeight AS SR_HeightTerm2,
		SR.StudentWeight AS SR_WeightTerm2,
		SR.PresentDays AS SR_PresentDaysTerm1,
	    SR.PresentDays AS SR_PresentDaysTerm2,
	    SR.TotalDays AS SR_TotalDaysTerm1,
	    SR.TotalDays AS SR_TotalDaysTerm2	
FROM 
	sAssessment.tResultDetail RD
	INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
	INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
	INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
	INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId	
	LEFT JOIN sSetup.tSubjectGroupMaster SG ON SG.Id = Sm.SubjectGroupId				 
	INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
	INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
	--LEFT JOIN sSetup.tOrgImages OI ON OI.Orgid = OM.Id
	INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId
	INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
	INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
	INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId	
	LEFT JOIN sHrm.tEmployeeMaster EMP ON EMP.Id = DM.InchargeEmployeeId
	INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
	
	LEFT JOIN sStudent.tAcademicDetail AD ON AD.AcademicId=A.Id	
	LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND R.ExamId = SR.ExamId	
	LEFT JOIN sAssessment.tOptionalSubject OS ON OS.AcademicId = R.AcademicId AND OS.ClassSubjectId = ED.ClassSubjectId  AND ED.ExamId = R.ExamId	
	LEFT JOIN sAssessment.tGradeSetDetail GS ON GS.GradeSetId=ED.GradeSetId AND ED.GradeSetId = @GradeSetId and RD.SubjectGrade = GS.GradeCode
	--LEFT JOIN sAssessment.tResultAnalysisDivisionDetail RAD ON RAD.ClassSubjectId = CS.Id AND RAD.DivisionId = A.DivisionId AND RAD.ExamId = Em.Id
		
	 WHERE
		R.ExamId = @rExamId 		
		AND((A.Id=@rAcademicId)OR (@rAcademicId=0))	
		 AND ISNULL(EMP.IsOtherUser,0) = 0		    
	Order By ED.DisplayOrder
 
 --print 'temp insert'
  --SET @IsIncludeSubExam = 1
	create TABLE #tempcombineExam
	(	Id int IDENTITY,
		ExamID int )

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

	IF (@IsIncludeSubExam = 1)
	BEGIN	
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 1
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		
		
			set @query ='update T set					 
					SubjectGradeTerm1=RD.SubjectGrade,
					SubjectObtainTerm1 = RD.Obtain,
					 SubjectMaxTerm1 = ED.Maximum
							 
					 From
						 sAssessment.tResultDetail RD
						INNER JOIN  sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		
				execute(@query)
				
		set @query ='update T set					 
					 
					TotalMarkTerm1 = R.TotalMarks,
					TotalObtainTerm1=R.TotalObtain,
					PercentageTerm1=R.Percentage,
					RankNumberTerm1=R.RankNumber,
					ResultGradeTerm1=R.ResultGrade,
					PercentileTerm1 = R.Percentile,
					ResultStatusTerm1 = R.ResultStatus,
					ExamNameTerm1 = ESGM.Code,
					AchievementsTerm1 = SR.Achievements,
					GeneralRemarkTerm1 = SR.GeneralRemark,
					ResultRemark1Term1 = SR.ResultRemark1,
					ResultRemark2Term1 = SR.ResultRemark2,
					SR_HeightTerm1 = SR.StudentHeight,
					SR_WeightTerm1 = SR.StudentWeight,
					SR_PresentDaysTerm1 = SR.PresentDays,
					SR_TotalDaysTerm1 = SR.TotalDays
					
					From
					 
						sAssessment.tResult  R 				
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
						
		 	
						
		execute(@query)
		
					select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 2
		--select @ExamTitle = Title from sAssessment.tExamMaster Where Id = @lSubExamId	
		set @query ='update T set					 
					SubjectGradeTerm2=RD.SubjectGrade,
					SubjectObtainTerm2 = RD.Obtain,
					SubjectMaxTerm2= ED.Maximum,
					AchievementsTerm2 = SR.Achievements,
					GeneralRemarkTerm2 = SR.GeneralRemark,
					ResultRemark1Term2 = SR.ResultRemark1,
					ResultRemark2Term2 = SR.ResultRemark2,
					SR_HeightTerm2 = SR.StudentHeight,
					SR_WeightTerm2 = SR.StudentWeight,
					SR_PresentDaysTerm2 = SR.PresentDays,
					SR_TotalDaysTerm2 = SR.TotalDays
									 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = R.AcademicId AND SR.ExamId = EM.Id
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		
				set @query ='update T set
 
					TotalMarkTerm2 = R.TotalMarks,
					TotalObtainTerm2=R.TotalObtain,
					PercentageTerm2=R.Percentage,
					RankNumberTerm2=R.RankNumber,
					ResultGradeTerm2=R.ResultGrade,
					PercentileTerm2 = R.Percentile,
					ResultStatusTerm2 = R.ResultStatus,
					ExamNameTerm2 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		
		select @lSubExamId = SubExamId from sAssessment.tExamCombine  Where ExamId  = @rExamId AND ExamOrder = 3
		set @query ='update T set					 
					SubjectGradeTerm3=RD.SubjectGrade,
					SubjectObtainTerm3 = RD.Obtain,
					SubjectMaxTerm3= ED.Maximum				 
					 From
						sAssessment.tResultDetail RD
						INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
						INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON T.ClassSubjectID = ED.ClassSubjectId And T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
		set @query ='update T set
 
					TotalMarkTerm3 = R.TotalMarks,
					TotalObtainTerm3=R.TotalObtain,
					PercentageTerm3=R.Percentage,
					RankNumberTerm3=R.RankNumber,
					ResultGradeTerm3=R.ResultGrade,
					PercentileTerm3 = R.Percentile,
					ResultStatusTerm3 = R.ResultStatus,
					ExamNameTerm3 = ESGM.Code			
					 From						 
					   sAssessment.tResult R  				 
						INNER JOIN sAssessment.tExamMaster EM ON EM.Id=R.ExamId
						INNER JOIN sAssessment.tExamSubgroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId					
						INNER JOIN 	#TempAllExam  T ON  T.AcademicId = R.AcademicId						
						WHERE R.AcademicId='+convert(nvarchar(20), @rAcademicId)+' AND EM.Id =' + convert(nvarchar(15), @lSubExamId)  
		execute(@query)
	END		
	
	SELECT T.*
	FROM #TempAllExam T  where 
	T.ExamId=@rExamId AND 
	AcademicId= @rAcademicId
	
	
	--Declare @Count AS Integer
    --SET @Count=(SELECT  count(ClassSubjectID) FROM #TempAllExam T)
    DECLARE @lCounter INT
    SET @lCounter = 1
    DECLARE @lMAXID INT=0
    
    SELECT @lMAXID = COUNT(*) FROM #TempAllExam
    Declare @FinalHtml nvarchar(max)=''
	Declare @tdHtml nvarchar(max)
	Declare @trHtml nvarchar(max)
	Declare @HeaderHtml nvarchar(max)
	Declare @HeaderCounter int=0
	Declare @thHtml nvarchar(max)
	
	WHILE (@lCounter <= @lMAXID)
	BEGIN 
	     Declare @ClassSubject nvarchar(max)
	     Declare @ResultDetailId1 nvarchar(max)
	     Declare @ResultDetailId2 nvarchar(max)
	     Declare @ResultDetailId3 nvarchar(max)
	     Declare @ResultDetailId4 nvarchar(max)
	     Declare @ResultDetailId5 nvarchar(max)
	     Declare @ResultDetailId6 nvarchar(max)
	     Declare @ResultDetailId7 nvarchar(max)
	     Declare @ResultDetailId8 nvarchar(max)
	     Declare @ResultDetailId9 nvarchar(max)
	     Declare @ResultDetailId10 nvarchar(max)
	     Declare @ResultDetailId11 nvarchar(max)
	     Declare @ResultDetailId12 nvarchar(max)
	     
	     Declare @Obtain1 decimal(10,2)
	     Declare @Obtain2 decimal(10,2)
	     Declare @Obtain3 decimal(10,2)
	     Declare @Obtain4 decimal(10,2)
	     Declare @Obtain5 decimal(10,2)
	     Declare @Obtain6 decimal(10,2)
	     Declare @Obtain7 decimal(10,2)
	     Declare @Obtain8 decimal(10,2)
	     Declare @Obtain9 decimal(10,2)
	     Declare @Obtain10 decimal(10,2)
	     Declare @Obtain11 decimal(10,2)
	     Declare @Obtain12 decimal(10,2)
	     
	     
	     Declare @ExamMaximumMarks1 decimal(10,2)
	     Declare @ExamMaximumMarks2 decimal(10,2)
	     Declare @ExamMaximumMarks3 decimal(10,2)
	     Declare @ExamMaximumMarks4 decimal(10,2)
	     Declare @ExamMaximumMarks5 decimal(10,2)
	     Declare @ExamMaximumMarks6 decimal(10,2)
	     Declare @ExamMaximumMarks7 decimal(10,2)
	     Declare @ExamMaximumMarks8 decimal(10,2)
	     Declare @ExamMaximumMarks9 decimal(10,2)
	     Declare @ExamMaximumMarks10 decimal(10,2)
	     Declare @ExamMaximumMarks11 decimal(10,2)
	     Declare @ExamMaximumMarks12 decimal(10,2)
	     
	     
	     Declare @Exam1Name nvarchar(max)
	     Declare @Exam2Name nvarchar(max)
	     Declare @Exam3Name nvarchar(max)
	     Declare @Exam4Name nvarchar(max)
	     Declare @Exam5Name nvarchar(max)
	     Declare @Exam6Name nvarchar(max)
	     Declare @Exam7Name nvarchar(max)
	     Declare @Exam8Name nvarchar(max)
	     Declare @Exam9Name nvarchar(max)
	     Declare @Exam10Name nvarchar(max)
	     Declare @Exam11Name nvarchar(max)
	     Declare @Exam12Name nvarchar(max)
	     Declare @IsMarksInDecimal bit
	     
	     
	     SET @ClassSubject=(SELECT SubjectName from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId1=(SELECT ResultDetailId1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId2=(SELECT ResultDetailId2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId3=(SELECT ResultDetailId3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId4=(SELECT ResultDetailId4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId5=(SELECT ResultDetailId5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId6=(SELECT ResultDetailId6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId7=(SELECT ResultDetailId7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId8=(SELECT ResultDetailId8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId9=(SELECT ResultDetailId9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId10=(SELECT ResultDetailId10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId11=(SELECT ResultDetailId11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ResultDetailId12=(SELECT ResultDetailId12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     SET @Obtain1=(SELECT Obtain1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain2=(SELECT Obtain2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain3=(SELECT Obtain3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain4=(SELECT Obtain4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain5=(SELECT Obtain5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain6=(SELECT Obtain6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain7=(SELECT Obtain7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain8=(SELECT Obtain8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain9=(SELECT Obtain9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain10=(SELECT Obtain10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain11=(SELECT Obtain11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Obtain12=(SELECT Obtain12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     
	     
	     SET @Exam1Name=(SELECT Exam1Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam2Name=(SELECT Exam2Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam3Name=(SELECT Exam3Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam4Name=(SELECT Exam4Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam5Name=(SELECT Exam5Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam6Name=(SELECT Exam6Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam7Name=(SELECT Exam7Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam8Name=(SELECT Exam8Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam9Name=(SELECT Exam9Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam10Name=(SELECT Exam10Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam11Name=(SELECT Exam11Name from #TempAllExam WHERE SRNO=@lCounter)
	     SET @Exam12Name=(SELECT Exam12Name from #TempAllExam WHERE SRNO=@lCounter)
	     
	     SET @ExamMaximumMarks1=(SELECT MaximumMark1 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks2=(SELECT MaximumMark2 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks3=(SELECT MaximumMark3 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks4=(SELECT MaximumMark4 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks5=(SELECT MaximumMark5 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks6=(SELECT MaximumMark6 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks7=(SELECT MaximumMark7 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks8=(SELECT MaximumMark8 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks9=(SELECT MaximumMark9 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks10=(SELECT MaximumMark10 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks11=(SELECT MaximumMark11 from #TempAllExam WHERE SRNO=@lCounter)
	     SET @ExamMaximumMarks12=(SELECT MaximumMark12 from #TempAllExam WHERE SRNO=@lCounter)
	     
	     
	     SET @IsMarksInDecimal=(SELECT IsMarksInDecimal from #TempAllExam WHERE SRNO=@lCounter)
	     --print @IsMarksInDecimal
	  IF(@rIsUseInStudent360 = 0)
	  BEGIN
	     IF(@HeaderCounter=0)
	     BEGIN
	      SET @thHtml='<th>Subjects</th>'
	      if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL)	    
	      SET @thHtml=@thHtml+'<th>'+@Exam1Name+'</th>';   
	      if(@Exam2Name<>'' OR @Exam2Name IS NOT NULL)	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam2Name+'</th>';  
	       if(@Exam3Name<>'' OR @Exam3Name IS NOT NULL)	    	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam3Name+'</th>';   
	       if(@Exam4Name<>'' OR @Exam4Name IS NOT NULL)	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam4Name+'</th>';  
	      if(@Exam5Name<>'' OR @Exam5Name IS NOT NULL)	  	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam5Name+'</th>';  
	       if(@Exam6Name<>'' OR @Exam6Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam6Name+'</th>';  
	        if(@Exam7Name<>'' OR @Exam7Name IS NOT NULL)	  	  	    	    
	      SET @thHtml=@thHtml+'<th>'+@Exam7Name+'</th>';  
	        if(@Exam8Name<>'' OR @Exam8Name IS NOT NULL)	  	  	    		    
	      SET @thHtml=@thHtml+'<th>'+@Exam8Name+'</th>';  
	       if(@Exam9Name<>'' OR @Exam9Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam9Name+'</th>';  
	          if(@Exam10Name<>'' OR @Exam10Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th>'+@Exam10Name+'</th>'; 
	       if(@Exam11Name<>'' OR @Exam11Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th>'+@Exam11Name+'</th>';  
	      if(@Exam12Name<>'' OR @Exam12Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th>'+@Exam12Name+'</th>';  
	     END   
	     SET @HeaderCounter=@HeaderCounter+1;
	    
	     
	     SET @tdHtml='<td class=Sub width=200>'+@ClassSubject+'</td>';
	     
	     Declare @SetDecimalFunction nvarchar(max)
	    --print @IsMarksInDecimal
	     IF(@IsMarksInDecimal=1)
			 BEGIN
			  SET @SetDecimalFunction='onblur="javascript:return fnValidateDecimal(this,10,2)" onKeypress="javascript:return MaskDecimal(event,10,2)"';
		
			  
		 if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain1)+'</div><input  class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks1)+' value='+CONVERT(varchar(20),@Obtain1)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain2)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks2)+' value='+CONVERT(varchar(20),@Obtain2)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain3)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks3)+' value='+CONVERT(varchar(20),@Obtain3)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain4)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks4)+' value='+CONVERT(varchar(20),@Obtain4)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain5)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks5)+' value='+CONVERT(varchar(20),@Obtain5)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain6)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks6)+' value='+CONVERT(varchar(20),@Obtain6)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain7)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks7)+' value='+CONVERT(varchar(20),@Obtain7)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain8)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks8)+' value='+CONVERT(varchar(20),@Obtain8)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain9)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks9)+' value='+CONVERT(varchar(20),@Obtain9)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain10)+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks10)+' value='+CONVERT(varchar(20),@Obtain10)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	     SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain11)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks11)+' value='+CONVERT(varchar(20),@Obtain11)+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),@Obtain12)+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks12)+' value='+CONVERT(varchar(20),@Obtain12)+' '+@SetDecimalFunction+' MaxLength="100"/></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
			  
			  
			  
			 END
	     ELSE
			 BEGIN
			   
			  SET @SetDecimalFunction='onblur="javascript:return fnValidateDecimal(this,10,0)" onKeypress="javascript:return MaskDecimal(event,10,0)"';
			  
			  
		if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain1 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks1)+' value='+CONVERT(varchar(20),CAST(@Obtain1 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain2 AS int))+'</div><input class=numbersOnly type=text   ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks2)+' value='+CONVERT(varchar(20),CAST(@Obtain2 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain3 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks3)+' value='+CONVERT(varchar(20),CAST(@Obtain3 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain4 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks4)+' value='+CONVERT(varchar(20),CAST(@Obtain4 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain5 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks5)+' value='+CONVERT(varchar(20),CAST(@Obtain5 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain6 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks6)+' value='+CONVERT(varchar(20),CAST(@Obtain6 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain7 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks7)+' value='+CONVERT(varchar(20),CAST(@Obtain7 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain8 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks8)+' value='+CONVERT(varchar(20),CAST(@Obtain8 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0  ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain9 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks9)+' value='+CONVERT(varchar(20),CAST(@Obtain9 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain10 AS int))+'</div><input class=numbersOnly type=text  ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks10)+' value='+CONVERT(varchar(20),CAST(@Obtain10 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	     SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain11 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks11)+' value='+CONVERT(varchar(20),CAST(@Obtain11 AS int))+' '+@SetDecimalFunction+' MaxLength="100"></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark><div class=MaxMarks>Max Marks:'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div><div class=ObtainMarks>Obtain Marks:'+CONVERT(varchar(20),CAST(@Obtain12 AS int))+'</div><input class=numbersOnly type=text ExamMaxMarks='+CONVERT(varchar(20),@ExamMaximumMarks12)+' value='+CONVERT(varchar(20),CAST(@Obtain12 AS int))+' '+@SetDecimalFunction+' MaxLength="100"/></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td>';
			  
			  
			 END
	     
	    SET @trHtml= '<tr>'+@tdHtml+'</tr>';
	    SET @FinalHtml=@FinalHtml+@trHtml;
       END
	   ELSE
	   BEGIN
	    IF(@HeaderCounter=0)
	     BEGIN
	      SET @thHtml='<th>Subjects</th>'
	      if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL)	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam1Name+'</th>';   
	      if(@Exam2Name<>'' OR @Exam2Name IS NOT NULL)	    	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam2Name+'</th>';  
	       if(@Exam3Name<>'' OR @Exam3Name IS NOT NULL)	    	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam3Name+'</th>';   
	       if(@Exam4Name<>'' OR @Exam4Name IS NOT NULL)	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam4Name+'</th>';  
	      if(@Exam5Name<>'' OR @Exam5Name IS NOT NULL)	  	    	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam5Name+'</th>';  
	       if(@Exam6Name<>'' OR @Exam6Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam6Name+'</th>';  
	        if(@Exam7Name<>'' OR @Exam7Name IS NOT NULL)	  	  	    	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam7Name+'</th>';  
	        if(@Exam8Name<>'' OR @Exam8Name IS NOT NULL)	  	  	    		    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam8Name+'</th>';  
	       if(@Exam9Name<>'' OR @Exam9Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam9Name+'</th>';  
	          if(@Exam10Name<>'' OR @Exam10Name IS NOT NULL)	  	  	    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam10Name+'</th>'; 
	       if(@Exam11Name<>'' OR @Exam11Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam11Name+'</th>';  
	      if(@Exam12Name<>'' OR @Exam12Name IS NOT NULL)	  		    
	      SET @thHtml=@thHtml+'<th colspan="2">'+@Exam12Name+'</th>';  

		  if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL OR @Exam2Name<>'' OR @Exam2Name IS NOT NULL OR @Exam3Name<>'' OR @Exam3Name IS NOT NULL OR
		     @Exam4Name<>'' OR @Exam4Name IS NOT NULL OR @Exam5Name<>'' OR @Exam5Name IS NOT NULL OR @Exam6Name<>'' OR @Exam6Name IS NOT NULL OR
			 @Exam7Name<>'' OR @Exam7Name IS NOT NULL OR @Exam8Name<>'' OR @Exam8Name IS NOT NULL OR @Exam9Name<>'' OR @Exam9Name IS NOT NULL OR
			 @Exam10Name<>'' OR @Exam10Name IS NOT NULL OR @Exam11Name<>'' OR @Exam11Name IS NOT NULL OR @Exam12Name<>'' OR @Exam12Name IS NOT NULL)
			 BEGIN
			 SET @thHtml=@thHtml+'<tr><td></td>';
				  if(@Exam1Name<>'' OR @Exam1Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam2Name<>'' OR @Exam2Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam3Name<>'' OR @Exam3Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam4Name<>'' OR @Exam4Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam5Name<>'' OR @Exam5Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam6Name<>'' OR @Exam6Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam7Name<>'' OR @Exam7Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam8Name<>'' OR @Exam8Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam9Name<>'' OR @Exam9Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam10Name<>'' OR @Exam10Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam11Name<>'' OR @Exam11Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				  if(@Exam12Name<>'' OR @Exam12Name IS NOT NULL)	    
					SET @thHtml=@thHtml+'<td>Max</td><td>Obt</td>';
				 
				 SET @thHtml=@thHtml+'</tr>';
			 END

	     END   
	     SET @HeaderCounter=@HeaderCounter+1;
	    
	     
	     SET @tdHtml='<td class=Sub width=200>'+@ClassSubject+'</td>';
	     
	     Declare @SetDecimalFunction1 nvarchar(max)
	    --print @IsMarksInDecimal
	     IF(@IsMarksInDecimal=1)
			 BEGIN
			  SET @SetDecimalFunction1='onblur="javascript:return fnValidateDecimal(this,10,2)" onKeypress="javascript:return MaskDecimal(event,10,2)"';
		
			  
		 if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml
		  +'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain1)+'</div></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain2)+'</div></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain3)+'</div></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain4)+'</div></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain5)+'</div></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain6)+'</div></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain7)+'</div></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain8)+'</div></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain9)+'</div></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	       SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain10)+'</div></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain11)+'</div></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain12)+'</div></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
			  
			  
			  
			 END
	     ELSE
			 BEGIN
			   
			  SET @SetDecimalFunction1='onblur="javascript:return fnValidateDecimal(this,10,0)" onKeypress="javascript:return MaskDecimal(event,10,0)"';
			  
			  
		if(@ResultDetailId1<>'' OR @ResultDetailId1 IS NOT NULL)	    
	      SET @tdHtml=@tdHtml
		  +'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId1+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks1)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain1)+'</div></td>';
	      ELSE IF(@Exam1Name<>'' OR  @Exam1Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId2 <>'' OR @ResultDetailId2 IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId2+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks2)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain2)+'</div></td>';
	       ELSE IF(@Exam2Name<>'' OR  @Exam2Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId3 <>'' OR @ResultDetailId3 IS NOT NULL)	    	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId3+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks3)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain3)+'</div></td>';
	       ELSE IF(@Exam3Name<>'' OR  @Exam3Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId4 <>'' OR @ResultDetailId4 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId4+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks4)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain4)+'</div></td>';
	       ELSE IF(@Exam4Name<>'' OR  @Exam4Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId5 <>'' OR @ResultDetailId5 IS NOT NULL)	    		
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId5+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks5)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain5)+'</div></td>';
	        ELSE IF(@Exam5Name<>'' OR  @Exam5Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	       if(@ResultDetailId6 <>'' OR @ResultDetailId6 IS NOT NULL)	    			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId6+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks6)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain6)+'</div></td>';
	     ELSE IF(@Exam6Name<>'' OR  @Exam6Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      if(@ResultDetailId7 <>'' OR @ResultDetailId7 IS NOT NULL)	    				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId7+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks7)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain7)+'</div></td>';
	         ELSE IF(@Exam7Name<>'' OR  @Exam7Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	      
	       if(@ResultDetailId8 <>'' OR @ResultDetailId8 IS NOT NULL)	
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId8+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks8)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain8)+'</div></td>';
	       ELSE IF(@Exam8Name<>'' OR  @Exam8Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	        if(@ResultDetailId9 <>'' OR @ResultDetailId9 IS NOT NULL)		 
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId9+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks9)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain9)+'</div></td>';
	       ELSE IF(@Exam9Name<>'' OR  @Exam9Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	       if(@ResultDetailId10 <>'' OR @ResultDetailId10 IS NOT NULL)			
	       SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId10+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks10)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain10)+'</div></td>';
	       ELSE IF(@Exam10Name<>'' OR  @Exam10Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	      
	        if(@ResultDetailId11 <>'' OR @ResultDetailId11 IS NOT NULL)				
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId11+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks11)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain11)+'</div></td>';
	      ELSE IF(@Exam11Name<>'' OR  @Exam11Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
	     
	      if(@ResultDetailId12 <>'' OR @ResultDetailId12 IS NOT NULL)			
	      SET @tdHtml=@tdHtml+'<td  IsTempSave=0 ResultDetailId='+@ResultDetailId12+' class=max_obtain_mark>
		  <div class=MaxMarks>'+CONVERT(varchar(20),@ExamMaximumMarks12)+'</div></td>
		  <td><div class=ObtainMarks>'+CONVERT(varchar(20),@Obtain12)+'</div></td>';
	      ELSE IF(@Exam12Name<>'' OR  @Exam12Name IS NOT NULL)
	      SET @tdHtml=@tdHtml+'<td></td><td></td>';
			  
			  
			 END
	     
	    SET @trHtml= '<tr>'+@tdHtml+'</tr>';
	    SET @FinalHtml=@FinalHtml+@trHtml;
	   END
	     SET @lCounter = @lCounter + 1
	END
	 --print @thHtml
	select '<table id="ExamDataTbl" class="table table-striped table-bordered table-hover" style=position:relative><tr>'+@thHtml+'</tr>'+@FinalHtml+'</table>' AS Html; 
	--if(@FinalHtml IS NOT NULL and @FinalHtml <> '')	    
 --   select '<table  id="ExamDataTbl" class="table table-striped table-bordered table-hover" ><tr>'+@thHtml+'</tr>'+@FinalHtml+'</table>' AS Html; 
 --   ELSE
 --   select '<table id="ExamDataTbl" class="table table-striped table-bordered table-hover"><tr>No record found.</tr></table>' AS Html; 
			
	drop table #tempcombineExam
	Drop table #TempAllExam
	END

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


GO

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

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

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

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


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

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

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

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

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

 --             0 As Percentile ,

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

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

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

 --       '' AS ExamCode,

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

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

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

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

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


GO
ALTER PROCEDURE [sAssessment].[pRptResultWithSubjectListGet]
	 
   	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int,
	 @rClassId int,
	 @rDivisionId int,
	 @rExamId int=0,
     @rExamSubGroupId int=0,
	 @rCode nvarchar(20),
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int,
	 @rToRank int,
	 @rGrade nvarchar(20),
	 @rStatusId int = 0,
	 @rFromPercentage decimal(5,2)=0,
	 @rToPercentage decimal(5,2)=0,
	 @rResultStatus nvarchar(20)='',
	 @rDepartmentId int=0,
	 @rClassStatusId int=0,
	 @rGenderId int = 0
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
BEGIN 
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SO.GenderId,
			ESGM.Title AS Exam,
			StuM.Code,
			[sStudent].[fStudentNameGet](StuM.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,
			RD.Obtain,
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			Cm.Id AS ClassId,
			DM.DisplayTitle AS Division,
			DM.Id AS DivisionId,
			DM.OrderIndex AS DivisinOrderIndex,
			R.TotalMarks,
			R.TotalObtain,
			R.Percentage,
			R.RankNumber,
			R.ResultGrade,
			SM.Title AS ClassSubject,
			RD.Id AS ResultDetailId,
			R.Id AS ResultId,
			CS.Id AS SubjectId,
			ED.Maximum,
			RD.SubjectGrade, 
			
			EM.IsMarksInDecimal,
			--SM.OrderIndex AS SubjectCode,
			SM.Code AS SubjectCode,
			ED.DisplayOrder AS SubjectOrderIndex,
			CM.OrderIndex AS ClassOrderIndex,
			RD.IsPresent,
			EM.IsGrade,
			EM.IsPercentage,
			EM.IsResultStatus,
			EM.IsRankNo ,
			ED.Minimum,
			RD.GraceMark,
			EM.DecimalFormat,
			CS.IsOptional,
			SR.PresentDays,
			SR.TotalDays,
			ED.IsShowSubjectGrade,
			ED.IsShowSubjectMark,
			(EmpM.FirstName + ' ' +EmpM.LastName ) AS InchargeEmployeeName

	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId		
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId
			INNER JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId =  EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			LEFT JOIN sHrm.tEmployeeMaster EmpM ON EmpM.Id = DM.InchargeEmployeeId AND EmpM.StatusId = 7
			
	WHERE 
			
		EM.BatchId = @rBatchId 
		AND (A.ClassId=@rClassId OR @rClassId=0) 
		AND ((SM.Id=@rSubjectId) OR (RD.ExamDetailId=@rSubjectId) OR (@rSubjectId=0))
		AND (A.DivisionId=@rDivisionId OR @rDivisionId=0)
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		AND ((ESGM.Id = @rExamSubGroupId) OR (@rExamSubGroupId = 0))		
		AND ((EM.Id=@rExamId )	OR (@rExamId = 0))		
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		AND ((R.Percentage<=@rToPercentage) OR(@rToPercentage=0))	
		AND ((R.ResultStatus=@rResultStatus) OR (@rResultStatus=''))
		AND ((CM.DepartmentId = @rDepartmentId) OR (@rDepartmentId=0))
		AND	A.BatchId = @rBatchId 
		AND (A.ClassStatusId=@rClassStatusId OR @rClassStatusId=0) 
		AND ((SO.GenderId=@rGenderId) OR (@rGenderId=0))
		--AND RD.IsPresent = 0
		order by A.RollNo,CS.OrderIndex 

		
END
GO
PRINT N'Altering [sAssetManagement].[pRptAssetMaintenanceListGet]...';


GO
 
ALTER PROCEDURE [sAssetManagement].[pRptAssetMaintenanceListGet]
	@rOrgId [int] ,
	@rNumber nvarchar(100),
	@rStoreLocationId int
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
BEGIN
	 SELECT 
			LOC.Title AS Location,
			AM.CODE AS AssetTag,
			AM.Title AS AssetDescription,
			STAT.title AS Status,
			Cat.TITLE AS Category,
			AMN.MaintenenceDate AS LastMaintenanceDate,
			AMN.NextMaintenenceDate AS NextMaintenanceDate,
			AM.IsCritical AS Critical,
			VM.Title AS Supplier,
			AD.Title AS DepartmentName,
			AMN.Number AS MaintenanceNumber,
			AMN.MaintenenceCost,
			AMN.MaintenenceBy
			
	FROM
		sAssetManagement.tMaintenence AMN
	INNER JOIN
		sAssetManagement.tAssetMaster AM
	ON AMN.AssetId = AM.Id
	INNER JOIN sSetup.tDepartmentMaster AD
	ON AD.Id=AM.DepartmentId
	INNER JOIN  sFixedAsset.tCategoryMaster Cat
	ON AM.CategoryId = CAT.ID
	INNER JOIN  sCommon.tStatusMaster STAT
	ON STAT.ID =  AM.UsageStatusId 
	INNER JOIN  sFixedAsset.tLocationMaster LOC
	ON LOC.ID = AM.LocationId
	LEFT JOIN
	sProcurement.tVendorMaster VM
	ON VM.Id = AM.AmcVendorId
	
	WHERE (AMN.Number=@rNumber) OR (@rNumber = '')
	AND AMN.OrgId = @rOrgId
	AND AMN.StoreLocationId=@rStoreLocationId
	ORDER BY AMN.MaintenenceDate ASC
				 
END
GO
PRINT N'Altering [sAttendance].[pRptStudentRegisterGet]...';


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

BEGIN 
IF(@rIsHolidayWeekoff = 1)
BEGIN
Declare @Days int 
select @Days=sCommon.fGetDaysInMonth(Month(GetDate()),Year(GetDate()))
--Select @Days
	
DECLARE @li int 
SET @li=1

CREATE TABLE #TempDaysTempTable
(
 DayPart int,
 Value nvarchar(20)
 )
WHILE @li <= @Days
BEGIN
INSERT INTO #TempDaysTempTable
(
   DayPart ,
   Value
)

SELECT 
@li AS DayPart,
 [sAttendance].[fWeekHOffGet](YEAR(GetDate()),MONTH(GetDate()),@li,@rBatchId,@rClassId,@rDivisionId,'',@rOrgId)
SET @li = @li + 1
END
--Select * from #TempDaysTempTable
CREATE TABLE #TempDaysTempTable1
(
 [1] nvarchar(10),
 [2] nvarchar(10),
 [3] nvarchar(10),
 [4] nvarchar(10),
 [5] nvarchar(10),
 [6] nvarchar(10),
 [7] nvarchar(10),
 [8] nvarchar(10),
 [9] nvarchar(10),
 [10] nvarchar(10),
 [11] nvarchar(10),
 [12] nvarchar(10),
 [13] nvarchar(10),
 [14] nvarchar(10),
 [15] nvarchar(10),
 [16] nvarchar(10),
 [17] nvarchar(10),
 [18] nvarchar(10),
 [19] nvarchar(10),
 [20] nvarchar(10),
 [21] nvarchar(10),
 [22] nvarchar(10),
 [23] nvarchar(10),
 [24] nvarchar(10),
 [25] nvarchar(10),
 [26] nvarchar(10),
 [27] nvarchar(10),
 [28] nvarchar(10),
 [29] nvarchar(10),
 [30] nvarchar(10),
 [31] nvarchar(10)
  
 )
INSERT INTO #TempDaysTempTable1
select [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31]
from
(
  select DayPart, Value
  from #TempDaysTempTable
) d
pivot
(
  max(value)
  for DayPart in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) piv;
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SA.DivisionOrder,
			@rIsHolidayWeekoff AS IsHolidayWeekoff,
			(Select [1] from #TempDaysTempTable1)AS D1,
			(Select [2] from #TempDaysTempTable1)AS D2,
			(Select [3] from #TempDaysTempTable1)AS D3,
			(Select [4] from #TempDaysTempTable1)AS D4,
			(Select [5] from #TempDaysTempTable1)AS D5,
			(Select [6] from #TempDaysTempTable1)AS D6,
			(Select [7] from #TempDaysTempTable1)AS D7,
			(Select [8] from #TempDaysTempTable1)AS D8,
			(Select [9] from #TempDaysTempTable1)AS D9,
			(Select [10] from #TempDaysTempTable1)AS D10,
			(Select [11] from #TempDaysTempTable1)AS D11,
			(Select [12] from #TempDaysTempTable1)AS D12,
			(Select [13] from #TempDaysTempTable1)AS D13,
			(Select [14] from #TempDaysTempTable1)AS D14,
			(Select [15] from #TempDaysTempTable1)AS D15,
			(Select [16] from #TempDaysTempTable1)AS D16,
			(Select [17] from #TempDaysTempTable1)AS D17,
			(Select [18] from #TempDaysTempTable1)AS D18,
			(Select [19] from #TempDaysTempTable1)AS D19,
			(Select [20] from #TempDaysTempTable1)AS D20,
			(Select [21] from #TempDaysTempTable1)AS D21,
			(Select [22] from #TempDaysTempTable1)AS D22,
			(Select [23] from #TempDaysTempTable1)AS D23,
			(Select [24] from #TempDaysTempTable1)AS D24,
			(Select [25] from #TempDaysTempTable1)AS D25,
			(Select [26] from #TempDaysTempTable1)AS D26,
			(Select [27] from #TempDaysTempTable1)AS D27,
			(Select [28] from #TempDaysTempTable1)AS D28,
			(CASE WHEN @Days > = 29 THEN (Select [29] from #TempDaysTempTable1) ELSE '' END )AS D29,
			(CASE WHEN @Days > = 30 THEN (Select [30] from #TempDaysTempTable1) ELSE '' END )AS D30,
			(CASE WHEN @Days > = 31 THEN (Select [31] from #TempDaysTempTable1) ELSE '' END )AS D31
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StatusId=@rStatus) OR (@rStatus=0))
		AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))


		DROP TABLE #TempDaysTempTable
END
ELSE
BEGIN
	SELECT 
			@rBuilder1 AS Builder1,
			@rBuilder2 AS Builder2,
			SA.AcademicId,
			SA.ClassId,
			SA.DivisionId,
			SA.ClassName,
			SA.DivisionName,
			SA.ClassName+' - '+SA.DivisionName AS ClassDivision,
			SA.Code,
			SA.RollNo,			
			SA.Name,
			ISNULL(SO.DateOfBirth,NULL) AS DateOfBirth,
			SA.DivisionOrder
	FROM 
			sStudent.vStudentAcademic SA
        INNER JOIN sStudent.tStudentOther SO ON SA.StudentId = SO.StudentId 			
	WHERE 
			(SA.OrgId=@rOrgId)
		AND	(SA.BatchId = @rBatchId) 
		AND ((SA.ClassId=@rClassId) OR (@rClassId=0))
		AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SA.StatusId=@rStatus) OR (@rStatus=0))
		AND ((SA.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))
END
		--SELECT 
		--	'' AS Builder1,
		--	'' AS Builder2,
		--	0 AS AcademicId,
		--	0 AS ClassId,
		--	0 AS DivisionId,
		--	'' AS ClassName,
		--	'' AS DivisionName,
		--	'' AS ClassDivision,
		--	'' AS Code,
		--	0 AS RollNo,			
		--	'' AS Name,
		--	'' AS DateOfBirth,
		--	0 AS DivisionOrder,
		--	0 AS IsHolidayWeekoff,
		--	'' AS D1,
		--	'' AS D2,
		--	'' AS D3,
		--	'' AS D4,
		--	'' AS D5,
		--	'' AS D6,
		--	'' AS D7,
		--	'' AS D8,
		--	'' AS D9,
		--	'' AS D10,
		--	'' AS D11,
		--	'' AS D12,
		--	'' AS D13,
		--	'' AS D14,
		--	'' AS D15,
		--	'' AS D16,
		--	'' AS D17,
		--	'' AS D18,
		--	'' AS D19,
		--	'' AS D20,
		--	'' AS D21,
		--	'' AS D22,
		--	'' AS D23,
		--	'' AS D24,
		--	'' AS D25,
		--	'' AS D26,
		--	'' AS D27,
		--	'' AS D28,
		--	'' AS D29,
		--	'' AS D30,
		--	'' AS D31
END
GO
PRINT N'Altering [sAttendance].[pYearlyRegisterGet]...';


GO
 

ALTER PROCEDURE [sAttendance].[pYearlyRegisterGet]

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

BEGIN 

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


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


GO
ALTER PROCEDURE [sCommunication].[pAllPhotoCategory_Get]
	 @rId int = 0,
	 @rSyncedPhotoCategoryId int = 0,
	 @rBatchId int,
	 @rIsDivisionWise bit=true,
	 @rBatchYear int = 0
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN 
	
    DECLARE @lOrgGroupId smallint,@lOrgGroupBatchID int,@lOrgId smallint
    
	SELECT @lOrgGroupId=OM.OrgGRoupId FROM sSetup.tOrganizationMaster OM
	INNER JOIN sSetup.tBatchMaster BM ON BM.OrgId=OM.Id
	WHERE Bm.Id=@rBatchId
    IF(@rIsDivisionWise=0)
    BEGIN
		SELECT   
			PCM.[Id]
			,PCM.[Title]
			,PCM.[IsObsolete]
			,ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(PCM.Remark,'') AS Remark,
			PCM.CreatedDateTime,
			CASE WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			END +' - '+ [sCommunication].[fPhotoCategoryScopeGet](PCM.Id,PCM.ScopeSourceTypeId) AS ScopeSourceType,
			U.DisplayTitle AS UserName
		FROM    
			[sCommunication].[tPhotoCategoryMaster]  PCM 
			INNER JOIN sSecurity.tUser U ON PCM.CreatedUserId = U.Id
		WHERE   
			((PCM.Id = @rId) OR (@rId = 0))
			AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			AND PCM.IsObsolete =0
			AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
		ORDER BY 
			PCM.CreatedDateTime DESC
	END		
	ELSE
	
	 BEGIN
		SELECT   
			PCM.[Id]
			,PCM.[Title]
			,PCM.[IsObsolete]
			,ISNULL(PCM.ScopeSourceTypeId,0) AS ScopeSourceTypeId
			,ISNULL(PCM.Remark,'') AS Remark,
			PCM.CreatedDateTime,
			CASE WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2021 THEN 'Organization'
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2017 THEN 'Department' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2016 THEN 'Class' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2005 THEN 'Division' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2014 THEN 'Hostel' 
			WHEN ISNULL(PCM.ScopeSourceTypeId,0) = 2029 THEN 'House' 
			END +' - '+ [sCommunication].[fPhotoCategoryScopeGet](PCM.Id,PCM.ScopeSourceTypeId) AS ScopeSourceType,
			U.DisplayTitle AS UserName
		FROM    
			[sCommunication].[tPhotoCategoryMaster]  PCM 
			INNER JOIN sSecurity.tUser U ON PCM.CreatedUserId = U.Id
		WHERE   
			((PCM.Id = @rId) OR (@rId = 0))
			AND ((PCM.Id > @rSyncedPhotoCategoryId) OR (@rSyncedPhotoCategoryId = 0))
			AND OrgGroupId=@lOrgGroupId
			AND ScopeSourceTypeId=2005
			AND PCM.IsObsolete =0
			AND ((YEAR(PCM.CreatedDateTime) = @rBatchYear) OR (@rBatchYear = 0))
		ORDER BY 
			PCM.CreatedDateTime DESC
	END		
END
GO
PRINT N'Altering [sCommunication].[pAssignmentGet]...';


GO
 
 
ALTER PROCEDURE [sCommunication].[pAssignmentGet]
	 @rId bigint = 0,
	 @rSubjectId int,
	 @rTitle nvarchar(100),
	 @rFromDate date,
	 @rToDate date,
	 @rBatchId int,
	 @rIsSearch bit = 1,
	 @rCreatedUserId bigint=0
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
	
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			ISNULL(IsAssignmentDocumentUpload,0) AS IsAssignmentDocumentUpload,
			ISNULL(AV.Remark,'') AS ViewRemark
		    
  FROM 
            sCommunication.tAssignment A
            INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			LEFT JOIN sCommunication.tAssignmentView AV ON A.Id = AV.AssignmentId
  WHERE 
  
      ((A.Id = @rId) OR (@rId = 0))
    AND ((A.SubjectId = @rSubjectId) OR (@rSubjectId = 0))
	AND ((A.Title like @rTitle) OR (ISNULL(@rTitle,'') = ''))
	AND ((A.StartDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
	AND ((A.StartDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
	AND ((A.CreatedUserId = @rCreatedUserId) OR (@rCreatedUserId = 0))
	AND A.BatchId=@rBatchId
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


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

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


GO



ALTER PROCEDURE [sHrm].[pEmployeeDetailFormGet]	
	@rEmployeeId bigint = 0,	
	@rOrgId int = 0,
	@Tab nvarchar(20) = '',
	@rOrgGroupId int = 0,
	@rBatchId int = 0

	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @lTimesheetCol nvarchar(20) = DAY(sCommon.fGetDate())
	DECLARE @lFromDate Date = CAST(sCommon.fGetDate()-1 AS DATE)
	DECLARE @lToDate Date = CAST(sCommon.fGetDate() AS DATE)
	IF(LEN(@lTimesheetCol) = 1)
	BEGIN
		SET @lTimesheetCol = '0' + @lTimesheetCol
	END
	--Start
	IF(LOWER(@Tab) = 'overview')
	BEGIN
		-- Employee Header Details
		SELECT 
			EM.Id,
			EM.Code,
			ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
			ISNULL(EP.DateOfBirth,'') AS DateOfBirth,
			ISNULL(GM.Title,'') AS Gender,
			ISNULL(EI.EmployeePhoto,0x) AS EmployeePhoto,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(EDM.Title,'') AS EmployeeDesignation,
			ISNULL(DM.Title,'') AS OrganizationDepartment,
			ISNULL(ETM.Title,'') AS EmployeeType
		FROM 
			sHrm.tEmployeeMaster EM 
			INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.ID	
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id
			INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = EM.Id
			LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.ID = EJ.EmployeeDesignationId
			LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJ.OrganizationDepartmentId 
			LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EP.GenderId
		LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id=EJ.EmployeeTypeId
	  WHERE 
			(EM.Id=@rEmployeeId)


		-- Attendance Card
		SELECT 
		(SELECT ISNULL(IsPresent,0) FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId = @rEmployeeId AND AttendanceDate = CAST(sCommon.fGetDate() AS DATE)) AS TodayAttendance,
		(SELECT ISNULL(IsPresent,0) FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId = @rEmployeeId AND AttendanceDate = CAST(sCommon.fGetDate() - 1 AS DATE)) AS YesterdayAttendance,	
		(SELECT ISNULL(COUNT(IsPresent),0) FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId = @rEmployeeId AND MONTH(AttendanceDate) = MONTH(sCommon.fGetDate()) AND YEAR(AttendanceDate) = YEAR(sCommon.fGetDate()) AND IsPresent = 1) AS MonthlyPresence,
		(SELECT ISNULL(COUNT(IsPresent),0) FROM sHrm.tEmployeeAttendanceRegister WHERE EmployeeId = @rEmployeeId AND MONTH(AttendanceDate) = MONTH(sCommon.fGetDate()) AND YEAR(AttendanceDate) = YEAR(sCommon.fGetDate()) AND IsPresent = 0) AS MonthlyAbsence,
		ISNULL(WD.TotalDays,0) AS TotalDays,ISNULL(WD.TotalDays,0) AS WorkingDays FROM
		sHrm.vEmployeeCommonDetail EM INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId AND WD.BatchId = @rBatchId
		WHERE EmployeeId = @rEmployeeId AND WD.ForMonth =MONTH(sCommon.fGetDate())  AND WD.Foryear = YEAR(sCommon.fGetDate())

		--TimeSheet Card
		DECLARE @fDay nvarchar(10) = DAY(sCommon.fGetDate()-1)
		set @fDay= (SELECT CASE WHEN @fDay BETWEEN 0 AND 9 THEN RIGHT('0' + CAST(@fDay AS VARCHAR(2)), 2) ELSE CAST(@fDay AS NVARCHAR(10)) END)
		DECLARE @lDay nvarchar(10) = DAY(sCommon.fGetDate())
		set @lDay= (SELECT CASE WHEN @lDay BETWEEN 0 AND 9 THEN RIGHT('0' + CAST(@lDay AS VARCHAR(2)), 2) ELSE CAST(@lDay AS NVARCHAR(10)) END)
		Declare  @lQuery nvarchar(max) = '(Select 
					 D'+CAST(@lDay AS VARCHAR)+'_IN AS FirstIn,
					D'+CAST(@lDay AS VARCHAR)+'_OUT AS LastOut,
					D'+CAST(@lDay AS VARCHAR)+'_E AS Early,
					D'+CAST(@lDay AS VARCHAR)+'_L AS LateBy,
					D'+CAST(@lDay AS VARCHAR)+'_T AS Duration
					 from sBiometric.tMonthTrans
					WHERE EmployeeId = '+CAST(@rEmployeeId AS VARCHAR) + 'AND MONTH(Attn_Dt) = ''' +    CAST(MONTH(sCommon.fGetDate()) AS VARCHAR) + '''   AND SourceTypeId = '+CAST(95 AS VARCHAR)
					+') Union (Select 
					D'+CAST(@fDay AS VARCHAR)+'_IN AS FirstIn,
					D'+CAST(@fDay AS VARCHAR)+'_OUT AS LastOut,
					D'+CAST(@fDay AS VARCHAR)+'_E AS Early,
					D'+CAST(@fDay AS VARCHAR)+'_L AS LateBy,
					D'+CAST(@fDay AS VARCHAR)+'_T AS Duration
					from sBiometric.tMonthTrans
					WHERE EmployeeId = '+CAST(@rEmployeeId AS VARCHAR) + 'AND MONTH(Attn_Dt) = ''' +   CAST(MONTH(sCommon.fGetDate()) AS VARCHAR) + '''   AND SourceTypeId = '+CAST(95 AS VARCHAR)+')'
			EXEC (@lQuery)	
			print(@lQuery)


		-- Leave Card
		SELECT 
		ReportDate,FromDate,ToDate,NoOfLeave,LTM.Title AS LeaveType,LeaveReason,ISNULL(SM.Title,'Pending') AS StatusName 
		FROM sHrm.tLeave L INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId INNER JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId AND SM.StatusTypeId = 113 
		WHERE EmployeeId = @rEmployeeId AND MONTH(ReportDate) = MONTH(sCommon.fGetDate()) AND YEAR(ReportDate) = YEAR(sCommon.fGetDate())
		
		--Payroll Card
		SELECT 
		ISNULL((SELECT ISNULL( IsApproved,0) FROM [sPayroll].[tPayProcess] PP inner join [sPayroll].[tPayProcessEmployee] PPE on PP.ID=PPe.PayProcessId WHERE EmployeeId = @rEmployeeId  AND  MONTH(SalaryMonth) = MONTH(sCommon.fGetDate()) AND YEAR(SalaryYear) = YEAR(sCommon.fGetDate())),0) AS CurrentMonthPayrollStatus,
		ISNULL((SELECT ISNULL( IsApproved, 0) FROM [sPayroll].[tPayProcess] PP inner join [sPayroll].[tPayProcessEmployee] PPE on PP.ID=PPe.PayProcessId WHERE EmployeeId = @rEmployeeId  AND  MONTH(SalaryMonth) = MONTH(sCommon.fGetDate()) AND YEAR(SalaryYear) = YEAR(sCommon.fGetDate())),0) AS LastMonthPayrollStatus

		--Timetable Card
		SELECT 
			ISNULL(SubjectId,0) AS SubjectId,
			ISNULL(SM.Title,'') AS Subject,
			ISNULL(TT.LectureNumber,'') AS LactureNumber,
			ISNULL(DM.Title,'') +'-'+ISNULL(convert(nvarchar(4),TT.LectureNumber),'') AS DayLacture,
			ISNULL(CL.Id,0) AS ClassId,
			ISNULL(DV.Code,'') AS ClassDivisionName,
			ISNULL(TTT.FromTime,'') AS Time
		FROM 
			sTimetable.tTimeTable TT  
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TT.SubjectId 
			INNER JOIN sHrm.tEmployeeMaster Em ON Em.Id = TT.EmployeeId
			INNER JOIN sCommon.tDayMaster DM ON DM.Id = TT.DayId
			INNER JOIN sSetup.tDivisionMaster DV ON DV.Id = TT.DivisionId
			INNER JOIN sSetup.tClassMaster CL ON CL.Id = DV.ClassId
			INNER JOIN sTimetable.tTimeTableTime TTT ON TTT.DayId=TT.DayId AND TTT.TimeTableSchemaId=TT.TimeTableSchemaId AND TTT.LectureNumber=TT.LectureNumber AND TTT.DivisionId=TT.DivisionId
	
		WHERE
			((EmployeeId = @rEmployeeId))
			AND ((TT.DayId = DATEPART(WEEKDAY, sCommon.fGetDate())))
			AND ((DV.OrgId=@rOrgId) OR (@rOrgId=0))
			AND  ISNULL(EM.IsOtherUser,0) = 0
			order by TT.LectureNumber
		-- Lecture Online learning Card
		select 
			ISNULL(CM.Title,'') AS ClassName,
			ISNULL(SM.Title,'') AS SubjectName ,
			ISNULL(OL.Title,'') AS Title,
			CONVERT(NVARCHAR(5),OL.StartTime,108) AS  StartTime,
			CONVERT(NVARCHAR(5),OL.EndTime,108) AS EndTime,
			OL.IsCompleted as Status,
			  (SELECT
						  (
						  STUFF((SELECT ',' + a.Code
						  FROM
						  (
						  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tClassMaster CM ON OLS.SourceId = CM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2016
						  UNION ALL
						  SELECT Code FROM sAcademic.tOnlineLearningScope OLS INNER JOIN sSetup.tDivisionMaster DM ON OLS.SourceId = DM.Id Where  OnlineLearningId = OL.Id AND OLS.SourceTypeId = 2005
						  ) a
						  FOR XML PATH ('')), 1, 1, '') ) ) as Source 
		from
			sAcademic.tOnlineLearning OL
						INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=OL.SubjectId
						LEFT JOIN sSetup.tClassMaster CM ON CM.Id = OL.ClassId
						LEFT JOIN sAcademic.tTopicMaster TM ON TM.Id = OL.TopicId


		Where OL.TeacherEmployeeId=@rEmployeeId AND OL.StartDate = CAST(sCommon.fGetDate() AS DATE)

		--Subject Card
		select distinct SM.Title AS SubjectName from
			[sAcademic].[tTeacherSubject] TS 
		  inner join [sSetup].[tSubjectMaster] SM on SM.Id=TS.SubjectId
		  where TS.EmployeeId=@rEmployeeId
		    -- Exam Schedule
		  SELECT
				ESGM.Title AS ExamName,
				SM.Title AS 'Subject',
				ED.ExamDate AS ExamDate,
				ED.ExamTime AS ExamTime,
				CM.Title AS ClassName,
				ISNULL(ED.ExamTopic,'') AS ExamTopic
			FROM 
				sAssessment.tExamMaster E 
				INNER JOIN sAssessment.tExamDetail ED ON E.Id = ED.ExamId
				INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
				INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId
				LEFT JOIN sSetup.tClassMaster CM ON CM.Id = CS.ClassId
				INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = CS.SubjectId
				Where E.Id in (SELECT
								E.Id AS ExamId
								FROM 
								sAssessment.tExamMaster E
								INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = E.ExamSubGroupId
								Inner join sSetup.tDivisionMaster DM ON E.ClassId=DM.ClassId
								WHERE 
								E.BatchId = @rBatchId  AND ISNULL(E.IsPublishExamSchedule,0) = 1 AND DM.InchargeEmployeeId=@rEmployeeId)
	END
	IF(LOWER(@Tab) = 'employeealldetails')
	BEGIN
		SELECT 
		 --Personal Details
		 EM.Id,
		 EM.Code,
		 ISNULL(EM.FirstName,'') + ' ' + ISNULL(EM.MiddleName,'') + ' ' + ISNULL(EM.LastName,'') AS EmployeeName,
		 IsNull(EM.ShortName,'') AS ShortName,
		 ISNULL(EP.UIDNumber,'') AS UIDNumber,
		 ISNULL(EP.DateOfBirth,'') AS DateOfBirth,
		 CONVERT(varchar(20) ,ISNULL(EP.DateOfBirth,''),105) AS DateOfBirthJSON,
		 ISNULL(GM.Title,'') AS Gender,
		 ISNULL(MM.Title,'') AS MeritalStatus,
		 ISNULL(BGM.Title,'') AS BloodGroup,
		 ISNULL(EP.Qualification,'') AS Qualification,
		 ISNULL(EP.FamilyCast,'') AS FamilyCast,
		 ISNULL(EM.StatusId,'') AS StatusId,
		 ISNULL(EM.Number,'') AS Number,
		 
		 --Communication
		 ISNULL(EC.PresentStreetOne,'')+' '+ISNULL(EC.PresentStreetTwo,'')+' '+ISNULL(EC.PresentStreetThree,'') AS PresentAddress,
		 ISNULL(EC.PresentCity,'') AS PresentCity,
		 ISNULL(EC.PresentState,'') AS PresentState,
		 ISNULL(EC.PresentCountry,'') AS PresentCountry,
		 ISNULL(EC.PresentZipCode,'') AS PresentZipCode,
		 ISNULL(EC.PresentContactNo,'') AS PresentContactNo,
		
		 ISNULL(EC.PermanentStreetOne,'')+' '+ISNULL(EC.PermanentStreetTwo,'')+' '+ISNULL(EC.PermanentStreetThree,'') AS PermanentAddress,
		 ISNULL(EC.PermanentCity,'') AS PermanentCity,
		 ISNULL(EC.PermanentState,'') AS PermanentState,
		 ISNULL(EC.PermanentCountry,'') AS PermanentCountry,
		 ISNULL(EC.PermanentZipCode,'') AS PermanentZipCode,
		 ISNULL(EC.PermanentContactNo,'') AS PermanentContactNo,
		 
		 ISNULL(EC.EmergencyStreetOne,'')+' '+ISNULL(EC.EmergencyStreetTwo,'')+' '+ISNULL(EC.EmergencyStreetThree,'') AS EmergencyAddress,
		 ISNULL(EC.EmergencyCity,'') AS EmergencyCity,
		 ISNULL(EC.EmergencyState,'') AS EmergencyState,
		 ISNULL(EC.EmergencyCountry,'') AS EmergencyCountry,
		 ISNULL(EC.EmergencyZipCode,'') AS EmergencyZipCode,
		 ISNULL(EC.EmergencyContactNo,'') AS EmergencyContactNo,
		
		 --Job Details
		 ISNULL(EJ.DateOfJoining,'') AS DateOfJoining,	
		 CONVERT(varchar(20),ISNULL(EJ.DateOfJoining,''),105) AS DateOfJoiningJSON,		
		 ISNULL(EJ.DateOfleaving ,'') AS DateOfLeaving,
		 (CONvert(varchar(20),EJ.DateOfleaving, 105)) AS DateOfLeavingJSON,
		 ISNULL(EJ.JobRemark,'') AS JobRemark,
		 ISNULL(EJ.ReferenceRemark,'') AS ReferenceRemark,
		 ISNULL(EDM.Title,'') AS EmployeeDesignation,
		 ISNULL(DM.Title,'') AS OrganizationDepartment,
		 ISNULL(EGM.Title,'') AS EmployeeGrade,
		 ISNULL(GrpM.Title,'') AS EmployeeGroup,
		 ISNULL(ETM.Title,'') AS EmployeeType,
		 ISNULL(EJ.ReasonOfleaving,'') AS ReasonOfleaving,
		 ISNULL(EJ.ProbationDays,'') AS ProbationDays,
		 ISNULL(EJ.ProbationUptoDate,'') AS ProbationUptoDate,
		 ISNULL(EJ.AhdocUptoDate,'') AS AhdocUptoDate,
		 ISNULL(EJ.PermanentDate,'') AS PermanentDate,
		 ISNULL(EJ.DateOfResignation,'') AS DateOfResignation,
		 ISNULL(EMM.FirstName,'') + ' ' + ISNULL(EMM.MiddleName,'') + ' ' + ISNULL(EMM.LastName,'') AS EmployeeManager,
		 ISNULL(OHM.FirstName,'') + ' ' + ISNULL(OHM.MiddleName,'') + ' ' + ISNULL(OHM.LastName,'') AS OrganizationHeadManager,
		 ISNULL(OH.DisplayTitle,'') AS OrganizationHead,
		 ISNULL(OGDM.Title,'') AS OrgGroupDepartment, 
		 ----Previous Employment
		 --ISNULL(EPE.CompanyName,'') AS PrevCompanyName,
		 --ISNULL(EPE.Designation,'') AS PrevDesignation,
		 --ISNULL(EPE.Duration,'') AS Duration,
		 --ISNULL(EPE.LastSalary,0) AS LastSalary,
		 --ISNULL(EPE.ReasonForLeaving,'') AS ReasonForLeaving,
		 --ISNULL(EPE.JobDescription,'') AS JobDescription,
		
		 --Notification Details
		 ISNULL(EC.PersonalEmail,'') As PersonalEmail,
		 ISNULL(EC.MobileNumber,'') AS MobileNumber,
		 ISNULL(EC.PhoneNoCompany,'') AS PhoneNoCompany,
		 ISNULL(EC.ExtensionNo,'') AS ExtensionNo,
		 ISNULL(EC.CompanyEmail,'') AS CompanyEmail,
		 ISNULL(EC.WhatsAppContactNo,'') AS WhatsAppContactNo,
		
		 --EI.EmployeePhoto,
		 ISNULL(ESO.AccountNumber,'') AS AccountNumber,
		 ISNULL(ESO.BankName,'') AS BankName,
		 ISNULL(ESO.Branch,'') AS BankBranch,
		 ISNULL(ESO.IFSCNumber,'') AS IFSCNumber,
		 ISNULL(ESO.PanNumber,'') AS PanNumber,
		 ISNULL(ESO.EPFNumber,'') AS EPFNumber,
		 ISNULL(ESO.IncrementDate,'') AS IncrementDate,
		 Convert( varchar(20),ISNULL(ESO.IncrementDate,''),105) AS IncrementDateJSON,
		 ISNULL(ESO.BasicPay,0) AS BasicPay,
		 ISNULL(ESO.ESINumber,'') AS ESINumber,
		 ISNULL(ESO.EPFJoinDate,'') AS EPFJoinDate,
		 ISNULL(ESO.UAN,'') AS UAN,
		 ISNULL(ESO.AccountHolderName,'') AS AccountHolderName,
		 ISNULL(ESO.RetirementDate,'') AS RetirementDate,
		 ISNULL(PM.Title,'') AS PayRollTitle,
		 ISNULL(PGM.Title,'') AS PayRollGroupTitle,

	     --ISNULL(EFD.Occupation,'') AS Occupation,
		 convert(nvarchar(20),EM.Id) AS EmployeeIdText,
		 convert(nvarchar(20),@rOrgId) AS OrgIdText,
		 ISNULL(EJ.OrganizationDepartmentId,0) AS DepartmentId,
		 OM.DisplayTitle AS OrgTitle,
		 ISNULL(EP.AdhaarNumber,'') AS AdhaarNumber,
		 ISNULL(ESO.Payscale,'') AS Payscale,
		 --[sHrm].[fTeachingSubjectGet] (EM.Id) AS TeachingSubject
		 EJ.Subjects AS TeachingSubject,
		 RM.Title AS Religion,
		 CCM.Title AS CasteCategory,
		 EP.FamilyCast AS FamilyCast,
		 EP.UIDNumber,
		 EP.IdentificationMark1,
		 EP.AdhaarNumber,
		 EP.Qualification,
		 ISNULL(EI.EmployeePhoto,0x) AS EmployeePhoto,
		 ISNULL(EI.EmployeeSign,0x) AS EmployeeSign 
  FROM 
		sHrm.tEmployeeMaster EM 
		LEFT JOIN sHrm.tEmployeeCommunications EC ON EM.ID = EC.EmployeeId
		INNER JOIN sHrm.tEmployeeJobDetail EJ ON EJ.EmployeeId = EM.Id
		INNER JOIN sHrm.tEmployeePersonalDetail EP ON EP.EmployeeId = EM.ID	
		--INNER JOIN sHrm.tEmployeePreviousEmployment EPE ON EPE.EmployeeId=EM.ID
		LEFT JOIN sHrm.tEmployeeMaster EMM ON EMM.Id=EJ.EmployeeManagerId
		LEFT JOIN sHrm.tEmployeeMaster OHM ON OHM.Id=EJ.EmployeeBusinessHeadId
		LEFT JOIN sSetup.tOrganizationMaster OH ON OH.Id=LEFT(EJ.EmployeeBusinessHeadId,4)
		LEFT JOIN sCommon.tOrgGroupDepartmentMaster OGDM ON OGDM.Id=EJ.OrgGroupDepartmentId
		LEFT JOIN sCommon.tBloodGroupMaster BGM ON BGM.Id = EP.BloodGroupId    
		LEFT JOIN sCommon.tGenderMaster GM ON GM.Id = EP.GenderId
		LEFT JOIN sCommon.tMaritalStatusMaster MM ON MM.Id =  EP.MaritalstatusId
		LEFT JOIN sCommon.tReligionMaster RM ON RM.Id=EP.ReligionId
		LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = EM.Id
		LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.ID = EJ.EmployeeDesignationId
		LEFT JOIN sSetup.tDepartmentMaster DM ON DM.Id = EJ.OrganizationDepartmentId
		LEFT JOIN sHrm.tEmployeeTypeMaster ETM ON ETM.Id=EJ.EmployeeTypeId
		LEFT JOIN sHrm.tEmployeeGradeMaster EGM ON EGM.Id=EJ.EmployeeGradeId
		LEFT JOIN sHrm.tEmployeeGroupMaster GrpM ON GrpM.Id=EJ.EmployeeGroupId
		LEFT JOIN sHrm.tEmployeeStatutoryAndOther ESO ON ESO.EmployeeId = EM.Id
		LEFT JOIN sPayroll.tPayrollMaster PM ON ESO.PayrollId=PM.Id
		LEFT JOIN sPayroll.tPayrollGroupMaster PGM ON ESO.PayrollGroupId=PGM.Id
		LEFT JOIN sCommon.tCastCategoryMaster CCM ON CCM.Id = EP.CastCategoryId
		--LEFT JOIN sHrm.tEmployeeFamilyDetails EFD ON EFD.EmployeeId = EM.Id
		INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=EM.OrgId  
  WHERE 
		(EM.Id=@rEmployeeId)
	END
	IF(LOWER(@Tab) = 'employeeattendance')
	BEGIN
		

		SELECT  
			EM.EmployeeName,
			ISNULL(EM.EmployeeGrade,'') AS EmployeeGrade,
			ISNULL(WD.TotalDays,0) AS TotalDays,
			ISNULL(AT.TotalWorkingDays,ISNULL(WD.WorkingDays,0)) AS WorkingDays,
			(ISNULL(AT.TotalWorkingDays,0) - ((ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)))) AS PresentDays,
			(ISNULL(AT.TotalWorkingDays,0) - ISNULL(AT.LWP,0)) AS PayrollDays,
			(ISNULL(AT.LWP,0) + ISNULL(AT.PaidLeave,0)) AS LWP,  
			ISNULL(AT.PaidLeave,0) AS PaidLeave,
			ISNULL(AT.LWP,0) AS UnPaidLeave,
			MM.Title AS Month,
			WD.ForYear
		FROM 
			sHrm.vEmployeeCommonDetail EM 
			INNER JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId = EM.EmployeeId		
			INNER JOIN sHrm.tEmployeeAttendance AT ON AT.EmployeeId=EM.EmployeeId AND AT.BatchId = @rBatchId
			INNER JOIN sHrm.tWorkingDays WD ON  EM.EmployeeGradeId = WD.EmployeeGradeId AND WD.ForMonth = AT.ForMonth AND WD.Foryear = AT.ForYear AND WD.BatchId = @rBatchId
			INNER JOIN sCommon.tMonthMaster MM ON MM.Id = WD.ForMonth
		WHERE 
			EM.OrgID = @rOrgId AND EM.EmployeeId = @rEmployeeId 
		ORDER BY 
			WD.ForMonth
	END
	IF(LOWER(@Tab)='employeeleave')
	BEGIN
	SELECT 
			L.Id AS LeaveId
			,L.EmployeeId
			,L.ReportDate
			,L.FromDate
			,L.ToDate
			,LeavePeriodId
			,L.LeaveTypeId
			,CASE WHEN LeaveReason = '- Select -' THEN 'NA' ELSE LeaveReason END AS LeaveReason
			,LPM.Title AS LeavePeriod
			,LTM.Title AS LeaveType
			,EM.EmployeeName
			,EM.Code AS EmployeeCode
			,ISNULL(L.StatusId,0) AS StatusId
			,ISNULL(SM.Title,'Pending') AS StatusName
			,L.NoOfLeave      
			,ISNULL(L.FromTime,'') AS FromTime
			,ISNULL(L.ToTime,'') AS ToTime
			,ISNULL(L.LeaveRemark,'') AS LeaveRemark		       
		FROM 
			sHrm.tLeave L 
			INNER JOIN sHrm.tLeavePeriodMaster LPM ON LPM.Id = L.LeavePeriodId
			INNER JOIN sHrm.tLeaveTypeMaster LTM ON LTM.Id = L.LeaveTypeId
			INNER JOIN sHrm.vEmployeeCommonDetail EM ON EM.EmployeeId = L.EmployeeId 
			INNER JOIN sCommon.tStatusMaster SM ON SM.Id = L.StatusId			
		WHERE 				
			L.EmployeeId = @rEmployeeId AND BatchId = @rBatchId AND L.OrgId = @rOrgId
		Order By L.FromDate DESC

	SELECT 
		ISNULL(LB.BalanceLeave,0) AS TotalBalance, 
		ISNULL(SUM(L.NoOfLeave),0) AS UsedBalance, 
		ISNULL(LB.BalanceLeave,0) - ISNULL(SUM(L.NoOfLeave),0) AS AvailableBalance, 
		ISNULL(LTM.Title,'') AS LeaveType ,
		ISNULL(SUM(L1.NoOfLeave),0) AS PendingBalance
	FROM 
		sHrm.tLeaveBalance LB 
		LEFT JOIN sHrm.tLeave L ON LB.EmployeeId=L.EmployeeId AND LB.BatchId = L.BatchId AND LB.LeaveTypeId = L.LeaveTypeId AND L.StatusId = 550 
		LEFT JOIN sHrm.tLeave L1 ON LB.EmployeeId=L1.EmployeeId AND LB.BatchId = L1.BatchId AND LB.LeaveTypeId = L1.LeaveTypeId  AND L1.StatusId = 549 
		LEFT JOIN sHrm.tLeaveTypeMaster LTM ON LB.LeaveTypeId = LTM.Id 
		WHERE LB.BatchId =@rBatchId AND LB.EmployeeId = @rEmployeeId
		GROUP BY LTM.Title,LB.BalanceLeave

	END

	IF(LOWER(@Tab)='certificate')
	BEGIN
	SELECT 'Employment' AS CertificateName,CreatedDateTime,Number AS CertificateNumber FROM [sHrm].[tCertificateEmployment] WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId
		UNION ALL
		SELECT 'Experience' AS CertificateName,CreatedDateTime,Number AS CertificateNumber FROM [sHrm].[tCertificateExperience] WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId 
		UNION ALL
		SELECT 'Increment' AS CertificateName,CreatedDateTime,Number AS CertificateNumber FROM [sHrm].[tCertificateIncrement] WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId AND BatchId = @rBatchId
		UNION ALL
		SELECT 'Relieving' AS CertificateName,CreatedDateTime,Number AS CertificateNumber FROM [sHrm].[tCertificateRelieving] WHERE EmployeeId = @rEmployeeId AND OrgId = @rOrgId		
		
	END
END
GO
PRINT N'Altering [sLibrary].[pRptBookLogRegisterGet]...';


GO

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

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


GO
ALTER PROCEDURE [sPayroll].[pPayrollPaySetupImport]
	
	@rPayrollId int,
	@rFromPayrollYearId int,
	@rToPayrollYearId int,
	@rOrgGroupId int
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
BEGIN TRY 

	IF EXISTS (SELECT 1 FROM sPayroll.tPaySetup WHERE PayrollId = @rPayrollId AND PayrollYearId = @rToPayrollYearId)
	BEGIN
		SELECT -101 AS RESULT
		RETURN
	END
	
	BEGIN TRANSACTION
	DECLARE @lCount int
	DECLARE @lNextNumber int
	
	-- Pay Setup Temp Table
	CREATE TABLE #TempPaySetup(
	[AutoId] int identity,
	[ID] [int] NOT NULL,
	[SourceTypeId] [smallint] NOT NULL,
	[SourceId] [bigint] NOT NULL,
	[PayElementId] [int] NOT NULL,
	[Amount] [decimal](22, 2) NULL,
	[Percentage] [decimal](5, 2) NULL,
	[ProcessOrder] [tinyint] NOT NULL,
	[PayrollId] [int] NULL,
	[OrderIndex] [int] NULL,
	[PayrollYearId] [int] NULL,
	[DefaultAmount] [decimal](22,2) NULL,
	[Formula] [nvarchar](200) NULL
	)
	-- End Create Table
	
	INSERT INTO #TempPaySetup SELECT * FROM sPayroll.tPaySetup WHERE PayrollId = @rPayrollId AND PayrollYearId = @rFromPayrollYearId
	
	Select @lCount = COUNT(Id) From #TempPaySetup
	
	WHILE (@lCount > 0)
	BEGIN
		-- Pay Setup Entry
		
		EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sPayroll.tPaySetup', 0, 1, 1,@outNextNumber = @lNextNumber output
		
		INSERT INTO sPayroll.tPaySetup
		SELECT @lNextNumber,SourceTypeId,SourceId,PayElementId,Amount,Percentage,ProcessOrder,@rPayrollId,OrderIndex,@rToPayrollYearId,DefaultAmount,Formula
		FROM #TempPaySetup Where AutoId = @lCount
		
		-- END Pay Setup Entry
		SET @lCount = @lCount -1
	END

	DROP TABLE #TempPaySetup 
	SELECT 1 AS Result
	COMMIT TRANSACTION
END TRY

BEGIN CATCH 
DROP TABLE #TempPaySetup 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
END CATCH	
END
GO
PRINT N'Altering [sSecurity].[pEmployeePasswordAdd]...';


GO
 

ALTER PROCEDURE [sSecurity].[pEmployeePasswordAdd]
	
	@rId bigint,
	@rEmployeeId bigint,
	@rOrgGroupId smallint,
	@rOrgId smallint,
	@rName nvarchar(100),
	@rEmailId nvarchar(100),
	@rMobileNo nvarchar(20),
	@rUserName nvarchar(100),
	@rLoginPassword nvarchar(100),
	@rIsObsolete bit,
	@rCreatedUserId bigint,
	@rIsFullUpdate bit,
	@rRoleId int

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
		
		
		
		IF(@rId = 0)	
		BEGIN
			IF(@rEmployeeId <> 0)
			BEGIN
				IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE SourceTypeId = 95 AND SourceId = @rEmployeeId AND OrgId=@rOrgId)
				BEGIN
					SELECT -101 AS UserId
					RETURN
				END
			END
			
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rUserName AND OrgId = @rOrgId)
			BEGIN
				SELECT -101 AS UserId
				RETURN
			END
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT Id FROM sSecurity.tUser WHERE LoginTitle = @rUserName AND OrgId = @rOrgId AND Id<>@rId)
			BEGIN
				SELECT -101 AS UserId
				RETURN
			END
		END

		DECLARE @lOrgId int=0
		DECLARE @lUserSourceId bigint = 0
		DECLARE @rUserSourceTypeId smallint=0

		SELECT @lOrgId= OrgId,@lUserSourceId=SourceId,@rUserSourceTypeId=SourceTypeId FROM sSecurity.tUser WHERE Id =@rId

		DECLARE @lOrgGroupId int =0 
		SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @lOrgId

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

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

		--IF @lConfigValue = 'True'
		--BEGIN
		DELETE FROM sCommunication.tRegisteredUsers WHERE OrgId=@lOrgId AND UserId=@rId AND UserSourceId=@lUserSourceId AND UserSourceTypeId = @rUserSourceTypeId
		--AND DeviceToken=@rDeviceToken
		--END
		
	 DECLARE @lCurrentDateTime DATETIME
	 EXECUTE @lCurrentDateTime = sCommon.fGetDate
	 IF(@rIsFullUpdate=0)
	 BEGIN
	 UPDATE sHrm.tEmployeeCommunications
     SET
		MobileNumber=@rMobileNo,
		CompanyEmail=@rEmailId,
		UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=@lCurrentDateTime
      WHERE (EmployeeId = @rEmployeeId) 
      SELECT 1 AS Result
      RETURN
     END

	BEGIN TRY
	
	 BEGIN TRANSACTION

IF(@rId = 0)	
BEGIN
	
	DECLARE @lNextNumber BIGINT	
	EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sSecurity.tUser', 0, 101, 1,@outNextNumber = @lNextNumber output

	INSERT INTO sSecurity.tUser
		(
			Id,		
			DisplayTitle,
			LoginTitle,
			LoginPassword,
			LastLockOutDate,
			NumberOfLogonAttempt,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			OrgId,
			SourceTypeId,
			SourceId
        )
	VALUES
		(
			@lNextNumber,
			@rName,					
			@rUserName,
			@rLoginPassword,
			@lCurrentDateTime,
			0,
			@rIsObsolete,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rOrgId,
			95,
			@rEmployeeId
		)
		
		INSERT INTO sSecurity.tUserRole
		(
			RoleId,
			UserId,
			IsObsolete,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			IsPrimary
		)
		VALUES
		(
			@rRoleId,
			--sCommon.fGetIntIdForOrg(10,@rOrgGroupId),
			@lNextNumber,
			@rIsObsolete,
			@rCreatedUserId,
			@lCurrentDateTime,
			@rCreatedUserId,
			@lCurrentDateTime,
			1
		)
		              
	END	 
	 ELSE
	 BEGIN
	 
	 SET @lNextNumber = @rId
	    UPDATE  sSecurity.tUser
	    SET
			LoginTitle=@rUserName,
			LoginPassword=@rLoginPassword,
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=@lCurrentDateTime
	      WHERE (Id = @rId) 
	 END  
	 
	 UPDATE sHrm.tEmployeeCommunications
     SET
		MobileNumber=@rMobileNo,
		CompanyEmail=@rEmailId,
		UpdatedUserId=@rCreatedUserId,
		UpdatedDateTime=@lCurrentDateTime
      WHERE (EmployeeId = @rEmployeeId) 
      
		SELECT @lNextNumber AS Result
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [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')
			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
	
			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
							
							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
						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
						 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
							
							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
						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
						 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 [sStudent].[pIDNoGenerationUpdate]...';


GO
 
 
ALTER PROCEDURE [sStudent].[pIDNoGenerationUpdate]
	 
	@rStudentId bigint,
	@rIDNo nvarchar(20),
	@rCreatedUserId bigint,
	@rOrgId smallint,
	@rIsNumber bit,
	@rRecordStatusId smallint,
	@rRollNo int = 0,
	@rDivisionId int = 0,
	@rAcademicId bigint = 0
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

		   DECLARE @lCode nvarchar(20)
		   SELECT @lCode=Code FROM sStudent.tStudentMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rStudentId
		   IF @lCode IS NOT NULL
		   BEGIN
					SELECT -103 AS Result,@lCode AS Code
					RETURN
		   END 		   
		   
		 --  IF EXISTS(SELECT @lCode=Code FROM sStudent.tStudentMaster WHERE Code=@rIDNo AND OrgId=@rOrgId AND Id<>@rStudentId)
			--	BEGIN
			--	SELECT -103 AS RESULT
			--	RETURN
			--END 
	--BEGIN TRY
	-- BEGIN TRANSACTION	
	 BEGIN
	    UPDATE  sStudent.tStudentMaster
	    SET
		    Code=@rIDNo,
			Number = (CASE WHEN @rIsNumber = 0 THEN Number WHEN @rIsNumber = 1 THEN @rIDNo END), 
			RecordStatusId = @rRecordStatusId,				  
			UpdatedUserId=@rCreatedUserId,
			UpdatedDateTime=sCommon.fGetDate() 
	      WHERE Id = @rStudentId 
		  
		IF(@rAcademicId <> 0 AND @rRollNo <> 0 AND @rDivisionId <> 0)
		BEGIN
		DECLARE @lRollNo int
		SELECT @lRollNo=RollNo FROM sStudent.tAcademic WHERE RollNo=@rRollNo AND OrgId=@rOrgId AND DivisionId = @rDivisionId AND Id<>@rStudentId
		IF @lRollNo IS NOT NULL
		BEGIN
				SELECT -104 AS Result,@lRollNo AS RollNo
				RETURN
		END 

		UPDATE sStudent.tAcademic SET RollNo = @rRollNo, DivisionId = @rDivisionId WHERE Id = @rAcademicId
		END
	 END  
		SELECT 1 AS RESULT
	--	COMMIT TRANSACTION
	--END TRY
	--BEGIN CATCH 
	--	ROLLBACK TRANSACTION
	--	SELECT -1 AS RESULT
	--END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pOnlineRegistrationStudentAdd]...';


GO

ALTER PROCEDURE [sStudent].[pOnlineRegistrationStudentAdd]
	 
	@rId bigint,
	@rCode nvarchar(20),
	@rRegistrationNumber nvarchar(20),
	--@rNumber bigint,
	@rFirstName nvarchar(100),
	@rMiddleName nvarchar(100),
	@rLastName nvarchar(100),
	@rOrgId int,
	@rAdmissionCategoryId int,
	@rStatusId smallint,
	@rRecordStatusId smallint,
	@rCreatedUserId bigint,
	@rUpdatedUserId bigint,
	@rOrgGroupBatchId int =0,
	@OutStudentId BIGINT = NULL OUTPUT,
	--@rSUId nvarchar(20) = '',
	@rOrgGroupId int = 0,
	--@rMobileNo nvarchar(50)='',
	@rStudentGroupId int=0,
	@rStudentOtherGroupId int=0,
	@rDateOfBirth Date=NULL,
    @rGenderId int=0,
    @rAcademicId bigint = 0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rBatchId int=0,
	@rStudentStatusId int,
	@rStudentPhoto varbinary(max)=0,
	--Other
	@rUIDNumber nvarchar(50),
	@rBirthdateInWord nvarchar(150),
	@rTransportModeId int,
	@rBloodGroupId tinyint,
	@rBirthPlace nvarchar(150),
    @rBirthTaluka nvarchar(150),
    @rBirthDistrict nvarchar(150),
	@rFamilyCast nvarchar(100),
    @rFamilySubCast nvarchar(100),
    @rCastCategoryId int,
	@rReligionId int,
	@rHouseId int,
    @rMotherTongueId int,
	@rNationalityId int,
	@rHobby nvarchar(50),
	@rReferenceRemark nvarchar(100) = '',
	@rAdhaarNumber nvarchar(20) = '',
	@rMotherTongue nvarchar(100) = '',
	@rQuotaId int =0,
    @rbirthState nvarchar(100)='',
    @rBirthCountry nvarchar(100)='',
	@rBankAccountNumber nvarchar(20),
	@rBankName nvarchar(100),
	@rBankBranch nvarchar(100),
	@rBankIFSCCode nvarchar(20),
	@rClass9BoardRegistrationNumber nvarchar(20),
	@rClass11BoardRegistrationNumber nvarchar(20),
	@rPassportNumber nvarchar(20),
	@rPassportType nvarchar(20),
	@rPassportCountryCode nvarchar(100),
	@rPassportIssueDate date,
	@rPassportExpiryDate date,
	@rBankAccountHolderName nvarchar(200) = '',

	--Family
	@rFatherName	nvarchar(100),
	@rFatherDateOfBirth	date,
	@rFatherOccupation	nvarchar(50),
	@rFatherQualification	nvarchar(50),
	@rFatherContactNo	nvarchar(50),
	@rFatherMail	nvarchar(50),
	@rFatherOfficeAddress	nvarchar(500),
	@rFatherIncome	int,
	@rMotherName	nvarchar(100),
	@rMotherDateOfBirth	date,
	@rMotherOccupation	nvarchar(50),
	@rMotherQualification	nvarchar(50),
	@rMotherContactNo	nvarchar(50),
	@rMotherMail	nvarchar(50),
	@rMotherOfficeAddress	nvarchar(500),
	@rMotherIncome	int,
	@rRelationshipName	nvarchar(100),
	@rRelativeName	nvarchar(100),
	@rRelativeDateOfBirth	date,
	@rRelativeOccupation	nvarchar(50),
	@rRelativeQualification	nvarchar(50),
	@rRelativeContactNo	nvarchar(50),
	@rRelativeMail	nvarchar(50),
	@rRelativeOfficeAddress	nvarchar(500),
	@rRelativeIncome	int,
	@rFatherPhoto varbinary(max)=0,
	@rMotherPhoto varbinary(max)=0,
	@rRelativePhoto varbinary(max)=0,
	@rMarriageAnniversaryDate Date,
	@rLiveWithId tinyint=0,
	@rIsFatherExStudent bit=0,
	@rFatherPassOutYear nvarchar(20)='',
	@rIsMotherExStudent bit=0,
	@rMotherPassOutYear nvarchar(20)='',
	@rIsRelativeExStudent bit=0,
	@rRelativePassOutYear nvarchar(20)='',
	@rIsSingleChild bit = 0,
	@rFatherOrganization nvarchar(200),
	@rFatherDesignation nvarchar(100),
	@rMotherOrganization nvarchar(200),
	@rMotherDesignation nvarchar(100),
	@rRelativeOrganization nvarchar(200),
	@rRelativeDesignation nvarchar(100),
	@rFatherAadharNo nvarchar(20)= '',
	@rMotherAadharNo nvarchar(20)= '',
	@rFatherOfficeContactNo nvarchar(50) = '',
	@rMotherOfficeContactNo nvarchar(50) = '',

	--Communication
	@rPresentStreetOne nvarchar(150),
	@rPresentStreetTwo nvarchar(150),
	@rPresentStreetThree nvarchar(150),
	@rPresentCountry nvarchar(50),
	@rPresentState nvarchar(50),
	@rPresentCity nvarchar(50),
	@rPresentZipCode nvarchar(20),
	@rPresentContactNo nvarchar(20),
	@rPermanentStreetOne nvarchar(150),
	@rPermanentStreetTwo nvarchar(150),
	@rPermanentStreetThree nvarchar(150),
	@rPermanentCountry nvarchar(50),
	@rPermanentState nvarchar(50),
	@rPermanentCity nvarchar(50),
	@rPermanentZipCode nvarchar(20),
	@rPermanentContactNo nvarchar(20),
	@rEmergencyStreetOne nvarchar(150),
	@rEmergencyStreetTwo nvarchar(150),
	@rEmergencyStreetThree nvarchar(150),
	@rEmergencyCountry nvarchar(50),
	@rEmergencyState nvarchar(50),
	@rEmergencyCity nvarchar(50),
	@rEmergencyZipCode nvarchar(20),
	@rEmergencyContactNo nvarchar(20),
	@rParentContactNo nvarchar(20),
	@rParentEmail nvarchar(50),
	@rStudentContactNo nvarchar(50),
	@rStudentEmail nvarchar(50),
	@rPresentDistanceFromSchool decimal(10,2),
	@rStudentCustomAlert nvarchar(1000) = '',
	@rWhatsAppContactNo nvarchar(20) = '',

	--Admission
	@rPreviousSchool nvarchar(200) ,
	@rPreviousSchoolTypeId int,
	@rPreviousStudentId bigint ,
	@rAdmissionFormId bigint ,
	@rAdmissionFormNumber nvarchar(20) ,
	@rAdmissionStandardId int ,
	@rAdmissionDate date ,
	@rAdmissionYear nvarchar(10) ,
	@rLeftStandardId int ,
	@rLeftDate date ,
	@rLeftYear nvarchar(10) ,
	@rInactiveDate date ,
	@rInActiveReason nvarchar(200) ,
	@rLeftReason nvarchar(200) ,
	@rLCProgress nvarchar(200) ,
	@rLCConduct nvarchar(200) ,
	@rLCBook nvarchar(20) ,
	@rLCNumber nvarchar(20) ,
	@rLCDate date ,
	@rLCRemark nvarchar(200) ,
	@rLCCopy tinyint ,
	@rLcId bigint ,
	@rExamSeatNo nvarchar(20) ,
	@rAdmissionNumber nvarchar(50) ,
	@rIsTransfer bit ,
	@rTransferFrom nvarchar(150) ,
	@rPassingYear nvarchar(20) ,
	@rIsTFWS bit ,
	@rIsCertificateHolder bit ,
	@rCertificateName nvarchar(100),
	@rAdmissionQuotaId int ,
	@rPreviousStandard nvarchar (50),
	@rPreviousLCNumber nvarchar (50) ,
	@rPreviousLCDate date,
	@rPreviousLCResult nvarchar (50) ,
	@rProofOfDOB nvarchar (200),

	--CollegeDetail
	--@rAdmissionNumber nvarchar(50),
    --@rIsTransfer bit,
    --@rTransferFrom nvarchar(150),
    --@rPassingYear nvarchar(20),
    --@rIsTFWS bit,
    --@rIsCertificateHolder bit,
    --@rCertificateName nvarchar(100),
    @rSSCBoard nvarchar(200),
    @rSSCSchool nvarchar(200),
    @rSSCPassingYear nvarchar(10),
    @rSSCObtainMarks decimal(10,2),
    @rSSCOutOfMarks decimal(10,2),
    @rSSCPercentage decimal(10,2),
    @rSSCMathMarks decimal(10,2),
    @rSSCMathOutOfMarks decimal(10,2),
    @rHSCBoard nvarchar(200),
    @rHSCSchool nvarchar(200),
    @rHSCPassingYear nvarchar(10),
    @rHSCObtainMarks decimal(10,2),
    @rHSCOutOfMarks decimal(10,2),
    @rHSCPercentage decimal(10,2),
    @rHSCPhysicsMarks decimal(10,2),
    @rHSCPhysicsOutOfMarks decimal(10,2),
    @rHSCChemistryMarks decimal(10,2),
    @rHSCChemistryOutOfMarks decimal(10,2),
    @rHSCMathMarks decimal(10,2),
    @rHSCMathOutOfMarks decimal(10,2),
    @rHSCBiologyMarks decimal(10,2),
    @rHSCBiologyOutOfMarks decimal(10,2),
    @rPCMMarks decimal(10,2),
    @rPCBMarks decimal(10,2),
    @rJEERollNo nvarchar(20),
    @rJEEMeritNo nvarchar(20),
    @rJEEMeritMarks decimal(10,2),
    @rJEEOutOfMarks decimal(10,2),
    @rDiplomaBoard nvarchar(200),
    @rDiplomaCollege nvarchar(200),
    @rDiplomaPassingYear nvarchar(10),
    @rDiplomaObtainMarks decimal(10,2),
    @rDiplomaOutOfMarks decimal(10,2),
    @rDiplomaPercentage decimal(10,2),
    @rApplicationNo nvarchar(20),
    @rAdmissionRound nvarchar(20),
    @rMaritalStatusId tinyint,
    @rSSCPercentile decimal(10,2),
    @rSSCGrade nvarchar(20)

WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	

	Declare @rNumber bigint
	Select @rNumber = ISNULL(Max(Id),0) + 1 from sStudent.tOnlineRegistrationStudentMaster Where OrgId = @rOrgId

	IF(@rId=0)
	BEGIN		 
	 
					
			IF EXISTS (SELECT Id from sStudent.tOnlineRegistrationStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId)
			BEGIN
				SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
				RETURN
			END 
		
			IF(ISNULL(@rUIDNumber,'')!='')		
			  BEGIN
				IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND UIDNumber=@rUIDNumber)
				BEGIN
					SELECT -101 AS Result
					RETURN
				END 
			  END
		 
			IF(ISNULL(@rAdhaarNumber,'')!='')		 		 
			  BEGIN
				IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND  AdhaarNumber=@rAdhaarNumber)
					BEGIN
						SELECT -102 AS Result
						RETURN
					END 
			  END
		--END
	END
	ELSE
	BEGIN
	
		IF EXISTS (SELECT Id from sStudent.tOnlineRegistrationStudentMaster WHERE Code=@rCode AND OrgId=@rOrgId AND Id<>@rId)
		BEGIN
			SELECT -100 AS RESULT, '' AS Code, 0 AS Id 
			RETURN
		END 
	
		IF(ISNULL(@rUIDNumber,'')!='')		
		  BEGIN
			IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND UIDNumber=@rUIDNumber AND StudentId <> @rId)
			BEGIN
				SELECT -101 AS Result
				RETURN
			END 
		  END
		  
		 IF(ISNULL(@rAdhaarNumber,'')!='')	
		  BEGIN
			IF EXISTS(SELECT 1 FROM sStudent.tStudentOther SO INNER JOIN sStudent.tStudentMaster SM ON SM.Id = SO.StudentId WHERE SM.OrgId = LEFT(@rBatchId,4) AND AdhaarNumber=@rAdhaarNumber AND StudentId <> @rId)
				BEGIN
					SELECT -102 AS Result
					RETURN
				END 
		  END
	END

	BEGIN TRY
	
	 BEGIN TRANSACTION	
	IF(@rId=0)
	BEGIN	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tOnlineRegistrationStudentMaster', 0, 1, 1,@outNextNumber = @lNextNumber output
	--PRINT(@lNextNumber)
	IF(@rNumber=0)
	BEGIN
	SET @rNumber=@lNextNumber
	END
	INSERT INTO sStudent.tOnlineRegistrationStudentMaster
		(
			Id,
			Code,
			Number,
			RegistrationNumber,
			FirstName,
			MiddleName,
			LastName,
			OrgId,
			--DepartmentId,
			AdmissionCategoryId,
			StatusId,
			RecordStatusId,
			CreatedUserId,
			CreatedDateTime,
			ClassId,
			DivisionId,
			RollNo,
			BatchId,
			StudentStatusId,
			StudentPhoto
		)
	VALUES
		(
			@lNextNumber,
			@rCode,
			@rNumber,
			@rRegistrationNumber,
			@rFirstName,
			@rMiddleName,
			@rLastName,
			@rOrgId,
			--@rDepartmentId,
			@rAdmissionCategoryId,
			@rStatusId,
			@rRecordStatusId,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rClassId,
			@rDivisionId,
			@rRollNo,
			@rBatchId,
			@rStudentStatusId,
			@rStudentPhoto
			
		)
		
	INSERT INTO sStudent.tOnlineRegistrationStudentOther
		(
			StudentId,
			UIDNumber,
			DateOfBirth,
			BirthDateInWord,
			TransportModeId,
			GenderId,
			BloodGroupId,
			BirthPlace,
			BirthTaluka,
			BirthDistrict,
			FamilyCast,
			FamilySubCast,
			CastCategoryId,
			ReligionId,
			HouseId,
			MotherTongueId,
			NationalityId,
			Hobby,
			CreatedUserId,
			CreatedDateTime,
			ReferenceRemark,
			AdhaarNumber,
			MotherTongue,
			QuotaId,
			BirthState,
			BirthCountry,
			BankAccountNumber,
			BankName,
			BankBranch,
			BankIFSCCode,
			Class9BoardRegistrationNumber,
			Class11BoardRegistrationNumber,
			PassportNumber,
			PassportType,
			PassportCountryCode,
			PassportIssueDate,
			PassportExpiryDate,
			BankAccountHolderName

		)
		VALUES
		(
			@lNextNumber,
			@rUIDNumber,
			@rDateOfBirth,
			@rBirthDateInWord,
			@rTransportModeId,
			@rGenderId,
			@rBloodGroupId,
			@rBirthPlace,
			@rBirthTaluka,
			@rBirthDistrict,
			@rFamilyCast,
			@rFamilySubCast,
			@rCastCategoryId,
			@rReligionId,
			@rHouseId,
			@rMotherTongueId,
			@rNationalityId,
			@rHobby,
			@rCreatedUserId,
			sCommon.fGetDate(),
		    @rReferenceRemark,
			@rAdhaarNumber,
			@rMotherTongue,
			@rQuotaId,
			@rBirthState,
			@rBirthCountry,
			@rBankAccountNumber,
			@rBankName,
			@rBankBranch,
			@rBankIFSCCode,
			@rClass9BoardRegistrationNumber,
			@rClass11BoardRegistrationNumber,
			@rPassportNumber,
			@rPassportType,
			@rPassportCountryCode,
			@rPassportIssueDate,
			@rPassportExpiryDate,
			@rBankAccountHolderName
		)
	
	INSERT INTO sStudent.tOnlineRegistrationStudentFamily
           (StudentId
           ,FatherName
           ,FatherDateOfBirth
           ,FatherOccupation
           ,FatherQualification
           ,FatherContactNo
           ,FatherMail
           ,FatherOfficeAddress
           ,FatherIncome
           ,MotherName
           ,MotherDateOfBirth
           ,MotherOccupation
           ,MotherQualification
           ,MotherContactNo
           ,MotherMail
           ,MotherOfficeAddress
           ,MotherIncome
           ,RelationshipName
           ,RelativeName
           ,RelativeDateOfBirth
           ,RelativeOccupation
           ,RelativeQualification
           ,RelativeContactNo
           ,RelativeMail
           ,RelativeOfficeAddress
           ,RelativeIncome
           ,CreatedUserId
           ,CreatedDateTime
           ,FatherPhoto
           ,MotherPhoto
           ,RelativePhoto
           ,MarriageAnniversaryDate
           ,LiveWithId
           ,IsFatherExStudent
           ,FatherPassOutYear
           ,IsMotherExStudent
           ,MotherPassOutYear
           ,IsRelativeExStudent
           ,RelativePassOutYear
           ,IsSingleChild
           ,FatherOrganization
           ,FatherDesignation
           ,MotherOrganization
           ,MotherDesignation
           ,RelativeOrganization
           ,RelativeDesignation
           ,FatherAdhaarNumber
           ,MotherAdhaarNumber
           ,FatherOfficeContactNo
           ,MotherOfficeContactNo)
     VALUES
			(@lNextNumber,
			@rFatherName,
			@rFatherDateOfBirth,
			@rFatherOccupation,
			@rFatherQualification,
			@rFatherContactNo,
			@rFatherMail,
			@rFatherOfficeAddress,
			@rFatherIncome,
			@rMotherName,
			@rMotherDateOfBirth,
			@rMotherOccupation,
			@rMotherQualification,
			@rMotherContactNo,
			@rMotherMail,
			@rMotherOfficeAddress,
			@rMotherIncome,
			@rRelationshipName,
			@rRelativeName,
			@rRelativeDateOfBirth,
			@rRelativeOccupation,
			@rRelativeQualification,
			@rRelativeContactNo,
			@rRelativeMail,
			@rRelativeOfficeAddress,
			@rRelativeIncome,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rFatherPhoto,
			@rMotherPhoto,
			@rRelativePhoto,
			@rMarriageAnniversaryDate,
			@rLiveWithId,
			@rIsFatherExStudent,
			@rFatherPassOutYear,
			@rIsMotherExStudent,
			@rMotherPassOutYear,
			@rIsRelativeExStudent,
			@rRelativePassOutYear,
			@rIsSingleChild,
			@rFatherOrganization,
			@rFatherDesignation,
			@rMotherOrganization,
			@rMotherDesignation,
			@rRelativeOrganization,
			@rRelativeDesignation,
			@rFatherAadharNo,
			@rMotherAadharNo,
			@rFatherOfficeContactNo,
			@rMotherOfficeContactNo
			)	

	INSERT INTO sStudent.tOnlineRegistrationStudentCommunication
		(
			StudentId,
			PresentStreetOne,
			PresentStreetTwo,
			PresentStreetThree,
			PresentCountry,
			PresentState,
			PresentCity,
			PresentZipCode,
			PresentContactNo,
			PermanentStreetOne,
			PermanentStreetTwo,
			PermanentStreetThree,
			PermanentCountry,
			PermanentState,
			PermanentCity,
			PermanentZipCode,
			PermanentContactNo,
			EmergencyStreetOne,
			EmergencyStreetTwo,
			EmergencyStreetThree,
			EmergencyCountry,
			EmergencyState,
			EmergencyCity,
			EmergencyZipCode,
			EmergencyContactNo,
			ParentContactNo,
			ParentEmail,
			StudentContactNo,
			StudentEmail,
			CreatedUserId,
			CreatedDateTime,
			PresentDistanceFromSchool,
			StudentCustomAlert
			--WhatsAppContactNo
		)
	VALUES
		(
			@lNextNumber,
			@rPresentStreetOne,
			@rPresentStreetTwo,
			@rPresentStreetThree,
			@rPresentCountry,
			@rPresentState,
			@rPresentCity,
			@rPresentZipCode,
			@rPresentContactNo,
			@rPermanentStreetOne,
			@rPermanentStreetTwo,
			@rPermanentStreetThree,
			@rPermanentCountry,
			@rPermanentState,
			@rPermanentCity,
			@rPermanentZipCode,
			@rPermanentContactNo,
			@rEmergencyStreetOne,
			@rEmergencyStreetTwo,
			@rEmergencyStreetThree,
			@rEmergencyCountry,
			@rEmergencyState,
			@rEmergencyCity,
			@rEmergencyZipCode,
			@rEmergencyContactNo,
			@rParentContactNo,
			@rParentEmail,
			@rStudentContactNo,
			@rStudentEmail,
			@rCreatedUserId,
			sCommon.fGetDate(),
			@rPresentDistanceFromSchool,
			@rStudentCustomAlert
			--@rWhatsAppContactNo
			
		)

	INSERT INTO sStudent.tOnlineRegistrationStudentAdmission
           (
		   StudentId,
           PreviousSchool,
           PreviousSchoolTypeId,
           PreviousStudentId,
           --AdmissionFormId,
           AdmissionFormNumber,
           AdmissionStandardId,
           AdmissionDate,
           AdmissionYear,
           LeftStandardId,
           LeftDate,
           LeftYear,
           InactiveDate,
           InActiveReason,
           LeftReason,
           LCProgress,
           LCConduct,
           LCBook,
           LCNumber,
           LCDate,
           LCRemark,
           LCCopy,
           LcId,
           CreatedUserId,
           CreatedDateTime,
           ExamSeatNo,
           AdmissionNumber,
           IsTransfer,
           TransferFrom,
           PassingYear,
           IsTFWS,
           IsCertificateHolder,
           CertificateName,
           AdmissionQuotaId,
           PreviousStandard,
           PreviousLCNumber,
           PreviousLCDate,
           PreviousLCResult,
           ProofOfDOB
		   )
     VALUES
           (
		   @lNextNumber,
           @rPreviousSchool,
           @rPreviousSchoolTypeId,
           @rPreviousStudentId,
          -- @rAdmissionFormId,
           @rAdmissionFormNumber,
           @rAdmissionStandardId,
           @rAdmissionDate,
           @rAdmissionYear,
           @rLeftStandardId,
           @rLeftDate,
           @rLeftYear,
           @rInactiveDate,
           @rInActiveReason,
           @rLeftReason,
           @rLCProgress,
           @rLCConduct,
           @rLCBook,
           @rLCNumber,
           @rLCDate,
           @rLCRemark,
           @rLCCopy,
           @rLcId,
           @rCreatedUserId,
		   sCommon.fGetDate(),
           @rExamSeatNo,
           @rAdmissionNumber,
           @rIsTransfer,
           @rTransferFrom,
           @rPassingYear,
           @rIsTFWS,
           @rIsCertificateHolder,
           @rCertificateName,
           @rAdmissionQuotaId,
           @rPreviousStandard,
           @rPreviousLCNumber,
           @rPreviousLCDate,
           @rPreviousLCResult,
           @rProofOfDOB
		   )

	INSERT INTO sStudent.tOnlineRegistrationCollegeDetail
           (
		   StudentId,
           --AdmissionNumber,
           --IsTransfer,
           --TransferFrom,
           --PassingYear,
           --IsTFWS,
           --IsCertificateHolder,
           --CertificateName,
           SSCBoard,
           SSCSchool,
           SSCPassingYear,
           SSCObtainMarks,
           SSCOutOfMarks,
           SSCPercentage,
           SSCMathMarks,
           SSCMathOutOfMarks,
           HSCBoard,
           HSCSchool,
           HSCPassingYear,
           HSCObtainMarks,
           HSCOutOfMarks,
           HSCPercentage,
           HSCPhysicsMarks,
           HSCPhysicsOutOfMarks,
           HSCChemistryMarks,
           HSCChemistryOutOfMarks,
           HSCMathMarks,
           HSCMathOutOfMarks,
           HSCBiologyMarks,
           HSCBiologyOutOfMarks,
           PCMMarks,
           PCBMarks,
           JEERollNo,
           JEEMeritNo,
           JEEMeritMarks,
           JEEOutOfMarks,
           DiplomaBoard,
           DiplomaCollege,
           DiplomaPassingYear,
           DiplomaObtainMarks,
           DiplomaOutOfMarks,
           DiplomaPercentage,
           ApplicationNo,
           AdmissionRound,
           MaritalStatusId,
           SSCPercentile,
           SSCGrade
		   )
     VALUES
           (
		   @lNextNumber,
           --@rAdmissionNumber,
           --@rIsTransfer,
           --@rTransferFrom,
           --@rPassingYear,
           --@rIsTFWS,
           --@rIsCertificateHolder,
           --@rCertificateName,
           @rSSCBoard,
           @rSSCSchool,
           @rSSCPassingYear,
           @rSSCObtainMarks,
           @rSSCOutOfMarks,
           @rSSCPercentage,
           @rSSCMathMarks,
           @rSSCMathOutOfMarks,
           @rHSCBoard,
           @rHSCSchool,
           @rHSCPassingYear,
           @rHSCObtainMarks,
           @rHSCOutOfMarks,
           @rHSCPercentage,
           @rHSCPhysicsMarks,
           @rHSCPhysicsOutOfMarks,
           @rHSCChemistryMarks,
           @rHSCChemistryOutOfMarks,
           @rHSCMathMarks,
           @rHSCMathOutOfMarks,
           @rHSCBiologyMarks,
           @rHSCBiologyOutOfMarks,
           @rPCMMarks,
           @rPCBMarks,
           @rJEERollNo,
           @rJEEMeritNo,
           @rJEEMeritMarks,
           @rJEEOutOfMarks,
           @rDiplomaBoard,
           @rDiplomaCollege,
           @rDiplomaPassingYear,
           @rDiplomaObtainMarks,
           @rDiplomaOutOfMarks,
           @rDiplomaPercentage,
           @rApplicationNo,
           @rAdmissionRound,
           @rMaritalStatusId,
           @rSSCPercentile,
           @rSSCGrade
		   )
		      
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rId
			IF(@rNumber=0)
			BEGIN
			SET  @rNumber=(SELECT ISnull(Number,0) FROM sStudent.tOnlineRegistrationStudentMaster WHERE  Id=@rId)
			IF(@rNumber=0)
			SET @rNumber=@lNextNumber
			END
	    UPDATE  sStudent.tOnlineRegistrationStudentMaster
	    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(),
			ClassId=@rClassId,
			DivisionId=@rDivisionId,
			RollNo=@rRollNo,
			BatchId=@rBatchId
			--StudentGroupId=@rStudentGroupId ,
		 --   StudentOtherGroupId=@rStudentOtherGroupId
	      
	      WHERE Id = @rId 
	      
	    UPDATE  sStudent.tOnlineRegistrationStudentOther
		SET
			UIDNumber =@rUIDNumber,
			DateOfBirth=@rDateOfBirth,
			BirthDateInWord=@rBirthDateInWord,
			TransportModeId=@rTransportModeId,
			GenderId=@rGenderId,
			BloodGroupId=@rBloodGroupId,
			BirthPlace=@rBirthPlace,
			BirthTaluka=@rBirthTaluka,
			BirthDistrict=@rBirthDistrict,
			FamilyCast=@rFamilyCast,
			FamilySubCast=@rFamilySubCast,
			CastCategoryId=@rCastCategoryId,
			ReligionId=@rReligionId,
			HouseId=@rHouseId,
			MotherTongueId=@rMotherTongueId,
			NationalityId=@rNationalityId,
			Hobby=@rHobby,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			ReferenceRemark=@rReferenceRemark,
			AdhaarNumber=@rAdhaarNumber,
			MotherTongue=@rMotherTongue,
			QuotaId=@rQuotaId,
			BirthState=@rBirthState,
			BirthCountry=@rBirthCountry,
			BankAccountNumber=@rBankAccountNumber,
			BankName=@rBankName,
			BankBranch=@rBankBranch,
			BankIFSCCode=@rBankIFSCCode,
			Class9BoardRegistrationNumber=@rClass9BoardRegistrationNumber,
			Class11BoardRegistrationNumber=@rClass11BoardRegistrationNumber,
			PassportNumber=@rPassportNumber,
			PassportType=@rPassportType,
			PassportCountryCode=@rPassportCountryCode,
			PassportIssueDate=@rPassportIssueDate,
			PassportExpiryDate=@rPassportExpiryDate,
			BankAccountHolderName=@rBankAccountHolderName
	       
	      WHERE StudentId = @rId 
	     
		UPDATE sStudent.tOnlineRegistrationStudentFamily 
	SET
           FatherName=@rFatherName,
           FatherDateOfBirth=@rFatherDateOfBirth,
           FatherOccupation=@rFatherOccupation,
           FatherQualification=@rFatherQualification,
           FatherContactNo=@rFatherContactNo,
           FatherMail=@rFatherMail,
           FatherOfficeAddress=@rFatherOfficeAddress,
           FatherIncome=@rFatherIncome,
           MotherName=@rMotherName,
           MotherDateOfBirth=@rMotherDateOfBirth,
           MotherOccupation=@rMotherOccupation,
           MotherQualification=@rMotherQualification,
           MotherContactNo=@rMotherContactNo,
           MotherMail=@rMotherMail,
           MotherOfficeAddress=@rMotherOfficeAddress,
           MotherIncome=@rMotherIncome,
           RelationshipName=@rRelationshipName,
           RelativeName=@rRelativeName,
           RelativeDateOfBirth=@rRelativeDateOfBirth,
           RelativeOccupation=@rRelativeOccupation,
           RelativeQualification=@rRelativeQualification,
           RelativeContactNo=@rRelativeContactNo,
           RelativeMail=@rRelativeMail,
           RelativeOfficeAddress=@rRelativeOfficeAddress,
           RelativeIncome=@rRelativeIncome,
           UpdatedUserId=@rUpdatedUserId,
           UpdatedDateTime=sCommon.fGetDate(),
           FatherPhoto=@rFatherPhoto,
           MotherPhoto=@rMotherPhoto,
           RelativePhoto=@rRelativePhoto,
           MarriageAnniversaryDate=@rMarriageAnniversaryDate,
           LiveWithId=@rLiveWithId,
           IsFatherExStudent=@rIsFatherExStudent,
           FatherPassOutYear=@rFatherPassOutYear,
           IsMotherExStudent=@rIsMotherExStudent,
           MotherPassOutYear=@rMotherPassOutYear,
           IsRelativeExStudent=@rIsRelativeExStudent,
           RelativePassOutYear=@rRelativePassOutYear,
           IsSingleChild=@rIsSingleChild,
           FatherOrganization=@rFatherOrganization,
           FatherDesignation=@rFatherDesignation,
           MotherOrganization=@rMotherOrganization,
           MotherDesignation=@rMotherDesignation,
           RelativeOrganization=@rRelativeOrganization,
           RelativeDesignation=@rRelativeDesignation,
           FatherAdhaarNumber=@rFatherAadharNo,
           MotherAdhaarNumber=@rMotherAadharNo,
           FatherOfficeContactNo=@rFatherOfficeContactNo,
           MotherOfficeContactNo=@rMotherOfficeContactNo
	      WHERE StudentId = @rId 

		UPDATE  sStudent.tOnlineRegistrationStudentCommunication
	    SET
			
			PresentStreetOne=@rPresentStreetOne, 
			PresentStreetTwo=@rPresentStreetTwo, 
			PresentStreetThree=@rPresentStreetThree,
			PresentCountry=@rPresentCountry,
			PresentState=@rPresentState,
			PresentCity=@rPresentCity,
			PresentZipCode=@rPresentZipCode,
			PresentContactNo=@rPresentContactNo,
			PermanentStreetOne=@rPermanentStreetOne,
			PermanentStreetTwo=@rPermanentStreetTwo,
			PermanentStreetThree=@rPermanentStreetThree,
			PermanentCountry=@rPermanentCountry,
			PermanentState=@rPermanentState,
			PermanentCity=@rPermanentCity,
			PermanentZipCode=@rPermanentZipCode,
			PermanentContactNo=@rPermanentContactNo,
			EmergencyStreetOne=@rEmergencyStreetOne,
			EmergencyStreetTwo=@rEmergencyStreetTwo,
			EmergencyStreetThree=@rEmergencyStreetThree,
			EmergencyCountry=@rEmergencyCountry,
			EmergencyState=@rEmergencyState,
			EmergencyCity=@rEmergencyCity,
			EmergencyZipCode=@rEmergencyZipCode,
			EmergencyContactNo=@rEmergencyContactNo,
			ParentContactNo=@rParentContactNo,
			ParentEmail=@rParentEmail,
			StudentContactNo=@rStudentContactNo,
			StudentEmail=@rStudentEmail,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate(),
			PresentDistanceFromSchool=@rPresentDistanceFromSchool,
			StudentCustomAlert = @rStudentCustomAlert,
			WhatsAppContactNo = @rWhatsAppContactNo
	      
	     WHERE StudentId = @rId 	

		UPDATE sStudent.tOnlineRegistrationStudentAdmission
		
		SET 
          PreviousSchool = @rPreviousSchool ,
		  PreviousSchoolTypeId = @rPreviousSchoolTypeId ,
		  PreviousStudentId = @rPreviousStudentId ,
		 -- AdmissionFormId = @rAdmissionFormId ,
		  AdmissionFormNumber = @rAdmissionFormNumber,
		  AdmissionStandardId = @rAdmissionStandardId,
		  AdmissionDate = @rAdmissionDate,
		  AdmissionYear = @rAdmissionYear,
		  LeftStandardId = @rLeftStandardId,
		  LeftDate = @rLeftDate,
		  LeftYear = @rLeftYear,
		  InactiveDate = @rInactiveDate, 
		  InActiveReason = @rInActiveReason,
		  LeftReason = @rLeftReason,
		  LCProgress = @rLCProgress,
		  LCConduct = @rLCConduct,
		  LCBook = @rLCBook,
		  LCNumber = @rLCNumber,
		  LCDate = @rLCDate,
		  LCRemark = @rLCRemark,
		  LCCopy = @rLCCopy,
		  LcId = @rLcId,
		  UpdatedUserId=@rUpdatedUserId,
		  UpdatedDateTime=sCommon.fGetDate(),
		  ExamSeatNo = @rExamSeatNo,
		  AdmissionNumber = @rAdmissionNumber,
		  IsTransfer = @rIsTransfer,
		  TransferFrom = @rTransferFrom,
		  PassingYear = @rPassingYear,
		  IsTFWS = @rIsTFWS,
		  IsCertificateHolder = @rIsCertificateHolder,
		  CertificateName = @rCertificateName,
		  AdmissionQuotaId = @rAdmissionQuotaId,
		  PreviousStandard = @rPreviousStandard,
		  PreviousLCNumber = @rPreviousLCNumber,
		  PreviousLCDate = @rPreviousLCDate,
		  PreviousLCResult = @rPreviousLCResult,
		  ProofOfDOB = @rProofOfDOB
		WHERE StudentId = @rId 
		
		UPDATE sStudent.tOnlineRegistrationCollegeDetail

		SET
           --AdmissionNumber = @rAdmissionNumber,
           --IsTransfer = @rIsTransfer,
           --TransferFrom = @rTransferFrom,
           --PassingYear = @rPassingYear,
           --IsTFWS = @rIsTFWS,
           --IsCertificateHolder = @rIsCertificateHolder,
           --CertificateName = @rCertificateName,
           SSCBoard = @rSSCBoard,
           SSCSchool =@rSSCSchool,
           SSCPassingYear =@rSSCPassingYear,
           SSCObtainMarks = @rSSCObtainMarks,
           SSCOutOfMarks = @rSSCOutOfMarks,
           SSCPercentage = @rSSCPercentage,
           SSCMathMarks = @rSSCMathMarks,
           SSCMathOutOfMarks = @rSSCMathOutOfMarks,
           HSCBoard = @rHSCBoard,
           HSCSchool = @rHSCSchool,
           HSCPassingYear = @rHSCPassingYear,
           HSCObtainMarks = @rHSCObtainMarks,
           HSCOutOfMarks = @rHSCOutOfMarks,
           HSCPercentage = @rHSCPercentage,
           HSCPhysicsMarks = @rHSCPhysicsMarks,
           HSCPhysicsOutOfMarks = @rHSCPhysicsOutOfMarks,
           HSCChemistryMarks = @rHSCChemistryMarks,
           HSCChemistryOutOfMarks = @rHSCChemistryOutOfMarks,
           HSCMathMarks = @rHSCMathMarks,
           HSCMathOutOfMarks = @rHSCMathOutOfMarks,
           HSCBiologyMarks = @rHSCBiologyMarks,
           HSCBiologyOutOfMarks = @rHSCBiologyOutOfMarks,
           PCMMarks = @rPCMMarks,
           PCBMarks = @rPCBMarks,
           JEERollNo = @rJEERollNo,
           JEEMeritNo = @rJEEMeritNo,
           JEEMeritMarks = @rJEEMeritMarks,
           JEEOutOfMarks = @rJEEOutOfMarks,
           DiplomaBoard = @rDiplomaBoard,
           DiplomaCollege = @rDiplomaCollege,
           DiplomaPassingYear =@rDiplomaPassingYear,
           DiplomaObtainMarks = @rDiplomaObtainMarks,
           DiplomaOutOfMarks = @rDiplomaOutOfMarks,
           DiplomaPercentage = @rDiplomaPercentage,
           ApplicationNo = @rApplicationNo,
           AdmissionRound = @rAdmissionRound,
           MaritalStatusId = @rMaritalStatusId,
           SSCPercentile = @rSSCPercentile,
           SSCGrade =@rSSCGrade
		   WHERE StudentId = @rId

	 --    IF(@rStatusId=3)
		--BEGIN
		--    UPDATE sSecurity.tUser
		--	   SET IsObsolete=1 
		--	WHERE SourceTypeId=2003 AND SourceId=@rId
		--END
	 END  
	 
		SET @OutStudentId = @lNextNumber
	  SELECT 1 AS Result, @rCode AS Code, @lNextNumber AS Id 
		--SELECT @lNextNumber AS Result
	
	
	
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
		
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pOnlineStudentSearchGet]...';


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

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

	SELECT 
			SM.Id AS StudentId,
			SM.Code,
			SM.FirstName,
			SM.MiddleName,
			SM.LastName,
			SM.ClassId,
			SM.DivisionId,
			SM.FirstName +' '+SM.MiddleName +' '+SM.LastName AS Name,
			SM.RollNo,
			(CM.DisplayTitle+'-'+DM.DisplayTitle) AS ClassDivision,
			CM.DisplayTitle AS ClassName,
			DM.DisplayTitle AS DivisionName,
			SM.StudentStatusId,
            SM.OrgId,
			SM.StatusId,
			SM.RecordStatusId,
			SM.AdmissionCategoryId,
			SM.RegistrationNumber,
			SM.BatchId,
			(CASE WHEN SM.StatusId =1 THEN 'Active'
			WHEN SM.StatusId =2 THEN 'InActive'
			WHEN SM.StatusId =2 THEN 'Left' ELSE '' END) AS StatusName,
			SM.StudentPhoto,

			--Other
			SO.UIDNumber,
			ISNULL(SO.DateOfBirth,'0001/01/01')AS DateOfBirth,
			SO.BirthDateInWord,
			SO.TransportModeId,
			SO.GenderId,
			SO.BloodGroupId,
			SO.BirthPlace,
			SO.BirthTaluka,
			SO.BirthDistrict,
			SO.FamilyCast,
			SO.FamilySubCast,
			SO.CastCategoryId,
			SO.ReligionId,
			SO.HouseId,
			SO.MotherTongueId,
			SO.NationalityId,
			SO.Hobby,
			SO.CreatedUserId,
			--SO.CreatedDateTime,
			SO.UpdatedUserId,
			--SO.UpdatedDateTime,
			SO.ReferenceRemark,
			SO.AdhaarNumber,
			SO.MotherTongue,
			SO.QuotaId,
			SO.BirthState,
			SO.BirthCountry,
			SO.BankAccountNumber,
			SO.BankName,
			SO.BankBranch,
			SO.BankIFSCCode,
			SO.Class9BoardRegistrationNumber,
			SO.Class11BoardRegistrationNumber,
			SO.PassportNumber,
			SO.PassportType,
			SO.PassportCountryCode,
			ISNULL(SO.PassportIssueDate,'0001/01/01')AS PassportIssueDate,
			ISNULL(SO.PassportExpiryDate,'0001/01/01')AS PassportExpiryDate,
			SO.BankAccountHolderName,

			--Family

			SF.FatherName,
			ISNULL(SF.FatherDateOfBirth ,'0001/01/01')AS FatherDateOfBirth,
			SF.FatherOccupation,
			SF.FatherQualification,
			SF.FatherContactNo,
			SF.FatherMail,
			SF.FatherOfficeAddress,
			SF.FatherIncome,
			SF.MotherName,
			ISNULL(SF.MotherDateOfBirth ,'0001/01/01')AS MotherDateOfBirth,
			SF.MotherOccupation,
			SF.MotherQualification,
			SF.MotherContactNo,
			SF.MotherMail,
			SF.MotherOfficeAddress,
			SF.MotherIncome,
			SF.RelationshipName,
			SF.RelativeName,
			ISNULL(SF.RelativeDateOfBirth ,'0001/01/01')AS RelativeDateOfBirth,
			SF.RelativeOccupation,
			SF.RelativeQualification,
			SF.RelativeContactNo,
			SF.RelativeMail,
			SF.RelativeOfficeAddress,
			SF.RelativeIncome,
			SF.FatherPhoto,
			SF.MotherPhoto,
			SF.RelativePhoto,
			ISNULL(SF.MarriageAnniversaryDate ,'0001/01/01')AS MarriageAnniversaryDate,
			SF.LiveWithId,
			SF.IsFatherExStudent,
			SF.FatherPassOutYear,
			SF.IsMotherExStudent,
			SF.MotherPassOutYear,
			SF.IsRelativeExStudent,
			SF.RelativePassOutYear,
			SF.IsSingleChild,
			SF.FatherOrganization,
			SF.FatherDesignation,
			SF.MotherOrganization,
			SF.MotherDesignation,
			SF.RelativeOrganization,
			SF.RelativeDesignation,
			SF.FatherAdhaarNumber,
			SF.MotherAdhaarNumber,
			SF.FatherOfficeContactNo,
			SF.MotherOfficeContactNo,

			--Admission
			SA.PreviousSchool,
			SA.PreviousSchoolTypeId,
			SA.PreviousStudentId,
			SA.AdmissionFormNumber,
			SA.AdmissionStandardId,
			ISNULL(SA.AdmissionDate ,'0001/01/01')AS AdmissionDate,
			SA.AdmissionYear,
			SA.LeftStandardId,
			ISNULL(SA.LeftDate ,'0001/01/01')AS LeftDate,
			SA.LeftYear,
			ISNULL(SA.InactiveDate ,'0001/01/01')AS InactiveDate,
			SA.InActiveReason,
			SA.LeftReason,
			SA.LCProgress,
			SA.LCConduct,
			SA.LCBook,
			SA.LCNumber,
			ISNULL(SA.LCDate ,'0001/01/01')AS LCDate,
			SA.LCRemark,
			SA.LCCopy,
			SA.LcId,
			SA.ExamSeatNo,
			SA.AdmissionNumber,
			SA.IsTransfer,
			SA.TransferFrom,
			SA.PassingYear,
			SA.IsTFWS,
			SA.IsCertificateHolder,
			SA.CertificateName,
			SA.AdmissionQuotaId,
			SA.PreviousStandard,
			SA.PreviousLCNumber,
			ISNULL(SA.PreviousLCDate ,'0001/01/01')AS PreviousLCDate,
			SA.PreviousLCResult,
			SA.ProofOfDOB,

			--Communication
			SC.PresentStreetOne,
			SC.PresentStreetTwo,
			SC.PresentStreetThree,
			SC.PresentCountry,
			SC.PresentState,
			SC.PresentCity,
			SC.PresentZipCode,
			SC.PresentContactNo,
			SC.PermanentStreetOne,
			SC.PermanentStreetTwo,
			SC.PermanentStreetThree,
			SC.PermanentCountry,
			SC.PermanentState,
			SC.PermanentCity,
			SC.PermanentZipCode,
			SC.PermanentContactNo,
			SC.EmergencyStreetOne,
			SC.EmergencyStreetTwo,
			SC.EmergencyStreetThree,
			SC.EmergencyCountry,
			SC.EmergencyState,
			SC.EmergencyCity,
			SC.EmergencyZipCode,
			SC.EmergencyContactNo,
			SC.ParentContactNo,
			SC.ParentEmail,
			SC.StudentContactNo,
			SC.StudentEmail,
			SC.PresentDistanceFromSchool,
			SC.StudentCustomAlert,
			SC.WhatsAppContactNo,

			--College
			SCD.SSCBoard,
			SCD.SSCSchool,
			SCD.SSCPassingYear,
			SCD.SSCObtainMarks,
			SCD.SSCOutOfMarks,
			SCD.SSCPercentage,
			SCD.SSCMathMarks,
			SCD.SSCMathOutOfMarks,
			SCD.HSCBoard,
			SCD.HSCSchool,
			SCD.HSCPassingYear,
			SCD.HSCObtainMarks,
			SCD.HSCOutOfMarks,
			SCD.HSCPercentage,
			SCD.HSCPhysicsMarks,
			SCD.HSCPhysicsOutOfMarks,
			SCD.HSCChemistryMarks,
			SCD.HSCChemistryOutOfMarks,
			SCD.HSCMathMarks,
			SCD.HSCMathOutOfMarks,
			SCD.HSCBiologyMarks,
			SCD.HSCBiologyOutOfMarks,
			SCD.PCMMarks,
			SCD.PCBMarks,
			SCD.JEERollNo,
			SCD.JEEMeritNo,
			SCD.JEEMeritMarks,
			SCD.JEEOutOfMarks,
			SCD.DiplomaBoard,
			SCD.DiplomaCollege,
			SCD.DiplomaPassingYear,
			SCD.DiplomaObtainMarks,
			SCD.DiplomaOutOfMarks,
			SCD.DiplomaPercentage,
			SCD.ApplicationNo,
			SCD.AdmissionRound,
			SCD.MaritalStatusId,
			SCD.SSCPercentile,
			SCD.SSCGrade,

			OM.Title AS OrgName,
			BM.Title AS BatchName,
			StM.Title AS RecordStatus,
			GM.Title AS Gender,
			RM.Title AS Religion,
			BGM.Title AS BloodGroup,
			CCM.Title AS CastCategory,
			HM.Title AS House,
			MT.Title AS MotherTongue,
			CM1.Nationality AS Nationality,
			TM.Title AS Transport,
			QM.Title AS Quota,
			LWM.Title AS LiveWith

			--ACM.Title AS AdmissionCategory,
			--CM.Title AS AdmissionStandard
  FROM 
         sStudent.tOnlineRegistrationStudentMaster SM    
		 INNER JOIN sSetup.tClassMaster CM ON CM.Id=SM.ClassId
	     INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=SM.DivisionId  
		 LEFT JOIN sStudent.tOnlineRegistrationStudentOther SO ON SM.Id = SO.StudentId
		 LEFT JOIN sStudent.tOnlineRegistrationStudentFamily SF ON SM.Id = SF.StudentId
		 LEFT JOIN sStudent.tOnlineRegistrationStudentAdmission SA ON SM.Id = SA.StudentId
		 LEFT JOIN sStudent.tOnlineRegistrationStudentCommunication SC ON SM.Id = SC.StudentId
		 LEFT JOIN sStudent.tOnlineRegistrationCollegeDetail SCD on SM.Id = SCD.StudentId
		 INNER JOIN sSetup.tOrganizationMaster OM ON SM.OrgId = OM.Id
		 INNER JOIN sSetup.tBatchMaster BM ON SM.BatchId = BM.Id
		 LEFT JOIN sCommon.tStatusMaster StM ON SM.RecordStatusId = StM.Id
		 LEFT JOIN sCommon.tGenderMaster GM ON SO.GenderId = GM.Id
		 LEFT JOIn sCommon.tReligionMaster RM ON SO.ReligionId = RM.Id
		 LEFT JOIN sCommon.tBloodGroupMaster BGM ON SO.BloodGroupId = BGM.Id
		 LEFT JOIN sCommon.tCastCategoryMaster CCM ON SO.CastCategoryId = CCM.Id
		 LEFT JOIN sActivity.tHouseMaster HM ON SO.HouseId = HM.Id
		 LEFT JOIN sCommon.tMotherTongueMaster MT ON SO.MotherTongueId = MT.Id
		 LEFT JOIN sCommon.tCountryMaster CM1 ON SO.NationalityId = CM1.Id 
		 LEFT JOIN sTransport.tTransportMaster TM ON SO.TransportModeId = TM.Id
		 LEFT JOIn sCommon.tQuotaMaster QM ON SO.QuotaId = QM.Id
		 LEFT JOIn sCommon.tLiveWithMaster LWM ON SF.LiveWithId = LWM.Id
		 --LEFT JOIN sStudent.tAdmissionCategoryMaster ACM ON SM.AdmissionCategoryId = ACM.Id
		 --LEFT JOIN sStudent.tOnlineRegistrationStudentAdmission SA1 ON CM.Id = SA1.AdmissionStandardId
  WHERE 
		((SM.Id = @rStudentId) OR (@rStudentId = 0))
        AND((SM.Code like @rCode) OR (ISNULL(@rCode,'') = '')) 
		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((SM.ClassId=@rClassId)OR(@rClassId=0))
		AND((SM.DivisionId=@rDivisionId)OR(@rDivisionId=0))
		--AND(SM.RollNo=@rRollNo)
		AND((SM.StatusId=@rStatusId)OR(@rStatusId=0))	
		AND(SM.OrgId=@rOrgId)
		AND(SM.BatchId=@rBatchId or @rBatchId = 0)
		
ORDER BY SM.RollNo

		
END
GO
PRINT N'Altering [sWorkflow].[pLCApprovalStatusGet]...';


GO

ALTER PROCEDURE [sWorkflow].[pLCApprovalStatusGet]
			 @rCode nvarchar(50) =0,
			 @rStatusId int=0,
			 @rParticipantSourceId bigint = 0,
			 @rApprovingDepartmentId int

	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
			SELECT 

			ADM.Title AS DepartmentTitle,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.CreatedDateTime AS CreatedDateTime,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status
			--(select Title from sWorkflow.tActionStatusMaster WHERE Id=3) AS Status 
			--CASE WHEN @rStatusId= 0 THEN (select Top 1 Title from sWorkflow.tActionStatusMaster WHERE Id=3) WHEN ASM.Id = @rStatusId THEN ASM.Title  END AS Status
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
			INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
			INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
			LEFT JOIN sSecurity.tRole R ON R.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 2015
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID AND AA.ApprovingDepartmentId = @rApprovingDepartmentId
			AND ADM.Id = @rApprovingDepartmentId
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId AND((ASM.Id = @rStatusId) OR (@rStatusId =0))
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
		WHERE  (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
		 
		AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		AND FAD.ApprovingDepartmentId = @rApprovingDepartmentId

		UNION 

		SELECT 

			ADM.Title AS DepartmentTitle,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Code WHEN ParticipantSourceTypeId= 95 THEN EM.Code END AS Code ,
			CASE WHEN ParticipantSourceTypeId= 2001 THEN SA.Name WHEN ParticipantSourceTypeId= 95 THEN EM.FirstName +' '+ EM.MiddleName +' ' +EM.LastName END AS Name ,
			AR.CreatedDateTime AS CreatedDateTime,
			(CASE ISNULL(asm.Id,'') WHEN '' THEN 3 ELSE asm.Id END) AS statusId,
			(CASE ISNULL(asm.title,'') WHEN '' THEN 'Pending' ELSE asm.title END) AS status
			--(select Title from sWorkflow.tActionStatusMaster WHERE Id=3) AS Status 
			--CASE WHEN @rStatusId= 0 THEN (select Top 1 Title from sWorkflow.tActionStatusMaster WHERE Id=3) WHEN ASM.Id = @rStatusId THEN ASM.Title  END AS Status
		FROM sWorkflow.tApprovalRequest AR
			INNER JOIN sWorkflow.tFunctionalityApprovingDepartment FAD  ON AR.WorkflowFunctionalityId = FAD.WorkflowFunctionalityId 
			INNER JOIN sWorkflow.tApprovingDepartmentMaster ADM ON FAD.ApprovingDepartmentId = ADM.Id
			INNER JOIN sWorkflow.tFunctionalityApprovingAuthority FAA ON ADM.Id = FAA.FunctionalityApprovingDepartmentId
			LEFT JOIN sSecurity.tUser U ON U.Id = FAA.AuthoritySourceId AND FAA.AuthoritySourceTypeId = 1019
			LEFT JOIN sWorkflow.tApprovalAction AA ON AA.ApprovalRequestId = AR.Id AND AA.ApprovingDepartmentId = ADM.ID  AND AA.ApprovingDepartmentId = @rApprovingDepartmentId
			AND ADM.Id = @rApprovingDepartmentId
			LEFT JOIN sWorkflow.tActionStatusMaster ASM ON ASM.Id = AA.ActionStatusId AND((ASM.Id = @rStatusId) OR (@rStatusId =0)) 
			INNER JOIN sWorkflow.tWorkflowFunctionalityMaster WFM ON AR.WorkflowFunctionalityId = WFM.Id
			LEFT JOIN  sStudent.vStudentAcademic  SA ON SA.AcademicId = AR.ParticipantSourceId
			LEFT JOIN  sHrm.tEmployeeMaster  EM ON EM.Id = AR.ParticipantSourceId
		WHERE  (((SA.Code = @rCode) OR (@rCode ='')) OR ((EM.Code = @rCode) OR (@rCode =0)))
		
		AND ((AR.ParticipantSourceId = @rParticipantSourceId) OR (@rParticipantSourceId = 0))
		AND ISNULL(EM.IsOtherUser,0) = 0
		AND FAD.ApprovingDepartmentId = @rApprovingDepartmentId
	END
GO
PRINT N'Creating [sAssessment].[pStudentExamDetailGet]...';


GO

CREATE PROC [sAssessment].[pStudentExamDetailGet]
	
	@rDivisionId int=0,
	@rBatchId int=0,
	@rExamId int=0

AS
BEGIN
	
	Select DISTINCT 
		[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS StudentName,
		 StuM.Code,
		 A.RollNo,
		 R.AcademicId,
		 ISNULL(R.TotalMarks,0)AS TotalMarks,
		 ISNULL(R.TotalObtain,'')AS TotalObtain,
		 ISNULL(R.ResultStatus,'')AS ResultStatus,
		 ISNULL(R.Percentage,0)AS Percentage
     FROM sAssessment.tResultDetail RD 
     INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId 
     INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId 
     INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId 
     INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId 
     INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId 
     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.tOrganizationMaster OM ON OM.Id=A.OrgId 
     Where ((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
     AND ((A.DivisionId = @rDivisionId) OR (@rDivisionId = 0))
     AND ((R.ExamId = @rExamId) OR (@rExamId = 0))
END
GO
PRINT N'Creating [sAssessment].[pStudentWiseExamDetailGet]...';


GO

CREATE PROC [sAssessment].[pStudentWiseExamDetailGet]
	
	@rAcademicId bigint=0,
	@rBatchId int=0,
	@rExamId int=0

AS
BEGIN
	
	SELECT 
		ISNULL(SBM.Title,'') AS SubjectName,
		ISNULL(ED.Maximum,0)AS Maximum,
		ISNULL(ED.Minimum,0)AS Minimum,
		ISNULL(RD.Obtain,0)AS Obtain,
		ISNULL(RD.GraceMark,0) AS GraceMark,
		ISNULL(RD.Remark,'') AS Remark , 
		ISNULL(R.TotalMarks,0)AS TotalMarks,
		ISNULL(R.TotalObtain,'')AS TotalObtain,
		ISNULL(R.Percentage,0)AS Percentage
    FROM sStudent.tAcademic AD 
    INNER JOIN sAssessment.tExamMaster EM ON EM.BatchId = AD.BatchId AND EM.ClassId = AD.ClassId 
    INNER JOIN sAssessment.tExamDetail ED ON ED.ExamId = EM.Id 
    INNER JOIN sAssessment.tResult R ON AD.Id = R.AcademicId AND R.ExamId = EM.Id 
    INNER JOIN sAssessment.tResultDetail RD ON RD.ExamDetailId = ED.Id AND R.Id = RD.ResultId 
    INNER JOIN sSetup.tClassSubject CS ON CS.Id = ED.ClassSubjectId 
    INNER JOIN sSetup.tSubjectMaster SBM ON SBM.Id = CS.SubjectId 
    INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.ExamSubGroupId 
    Where 
	((AD.Id = @rAcademicId) OR (@rAcademicId = 0)) 
     AND ((AD.BatchId = @rBatchId) OR (@rBatchId = 0))
     AND ((EM.Id = @rExamId) OR (@rExamId = 0))
END
GO
PRINT N'Creating [sBiometric].[pCloudTransactionDataAdd]...';


GO
 
CREATE PROCEDURE [sBiometric].[pCloudTransactionDataAdd]

@rXmlDoc nvarchar(max) = ''

AS
SET NOCOUNT ON

BEGIN
	SET @rXmlDoc=REPLACE(@rXmlDoc,'&','AND')
	DECLARE @lInterrorCode INT,
			@intDoc INT
	BEGIN TRANSACTION					
	EXECUTE @lInterrorCode = sp_xml_preparedocument @intDoc OUTPUT, @rXmlDoc

	INSERT INTO sBiometric.tCloudTransactionRawData
	SELECT 
		A.TransactionId,
		A.PunchId,
		A.TransactionDateTime,
		A.DeviceIP,
		A.Mode,
		sCommon.fGetDate()
	FROM OPENXML (@intDoc, '/Table/CloudTransactionData', 1)
	WITH
	(
		TransactionId bigint '@TransactionId',
		PunchId nvarchar(20) '@PunchId',
		TransactionDateTime datetime '@TransactionDateTime',
		DeviceIP nvarchar(20) '@DeviceIP',		
		Mode nvarchar(10) '@Mode'	
	) A	

	INSERT INTO [sBiometric].[tCloudTransactionData]
	--Employee
	SELECT 
		EM.Id,
		CRD.TransactionDateTime,
		CASE WHEN (SELECT 1 FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR CRD.TransactionDateTime BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = EM.Id AND SourceTypeId = 95) IS NOT NULL THEN 
		(SELECT ShiftCode FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR CRD.TransactionDateTime BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = EM.Id AND SourceTypeId = 95)
		ELSE EM.ShiftId END AS ShiftCode,
		CONVERT(DATE,CRD.TransactionDateTime) AS Attn_Dt,
		CASE WHEN (SELECT TOP 1 ISNULL(Mode,'IN') FROM [sBiometric].[tCloudTransactionData] WHERE SourceId = EM.Id AND Attn_Dt = CONVERT(DATE,CRD.TransactionDateTime) ORDER BY In_Out_Time DESC) = 'IN' THEN 'OUT' ELSE 'IN' END AS Mode,
		sCommon.fGetDate(),
		CRD.DeviceIP,
		0,
		CRD.PunchId,
		CRD.TransactionId,
		95,
		NULL
	FROM 
		sBiometric.tCloudTransactionRawData CRD 		
		INNER JOIN sHrm.tEmployeeMaster EM ON EM.PunchId = CRD.PunchId
	WHERE
		CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData)

	UNION ALL

	--Student
	SELECT 
		SM.Id,
		CRD.TransactionDateTime,
		CASE WHEN (SELECT 1 FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR CRD.TransactionDateTime BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = SM.Id AND SourceTypeId = 2003) IS NOT NULL THEN 
		(SELECT ShiftCode FROM sBiometric.tShiftAllocationCloud WHERE (ShiftDay = DATEPART(WEEKDAY, CRD.TransactionDateTime - 1) OR CRD.TransactionDateTime BETWEEN FromShiftDate AND ToShiftDate) AND SourceId = SM.Id AND SourceTypeId = 2003)
		ELSE SM.ShiftId END AS ShiftCode,
		CONVERT(DATE,CRD.TransactionDateTime) AS Attn_Dt,
		CASE WHEN (SELECT TOP 1 ISNULL(Mode,'IN') FROM [sBiometric].[tCloudTransactionData] WHERE SourceId = SM.Id AND Attn_Dt = CONVERT(DATE,CRD.TransactionDateTime) ORDER BY In_Out_Time DESC) = 'IN' THEN 'OUT' ELSE 'IN' END AS Mode,
		sCommon.fGetDate(),
		CRD.DeviceIP,
		0,
		CRD.PunchId,
		CRD.TransactionId,
		2003,
		NULL
	FROM 
		sBiometric.tCloudTransactionRawData CRD 		
		INNER JOIN sStudent.tStudentMaster SM ON SM.PunchId = CRD.PunchId
	WHERE
		CRD.TransactionId NOT IN (SELECT TransactionId FROM sBiometric.tCloudTransactionData)

	COMMIT TRANSACTION
	SELECT 1 AS Result
END
GO
PRINT N'Creating [sFee].[pRptStudentFeeDetailsGet]...';


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

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN 
	SELECT 
		SA.AcademicId AS SourceId,
		SA.[Name] AS StudentName,
		SA.BatchId,
		SA.Code,
		SA.ClassId,
		SA.DivisionId,
		SA.AcademicId AS SourceIdText,
		2001 AS SourceTypeId,
		SA.ClassName,
		SA.DivisionName,
		SA.BatchName,
		SA.RollNo,
		ACM.Title AS FeeCategory
	FROM 
		sStudent.vStudentAcademic SA
		INNER JOIN [sStudent].[tAdmissionCategoryMaster] ACM ON ACM.Id = SA.AdmissionCategoryId
	WHERE 
		SA.AcademicId = @rSourceId 		
		AND SA.BatchId = @rBatchId 		

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


GO
 
 
CREATE PROCEDURE [sFee].[pRptStudentFeeRefundDetailsGet]
@rSourceIdText nvarchar(50) = '',
@rBatchId int = 0

WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN 
	SELECT 
		R.ReceiptNumber,
		RR.RefundDate,
		RR.RefundAmount,
		ISNULL(RR.ChequeNo,'') AS ChequeNumber,
		ISNULL(RR.BankName,'') AS BankName, 
		RBM.Title AS ReceiptBook,
		PTM.Title AS PayType,
		RR.SourceId,
		RR.BatchId,
		@rSourceIdText AS SourceIdText
	FROM 
		sFee.tReceiptRefund RR  
		INNER JOIN sFee.tReceipt R ON RR.ReceiptId = R.Id  
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = R.ReceiptBookId  
		INNER JOIN sFinanceCommon.tPayTypeMaster PTM ON PTM.Id = RR.PayTypeId  
	WHERE 
		RR.SourceId = @rSourceIdText 
		AND RR.SourceTypeId = 2001 
		AND RR.BatchId = @rBatchId 
		AND RR.IsObsolete = 0

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


GO
 

CREATE PROCEDURE [sFee].[pStudentwiseOptionalFeeGet]

		   @rClassId int = 0,
           @rAdmissionCategoryId int = 0,
		   @rBatchId int = 0,
		   @rOrgGroupId int = 0,
		   @rSourceTypeId int = 0,
		   @rSourceId bigint = 0,
		   @rType tinyint = 0
           
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 
BEGIN 
IF(@rType = 1)
BEGIN
	SELECT 
			ISNULL(FS.Id,0)AS Id,
			FM.Title AS Title,		
			ISNULL(FS.Amount,0)AS Amount,
			CASE WHEN ISNULL(FO.SourceId,0) = 0 THEN 'False' ELSE 'True' END AS IsCheck
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId AND FS.IsOptional=1
			AND (FS.ClassId=@rClassId) AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) AND (FS.BatchId=@rBatchId)
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS.Id AND FO.SourceTypeId=@rSourceTypeId AND FO.SourceId=@rSourceId
WHERE 
		FM.OrgGroupId=@rOrgGroupId
		ORDER BY FS.StartDate,FM.OrderIndex

END
ELSE
BEGIN
	SELECT 			
			FHM.Id AS Id,
			ISNULL(SUM(FS.Amount),0)AS Amount,			
			ISNULL(FHM.Title,'') AS Title,
			CASE WHEN ISNULL(COUNT(FO.SourceId),0) = COUNT(FS.Id) THEN 'True' ELSE 'False' END AS IsCheck
  FROM 
			sFee.tFeeMaster FM
		INNER JOIN sFee.tFeeSetup FS ON FM.Id=FS.FeeId AND FS.IsOptional=1
			AND (FS.ClassId=@rClassId) AND (FS.AdmissionCategoryId=@rAdmissionCategoryId) AND (FS.BatchId=@rBatchId)
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id=FM.FeeHeadId
		LEFT JOIN sFee.tFeeOptional FO ON FO.FeeSetupId=FS.Id AND FO.SourceTypeId=@rSourceTypeId AND FO.SourceId=@rSourceId
WHERE 
		FM.OrgGroupId=@rOrgGroupId		
	GROUP BY FHM.Id,FHM.Title--,FO.SourceId
END
END
GO
PRINT N'Creating [sStudent].[pOnlineStudentDocumentGet]...';


GO

CREATE PROCEDURE [sStudent].[pOnlineStudentDocumentGet]
	 
    @rStudentId bigint,
	@rOrgId bigint,
	@rClassId bigint,
	@rBatchId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
 
	BEGIN

	Select 
		ISNULL(D.Id,0) AS DocumentId,
		ISNULL(D.DocumentName,'')AS DocumentName,
		A.DocumentFileName ,
		A.StudentDocumentId
		from sCommon.tSubmitDocumentMaster D 
		INNER JOIN sCommon.tSubmitDocumentScope DS ON DS.SubmitDocumentId = D.Id
		INNER JOIN 
		(Select D1.DocumentName,D1.Id AS StudentDocumentId,S.DocumentName AS DocumentFileName FROM sCommon.tSubmitDocumentMaster D1
		INNER JOIN sStudent.tOnlineRegistrationStudentDocument  S ON S.SubmitDocumentMasterId=D1.Id 
		WHERE  D1.SubmitDocumentFunctionalityId='5' AND D1.OrgId=@rOrgId AND (S.StudentId= @rStudentId  OR @rStudentId=0)
		AND D1.Id IN (select SubmitDocumentMasterId from sStudent.tOnlineRegistrationCriteriaDocument WHERE ClassId=@rClassId AND BatchId = @rBatchId  ))A ON  A.DocumentName = D.DocumentName

		Where OrgId=@rOrgId AND SubmitDocumentFunctionalityId='1' AND DS.SourceTypeId = 2016 AND DS.SourceId = @rClassId
			
END
GO
PRINT N'Creating [sTransport].[pAssignRouteLogAdd]...';


GO
CREATE PROCEDURE [sTransport].[pAssignRouteLogAdd]
	 
	@rSourceTypeId smallint,
	@rSourceId bigint,
	@rNewPickupDestinationId int,
	@rNewDropDestinationId int,
	@rChangeDate datetime,
	@rStatusId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

IF NOT EXISTS(SELECT * FROM sTransport.tAssignRouteLog WHERE SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId)
BEGIN
	INSERT INTO sTransport.tAssignRouteLog
	(
		SourceTypeId,
		SourceId,
		NewPickupDestinationId,
		NewDropDestinationId,
		ChangeDate,
		StatusId,
		OrgGroupBatchId,
		CreatedUserId,
		CreatedDateTime
	)
	VALUES
	(
		@rSourceTypeId,
		@rSourceId,
		@rNewPickupDestinationId,
		@rNewDropDestinationId,
		@rChangeDate,
		@rStatusId,
		@rOrgGroupBatchId ,
		@rCreatedUserId ,
		sCommon.fGetDate()
	)
END
ELSE
BEGIN
	DELETE FROM sTransport.tAssignRouteLog WHERE SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId AND StatusId = @rStatusId

	INSERT INTO sTransport.tAssignRouteLog
	(
		SourceTypeId,
		SourceId,
		NewPickupDestinationId,
		NewDropDestinationId,
		ChangeDate,
		StatusId,
		OrgGroupBatchId,
		CreatedUserId,
		CreatedDateTime
	)
	VALUES
	(
		@rSourceTypeId,
		@rSourceId,
		@rNewPickupDestinationId,
		@rNewDropDestinationId,
		@rChangeDate,
		@rStatusId,
		@rOrgGroupBatchId ,
		@rCreatedUserId ,
		sCommon.fGetDate()
	)
END
END
GO
  
 
  
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('22.05.02',220502,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO