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

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


GO
ALTER TABLE [sConfig].[tConfigurationSetup] ALTER COLUMN [ItemValue] NVARCHAR (500) NULL;


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


GO
ALTER TABLE [sTransport].[tAssignRouteLog] DROP COLUMN [ChangeDate];


GO
PRINT N'Creating [sAttendance].[tAttendanceFollowup]...';


GO
CREATE TABLE [sAttendance].[tAttendanceFollowup] (
    [AcademicId]       BIGINT         NOT NULL,
    [AttendanceTypeId] TINYINT        NOT NULL,
    [FollowupDate]     DATE           NOT NULL,
    [IsPresent]        BIT            NOT NULL,
    [Remark]           NVARCHAR (500) NULL,
    [CreatedUserId]    BIGINT         NOT NULL,
    [CreatedDateTime]  DATETIME       NOT NULL,
    [UpdatedUserId]    BIGINT         NULL,
    [UpdatedDateTime]  DATETIME       NULL
);


GO
PRINT N'Creating [sAttendance].[tAttendanceFollowup].[IX_tAttendanceFollowup]...';


GO
CREATE NONCLUSTERED INDEX [IX_tAttendanceFollowup]
    ON [sAttendance].[tAttendanceFollowup]([AcademicId] ASC, [AttendanceTypeId] ASC, [IsPresent] ASC, [FollowupDate] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, MAXDOP = 0)
    ON [PRIMARY];


GO
PRINT N'Creating FK_sAttendance_tAttendanceFollowup_AcademicId...';


GO
ALTER TABLE [sAttendance].[tAttendanceFollowup] WITH NOCHECK
    ADD CONSTRAINT [FK_sAttendance_tAttendanceFollowup_AcademicId] FOREIGN KEY ([AcademicId]) REFERENCES [sStudent].[tAcademic] ([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION;


GO
ALTER TABLE [sAttendance].[tAttendanceFollowup] NOCHECK CONSTRAINT [FK_sAttendance_tAttendanceFollowup_AcademicId];


GO
PRINT N'Creating FK_sAttendance_tAttendanceFollowup_AttendanceTypeId...';


GO
ALTER TABLE [sAttendance].[tAttendanceFollowup] WITH NOCHECK
    ADD CONSTRAINT [FK_sAttendance_tAttendanceFollowup_AttendanceTypeId] FOREIGN KEY ([AttendanceTypeId]) REFERENCES [sAttendance].[tAttendanceTypeMaster] ([Id]) ON DELETE NO ACTION ON UPDATE NO ACTION;


GO
ALTER TABLE [sAttendance].[tAttendanceFollowup] NOCHECK CONSTRAINT [FK_sAttendance_tAttendanceFollowup_AttendanceTypeId];


GO

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


GO
ALTER PROCEDURE [sAcademic].[pGetLessonPlanApi]

	 @rAcademicId bigint,
	 @rBatchId int,
	 @rDivisionId int,
	 @rSubjectId int
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

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


GO

ALTER PROCEDURE [sActivity].[pHealthTrackGet]
	 
		   @rBuilder1 nvarchar(max)='',
		   @rBuilder2 nvarchar(max)='',     
           @rId bigint,
           @rAcadamicId bigint,
           @rHealthCheckUpTypeId int,
           @rCheckupFromDate date,
           @rCheckupToDate date,
           @rBatchId int,
		   @rDivisionId int=0 ,
		   @rClassId int=0    
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	 BEGIN TRY 
	 BEGIN TRANSACTION	
	   
   SELECT 
   
           @rBuilder1 AS Builder1,
		   @rBuilder2 AS Builder2,
		   HT.[Id]
		  ,HT.[AcademicId]
		  ,[HealthCheckupTypeId]
		  ,[CheckupFromDate]
		  ,[CheckupToDate]
		  ,[ChiefComplain]
		  ,[Diagnosis]
		  ,[ActionTaken]
		  ,[Remark]
		  ,[ExaminedBy]
		  ,SM.Code AS StudentCode
		  ,SM.Name AS StudentName
		  ,SM.RollNo
		  ,SM.ClassId
		  ,SM.ClassName+'-'+SM.DivisionName As ClassName
		  ,CTM.Title AS HealthCheckupType
		  ,ISNULL(HT.InTime,'') AS InTime
		  ,ISNULL(HT.OutTime,'') AS OutTime
		  ,DM.OrderIndex As OrderIndex
       
	FROM  [sActivity].[tHealthTrack]  HT INNER JOIN sStudent.vStudentAcademic SM ON SM.AcademicId = HT.AcademicId
		  INNER JOIN sActivity.tHealthCheckUpTypeMaster CTM ON CTM.Id = HT.HealthCheckupTypeId
		  Inner Join sSetup.tDivisionMaster DM on SM.DivisionId=DM.Id
  
	WHERE   (HT.Id = @rId OR @rId = 0)	   	 	
		AND (HT.AcademicId = @rAcadamicId OR @rAcadamicId =  0)
		AND (HealthCheckupTypeId = @rHealthCheckUpTypeId OR @rHealthCheckUpTypeId = 0)
		AND (CheckupFromDate >= @rCheckupFromDate OR ISNULL(@rCheckupFromDate,'') = '')
		AND (CheckupFromDate <= @rCheckupToDate OR ISNULL(@rCheckupToDate,'') = '')
		AND BatchId = @rBatchId AND (DM.Id=@rDivisionId OR @rDivisionId=0)
		AND (DM.ClassId=@rClassId OR @rClassId=0)
		
		order by HT.CheckupFromDate Asc
      
	COMMIT TRANSACTION		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sActivity].[pImportEvent]...';


GO
 
ALTER PROCEDURE [sActivity].[pImportEvent]
       
    @rOrgId int,
	@rXmldoc [nvarchar](max),
	@rBatchId int,
	@rCreatedUserId bigint 	  
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	DECLARE @lCount int,@intDoc INT,@lInterrorCode INT,@loXML XML,
			@lTitle nvarchar(100),
			@lFromDate date,
			@lToDate date,
			@lRemark nvarchar(200),
			@lEventTypeId int,			
			@lIsHoliday bit,
			@lBatchId int	
	
	SET @loXML = CAST(@rXmldoc AS XML)
	
	
	CREATE TABLE #tTable1 (
	Id bigint identity,
	Title nvarchar(100) ,
	FromDate date ,
	ToDate date ,
	Remark nvarchar(1000),
	EventTypeId int ,	
	IsHoliday bit,
	BatchId int)
	
	INSERT INTO #tTable1(
		Title,
		FromDate,
		ToDate,
		Remark, 
		EventTypeId,
		IsHoliday,
		BatchId )
	SELECT
		 T.c.value('@Title','nvarchar(100)') AS Title,
		 T.c.value('@FromDate','date') AS FromDate,
		 T.c.value('@ToDate','date') AS ToDate,
		 T.c.value('@Remark','nvarchar(1000)') AS Remark,
		 T.c.value('@EventTypeId','int') AS EventTypeId,
		-- T.c.value('@IsHoliday','bit') AS IsHoliday,
		 CASE WHEN (T.c.value('@IsHoliday','bit') = 1) THEN  'True' ELSE 'False' END AS IsHoliday,
		 @rBatchId
		 
	FROM @loXML.nodes('/Table/ImportEvent')T(c)
	
	
	
SELECT @lCount =  COUNT(Id) FROM #tTable1
	
	
WHILE @lCount > 0 

BEGIN				
	
SELECT	
		@lTitle = Title,
		@lFromDate = FromDate,
		@lToDate = ToDate,
		@lRemark = Remark,
		@lEventTypeId = EventTypeId,
		@lIsHoliday = IsHoliday,
		@lBatchId = BatchId
			
											 	 
FROM #tTable1 WHERE Id = @lCount 

	--IF EXISTS(SELECT Id FROM sActivity.tEventSchedule WHERE Title=@lTitle AND BatchId = @rBatchId)
	--	BEGIN
	--		UPDATE sActivity.tEventSchedule
	--		SET	
	--			Title = @lTitle,				
	--			FromDate = @lFromDate,			
	--			ToDate = @lToDate,
	--			Remark = @lRemark,
	--			EventTypeId = @lEventTypeId,
	--			IsHoliday = @lIsHoliday 
	--		WHERE 
	--			Title=@lTitle AND BatchId = @rBatchId			
	--	END
	--	ELSE
	--	BEGIN
			DECLARE @lNextNumber BIGINT	
			EXECUTE  sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEventSchedule', 0, 101, 1,@outNextNumber = @lNextNumber output
			INSERT INTO sActivity.tEventSchedule
				(
					Id,		
					Title,
					FromDate,
					ToDate,
					Remark,
					EventTypeId,
					IsHoliday,
					BatchId,
					IsCommonForAll,
					IsEnrollment,
					CreatedUserId,
					CreatedDateTime
				)
			VALUES
				(
					@lNextNumber,
					@lTitle,					
					@lFromDate,
					@lToDate,
					@lRemark,
					@lEventTypeId,
					@lIsHoliday,
					@rBatchId,
					0,
					0,
					@rCreatedUserId,
					sCommon.fGetDate()
				)
				
			    DECLARE @lNextNumber1 BIGINT
			    EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sActivity.tEventAssign', 0, 1, 1,@outNextNumber = @lNextNumber1 output	
				
				DECLARE @TempDivision TABLE (Id int,SourceTypeId int)
				DELETE FROM  @TempDivision 
				INSERT INTO @TempDivision
				Select Id AS DivisionId,2005 from sSetup.tDivisionMaster Where OrgId = @rOrgId
				UNION ALL
				Select Id AS DepartmentId,2004 from sSetup.tDepartmentMaster Where OrgId = @rOrgId
							
				INSERT INTO sActivity.tEventAssign
				SELECT 								
				@lNextNumber1+ ROW_NUMBER() OVER(ORDER BY @lNextNumber,Id,SourceTypeId),
				@lNextNumber,
				SourceTypeId,
				Id
				FROM @TempDivision
				
				

				DECLARE @lCount1 INT
				
				SELECT @lCount1 = COUNT(1) FROM  @TempDivision
				SET @lNextNumber1  = @lCount1 + @lNextNumber1 
				
				EXECUTE sCommon.pTableRowIdModify @rOrgId, @rTableTitle = 'sActivity.tEventAssign', @rCurrentNumber = @lNextNumber1 

				
		--END
		
		SET @lCount = @lCount - 1
	SELECT 1 AS Result, '' AS ResultDetail				

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


GO
 
 
ALTER PROCEDURE [sAdmission].[pAPIAdmissionInquiryGet]
	

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

	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.Number= @rInquiryNumber) OR (@rInquiryNumber = 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 [sAssessment].[pMarkEntryRankUpdate]...';


GO
ALTER PROCEDURE [sAssessment].[pMarkEntryRankUpdate]
	 
	 @rExamId int=0,
	 @rDivisionId int=0,
	 @rBatchId int=0
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
	
BEGIN 	

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

DECLARE  @lOrgId smallint,@lSiddhiKrupaApplicable bit, @lIsSkipRankConfigValue bit=0 

SELECT @lOrgId = OM.Id From sSetup.tBatchMaster BM INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id = BM.OrgId Where BM.Id = @rBatchId
	 
SELECT @lSiddhiKrupaApplicable = ISNULL(IsApplySiddhiKrupa,0) From sAssessment.tExamMaster Where Id = @rExamId

-- Configuration Value
-- Config Assessment.IsSkipRank						     
SELECT @lIsSkipRankConfigValue = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId WHERE CS.ConfigurationId = 315 AND SourceTypeId = 1016							     					     



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

IF @lSiddhiKrupaApplicable = 0
BEGIN
	IF(@lIsSkipRankConfigValue=0)
    BEGIN
		Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS' ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
    END
    ELSE
    BEGIN
	    Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS' ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
	END
END
ELSE
BEGIN

	
	DECLARE @lIsShowSiddhiKrupaExamField bit, @lIsSetSiddhiAppliedStudentRank0 bit, @lIsMoveSiddhiRankToLast bit,@lMaxRank int
		
	-- Config Assessment.IsShowSiddhiKrupaExamField
	SELECT @lIsShowSiddhiKrupaExamField = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationSetup CS LEFT JOIN sConfig.tConfigurationMaster CM ON CM.Id = CS.ConfigurationId	WHERE CS.ConfigurationId = 278 AND SourceId = @lOrgId AND SourceTypeId = 1016

	-- Config Assessment.IsSetSiddhiAppliedStudentRank0
	SELECT @lIsSetSiddhiAppliedStudentRank0 = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId WHERE CS.ConfigurationId = 280 AND SourceTypeId = 1016

	-- Config Assessment.IsMoveSiddhiRankToLast
	SELECT @lIsMoveSiddhiRankToLast = ISNULL(CS.ItemValue,CM.ItemValue) From sConfig.tConfigurationMaster CM LEFT JOIN sConfig.tConfigurationSetup CS ON CM.Id = CS.ConfigurationId	AND SourceId = @lOrgId	WHERE CS.ConfigurationId = 281 AND SourceTypeId = 1016	

	-- Create temp table for get ResultDetail(GraceMark,KrupaMark)
	CREATE TABLE #TempResultDetail (ResultId bigint,AcademicId bigint,GraceMark Decimal(5,2),KrupaMark Decimal(5,2))
	INSERT INTO #TempResultDetail
	SELECT DISTINCT RD.ResultId,SA.Id AS AcademicId,RD.GraceMark,RD.KrupaMark
	FROM sAssessment.tResult RS INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
	WHERE RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId

	IF(@lIsSkipRankConfigValue=0)
	BEGIN
		Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS' 
		AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0)
		) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
		AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0)
	END
	ELSE
	BEGIN
	   Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
		INNER JOIN
		(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
		AcademicId 
		from sAssessment.tResult RS	
		INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
		AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
		AND ResultStatus='PASS'
		AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0)
		 ) A
		ON A.AcademicId = R.AcademicId 
		WHERE R.ExamId = @rExamId
		AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0)
	END

If @lIsShowSiddhiKrupaExamField = 1 AND @lSiddhiKrupaApplicable = 1
BEGIN

-- Set Rank 0 to Those whose Siddhi/GraceMark > 0
IF @lIsSetSiddhiAppliedStudentRank0 = 1 
	BEGIN
		Update R Set R.RankNumber = 0 From sAssessment.tResult R 
		Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId  
		AND R.ExamId=@rExamId
		AND A.DivisionId = @rDivisionId 
		AND A.BatchId = @rBatchId
		
		IF(@lIsSkipRankConfigValue=0)
		BEGIN		
			Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
		END
		ELSE
		BEGIN
			Update R Set R.RankNumber=A.RankNumber 
			From sAssessment.tResult R
			INNER JOIN
			(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
			from sAssessment.tResult RS
			INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
			INNER JOIN sAssessment.tResultDetail RD ON RD.ResultId = RS.Id
			AND RS.ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
			AND ResultStatus in ('PASS','PROMOTED')
			AND RS.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
			) A
			ON A.AcademicId = R.AcademicId 
			WHERE R.ExamId = @rExamId
			AND R.Id NOT IN (Select ResultId from #TempResultDetail Where GraceMark > 0 OR KrupaMark > 0)
		END
	END
ELSE IF @lIsMoveSiddhiRankToLast = 1
	BEGIN
			SELECT @lMaxRank = Max(RankNumber) 
			FROM sAssessment.tResult R 
			INNER JOIN sStudent.tAcademic SA ON SA.Id= R.AcademicId 
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id = R.ExamId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = EM.ClassId and DM.Id = SA.DivisionId
			WHERE EM.Id = @rExamId  AND DM.Id = @rDivisionId AND EM.BatchId= @rBatchId AND R.Percentage > 0
 

			IF(@lIsSkipRankConfigValue=0)
			BEGIN				
				Update R Set R.RankNumber= convert(int,@lMaxRank) + convert(int,A.RankNumber) From sAssessment.tResult R
				INNER JOIN
				(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
				from sAssessment.tResult RS
				INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
				AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
				AND RS.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0 )
				AND ResultStatus in ('PASS','PROMOTED')) A
				ON A.AcademicId = R.AcademicId 
				WHERE R.ExamId = @rExamId
				AND R.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0 )
			END
			ELSE
			BEGIN
				Update R Set R.RankNumber=convert(int,@lMaxRank) + convert(int,A.RankNumber) From sAssessment.tResult R
				INNER JOIN
				(Select RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber, AcademicId 
				from sAssessment.tResult RS
				INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
				AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
				AND RS.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0)
				AND ResultStatus in ('PASS','PROMOTED')) A
				ON A.AcademicId = R.AcademicId 
				WHERE R.ExamId = @rExamId 
				AND R.Id IN (Select ResultId from #TempResultDetail Where GraceMark > 0 AND KrupaMark <= 0)	       	       	       
			END
			END		
END

	DROP TABLE #TempResultDetail

END 

	SELECT 1 AS Result
END
GO
PRINT N'Altering [sAssessment].[pRptResultListFloatingCombineExam]...';


GO

ALTER PROCEDURE [sAssessment].[pRptResultListFloatingCombineExam]
	 
	 @rBuilder1 nvarchar(max)='', 
	 @rBuilder2 nvarchar(max)='', 
	 @rSubjectId int=0,
	 @rBatchId int = 0,
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rExamId int,
	 @rCode nvarchar(20)='',
	 @rFromRollNo int,
	 @rToRollNo int,
	 @rFromRank int=0,
	 @rToRank int=0,
	 @rGrade nvarchar(20)='',
	 @rResultId bigint=0,
	 @rStatusId int=0,
	 @rAcademicId bigint=0,
	 @rIsShowWithDetail bit =0,
	 @rFilterId int=0,
	 @rOrgGroupBatchId int=0,
	 @rClassStatusId int=0
	 --@rFromPercentage decimal(5,2)=0,
	 --@rToPercentage decimal(5,2)=0
	 
	
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			 

BEGIN 
 --Select * from dbo.Float
 --Select
 --           ''  AS AcademicIdText,
	--		'' AS ExamIdText,
	--		'' AS IsDisplayMonthlyAttendanceText,
	--		'' AS Exam,
	--		'' AS Builder1,
	--		'' Code,
	--		'' AS Name,
	--		0 RollNo,
	--		0 AcademicId,			
	--		'' ResultStatus,
	--		'' AS Class,
	--		'' AS Division,
	--		0.0 TotalMarks,
	--		0.0 TotalObtain,
	--		0.0 Percentage,
	--		0 RankNumber,
	--		'' ResultGrade,
	--		0.0 Percentile,			
	--		0 AS ResultDetailId,		
	--		0 IsDisplayInMarksheet,
	--		0 IsShowSubjectGrade,
	--		0 IsIncludeInTotal,
	--		0.0 AS SubjectObtain,
	--		0.0 AS SubjectMinimum,
	--		0.0 AS SubjectMaximum,			
	--		'' AS SubjectCode,
	--		'' AS SubjectName,
	--		0 AS SubjectOrderIndex,
	--		0 AS ResultId,
	--		0 AS SubjectId,			 	
	--		0 IsMarksInDecimal,
			
	--		 '' AS Remark1,
	--		'' AS Remark2,
	--		'' AS Remark3,
	--		'' DisplayTitle,
	--		 0 IsRankNo, 
	--		0 IsGrade,
	--		0 IsPercentile,
	--		0 IsPercentage,
	--		0 IsSubjectPercentile,
	--		0 IsProcessResult,
			 
	--		0 IsNegativeMarks,
	--		 0 IsIncludeCoScholastic,
	--		0 IsOnPrePrinted,
	--		0 IsDisplayPhoto,
	--		0 IsDisplayBirthDate,
	--		0 IsLockForEdit,
	--		0 IsDisplaySchoolName,			
	--		0 IsDisplayAttendance,
	--		0 IsDisplayHeightWeight,
	--		0 IsResultStatus,
	--		'' AS FooterAdjustmentText,
	--		'' AS DetailAdjustmentText,
	--		0 FooterAdjustment,
	--		0 DetailAdjustment,
		 		 
	--		0 TermScopeId,
		 
	--		0 IsPresent,
	--		'' AS GradeString,
	--		0 IsDisplayGradeString,
	--		 ''  AS HighestDivisionGrade,			
	--		'' SmallAddress1,
	--		0 IsDisplayParentName,
			 
	--		0 AS IsShowSubjectMark,
			
	--		0 IsDisplayTeacherSign,
	--		0 IsDisplayPrincipalSign,
		 
	--		0 AS IsDisplayMonthlyAttendance,
			 
	--		0 AS IsImageHeader,
			 
	--		0 SubExamId,
	--		0 ExamOrderIndex,
	--		0 AnnualExamId ,
	--		'' DecimalFormat,
	--		0 TermExamId,
	--		'' AS ExamNAme, 			 
	--		'' AS AnnualSubjectGrade,
	--		0.00 As AnnualSubjectObtain,
	--		'' AS TermSubjectGrade,
	--		0.0 As TermSubjectObtain ,
	--		'' AS SubjectGrade,
	--		'' AS Remark,
	--		'' AS FatherName,
	--	'' AS	MotherName,
	--	0 AS	TotalDays,
	--	0 AS PresentDays,
	--		0 AS TotalMark,
	--		0 AS TotalObtain,
	--0 TermMaximum,
	--		0 AS AnnualMaximum
			
 
 
 
DECLARE @GradeString nvarchar(1000),
@GradeSetId int 
 
SELECT @GradeSetId = GradesetId FROM sAssessment.tExamMaster WHERE Id = @rExamId
SELECT @GradeString = [sAssessment].[fGradeStringGet](@GradeSetId)  

CREATE TABLE #TempExam
(
	SubExamId int, 
	ExamOrderIndex int,
	TermExamId int,
	AnnualExamId int, 
	Exam nvarchar(50) 
)


INSERT INTO #TempExam
(
	 --SubExamId,
	 ExamOrderIndex,
	 TermExamId,
	 AnnualExamId,
	 Exam 
	
)
 
SELECT EC.ExamOrder,
EM.Id AS TermExamId,
@rExamId AS AnnualExamId,
ESGM.Code AS Exam
  FROM [sAssessment].[tExamMaster] EM 
		INNER JOIN SASSESSMENT.TEXAMSUBGROUPmASTER ESGM ON ESGM.ID = EM.ExamSubGroupId 
		INNER JOIN sAssessment.tExamCombine EC ON EC.SubExamId=EM.Id AND EC.ExamId =@rExamId  AND (EM.ClassId=@rClassId) AND EM.BatchId =@rBatchId
	
	--Select * from #TempExam
	
 --Select * from #TempExam
		Declare @lAnnualExamMaximum int,@lExamId int
		Select @lExamId= AnnualExamId FROM #TempExam 

		Select @lAnnualExamMaximum=Maximum from sAssessment.tExamDetail Where ExamId=@lExamId
	
	SELECT 
			Convert(nvarchar(20),A.Id) AS AcademicIdText,
			Convert(nvarchar(20),@rExamId) AS ExamIdText,
			Convert(nvarchar(20),ISNULL(EM.IsDisplayMonthlyAttendance,0)) AS IsDisplayMonthlyAttendanceText,
			ESGM.Title AS Exam,
			 @rBuilder1 AS Builder1,
			StuM.Code,
			[sStudent].[fStudentNameGet](stum.FirstName , StuM.MiddleName, StuM.LastName,OM.StudentNameFormatId ) AS Name,
			A.RollNo,
			R.AcademicId,			
			R.ResultStatus,
			CM.DisplayTitle AS Class,
			DM.DisplayTitle AS Division,
			(Select R1.TotalObtain from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS TotalMarks,
			--R.TotalMarks,
			(Select R1.Percentage from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS Percentage,
			R.TotalObtain,
			R.RankNumber,
			(Select R1.ResultGrade from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS ResultGrade,
			--R.ResultGrade,
			R.Percentile,			
			RD.Id AS ResultDetailId,		
			ED.IsDisplayInMarksheet,
			ED.IsShowSubjectGrade,
			ED.IsIncludeInTotal,
			RD.Obtain AS SubjectObtain,
			ED.Minimum AS SubjectMinimum,
			ED.Maximum AS SubjectMaximum,			
			SM.Code AS SubjectCode,
			SM.Title AS SubjectName,
			(CASE ISNULL(ED.DisplayOrder,0)
			WHEN 0 THEN CS.OrderIndex
			ELSE ED.DisplayOrder END) AS SubjectOrderIndex,
			R.Id AS ResultId,
			CS.Id AS SubjectId,			 	
			EM.IsMarksInDecimal,
			
			ISNULL(EM.Remark1,'') AS Remark1,
			ISNULL(EM.Remark2,'') AS Remark2,
			ISNULL(EM.Remark3,'') AS Remark3,
			EM.DisplayTitle,
			EM.IsRankNo, 
			EM.IsGrade,
			EM.IsPercentile,
			EM.IsPercentage,
			EM.IsSubjectPercentile,
			EM.IsProcessResult,
			 
			EM.IsNegativeMarks,
			EM.IsIncludeCoScholastic,
			EM.IsOnPrePrinted,
			EM.IsDisplayPhoto,
			EM.IsDisplayBirthDate,
			EM.IsLockForEdit,
			EM.IsDisplaySchoolName,			
			EM.IsDisplayAttendance,
			EM.IsDisplayHeightWeight,
			EM.IsResultStatus,
			REPLICATE(',',EM.FooterAdjustment) AS FooterAdjustmentText,
			REPLICATE(',',EM.DetailAdjustment) AS DetailAdjustmentText,
			EM.FooterAdjustment,
			EM.DetailAdjustment,
		 		 
			EM.TermScopeId,
		 
			RD.IsPresent,
			@GradeString AS GradeString,
			EM.IsDisplayGradeString,
			(CASE EM.IsDisplayHighestDivisionMark
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionMark](A.DivisionId ,RD.ExamDetailId)
			ELSE 0 END) AS HighestDivisionMark,
			(CASE EM.IsDisplayHighestDivisionGrade
			WHEN 1 THEN [sAssessment].[fGetHighestDivisionGrade] (A.DivisionId ,RD.ExamDetailId)
			ELSE '' END) AS HighestDivisionGrade,			
			OM.SmallAddress1,
			EM.IsDisplayParentName,
			 
			ISNULL(ED.IsShowSubjectMark,1) AS IsShowSubjectMark,
			
			EM.IsDisplayTeacherSign,
			Em.IsDisplayPrincipalSign,
		 
			ISNULL(EM.IsDisplayMonthlyAttendance,0) AS IsDisplayMonthlyAttendance,
			 
			ISNULL(EM.IsDisplayImageHeader,0) AS IsImageHeader,
			 
			EC.SubExamId,
			EC.ExamOrderIndex,
			EC.AnnualExamId ,
			EM.DecimalFormat,
			EC.TermExamId,
			EC.Exam AS ExamNAme, 	
					 
			--ARD.SubjectGrade AS AnnualSubjectGrade,
			(Select RD1.SubjectGrade from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS AnnualSubjectGrade,
			(Select RD1.Obtain from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.AnnualExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS AnnualSubjectObtain,
			--ARD.Obtain As AnnualSubjectObtain,
			(Select RD1.SubjectGrade from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.TermExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS TermSubjectGrade,
			--TRD.SubjectGrade AS TermSubjectGrade,
			(Select RD1.Obtain from 
			sAssessment.tResultDetail RD1
			INNER JOIN sAssessment.tResult R1 ON R1.Id = RD1.ResultId
			INNER JOIN sAssessment.tExamDetail ED1 ON ED1.Id=RD1.ExamDetailId
			Where ED1.ExamId=EC.TermExamId AND ED1.ClassSubjectId=CS.Id 
			AND R1.AcademicId=R.AcademicId
			)AS TermSubjectObtain,
			EC.TermExamId,
			RD.Id,
			RD.SubjectGrade AS SubjectGrade,
			ISNULL(ARD.Remark,'')  AS Remark,
			SF.FatherName,
			SF.MotherName,
			SR.TotalDays,
			SR.PresentDays,
			--R.TotalMarks AS TotalMark,
			R.TotalObtain,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.TermExamId AND CS.Id=Exd.ClassSubjectId
			)AS TermMaximum,
			(Select Exd.Maximum from sAssessment.tExamDetail Exd Where 
			Exd.ExamId=EC.AnnualExamId AND CS.Id=Exd.ClassSubjectId
			)AS AnnualMaximum,
			(CASE WHEN SO.GenderId=1 THEN 'Male' ELSE 'Female' END)AS Gender
			--(Select R.TotalMarks From sAssessment.tResult)
			--@lAnnualExamMaximum AS AnnualMaximum,
			
			
			
			
	FROM 
			sAssessment.tResultDetail RD
			INNER JOIN sAssessment.tResult R ON R.Id = RD.ResultId
			INNER JOIN sAssessment.tExamDetail ED ON ED.Id=RD.ExamDetailId
			INNER JOIN sAssessment.tExamMaster EM ON EM.Id=ED.ExamId		
			INNER JOIN #TempExam EC ON EC.TermExamId = EM.Id 	
			INNER JOIN sAssessment.tExamSubGroupMaster ESGM ON ESGM.Id = EM.EXAMSUBGROUPID
			INNER JOIN sSetup.tClassSubject CS ON CS.Id=ED.ClassSubjectId
			INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=CS.SubjectId					 
			INNER JOIN sStudent.tAcademic A ON A.Id=R.AcademicId	
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id = A.BatchId		
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId			
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId			
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id			
			INNER JOIN sAssessment.tResult AR ON AR.AcademicId = A.Id AND AR.ExamId = EC.AnnualExamId 
			INNER JOIN sAssessment.tResultDetail ARD ON AR.Id = ARD.ResultId 
			INNER JOIN sAssessment.tExamDetail AED ON ARD.EXamDetailId = AED.Id 
			INNER JOIN sSetup.tClassSubject ACS ON AED.ClassSubjectId = ACS.Id 
			--AND ACS.SubjectId = @rSubjectId  
			INNER JOIN sAssessment.tResult TR ON TR.AcademicId = A.Id AND TR.ExamId = EC.TermExamId 
			INNER JOIN sAssessment.tResultDetail TRD ON TR.Id = TRD.ResultId 
			INNER JOIN sAssessment.tExamDetail TED ON TRD.EXamDetailId = TED.Id 
			INNER JOIN sSetup.tClassSubject TCS ON TED.ClassSubjectId = TCS.Id 
			--AND TCS.SubjectId = @rSubjectId 
			
			
			LEFT JOIN sHostel.tAssignRoom ARO ON  ARO.SourceId=StuM.Id AND ARO.SourceTypeId=2003 AND ((BM.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((ARO.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0) AND (BM.OrgGroupBatchId = ARO.OrgGroupBatchId)) 
		    LEFT JOIN
			(SELECT AT.SourceId,B.OrgGroupBatchId FROM sTransport.tAssignRoute AT 
			INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId 
			INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT
			ON RT.SourceId = StuM.Id 
		
			LEFT JOIN sAssessment.tStudentRemark SR ON R.AcademicId = SR.AcademicId AND  SR.ExamId=EC.AnnualExamId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = StuM.Id
			LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId=StuM.Id
			
	WHERE 
			
		((EM.BatchId = @rBatchId) OR  (@rBatchId = 0))
		AND ((A.ClassId=@rClassId) OR (@rClassId=0)) 
		AND ((SM.Id=@rSubjectId) OR (@rSubjectId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((A.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((A.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((R.RankNumber >= @rFromRank) OR (@rFromRank=0))
		AND ((R.RankNumber <= @rToRank) OR (@rToRank=0))
		AND ((R.ResultGrade = @rGrade) OR (@rGrade=''))
		--AND ((R.Percentage>=@rFromPercentage) OR (@rFromPercentage=0))
		--AND ((R.Percentage<=@rToPercentage) OR (@rToPercentage=0))Total Marks
		AND ((StuM.Code=@rCode) OR (@rCode=''))
		AND ((R.Id = @rResultId) OR (@rResultId = 0))
		AND ((StuM.StatusId=@rStatusId)OR(@rStatusId=0))
		
		 AND (
	 (@rFilterId = 0) -- All
     OR (@rFilterId = 2 AND isnull(ARO.SourceId,0)!=0) -- Hostel
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
     OR ((@rFilterId =1) AND ((isnull(ARO.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
    ) 
	AND ((A.ClassStatusId =  @rClassStatusId) OR (@rClassStatusId=0))
		--order by A.RollNo,CS.OrderIndex 
		
	 drop table #TempExam
		
END
GO
PRINT N'Altering [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
			LEFT JOIN sAssessment.tStudentRemark SR ON SR.AcademicId = A.Id AND SR.ExamId =  EM.Id
			INNER JOIN sStudent.tStudentMaster StuM ON StuM.Id=A.StudentId
			INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId
			INNER JOIN sSetup.tDivisionMaster DM ON DM.Id=A.DivisionId
			INNER JOIN sSetup.tOrganizationMaster OM ON StuM.OrgId = OM.Id
			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 [sBiometric].[pCloudTransactionDataAdd]...';


GO
 
ALTER 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,0
	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'Altering [sCertificate].[pRptCharacterCertificateGet]...';


GO
 


ALTER PROCEDURE [sCertificate].[pRptCharacterCertificateGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rNumber nvarchar(20)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromDate date='',
     @rToDate date='',
     @rCode nvarchar(20)='',
     @rName nvarchar(20)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lConfigValue nvarchar(50)

DECLARE @lIsDisplayImageHeader bit=0
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0

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

SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 180 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	IF (@lConfigValue IS NULL) OR (@lConfigValue = 'Default')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Blank')
	BEGIN
	SET @lIsOnPrePrinted = 1
	SET @lIsDisplayImageHeader = 0
	END
	ELSE IF (@lConfigValue = 'Image')
	BEGIN
	SET @lIsOnPrePrinted = 0
	SET @lIsDisplayImageHeader = 1
	END
	
	--SELECT @lConfigValue = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 158 AND SourceTypeId = 1016 AND SourceId = @rOrgId
	
	--IF (@lConfigValue IS NULL) OR (@lConfigValue = 'False')
	--SET @lIsDisplayImageHeader = 0
	--ELSE
	--SET @lIsDisplayImageHeader = 1	
	
	SELECT 
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			C.Id,
			C.AcademicId,
			SM.Code,
		--	SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
		   [sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CM.DisplayTitle AS ClassOnly,
			BM.Title AS Batch,
			SO.DateOfBirth,
			ISNULL(SO.BirthDateInWord,'') AS DOBInWords,
			ISNULL(SO.BirthPlace,'') AS BirthPlace,
			ISNULL(SO.BirthTaluka,'') AS Taluka,
			ISNULL(SO.BirthDistrict,'')	AS District,		
			C.characterDate,
			C.Number,
			ISNULL(SO.FamilyCast,'') AS Caste,
			ISNULL(SO.FamilySubCast,'') AS SubCaste,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SO.GenderId,
			SI.StudentPhoto,
			OM.OrgLogo,
			OM.Title AS OrgName,
			OM.StateName+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			SM.StatusId,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			SA.AdmissionDate,
			SF.FatherName,
			SF.MotherName,
			@lIDConfigValue AS ItemValue,
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			A.Id,
			SA.LeftDate AS LCDate,
			C.Remark AS Remark,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(OM.PrincipalSignature,0x) AS PrincipalSignature
	FROM 
			sCertificate.tCharacter C
			INNER JOIN sStudent.tAcademic A ON C.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			LEFT JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
	WHERE  
			A.OrgId=@rOrgId
		AND	A.BatchId = @rBatchId 
		AND ((A.ClassId=@rClassId) OR (@rClassId=0))
		AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
		AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
		AND ((C.Number=@rNumber) OR (@rNumber=''))
		AND ((C.Number >= @rFromNo) OR (@rFromNo=''))
		AND ((C.Number <= @rToNo) OR (@rToNo=''))
		AND ((C.characterDate >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
		AND ((C.characterDate <= @rToDate) OR (ISNULL(@rToDate,'')=''))
		--Group By C.AcademicId,C.Number,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,CM.DisplayTitle,BM.Title,SO.DateOfBirth,SO.BirthDateInWord,
		--SO.BirthPlace,SO.BirthTaluka,SO.BirthDistrict,C.characterDate,OM.CityName,OM.StateName,SO.FamilyCast,SO.FamilySubCast,SO.GenderId,SI.StudentPhoto,SM.StatusId,OM.OrgLogo,OM.Title,
		--OM.StreetOne,OM.StreetThree,OM.StreetTwo,OM.PhoneNo
	END
GO
PRINT N'Altering [sCertificate].[pRptFirstTrialCertificateGet]...';


GO
 
 

ALTER PROCEDURE [sCertificate].[pRptFirstTrialCertificateGet]
	 
	 @rBuilder1 nvarchar(max)='',
	 @rBuilder2 nvarchar(max)='', 
	 @rOrgId smallint,
	 @rBatchId int,
	 @rFromNo nvarchar(20)='',
	 @rToNo nvarchar(20)='',
	 @rNumber nvarchar(20)='',
	 @rClassId int=0,
	 @rDivisionId int=0,
	 @rFromDate date='',
	 @rToDate date='',
	 @rCode nvarchar(20)='',
     @rName nvarchar(20)=''
	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
DECLARE @lIsOnPrePrinted bit = 0

DECLARE @lIsDisplayImageHeader bit = 0

DECLARE @lConfigValue nvarchar(50)
Declare @lIDConfigValue nvarchar(50)='',@lOrgGroupId int=0

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

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

	SELECT 
	
			@rBuilder1 AS Builder1,
		    @rBuilder2 AS Builder2,
			FT.Id,
			FT.Number,
			FT.AcademicId,
			FT.FirstTrialDate,
			FT.ExamCentre,
			FT.ExamYear,
			FT.SeatNo,
			FT.Trial,
			SM.Code,
			--SM.FirstName+' '+SM.MiddleName+' '+SM.LastName AS Name,
			[sStudent].[fStudentNameGet](SM.FirstName , SM.MiddleName, SM.LastName,OM.StudentNameFormatId ) AS Name,
			SM.LastName as Surname,
			SO.GenderId,
			ISNULL(OM.CityName,'') AS City,
			ISNULL(OM.StateName,'') AS CityState,
			SM.StatusId,
			OM.OrgLogo,
			OM.Title AS OrgTitle,
			OM.StreetOne+' '+OM.StreetTwo+' '+OM.StreetThree AS OrgAddress,
			OM.PhoneNo,
			A.RollNo,
			DM.OrderIndex AS DivisionOrder,
			OM.ReportOrgTitle,
			OM.SmallAddress1,
			OM.SmallAddress2,
			OM.RegistrationDetail,
			@lIsOnPrePrinted AS IsOnPrePrinted,
			CM.DisplayTitle+' - '+DM.DisplayTitle AS Class,
			CM.DisplayTitle  AS ClassName,
			@lIsDisplayImageHeader AS IsDisplayImageHeader,
			--OI.CertificateHeaderA4  ,
			(CASE WHEN CGM.Title='10' THEN  'SSC'
			WHEN  CGM.Title='12'  THEN 'HSC'  ElSE CGM.Title + ' '+'std'
			 END) AS Exam,
			 FT.Remark AS Remark,
			 ISNULL(SF.FatherName,'') As FatherName,
			 ISNULL(SF.MotherName,'') As MotherName,
			 SA.AdmissionDate,
			 SO.BirthDateInWord ,
			 SO.DateOfBirth,
			 SI.StudentPhoto,
			 @lIDConfigValue AS ItemValue,
			 SM.SUID ,
			 STM.Title as StreamName,
			 ISNULL(OM.ReportOrgGroupTitle,'') AS ReportOrgGroupTitle,
			 OM.ReportOrgTitle,
			--(CASE WHEN OI.CertificateHeaderA4Portrait IS NULL THEN
			--OI.CertificateHeaderA4
			--ELSE OI.CertificateHeaderA4Portrait END ) AS CertificateHeader	
			OI.CertificateHeaderA4Portrait AS CertificateHeaderA4,
			BM.Title AS Batch,
			ISNULL(SA.LeftDate,'') AS LeftDate,
			ISNULL(EI.EmployeeSign,0x) AS EmployeeSign,
			ISNULL(OM.PrincipalSignature,0x) AS PrincipalSignature
	FROM 
			sCertificate.tFirstTrial FT
			INNER JOIN sStudent.tAcademic A ON FT.AcademicId=A.Id
			LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId=A.StudentId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id=A.StudentId			
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sStudent.tStudentOther SO ON SO.StudentId=A.StudentId
			INNER JOIN sSetup.tDivisionMaster DM ON A.DivisionId = DM.Id  
			INNER JOIN sSetup.tClassMaster CM ON CM.Id= DM.ClassId 
			INNER JOIN  sSetup.tStreamMaster STM ON STM.Id= CM.StreamId 
			Left JOIN sSetup.tOrgImages OI ON OI.OrgId = OM.Id
			LEFT JOIN sSetup.tClassGroupMaster CGM ON CGM.Id = CM.ClassGroupId
			LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId=A.StudentId
			LEFT JOIN sStudent.tStudentAdmission SA ON SA.StudentId=A.StudentId
			INNER JOIN sSetup.tBatchMaster BM ON BM.Id=A.BatchId
			LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId = DM.InchargeEmployeeId
			
	WHERE 
			A.OrgId=@rOrgId
			AND	A.BatchId = @rBatchId 
			AND ((A.ClassId=@rClassId) OR (@rClassId=0))
			AND ((A.DivisionId=@rDivisionId) OR (@rDivisionId=0))
			AND ((SM.Code = @rCode) OR (ISNULL(@rCode,'') = ''))
			AND ((SM.FirstName = @rName) OR (ISNULL(@rName,'') = ''))
			AND ((FT.FirstTrialDate>=@rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((FT.FirstTrialDate<=@rToDate) OR (ISNULL(@rToDate,'')=''))
			AND ((FT.Number=@rNumber) OR (@rNumber=''))
			AND ((FT.Number >= @rFromNo) OR (@rFromNo=''))
			AND ((FT.Number <= @rToNo) OR (@rToNo=''))
			--Group By FT.AcademicId,SM.Code,SM.FirstName,SM.LastName,SM.MiddleName,FT.SeatNo,FT.Trial,SM.Code,SM.FirstName,OM.StateName,SO.GenderId,
			--OM.CityName,OM.StateName,FT.FirstTrialDate,FT.ExamCentre,FT.ExamYear,SM.MiddleName,SM.LastName,OM.CityName,SM.StatusId
			--,OM.OrgLogo,OM.PhoneNo,OM.Title,OM.StreetOne,OM.StreetTwo,OM.StreetThree
	END
GO
PRINT N'Altering [sCommon].[pOrganizationSetupRemove]...';


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

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


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

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

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

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

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

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

DELETE FROM sTimetable.tAssignOrg WHERE OrgId = @rOrgId

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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


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

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

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

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

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

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

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

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


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


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

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

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

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

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


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

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


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

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


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

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


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

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

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

DELETE FROM sFrontOffice.tOTPLog WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId
DELETE FROM sHrm.tLeaveDeduction WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId


DELETE FROM sAdmission.tAdmissionCriteriaDocument WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAdmission.tAdmissionStudentDocument WHERE CAST(LEFT(AdmissionFormId, 4) AS bigint) = @rOrgId
DELETE FROM sTimetable.tTimeTableTime WHERE CAST(LEFT(DivisionId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeWorkingDays WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId

DELETE FROM sErp.tContactBookMaster WHERE OrgId= @rOrgId
DELETE FROM sErp.tEmployeeERPDetail WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sFrontOffice.tLostFoundRegisterScope WHERE CAST(LEFT(SourceId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeChangeHistory WHERE CAST(LEFT(EmployeeId, 4) AS bigint) = @rOrgId
DELETE FROM sCommon.tReportTemplate WHERE OrgId= @rOrgId
DELETE FROM sTransport.tBusRouteAssignedTo WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sWorkflow.tStudentDataChange WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearning WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignment WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAssignmentSubmit WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendance WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningAttendanceLog WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningReference WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningResource WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tOnlineLearningScope WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sAcademic.tTempOnlineLearningScope WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tChat WHERE CAST(LEFT(FromSourceId, 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tTempChatGroupScope WHERE CAST(LEFT(MemberSourceId, 4) AS bigint) = @rOrgId


DELETE FROM sAcademic.tOnlineMeetingSettings WHERE CAST(LEFT(OnlineLearningId, 4) AS bigint) = @rOrgId
DELETE FROM sStudent.tDigitalForm WHERE OrgId= @rOrgId
DELETE FROM sStudent.tDigitalFormScope WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormField WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId
DELETE FROM sStudent.tDigitalFormStudent WHERE CAST(LEFT(DigitalFormId, 4) AS int) = @rOrgId

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

DELETE FROM sOp.tPaymentTransactionHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeHistory WHERE CAST(LEFT(Id, 4) AS INT) = @rOrgId
DELETE FROM sFee.tOnlineFeeDetailHistory WHERE CAST(LEFT(OnlineFeeId, 4) AS INT) = @rOrgId
DELETE FROM sCommunication.tStudentDocumentUpload WHERE CAST(LEFT(BatchId, 4) AS INT) = @rOrgId

DELETE FROM sFee.tFeeAllocationHistory WHERE CAST(LEFT(SourceId, 4) AS bigint) = @rOrgId

DELETE FROM sCommon.tUploadDocument WHERE CAST(LEFT(CreatedUserId, 4) AS bigint) = @rOrgId

DELETE FROM sFee.tFeeAllocationStudent WHERE CAST(LEFT(AcademicId, 4) AS bigint) = @rOrgId
DELETE FROM sFee.tFeeClassBatchStatus WHERE CAST(LEFT(BatchId, 4) AS int) = @rOrgId
DELETE FROM sHrm.tEmployeeBatch WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sCommunication.tEmployeeDocumentUpload WHERE OrgId = @rOrgId

DELETE FROM [sHrm].[tEmployeeCustomFieldData] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommunication].[tDailyThoughtAssign] WHERE OrgId= @rOrgId
DELETE FROM [sFee].[tEMandate] WHERE CAST(LEFT(Id, 4) AS bigint) = @rOrgId

DELETE FROM [sAdmission].[tAdmissionInquiryCriteria] WHERE CAST(LEFT([ClassId], 4) AS int) = @rOrgId
DELETE FROM [sCommon].[tSubmitDocumentScope] WHERE CAST(LEFT([SubmitDocumentId], 4) AS int) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningRecording WHERE CAST(LEFT([OnlineLearningId], 4) AS bigint) = @rOrgId

DELETE FROM [sCommon].[tUserToken] WHERE CAST(LEFT([UserId], 4) AS bigint) = @rOrgId

DELETE FROM [sBiometric].[tEmployeeConfiguration] WHERE CAST(LEFT([EmployeeId], 4) AS bigint) = @rOrgId
DELETE FROM sAlert.tWhatsAppConfiguration WHERE OrgId= @rOrgId
DELETE FROM sFee.tDepositSetup WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sAlert].[tWhatsAppLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM sAcademic.tOnlineLearningHistoryLog WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId

DELETE FROM [sAlert].[tAlertTrack] WHERE OrgId = @rOrgId
DELETE FROM sTally.tJVPosting WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId

DELETE FROM [sHrm].[tLeavePeriod] WHERE OrgId = @rOrgId
DELETE FROM [sRecruitment].[tAssignOrganization] WHERE OrgId = @rOrgId

DELETE FROM sAdmission.tAdmissionCustomSearch WHERE OrgId = @rOrgId

DELETE FROM[sCommunication].[tTempQueryCategoryScope] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId


DELETE FROM [sStudent].[tOnlineRegistrationStudentAdmission] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCommunication] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentCustomFieldData] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentDocument] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentFamily] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentImages] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentOther] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCollegeDetail] WHERE CAST(LEFT([StudentId], 4) AS bigint) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationDisplayField]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaDocument]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationCriteriaForm]  WHERE CAST(LEFT([BatchId], 4) AS int) = @rOrgId
DELETE FROM [sStudent].[tOnlineRegistrationStudentMaster] WHERE OrgId = @rOrgId

DELETE FROM [sBiometric].[tShiftAllocationCloud] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sBiometric].[tCloudTransactionData] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId

DELETE FROM [sTransport].[tAssignRouteLog] WHERE CAST(LEFT([SourceId], 4) AS bigint) = @rOrgId
DELETE FROM [sAttendance].[tAttendanceFollowup] WHERE CAST(LEFT([AcademicId], 4) AS bigint) = @rOrgId




--EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

	SELECT 1 AS Result
 
-- COMMIT TRANSACTION
		
--	END TRY
	
--	BEGIN CATCH 
--		ROLLBACK TRANSACTION
--		SELECT -1 AS Result
		
--	END CATCH
END
GO
PRINT N'Altering [sCommunication].[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 
			DISTINCT
			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 [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
   --         INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
   --         INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			--INNER JOIN [sSetup].[tClassSubject] CS on CS.SubjectId = SM.Id	
			--LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId and CS.ClassId = Dm.classId 
			--LEFT JOIN sCommunication.tAssignmentView AV ON A.Id = AV.AssignmentId
			 sCommunication.tAssignment A
			INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
            INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId AND CAS.SourceTypeId = 2005
			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 [sCommunication].[pAssignmentGetWithScope]...';


GO

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

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
		DISTINCT
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			STUFF((
			SELECT ',' + DM.Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sSetup.tDivisionMaster DM ON CAS.SourceId = DM.Id Where  CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2005 
			FOR XML PATH ('')), 1, 1, '') as StudentSource ,			 
			STUFF((			  
			SELECT ',' + Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sSetup.tDepartmentMaster CM ON CAS.SourceId = CM.Id Where CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2017			  
			FOR XML PATH ('')), 1, 1, '') as EmployeeSource
		    
  FROM 
   --         sCommunication.tAssignment A
			--INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
   --         INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
   --         INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			--INNER JOIN [sSetup].[tClassSubject] CS on CS.SubjectId = SM.Id												
			--LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId and CS.ClassId = Dm.classId 

			 sCommunication.tAssignment A
			INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
            INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId AND CAS.SourceTypeId = 2005
  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 ((DM.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((DM.Id = @rDivisionId) OR (@rDivisionId = 0))
	AND A.BatchId=@rBatchId
	ORDER BY A.StartDate DESC
END
GO
PRINT N'Altering [sCommunication].[pMyUpdateGet]...';


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

 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN   
 DECLARE @lAcademicId bigint,  
  @lScopeSourceId int,  
  @lScopeSourceTypeId int,  
  @lStudentId bigint,  
  @lClassId int,  
  @lDivisionId int,  
  @lOrgId int,  
  @lDepartmentId int,  
  @lAssignmentStatus bit=0,  
  @lCircularStatus bit=0,  
  @lPollStatus bit=0,  
  @lQueryStatus bit=0,  
  @lBlogStatus bit=0,  
  @lNewsStatus bit=0,  
  @lBehaviourStatus bit=0,  
  @lActivityStatus bit=0,  
  @lResultStatus bit=0,  
  @lAssignTaskStatus bit=0,  
  @lPhotoCategoryStatus bit=0,  
  @lIsActive bit=0,  
  @lIsOptimizeAppImageUpload bit=0  
  
IF( @rUserSourceTypeId = 2003)   
BEGIN  
  SELECT @lAcademicId = A.Id,@lStudentId = A.StudentId,@lClassId = A.ClassId, @lDivisionId = A.DivisionId, @lOrgId= A.OrgId, @lDepartmentId=CM.DepartmentId  
  FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM  
 ON A.BatchId = BM.Id AND BM.IsActive = 1   
 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId  
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
--SELECT @lAcademicId = Id, @lScopeSourceId = DivisionId FROM sStudent.tAcademic WHERE StudentId = @rUserSourceId AND BatchId = @rBatchId  
SET @lScopeSourceId = @lDivisionId  
SET @lScopeSourceTypeId = 2005  
END  
ELSE  
BEGIN  
 SELECT @lDepartmentId=EJD.OrganizationDepartmentId,@lOrgId = EM.OrgId  FROM sHrm.tEmployeeMaster EM INNER JOIN sHrm.tEmployeeJobDetail EJD  
    ON EJD.EmployeeId = EM.Id WHERE EM.Id=@rUserSourceId AND ISNULL(EM.IsOtherUser,0) = 0  
--SELECT @lScopeSourceId = OrganizationDepartmentId FROM sHrm.tEmployeeJobDetail WHERE EmployeeId = @rUserSourceId  
SET @lScopeSourceId = @lDepartmentId  
SET @lScopeSourceTypeId = 2004  
END  
--IF EXISTS(SELECT 1 FROM sCommunication.tAssignmentScope ASO INNER JOIN  sCommunication.tAssignment A  
-- ON A.Id = ASO.AssignmentId  
--WHERE ASO.AssignmentId > @rSyncedAssignmentId AND ASO.SourceTypeId = @lScopeSourceTypeId AND ASO.SourceId = @lScopeSourceId AND A.BatchId=@rBatchId)  
--SET @lAssignmentStatus = 1  
  
  
--IF( @rUserSourceTypeId = 2003)   
--BEGIN  
  
--    IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS WHERE  
--      ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId)   
--      OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId)  
--      OR (CS.SourceTypeId = 2016 AND CS.SourceId =@lClassId)  
--      OR (CS.SourceTypeId = 2005 AND CS.SourceId =@lDivisionId)  
--      OR (CS.SourceTypeId = 2003 AND CS.SourceId =@lStudentId)  
--      OR (CS.SourceTypeId = 2001 AND CS.SourceId =@lAcademicId)  
--      )  
--       AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D ON D.CircularId= C.Id  
--      --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId  
--        WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)  
--        AND C.AssigneeId IN (1,2) AND C.OrgGroupBatchId=@rOrgGroupBatchId)   
--      SET @lCircularStatus = 1  
  
--END   
--ELSE  
--BEGIN  
-- IF EXISTS(SELECT 1 FROM sCommunication.tCircular C INNER JOIN (SELECT CS.CircularId FROM sCommunication.tCircularScope CS  
--       WHERE ((CS.SourceTypeId = 2021 AND CS.SourceId =@lOrgId) OR (CS.SourceTypeId = 2004 AND CS.SourceId =@lDepartmentId))  
--       AND (CS.CircularId > @rSyncedCircularId OR @rSyncedCircularId = 0)) D ON D.CircularId= C.Id  
--       --INNER JOIN sSetup.tOrgGroupBatchMaster OGBM ON OGBM.Id=C.OrgGroupBatchId AND OGBM.Id=@rOrgGroupBatchId  
--       WHERE ( c.Id > @rSyncedCircularId OR @rSyncedCircularId = 0)  
--       AND C.AssigneeId IN (1,3) AND C.OrgGroupBatchId=@rOrgGroupBatchId)   
--     SET @lCircularStatus = 1         
  
--END  
--IF EXISTS(SELECT 1 FROM sCommunication.tCircularScope WHERE  CircularId > @rSyncedCircularId AND SourceTypeId = @lScopeSourceTypeId AND SourceId = @lScopeSourceId)  
--SET @lCircularStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tPoll P INNER JOIN sCommunication.tPollMember PM ON P.Id=PM.PollId  
-- WHERE PM.PollId > @rSyncedPollId AND PM.SourceTypeId = @lScopeSourceTypeId AND PM.SourceId = @lScopeSourceId AND P.OrgGroupBatchId=@rOrgGroupBatchId)  
--SET @lPollStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tBlogScope BS INNER JOIN sCommunication.tBlog B  
--ON B.Id = BS.BlogId  
--WHERE B.IsPublish = 1 AND BS.BlogId > @rSyncedBlogId AND BS.SourceTypeId = 2021 AND BS.SourceId = @rOrgId AND B.OrgGroupBatchId = @rOrgGroupBatchId)  
--SET @lBlogStatus = 1  
  
--IF EXISTS(SELECT 1 FROM  sCommunication.tNews N INNER JOIN sCommunication.tNewsScope NS ON N.Id=NS.NewsId   
--   WHERE NS.NewsId > @rSyncedNewsId AND NS.SourceTypeId = 2021 AND NS.SourceId = @rOrgId AND N.OrgGroupBatchId = @rOrgGroupBatchId)  
--SET @lNewsStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tNewsScope WHERE NewsId > @rSyncedNewsId AND SourceTypeId = @rOrgId AND SourceId = 1016)  
--SET @lNewsStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tUploadResult WHERE Id > @rSyncedResultId AND DivisionId = @lScopeSourceId AND BatchId=@rBatchId AND IsObsolete=0 )  
--SET @lResultStatus = 1  
  
--IF EXISTS(SELECT 1 FROM    
--sCommunication.tPhotoCategoryMaster PCM  
--INNER JOIN sCommunication.tPhotoCategoryScope PCO   
--ON PCM.Id=PCO.PhotoCategoryId WHERE PCM.Id > @rSyncedPhotoCategoryId AND LEFT(PCO.ScopeSourceId,4) = @rOrgId  AND PCM.IsObsolete=0 )  
--SET @lPhotoCategoryStatus = 1  
  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tAssignTask WHERE  Id > @rSyncedAssignTaskId AND AssignedToSourceTypeId = @rUserSourceTypeId   
--AND AssignedToSourceId = @rUserSourceId AND IsCompleted=0 AND IsClosed=0 AND OrgId=@rOrgId)  
--SET @lAssignTaskStatus = 1  
  
  
--IF EXISTS(SELECT 1 FROM  sActivity.tActivity A INNER JOIN sActivity.tActivityParticipant AP ON A.Id=AP.ActivityId  
-- WHERE AP.ActivityId > @rSyncedActivityId AND AP.SourceTypeId = @rUserSourceTypeId AND AP.SourceId = @rUserSourceId AND A.BatchId=@rBatchId)  
--SET @lActivityStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tBehaviour WHERE Id > @rSyncedBehaviourId AND AcademicId = @lAcademicId )  
--SET @lBehaviourStatus = 1  
  
--IF EXISTS(SELECT 1 FROM sCommunication.tQuery Q INNER JOIN sCommunication.tQueryComment QC ON Q.Id=QC.QueryId  
--WHERE Q.CreatedUserId=@rUserId AND Q.IsUserView=0 AND QC.Id>@rSyncedQueryCommentId AND QC.CreatedUserId <> @rUserSourceId AND Q.OrgGroupBatchId=@rOrgGroupBatchId)  
--SET @lQueryStatus = 1  
   
IF(@rUserSourceTypeId = 2003)  
BEGIN   
 DECLARE @lStatusId1 smallint=0  
  SELECT @lStatusId1 = StatusId FROM sStudent.tStudentMaster SM WHERE Id = @rUserSourceId  
 IF(@lStatusId1=1)  
 BEGIN   
  SET @lIsActive = 1  
 END ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
ELSE IF(@rUserSourceTypeId = 95)  
BEGIN   
 DECLARE @lStatusId2 smallint=0  
 SELECT @lStatusId2 = StatusId FROM sHrm.tEmployeeMaster EM WHERE Id = @rUserSourceId --AND ISNULL(EM.IsOtherUser,0) = 0  
 IF(@lStatusId2=7)  
 BEGIN   
  SET @lIsActive = 1  
 END ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
ELSE IF(@rUserSourceTypeId = 1)  
BEGIN   
 DECLARE @IsObsolete smallint=0  
 SELECT @IsObsolete=ISNULL(IsObsolete,0) FROM sSecurity.tUser WHERE Id = @rUserId  
 IF(@IsObsolete=0)  
 BEGIN   
  SET @lIsActive = 1  
 END   
 ELSE  
 BEGIN  
  SET @lIsActive = 0  
 END  
END  
  
IF(@lIsActive=1)  
BEGIN  
 DECLARE @lIsObsolete bit=0  
 SELECT @lIsObsolete=ISNULL(IsObsolete,0) FROM sSecurity.tUser WHERE Id = @rUserId  
  
 IF(@lIsObsolete=0)  
  SET @lIsActive = 1  
 ELSE  
  SET @lIsActive = 0  
END  
  
  
DECLARE @lOrgGroupId int=0  
SELECT @lOrgGroupId=OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id =@rOrgId  
DECLARE @lOptimizeAppImageUpload nvarchar(50)  
SELECT @lOptimizeAppImageUpload = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 247 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
IF (@lOptimizeAppImageUpload IS NULL) OR (@lOptimizeAppImageUpload = 'False')  
 SET @lIsOptimizeAppImageUpload = 0  
ELSE  
 SET @lIsOptimizeAppImageUpload = 1   
   
DECLARE @lAlertRemark nvarchar(2000) = ''  
   
--IF(@rVersionNumber IS NULl OR @rVersionNumber='')  
--BEGIN  
-- DECLARE @lUserName nvarchar(100)=''  
-- DECLARE @lUserPassword nvarchar(100)=''  
-- DECLARE @lBatch nvarchar(100)=''  
-- SELECT @lBatch = Title  FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
   
-- SELECT @lUserName=UserName,@lUserPassword=UserPassword FROM sSecurity.tTempUser WHERE UserId = @rUserId  
-- SET @lAlertRemark = 'Plese install the new app from this location (https://play.google.com/store/apps/details?id=com.vidyalaya.pinnacleschoolgandhinagarnew) Uninstall the old app. Login in new app with  
--       Registration Number : '+LEFT(@rOrgGroupBatchId,4) +'  
--       User Name : '+@lUserName+'  
--       Password : '+@lUserPassword+'  
--       Batch :' + @lBatch  
--END  
--ELSE   
BEGIN  
 SELECT @lAlertRemark=AlertRemark FROM sSetup.tOrgGroupConfiguration WHERE OrgGroupId = @lOrgGroupId  
END  
  
DECLARE @lMobileAppModuleAutoSyncToken nvarchar(50)  
SELECT @lMobileAppModuleAutoSyncToken = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 317 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId  
  
  
DECLARE @lIsStopApplicationAccess bit=0  
DECLARE @lStudentCustomAlert nvarchar(1000)=''  
IF(@rUserSourceTypeId=2003)  
SELECT @lIsStopApplicationAccess = ISNULL(IsStopApplicationAccess,0) ,@lStudentCustomAlert= ISNULL(StudentCustomAlert,'') FROM sStudent.tStudentCommunication WHERE StudentId = @rUserSourceId  
  
  
IF(LEN(@rDeviceToken) > 0)  
BEGIN   
 DECLARE @lDeviceToken nvarchar(200)=''  
 SELECT @lDeviceToken = DeviceToken FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND OSTypeId = @rOSTypeId  
  
 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  
 IF(@lDeviceToken!=@rDeviceToken)  
  SET @lIsActive=0  
 END  
 
 SET @lDeviceToken = (SELECT DeviceToken FROM sCommunication.tRegisteredUsers WHERE OrgId=@rOrgId AND UserId=@rUserId AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId AND DeviceToken=@rDeviceToken)  	
 IF(@lDeviceToken IS NULL OR @lDeviceToken='' OR ISNULL(@lDeviceToken,'') = '')  
  SET @lIsActive=0  
END  
  
DECLARE @lActiceClassBatchId NVARCHAR(MAX) = '',@lBatchClassId int  
   
IF(@rUserSourceTypeId = 2003)  
BEGIN   
 SELECT @lBatchClassId = A.ClassId  
 FROM sStudent.tAcademic A INNER JOIN sSetup.tBatchMaster BM ON A.BatchId = BM.Id  
 INNER JOIN sSetup.tClassMaster CM ON CM.Id = A.ClassId  
 WHERE StudentId = @rUserSourceId AND BM.OrgGroupBatchId = @rOrgGroupBatchId  
  
 IF EXISTS(SELECT BatchId FROM [sSetup].[tBatchClass] BC INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId WHERE ClassId = @lBatchClassId AND IsBatchClassActive = 1 AND BM.IsActive = 1)  
 BEGIN  
  SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,BC.BatchId)+','+ BM.Title FROM [sSetup].[tBatchClass] BC INNER JOIN sSetup.tBatchMaster BM ON BM.Id = BC.BatchId WHERE BC.ClassId = @lBatchClassId AND BC.IsBatchClassActive = 1 AND BM.IsActive = 1  
 END  
 ELSE  
 BEGIN  
  SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,Id) +','+ Title FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
 END  
END  
ELSE IF(@rUserSourceTypeId = 95)  
BEGIN  
 SELECT @lActiceClassBatchId = CONVERT(NVARCHAR,Id) +','+ Title FROM sSetup.tBatchMaster WHERE Id = @rBatchId  
END  


IF(LEN(ISNULL(@rAppVersion,'')) > 0 AND LEN(ISNULL(@rAppVersion,'')) > 0)
BEGIN
	UPDATE sCommunication.tRegisteredUsers
	SET
		AppVersion = @rAppVersion,
		AppName = @rAppName,
		UpdatedDateTime = sCommon.fGetDate()
	WHERE 
		DeviceToken = @rDeviceToken 
		AND OsTypeId = @rOSTypeId
		AND OrgId=@rOrgId AND UserId=@rUserId 
		AND UserSourceId=@rUserSourceId AND UserSourceTypeId = @rUserSourceTypeId
END
CREATE TABLE #Module (  
Id int,  
Title nvarchar(2000),  
IsNew bit )  
INSERT INTO #Module VALUES (1,'IsActiveCheck',CONVERT(bit,@lIsActive))  
INSERT INTO #Module VALUES (2,'IsOptimizeAppImageUpload',@lIsOptimizeAppImageUpload)  
INSERT INTO #Module VALUES (3,ISNULL(@lAlertRemark,''),1)  
INSERT INTO #Module VALUES (4,ISNULL(@lMobileAppModuleAutoSyncToken,0),1)  
INSERT INTO #Module VALUES (5,'Is Stop Application Access',@lIsStopApplicationAccess)  
INSERT INTO #Module VALUES (6,@lStudentCustomAlert,1)  
INSERT INTO #Module VALUES (20085,'Circular',0)  
INSERT INTO #Module VALUES (20088,'Query',0)  
INSERT INTO #Module VALUES (20099,'Blog',0)  
INSERT INTO #Module VALUES (20104,'News',0)  
INSERT INTO #Module VALUES (20172,'AssignTask',0)  
INSERT INTO #Module VALUES (20183,'Gallery',0)  
INSERT INTO #Module VALUES (20204,'Poll',0)  
INSERT INTO #Module VALUES (20093,'Assignment',0)  
INSERT INTO #Module VALUES (20209,'Activity',0)  
INSERT INTO #Module VALUES (20130,'Behaviour',0)  
INSERT INTO #Module VALUES (20180,'Result',0)  
INSERT INTO #Module VALUES (7,@lActiceClassBatchId,1)  
   
SELECT * FROM #Module  
   
--SELECT @lAssignmentStatus AS Assignment,@lCircularStatus AS Circular,@lPollStatus AS Poll,@lQueryStatus AS Query,  
--@lBlogStatus AS Blog,@lNewsStatus AS News,@lBehaviourStatus AS Behaviour,  
--@lActivityStatus AS Activity,@lResultStatus AS Result,@lAssignTaskStatus AS AssignTask,@lPhotoCategoryStatus AS Gallery  
  
END
GO
PRINT N'Altering [sConfig].[pConfigurationSetupAdd]...';


GO
  
 
ALTER PROCEDURE [sConfig].[pConfigurationSetupAdd]
	 
	@rConfigurationId [int],
	@rItemValue nvarchar(500),
	@rSourceTypeId [int],
	@rSourceId [bigint],
	@rCreatedUserId [bigint],
	@rOrgId int
	 
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON

BEGIN

	 DELETE FROM sConfig.tConfigurationSetup 
     WHERE 
     ConfigurationId  = @rConfigurationId 
     AND SourceId=@rSourceId 
     AND SourceTypeId=@rSourceTypeId
 
	DECLARE @lNextNumber BIGINT     
	
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sConfig.tConfigurationSetup', 0, 1, 1,@outNextNumber = @lNextNumber output

 IF NOT EXISTS(Select 1 From sConfig.tConfigurationSetup Where ConfigurationId = @rConfigurationId AND SourceId = @rSourceId AND SourceTypeId=@rSourceTypeId)
  
   BEGIN
	
	IF(@rItemValue!='')
	BEGIN
	INSERT INTO [sConfig].[tConfigurationSetup]
           ([Id]
           ,[ConfigurationId]
           ,[ItemValue]
           ,[sourceTypeId]
           ,[SourceId]
           ,[CreatedUserId]
           ,[CreatedDateTime]        
            )
     VALUES
           (
            @lNextNumber,
            @rConfigurationId,
            @rItemValue,
            @rSourceTypeId,
            @rSourceId,
            @rCreatedUserId,
            sCommon.fGetDate()
            )
      END      
          select 1 as result
   END
  ELSE
   BEGIN
      UPDATE sConfig.tConfigurationSetup 
          SET ItemValue = @rItemValue,
          UpdatedUserId = @rCreatedUserId,
          UpdatedDateTime =  sCommon.fGetDate()
          
       Where ConfigurationId  = @rConfigurationId AND SourceId=@rSourceId AND SourceTypeId=@rSourceTypeId
		Select 11 as result
   END       
           
END
GO
PRINT N'Altering [sFee].[pFeeCustomSearchGet]...';


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

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


GO
 

ALTER PROCEDURE [sFee].[pRptFeeFolioGet]
		
		@rBuilder1 nvarchar(max)='',
		@rBuilder2 nvarchar(max)='',
		@rReportId int=0,
		@rIsFilter bit=0,
	    @rIsDisplayOrgGroup bit=0,
	    @rIsFeeInvoiceHeadwise bit=0,
		@rOrgGroupBatchId int=0,
		@rCommonBatch nvarchar(100)='',
		@rReceiptBookId int=0,
		@rOrgId int=0,
		@rBatchId int=0,
		@rDepartmentId int=0,
		@rAdmissionCategoryId int=0,
		@rClassId int=0,
		@rDivisionId int=0,
		@rStatusId int=0,
		@rFromRollNo int=0,
	    @rToRollNo int=0,
	    @rCode nvarchar(20)='',
	    @rCollectionGroupId int=0,
	    @rFeeHeadId nvarchar(max) = '',
	    @rFirstName nvarchar(100)='',
	    @rFromInvoiceNumber int=0,
		@rToInvoiceNumber int=0,
		@rCreatedUserName nvarchar(100)='',
		@rFeeInvoiceIds nvarchar(max)='',
		@rFilterId int=0,
		@rOrgIds nvarchar(max) = '' , 
		@rParentContactNo nvarchar(20) = '',
		@rClassStatusId int=0
	    
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
			
	BEGIN
			SET @rFirstName = sCommon.fSearchStringGet(@rFirstName)
			SET @rCreatedUserName = sCommon.fSearchStringGet(@rCreatedUserName)
	END		
			 
BEGIN
	SELECT 
		@rBuilder1 AS Builder1,
		@rBuilder2 AS Builder2,
		@rIsFilter AS IsFilter,
		@rIsDisplayOrgGroup AS IsDisplayOrgGroup,
		@rIsFeeInvoiceHeadwise AS IsFeeInvoiceHeadwise,
		SA.AcademicId,
		SA.Name,
		SA.ClassId,
		SA.ClassName,
		SA.DivisionId,
		SA.DivisionName,
		SA.DivisionOrder,
		SA.RollNo,
		SA.Code,
		SA.DepartmentId,
		SA.DepartmentName,
		FM.Id AS FeeId,
		FM.Title AS FeeName,
		FM.OrderIndex AS FeeOrderIndex,
		FHM.Id AS FeeHeadId,
		FHM.Title AS FeeHeadName,
		FHM.OrderIndex AS FeeHeadOrderIndex,
		RBM.Id AS ReceiptBookId,
		RBM.Title AS ReceiptBookName,
		RBM.BankName,
		RBM.BankAccountNumber,
		RBM.OrderIndex AS ReceiptBookOrderIndex,
		FID.Amount AS FeeAmount,
		CGM.Id AS CollectionGroupId,
		CGM.Title AS CollectionGroupName,
		CGM.OrderIndex AS CollectionGroupOrderIndex,
		CGM.FooterRemark1 AS FooterRemark1,
		CGM.FooterRemark2 AS FooterRemark2,
		CGM.FeePeriod AS FeePeriod,
		SA.BatchName,
		CGM.StartDate,
		CGM.EndDate,
		CGM.Remark,
		RBM.FullTitle,
		RBM.Address1,
		RBM.Address2,
		OM.OrgLogo,
		SC.ParentContactNo,
		ISNULL(RBM.IsOnPrePrinted,0) AS IsOnPrePrinted,
		ISNULL(RBM.IsSupressLogo,0) AS IsSupressLogo,
		OGM.Title AS OrgGroupName,
		sFinanceCommon.fDefaultCurrencyTitleGet(OM.OrgGroupId) AS CurrencyTitle,
		ISNULL(SO.GenderId,0) AS GenderId,
		sFinanceCommon.fDefaultCurrencyCodeGet(OM.OrgGroupId) AS CurrencyCode,
		FI.InvoiceNumber,
 
		CASE WHEN FAL.DiscountAmount=0 THEN  null
		 ELSE FAL.DiscountAmount END AS ExemptionAmount,
		 RBM.GroupTitle,
		 SA.Suid,
		ISnull(CGM.IsDisplayCashDetailInFolio,0) AS IsDisplayCashDetailInFolio,
       ISnull(CGM.IsOnPrePrinted,0) AS IsOnPrePrintedHeader,
		
       
       CASE
				 WHEN RBM.IsOnPrePrinted=1       
				 THEN 2
				 ELSE  ISNULL(RBM.FeeInvoiceHeaderDisplayId,1)
				END AS FeeInvoiceHeaderDisplayId,
       RBM.FeeInvoiceHeader,
       isnull(rt.pickuppoint,'') as Pickuppoint,
        isnull(rt.Droppoint,'') as Droppoint,
        SA.MiddleName AS FatherName,
		ISNULL(SF.FatherName,'') AS FatherNameFamily,
		ISNULL(SF.MotherName,'') AS MotherName,
		FI.InvoiceDate        
  FROM 
		sFee.tFeeInvoiceDetail FID 
		INNER JOIN sFee.tFeeInvoice FI ON FI.Id = FID.FeeInvoiceId
		INNER JOIN sFee.tFeeSetup FS ON FS.Id = FID.FeeSetupId		
		INNER JOIN sStudent.vStudentAcademic SA ON FI.SourceTypeId = 2001 AND FI.SourceId = SA.AcademicId AND FI.BatchId=SA.BatchId AND FI.OrgGroupBatchId = SA.OrgGroupBatchId
		INNER JOIN sFee.tFeeMaster FM ON FM.Id = FS.FeeId
		INNER JOIN sFee.tFeeHeadMaster FHM ON FHM.Id = FM.FeeHeadId
		INNER JOIN sFee.tReceiptBookMaster RBM ON RBM.Id = FS.ReceiptBookId
		INNER JOIN sSetup.tOrgGroupMaster OGM ON OGM.Id = RBM.OrgGroupId
		LEFT JOIN sFee.tCollectionGroupMaster CGM ON CGM.Id = FS.CollectionGroupId AND SA.OrgGroupBatchId = CGM.OrgGroupBatchId
		LEFT JOIN sSetup.tOrganizationMaster OM ON OM.Id=SA.OrgId
		LEFT JOIN sStudent.tStudentOther SO ON SO.StudentId = SA.StudentId
		LEFT JOIN sSecurity.tUser U ON U.Id=FI.CreatedUserId
		LEFT JOIN sFee.tFeeAllocation FAL  ON FAL.FeeSetupId  = FS.Id AND FAL.SourceId = FI.SourceId 
		 LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
       LEFT JOIN
	(SELECT AT.SourceId,BM.Title as pickuppoint,BM1.Title as droppoint 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))
    Left JOIN sTransport.tBusRouteDestinationMaster BM1 ON BM1.Id=AT.DropDestinationId
    LEFT JOIN sTransport.tBusRouteMaster B1 ON B1.Id=BM1.BusRouteId AND  AT.SourceTypeId=2003 AND ((B1.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))
    ) RT
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0)) 
	Left JOIN sStudent.tStudentCommunication SC  ON SC.StudentId = SA.StudentId
	LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId
WHERE 
		(SA.OrgGroupBatchId = @rOrgGroupBatchId)
		AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))	
		AND ((SA.BatchId=@rBatchId) OR (@rBatchId=0))	
		AND	((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))
		AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))
		AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))	
		AND ((SA.StatusId=@rStatusId) OR (@rStatusId=0))
		AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))
		AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))
		AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))
		AND ((SA.Code=@rCode) OR (@rCode=''))
		AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))
		AND	((FS.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))
		AND	((FS.CollectionGroupId = @rCollectionGroupId) OR (@rCollectionGroupId = 0))
		AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')
		AND ((SA.FirstName like @rFirstName) OR(ISNULL(@rFirstName,'')=''))
		AND ((FI.InvoiceNumber>=@rFromInvoiceNumber)OR(@rFromInvoiceNumber=0))
		AND ((FI.InvoiceNumber<=@rToInvoiceNumber)OR(@rToInvoiceNumber=0))
		AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))
		AND (ISNULL(FI.Id,0) IN( SELECT cast(item as bigint) FROM  sCommon.fnsplit(@rFeeInvoiceIds,','))OR @rFeeInvoiceIds='')
		AND (
		 (@rFilterId = 0) -- All
		 OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel
		 OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport
		 OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))
		)
		AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
		AND ((SC.ParentContactNo= @rParentContactNo) OR (ISNULL(@rParentContactNo,'')=''))
		AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
END
GO
PRINT N'Altering [sFee].[pRptFeeReceiptDetailListGet]...';


GO
 
 
ALTER PROCEDURE [sFee].[pRptFeeReceiptDetailListGet]  
  @rReportId int,  
  @rReceiptBookId int,  
  @rAdmissionCategoryId int,  
  @rClassId int,  
  @rDivisionId int,  
  @rFromDate date,  
  @rToDate date,  
  @rFromReceiptNo int,  
  @rToReceiptNo int,  
  @rBatchId int,  
  @rUserId bigint,  
  @rBuilder1 nvarchar(max),  
  @rBuilder2 nvarchar(max),  
  @rIsCancel bit,  
  @rOrgId int,  
  @rOrgGroupBatchId int,  
  @rStatusId int,  
  @rCommonBatch nvarchar(100),  
  @rDepartmentId int,  
  @rFromRollNo int,  
     @rToRollNo int,  
     @rCode nvarchar(20),  
     @rIsDetail bit=0,  
  @rIsFilter bit,  
  @rIsHeader bit,  
  @rCreatedUserName nvarchar(100)='',  
  @rFeeHeadId nvarchar(max) = '',  
  @rIsDisplayOrgGroup bit=0,  
  @rPayTypeId int=0,  
  @rFeeId nvarchar(max) = '',  
  @rFilterId int=0,
  @rOrgIds nvarchar(max) = '',
  @rClassStatusId int=0,
  @rPayTypeIds nvarchar(max) = '' ,
  @rBankName nvarchar(200)='' ,
  @rUserAcessUserId bigint = 0  
  
 WITH EXECUTE AS CALLER  
AS  
SET NOCOUNT ON  
      
BEGIN  
SET @rBankName = sCommon.fSearchStringGet(@rBankName)  
IF(@rReportId=10145)
	BEGIN
	SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,  
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherName,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
    --for UserAccess Wise (in ReceiptListFeeHeadHeadwise report)
  INNER JOIN sSecurity.tUserOrganization UO ON UO.OrgId=SA.OrgId AND O.IsObsolete=0 AND UO.UserId=@rUserAcessUserId  
 
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
     LEFT JOIN  
 (SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 --AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
 AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
 AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
 AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
   )  
  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
 ORDER BY R.ReceiptNumber  
	END

ELSE
	BEGIN
	SELECT   
  @rBuilder1 AS Builder1,  
  @rBuilder2 AS Builder2,  
  @rIsCancel AS IsCancel,  
  @rIsDetail AS IsDetail,  
  @rIsFilter As IsFilter,  
  @rIsHeader As IsHeader,  
  @rIsDisplayOrgGroup AS IsDisplayOrgGroup,  
  R.Id AS ReceiptId,  
  R.ReceiptNumber,  
  SA.ClassId,  
  SA.ClassName,  
  SA.DivisionId,  
  SA.DivisionName,  
  SA.ClassName+' - '+SA.DivisionName AS ClassDivision,  
  SA.RollNo,  
  SA.AcademicId,  
  SA.FirstName,  
  SA.MiddleName,  
  SA.LastName,  
  SA.Code,  
  SA.Name,  
  PTM.Title AS PayType,  
  --R.ChequeNo,  
  CASE WHEN ISNULL(R.ChequeNo,'') != '' THEN R.ChequeNo ELSE CONVERT(nvarchar(20),R.PaymentTransactionId) END AS ChequeNo,
  R.BankName,  
  --R.ReceiptAmount,  ,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.ReceiptAmount ELSE 0 END AS ReceiptAmount,
  R.ReceiptDate,  
  FM.Title AS FeeDetail,  
  FM.Code AS FeeCode,  
  FM.OrderIndex AS FeeOrderIndex,  
  RD.Amount AS DetailAmount,  
  ISNULL(R.ReceiptBookId,'0') As ReceiptBookId,  
  ISNULL(RBM.Title,'') AS ReceiptBookTitle,  
  ISNULL(RBM.OrderIndex,0) AS ReceiptOrderIndex,  
  ISNULL(FHM.Title,'') AS FeeHead,  
  ISNULL(FHM.Code,'') AS FeeHeadCode,  
  ISNULL(FHM.OrderIndex,0) AS FeeHeadOrderIndex,  
  SA.OrgId,  
  O.DisplayTitle AS OrgName,  
  O.OrderIndex AS OrgOrderIndex,  
  ISNULL(R.Remark,'') AS Remark,  
  DM.Id AS DepartmentId,  
  DM.Title AS DepartmentName,  
  SA.ClassOrderIndex,  
  ISNULL(SO.GenderId,0) AS GenderId,  
  ISNULL(SA.BatchName,'') BatchName,  
  ISNULL(FM.FeeHeadId,0) AS FeeHeadId,  
  sFinanceCommon.fNumberToWordsWithDecimal(ISNULL(R.ReceiptAmount,0.00),1,2,O.OrgGroupId) AS ReceiptAmountInWords,  
  R.ChequeDate,  
  ISNULL(FM.Id,0) AS FeeId,  
  ISNULL(FM.Title,'') AS Fee,  
  ISNULL(SF.FatherName,'' ) AS FatherName,  
  ISNULL(SF.MotherName,'' ) AS MotherName,
  CASE WHEN ROW_NUMBER() OVER (PARTITION BY R.Id  ORDER BY R.Id ) =1 THEN R.DiscountAmount ELSE 0 END AS Discount,
  RD.Amount AS PaidAmount,
  ISNULL(DM.OrderIndex,0) as DepartmentOrderIndex
  FROM   
   sFee.tReceipt R  
  INNER JOIN sStudent.vStudentAcademic SA  
   ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
   ON PTM.Id=R.PayTypeId  
  INNER JOIN sFee.tReceiptDetail RD  
   ON RD.ReceiptId=R.Id  
  INNER JOIN sFee.tFeeSetup FS  
   ON FS.Id=RD.FeeSetupId  
  INNER JOIN sFee.tFeeMaster FM  
   ON FM.Id=FS.FeeId  
  INNER JOIN sFee.tFeeHeadMaster FHM  
   ON FHM.Id=FM.FeeHeadId  
  INNER JOIN sFee.tReceiptBookMaster RBM   
   ON RBM.Id=R.ReceiptBookId  
  INNER JOIN sSetup.tDepartmentMaster DM  
   ON SA.DepartmentId=DM.Id  
  INNER JOIN sSetup.tOrganizationMaster O  
   ON O.Id=sa.OrgId 
 
  LEFT JOIN sStudent.tStudentOther SO  
   ON SO.StudentId = SA.StudentId  
  LEFT JOIN sStudent.tStudentFamily SF  
   ON SF.StudentId = SA.StudentId  
    LEFT JOIN sHostel.tAssignRoom AR ON  AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003 AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))  AND ((AR.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
     LEFT JOIN  
 (SELECT AT.SourceId FROM sTransport.tAssignRoute AT   
    INNER JOIN sTransport.tBusRouteDestinationMaster BM ON BM.Id=AT.PickupDestinationId  
    INNER JOIN sTransport.tBusRouteMaster B ON B.Id=BM.BusRouteId AND  AT.SourceTypeId=2003 AND ((B.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))) RT  
    ON RT.SourceId = SA.StudentId AND ((SA.OrgGroupBatchId = @rOrgGroupBatchId) OR (@rOrgGroupBatchId = 0))   
WHERE   
 R.SourceTypeId = 2001  
 AND ((SA.AdmissionCategoryId = @rAdmissionCategoryId) OR (@rAdmissionCategoryId = 0))  
 AND ((SA.ClassId = @rClassId) OR (@rClassId = 0))  
 AND ((SA.DivisionId = @rDivisionId) OR (@rDivisionId = 0))  
 AND ((R.ReceiptBookId = @rReceiptBookId) OR (@rReceiptBookId = 0))  
 AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
 AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
 AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
 AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
 AND (SA.OrgGroupBatchId = @rOrgGroupBatchId)  
 AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))  
 AND ((R.BatchId=@rBatchId) OR (@rBatchId=0))  
 AND ((R.CreatedUserId=@rUserId) OR (@rUserId=0))  
 AND (R.IsObsolete = @rIsCancel)   
 AND (SA.StatusId = @rStatusId OR @rStatusId=0)  
 AND ((SA.BatchName = @rCommonBatch) OR (@rCommonBatch = ''))  
 AND ((SA.RollNo >= @rFromRollNo) OR (@rFromRollNo=0))  
 AND ((SA.RollNo <= @rToRollNo) OR (@rToRollNo=0))  
 AND ((SA.Code=@rCode) OR (@rCode=''))  
 AND ((SA.DepartmentId=@rDepartmentId) OR (@rDepartmentId=0))  
 --AND ((ISNULL(U.LoginTitle,'') like @rCreatedUserName) OR (ISNULL(@rCreatedUserName,'')=''))  
 AND (ISNULL(FM.FeeHeadId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeHeadId,','))OR @rFeeHeadId='')  
 AND (ISNULL(FM.Id,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rFeeId,','))OR @rFeeId='')  
 AND ((R.PayTypeId=@rPayTypeId) OR (@rPayTypeId=0))  
 AND (  
  (@rFilterId = 0) -- All  
     OR (@rFilterId = 2 AND isnull(AR.SourceId,0)!=0) -- Hostel  
     OR (@rFilterId = 3 AND isnull(RT.SourceId,0)!=0) -- Transport  
     OR ((@rFilterId =1) AND ((isnull(AR.SourceId,0)=0) AND (isnull(RT.SourceId,0)=0)))  
   )  
  AND (ISNULL(SA.OrgId,0) IN( SELECT cast(item as int) FROM  sCommon.fnsplit(@rOrgIds,','))OR @rOrgIds='')
  	 AND ((SA.ClassStatusId=@rClassStatusId) OR (@rClassStatusId=0))
	AND (ISNULL(R.PayTypeId,0) IN (SELECT cast(item as tinyint) FROM sCommon.fnsplit(@rPayTypeIds,',')) OR @rPayTypeIds='')   
	AND ((UPPER(R.BankName) like UPPER(@rBankName)) OR(ISNULL(@rBankName,'')=''))    
 ORDER BY R.ReceiptNumber  
	END
 --ORDER BY R.Id 
-- UNION ALL  
   
-- SELECT   
--  R.Id AS ReceiptId,  
--  0 AS ClassId,  
--  --SA.ClassName,  
--  0 AS DivisionId,  
--  --SA.DivisionName,  
--  EM.DepartmentId,  
--  EM.DepartmentName AS ClassDept,  
--  0 AS RollNo,  
--  EM.Code,  
--  EM.EmployeeName,  
--  PTM.Title AS PayType,  
--  R.ReceiptAmount  
     
--  FROM   
--   sFee.tReceipt R  
--  INNER JOIN sCommon.tSourceTypeMaster STM  
--   ON STM.Id=R.SourceTypeId AND R.SourceTypeId = 95  
--  INNER JOIN sHrm.vExtEmployeeMaster EM  
--   ON EM.EmployeeId=R.SourceId  
--  INNER JOIN sFinanceCommon.tPayTypeMaster PTM  
--   ON PTM.Id=R.PayTypeId  
     
--WHERE   
--  ((EM.DepartmentId = @rDepartmentId) OR (@rDepartmentId = 0))  
-- AND ((R.ReceiptNumber >= @rFromReceiptNo) OR (@rFromReceiptNo = 0))  
-- AND ((R.ReceiptNumber <= @rToReceiptNo) OR (@rToReceiptNo = 0))  
-- AND ((R.ReceiptDate >= @rFromDate) OR (ISNULL(@rFromDate,'') = ''))  
-- AND ((R.ReceiptDate <= @rToDate) OR (ISNULL(@rToDate,'') = ''))  
-- AND (R.BatchId = @rBatchId)  
END
GO
PRINT N'Altering [sHostel].[pHostelStudentGatePassNewAdd]...';


GO

ALTER PROCEDURE [sHostel].[pHostelStudentGatePassNewAdd]
	
	@rOrgGroupId int,
	@rId int,
	@rStudentId bigint,
	@rRelationshipId tinyint,
	@rRelation nvarchar(50),
	@rVisitorName nvarchar(100),
	@rVisitorMobile nvarchar(50),
	@rHostelGatePassReasonId int,
	@rRemark nvarchar(200),
	@rVisitorPhoto varbinary(max)=0,
	@rGatePassDate date,
	@rGatePassTime datetime,
	@rEntryModeStatusId smallint,
	@rHostelId int,
	@rOrgGroupBatchId int,
	@rCreatedUserId bigint	,
	@rGatePassInDate date,
	@rGatePassInTime datetime,
	@rBulkNumber nvarchar=''			
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	
	BEGIN	
		DECLARE @lMaxId varchar(max)=''
		
		SELECT @lMaxId = Max(Id) from sHostel.tHostelStudentGatePass Where StudentId = @rStudentId 
		
		declare @lEntryModeStatusId varchar(max)=''
		Select @lEntryModeStatusId=EntryModeStatusId from sHostel.tHostelStudentGatePass Where Id = @lMaxId
			
		
		IF(@lEntryModeStatusId = 581 AND @rId = 0)
		BEGIN
			SELECT -101
			Return
		END		
	END
BEGIN TRY
BEGIN TRANSACTION	

	
IF(@rId = 0)
	BEGIN	
	DECLARE @lNextNumber INT,@lEntryMode int     
	EXECUTE sCommon.pTableRowIdGet @rOrgGroupId, 'sHostel.tHostelStudentGatePass', 0, 1, 1,@outNextNumber = @lNextNumber output
	INSERT INTO sHostel.tHostelStudentGatePass
		(
			Id,
			StudentId,
			RelationshipId,
			Relation,
			VisitorName,
			VisitorMobile,
			HostelGatePassReasonId,
			Remark,
			VisitorPhoto,
			GatePassDate,
			GatePassTime,
			EntryModeStatusId,
			HostelId,
			OrgGroupBatchId,
			CreatedUserId,
			CreatedDateTime,
			UpdatedUserId,
			UpdatedDateTime,
			GatePassInDate,
			GatePassInTime,
			BulkNumber
		)
	VALUES
		(
			@lNextNumber,
			@rStudentId,
			@rRelationshipId,
			@rRelation,
			@rVisitorName,
			@rVisitorMobile,
			@rHostelGatePassReasonId,
			@rRemark,
			@rVisitorPhoto,
			@rGatePassDate,
			@rGatePassTime,
			@rEntryModeStatusId,
			@rHostelId,
			@rOrgGroupBatchId,
			@rCreatedUserId,
			sCommon.fGetDate(),	
			@rCreatedUserId,
			sCommon.fGetDate()	,
			@rGatePassInDate,
			@rGatePassInTime	,
			@rBulkNumber	
		)
		             
END	 
ELSE	 
BEGIN
	SET @lNextNumber = @rId
	UPDATE  sHostel.tHostelStudentGatePass
	SET
	
		RelationshipId=@rRelationshipId,
			Relation= @rRelation,
			VisitorName=@rVisitorName,
			VisitorMobile=@rVisitorMobile,
			HostelGatePassReasonId=@rHostelGatePassReasonId,
			Remark= @rRemark,
			VisitorPhoto=@rVisitorPhoto ,
			GatePassDate=@rGatePassDate ,
			GatePassTime=@rGatePassTime,
			EntryModeStatusId=@rEntryModeStatusId,
			GatePassInDate=@rGatePassInDate ,
			GatePassInTime=@rGatePassInTime
	
	WHERE Id = @rId 	   
END  
	
	SELECT @lNextNumber AS Result
	
	COMMIT TRANSACTION
	
	END TRY
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
END
GO
PRINT N'Altering [sProcurement].[pRptStockIssueStudent]...';


GO
 
ALTER PROCEDURE [sProcurement].[pRptStockIssueStudent]
 
	@rId int = 0,
	@rStoreLocationId int = 0,
	@rMainGroupId int=0,
	@rSubGroupId int=0,
	@rItemCode nvarchar(50)='',
	@rItemName nvarchar(50)='',
	@rOrgGroupId int=0,
	@rBuilder1 nvarchar(max)='',
	@rBuilder2 nvarchar(max)='',
	@rReportId int=0,
	@rStockItemCategoryId int=0,
	@rFromDate date='',
	@rTodate date='',
	@rToDepartmentId int =0,
	@rNumber nvarchar(10)='',
	@rAcademicId bigint = 0,
	@rOrgId smallint = 0,
	@rBatchId int = 0
	
WITH EXECUTE AS CALLER
AS
BEGIN
	
	SET NOCOUNT ON;
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
	Declare @lIDConfigValue nvarchar(50)=''
	SELECT @lIDConfigValue =ItemValue From sConfig.tConfigurationSetup
	WHERE ConfigurationId = 236 AND SourceId = @rOrgGroupId

       SELECT  
			@rBuilder1 AS Builder1,
			SIM.Code AS ItemNumber,
			SIM.Title AS ItemName,		
			SI.IssuedByName,	
			SI.Number, 	
			SI.CreatedDateTime AS IssuedDate,
			ID.IssuedQuantity,
			ID.RequestedQuantity,
			SM.FirstName +' '+SM.MiddleName As StudentName,
			Sm.Code AS StudentCode,
			SG.Code AS ItemSubGroup,
			SG.Id AS ItemSubGroupId,
			OM.DisplayTitle,
			BM.Title AS BatchTitle,
			CM.Title +'-'+ DM.TItle As Class,
			(SELECT ISNULL(SUM(AvailableQuantity),0) FROM sProcurement.tStockBatch SB 
		    WHERE SB.StockItemId = SIM.Id 
		    AND ((SB.StorelocationId = @rStoreLocationId) OR (@rStoreLocationId = 0))
			) AS Quantity ,
			A.OrgId,
			A.BatchId,
			ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0') AS WeightedAverageCost,
			@lIDConfigValue AS IdNoLabel,
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)) AS Amount,

			(sFinanceCommon.fNumberToWordsWithDecimal(
			((ISNULL(CAST(SIP.WeightedAverageCost AS DECIMAL(18, 2)), '0')) * (ID.IssuedQuantity)),1,2,SI.OrgGroupId)
			) AS AmountInWords
		FROM  
			sProcurement.tStockIssue SI		
			INNER JOIN sProcurement.tStockIssueDetail ID ON SI.Id = ID.StockIssueId
			INNER JOIN sIp.tStockItemMaster SIM ON ID.StockItemId  = SIM.Id 
			LEFT JOIN sIp.tStockItemPlanning SIP ON SIP.StockItemId=SIM.Id AND SIP.StoreLocationId=@rStoreLocationId
			INNER JOIN sStudent.tAcademic A on A.Id=IssueToSourceId
			INNER JOIN sStudent.tStudentMaster SM ON SM.Id = A.StudentID
			INNER JOIN sIp.tItemSubGroupMaster SG ON SG.Id=SIM.ItemSubGroupId
			INNER JOIN sSetup.tOrganizationMaster OM ON OM.Id=A.OrgId
			INNER JOIN sSetup.tClassMaster CM on CM.id =A.ClassId 
			INNER JOIN sSetup.tDivisionMaster DM on DM.Id=A.DivisionId
			INNER JOIn sSetup.tBatchMaster BM ON BM.Id = A.BatchId
		WHERE 
			 ((SI.Id = @rId) OR (@rId=0))
			 AND SI.FromStoreLocationId =@rStoreLocationId
			 AND ((SIM.ItemSubGroupId= @rSubGroupId) OR (@rSubGroupId=0))
			 AND ((SIM.Code = @rItemCode) OR (@rItemCode=''))	
			 AND ((SIM.Title = @rItemName) OR (@rItemName=''))
			 AND ((convert(Date,ISNULL(SI.CreatedDateTime,'')) >= @rFromDate) OR (convert(date,ISNULL(@rFromDate,''))=''))
			 AND ((convert(date,ISNULL(SI.CreatedDateTime,'')) <= @rToDate) OR (convert(date,ISNULL(@rToDate,''))=''))
			 AND SI.OrgGroupId = @rOrgGroupId
			 AND ((SI.ToOrganizationDepartmentId=@rToDepartmentId) OR (@rToDepartmentId=0))
			 AND ((SI.Number like @rNumber) OR  (ISNULL(@rNumber,'')= ''))
			 AND ((SI.IssueToSourceId= @rAcademicId) OR (ISNULL(@rAcademicId,0)=0))
			 AND SI.IssueToSourceTypeId = 2001
			 AND ((A.OrgId = @rOrgId) OR (ISNULL(@rOrgId,0) = 0))
			 --AND ((A.BatchId = @rBatchId) OR (ISNULL(@rBatchId,0) = 0))
END




/****** Object:  StoredProcedure [sProcurement].[pRptStockItemMaxInventory]    Script Date: 07/09/2013 16:27:32 ******/
SET ANSI_NULLS ON
GO
PRINT N'Altering [sRecruitment].[pCandidateMasterListGet]...';


GO

ALTER PROCEDURE [sRecruitment].[pCandidateMasterListGet]
(
		@rOrgGroupID smallint, 
		@rVacancyId int=0,		
		@rCandidateNumber int=0, 
		@rFirstName nvarchar(100), 
		@rLastName nvarchar(100),
		@rRecruitmentStatusId smallint ,
		@rFromDate date=null,
		@rToDate date=null,
		@rOrgId int = 0
		
	
 )
AS
SET NOCOUNT ON

BEGIN
 
 		--SET @rCandidateNumber = ISNULL( sCommon.fSearchStringGet(@rCandidateNumber),0)
		SET @rFirstname = ISNULL( sCommon.fSearchStringGet(@rFirstname),'')
		SET @rLastName = ISNULL( sCommon.fSearchStringGet(@rLastName),'')
		
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				--RSL.RecruitmentStatusId AS RecruitmentStatusId
				CM.RecruitmentStatusId,
				ISNULL(OM.Title,'') AS OrganizationTitle
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			--LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId		
			--LEFT JOIN sRecruitment.tRecruitmentStatusLog  RSL  ON RSL.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM.Id			
		WHERE 
		--RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
		--		AND
				((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((CM.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))   
			AND ((CM.OrgId = @rOrgId) OR (@rOrgId = 0))	
			ORDER BY CM.CandidateNumber
END
GO
PRINT N'Altering [sRecruitment].[pCandidateMasterListWithPhotoGet]...';


GO
ALTER PROCEDURE [sRecruitment].[pCandidateMasterListWithPhotoGet]
(
		@rOrgGroupID smallint, 
		@rVacancyId int=0,		
		@rCandidateNumber int=0, 
		@rFirstName nvarchar(100), 
		@rLastName nvarchar(100),
		@rRecruitmentStatusId smallint,
		@rFromDate date=null,
		@rToDate date=null ,
		@rOrgId int = 0
		
	
 )
AS
SET NOCOUNT ON

BEGIN
 
 		--SET @rCandidateNumber = ISNULL( sCommon.fSearchStringGet(@rCandidateNumber),0)
		SET @rFirstname = ISNULL( sCommon.fSearchStringGet(@rFirstname),'')
		SET @rLastName = ISNULL( sCommon.fSearchStringGet(@rLastName),'')
		
		SELECT 
				CM.Id,
				CM.Id AS CandidateId,
				CM.CandidateNumber,
				ISNULL(CM.FirstName, '') + ' ' + ISNULL(CM.MiddleName, '') + ' ' + ISNULL(CM.LastName, '') AS Name,
				CM.MiddleName,
				CM.FirstName,
				CM.LastName,
				CM.DateOfBirth,
				VM.Id AS VacancyId,
				VM.Title AS VacancyName,
				--RS.Id AS RecruitmentStatusId,
				RS.Title AS RecruitmentStatus,
				RSL.RecruitmentStatusId AS RecruitmentStatusId,
				ISNULL(CI.CandidatePhoto, CONVERT(VARBINARY(MAX), 0)) AS CandidatePhoto,
				ISNULL(OM.Title,'') AS OrganizationTitle
					
		FROM 
		
			sRecruitment.tCandidateMaster CM
			LEFT JOIN sRecruitment.tVacancy VM ON VM.Id=CM.VacancyId
			--LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=CM.RecruitmentStatusId	
			LEFT JOIN sRecruitment.tCandidateImages CI ON CI.CandidateId= CM.Id		
			LEFT JOIN sRecruitment.tRecruitmentStatusLog  RSL  ON RSL.CandidateId=CM.Id	
			LEFT JOIN sRecruitment.tRecruitmentStatusMaster RS on RS.Id=RSL.RecruitmentStatusId	
			LEFT JOIN sSetup.tOrganizationMaster OM ON CM.OrgId = OM.Id	AND ((CM.OrgId = @rOrgId) OR (@rOrgId = 0))				
		WHERE 
			RSL.CreatedDateTime = (SELECT MAX(t2.CreatedDateTime)FROM sRecruitment.tRecruitmentStatusLog t2 WHERE t2.CandidateId = RSL.CandidateId)
			AND	((CM.CandidateNumber=@rCandidateNumber ) OR (@rCandidateNumber = 0))
			AND ((CM.FirstName Like '%' + @rFirstName  + '%') OR (@rFirstName = ''))	
		    AND ((CM.LastName Like '%' + @rLastName  + '%') OR (@rLastName = ''))
			AND ((VM.Id = @rVacancyId) OR (@rVacancyId = 0))	
			AND ((RSL.RecruitmentStatusId = @rRecruitmentStatusId) OR (@rRecruitmentStatusId = 0))	
			AND CM.OrgGroupID = @rOrgGroupID
			AND ((CONVERT(date,CM.CreatedDateTime) >= @rFromDate) OR (ISNULL(@rFromDate,'')=''))
			AND ((CONVERT(date,CM.CreatedDateTime) <= @rToDate) OR (ISNULL(@rToDate,'')=''))
			ORDER BY CM.CandidateNumber
END
GO
PRINT N'Altering [sStudent].[pAcademicAdd]...';


GO
 
 
ALTER PROCEDURE [sStudent].[pAcademicAdd]
	 
	@rAcademicId bigint=0,
	@rStudentId bigint=0,
	@rClassId int=0,
	@rDivisionId int=0,
	@rRollNo int=0,
	@rOrgId int=0,
	@rBatchId int=0,
	@rCreatedUserId bigint=0,
	@rUpdatedUserId bigint=0,
	@rAdmissionCategoryId int = 0,
	@rClassStatusId int=0
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN
	BEGIN TRY
	
	SET @rRollNo = ISNULL(@rRollNo,0)
	
	 BEGIN TRANSACTION	
 IF NOT EXISTS(Select Id from sStudent.tAcademic where StudentId=@rStudentId AND BatchId=@rBatchId)
BEGIN
	
	DECLARE @lNextNumber BIGINT     
	EXECUTE sCommon.pTableRowIdGet @rOrgId, 'sStudent.tAcademic', 0, 1, 1,@outNextNumber = @lNextNumber output



--IF ISNULL(@rRollNo,0) <> 0
--BEGIN
--IF EXISTS(Select Id from sStudent.tAcademic where RollNo = @rRollNo AND DivisionId = @rDivisionId )
--BEGIN
--SET @rRollNo = 0
--END
--END
--ELSE
--BEGIN
--  SELECT @rRollNo =  (ISNULL(max(RollNo),0) + 1) FROM  sStudent.tAcademic where DivisionId=@rDivisionId AND BatchId=@rBatchId
--END
 
	INSERT INTO sStudent.tAcademic
		(
			Id,
			StudentId,
			ClassId,
			DivisionId,
			RollNo,
			OrgId,
			BatchId,
			CreatedUserId,
			CreatedDateTime,
			IsCurrent,
			BatchStatusId,
			AdmissionCategoryId,
			ClassStatusId
		)
	VALUES
		(
			@lNextNumber,
			@rStudentId,
			@rClassId,
			@rDivisionId,
			@rRollNo,
			@rOrgId,
			@rBatchId,
			@rCreatedUserId,
			sCommon.fGetDate()
			,1
			,1
			,@rAdmissionCategoryId,
			@rClassStatusId
		)	
		
	   INSERT INTO sStudent.tAcademicDetail
		(
		AcademicId,
		RepeatCount
		)
		VALUES
		(
		@lNextNumber,
		1
		)
			
        UPDATE sStudent.tAcademic SET IsCurrent = 0 WHERE StudentId = @rStudentId AND OrgId = @rOrgId AND BatchId <>  @rBatchId        
	END	 
	 ELSE
	 BEGIN
	 SET @lNextNumber = @rAcademicId
	 
	 
--if ISNULL(@rRollNo,0) <> 0
--BEGIN
--IF EXISTS(Select Id from sStudent.tAcademic where RollNo = @rRollNo AND DivisionId = @rDivisionId AND Id <> @rAcademicId )
--BEGIN
--SET @rRollNo = 0
--END
--END
	 
	    UPDATE sStudent.tAcademic
	    SET
			ClassId=@rClassId,
			DivisionId=@rDivisionId,
			RollNo=@rRollNo,
			OrgId=@rOrgId,
			BatchId=@rBatchId,
			UpdatedUserId=@rUpdatedUserId,
			UpdatedDateTime=sCommon.fGetDate() ,
			AdmissionCategoryId = @rAdmissionCategoryId,
			ClassStatusId=@rClassStatusId
	      WHERE 
	       --Id = @rAcademicId  AND 
	       StudentId=@rStudentId  AND 
	       BatchId = @rBatchId
	      
	 END  			
		COMMIT TRANSACTION
		SELECT @lNextNumber AS Result
		
	--UPDATE sStudent.tAcademic SET BatchStatusId = 1 WHERE BatchStatusId is null
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Altering [sStudent].[pRptStudentIcardGet]...';


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

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

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

	ISNULL(TM.Title,'') AS StudentTransportMode

   --CM.Title as Club 

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


GO
 
 
ALTER PROCEDURE [sStudent].[pStudentDetailFormGet]
	@rBatchId int = 0,
	@rStudentId bigint = 0,
	@rOrgGroupBatchId int = 0,
	@rOrgId int = 0,
	@Tab nvarchar(20) = '',
	@rAttendanceTypeId smallint = 0,
	@rDepositHeadId int = 0,
	@rAlertModeId smallint = 0

	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	DECLARE @lSUIdBarcode nvarchar(50)
	DECLARE @lAcademicId bigint = 0, @lClassId int  = 0, @lAdmissionCategoryId int = 0,@lCode nvarchar(20) = '',@lEmail nvarchar(50) = '',@lContactNo nvarchar(50) ='',@lDate datetime = (SELECT sCommon.fGetDate()),@lOrgGroupId int = 0,
	@lDepartmentId int = 0, @lDivisionId int = 0
	SELECT @lAcademicId = Id,@lClassId=ClassId,@lAdmissionCategoryId=AdmissionCategoryId,@lDivisionId = DivisionId from sStudent.tAcademic
	Where StudentId = @rStudentId AND BatchId = @rBatchId
	SELECT @lCode = Code FROM sStudent.tStudentMaster WHERE Id = @rStudentId
	SELECT @lEmail = ParentEmail, @lContactNo = ParentContactNo FROM sStudent.tStudentCommunication WHERE StudentId = @rStudentId
	SELECT @lOrgGroupId = OrgGroupId FROM sSetup.tOrganizationMaster WHERE Id = @rOrgId	
	SELECT @lDepartmentId = DepartmentId FROM sSetup.tClassMaster WHERE Id = @lClassId
	SELECT @lSUIdBarcode = ItemValue FROM sConfig.tConfigurationSetup WHERE ConfigurationId = 168 AND SourceTypeId = 2010 AND SourceId = @lOrgGroupId



	IF(LOWER(@Tab) = 'overview')
	BEGIN
		SELECT
			SA.StudentId AS Id,			
			SA.Name AS StudentName,
			SA.FirstName as FirstName,
			SA.MiddleName as MiddleName,
			SA.LastName as LastName,
			SA.Batch AS AcademicYear,
			ISNULL(SA.Code,' - ') AS Code,
			SA.ClassDivision AS ClassDiv,			
			SA.RollNo,
			ISNULL(SM.Title,'-') AS House,
			--Other
			ISNULL(SA.DateOfBirth,'0001/01/01') AS DateOfBirth,
			ISNULL(SA.BirthTaluka,'') AS BirthTaluka,
			ISNULL(SA.BirthPlace,'') AS BirthPlace,	
			ISNULL(SA.BirthDistrict,'') AS BirthDistrict,
			ISNULL(SA.BirthDateInWord,'') AS BirthDateInWord,                           
			ISNULL(SA.Gender,'') AS Gender,
			ISNULL(SA.Religion,'') AS Religion,
			--Admission			
			ISNULL(SA.AdmissionStandard,'') AS AdmissionStandard,			
			ISNULL(SA.AdmissionDate,'0001/01/01') AS AdmissionDate,	
			ISNULL(SA.PreviousSchool,'') AS PreviousSchool,
			ISNULL(SA.AdmissionCategory,'') AS StudentAdmissionCategory,
			ISNULL(SA.LeftDate,'0001/01/01') AS LeftDate,						 
			ISNULL(SA.LeftStandard,'') AS LeftStandard,			
			ISNULL(SA.InactiveDate,'0001/01/01') AS InactiveDate,		
			ISNULL(SA.LCNumber,'') AS LCNumber,			
			ISNULL(SA.LCDate,'0001/01/01') AS LCDate,
			--Communication
			ISNULL(SA.PresentStreetone,'') + ' ' + ISNULL(SA.PresentStreetTwo,'') + ' ' + ISNULL(SA.PresentStreetThree,'') AS PresentAddress,
			ISNULL(SA.PresentCity,'') AS PresentCity,
			ISNULL(SA.PresentState,'') AS PresentState,
			ISNULL(SA.PresentCountry,'') AS PresentCountry,
			ISNULL(SA.PresentZipCode,'') AS PresentZipCode,
			ISNULL(SA.PresentContactNo,'') AS PresentContactNo,
			
			ISNULL(SA.EmergencyStreetOne,'') + ' ' + ISNULL(SA.EmergencyStreetTwo,'') + ' ' + ISNULL(SA.EmergencyStreetThree,'') AS EmergencyAddress,
			ISNULL(SA.EmergencyCity,'') AS EmergencyCity,
			ISNULL(SA.EmergencyState,'') AS EmergencyState,
			ISNULL(SA.EmergencyCountry,'') AS EmergencyCountry,
			ISNULL(SA.EmergencyZipCode,'') AS EmergencyZipCode,
			ISNULL(SA.EmergencyContactNo,'') AS EmergencyContactNo,
			
			ISNULL(SA.PermanentStreetOne,'') + ' ' + ISNULL(SA.PermanentStreetTwo,'') + ' ' + ISNULL(SA.PermanentStreetThree,'') AS PermanentAddress,
			ISNULL(SA.PermanentCity,'') AS PermanentCity,
			ISNULL(SA.PermanentState,'') AS PermanentState,
			ISNULL(SA.PermanentCountry,'') AS PermanentCountry,
			ISNULL(SA.PermanentZipCode,'') AS PermanentZipCode,
			ISNULL(SA.PermanentContactNo,'') AS PermanentContactNo,
			
			--Parent Information
			ISNULL(SF.FatherName,'') AS FatherName,
			ISNULL(SF.FatherOccupation,'') AS FatherOccupation,
			ISNULL(SF.FatherQualification,'') AS FatherQualification,
			ISNULL(SF.FatherContactNo,'') AS FatherContactNo,
			ISNULL(SF.FatherMail,'') AS FatherMail,
			ISNULL(SF.FatherOfficeAddress,'') AS FatherOfficeAddress,
			ISNULL(SF.FatherDesignation,'') AS FatherDesignation,
			ISNULL(SF.FatherOrganization,'') AS FatherOrganization,
			ISNULL(SF.FatherIncome,'') AS FatherIncome,

			ISNULL(SF.MotherName,'') AS MotherName,
			ISNULL(SF.MotherOccupation,'') AS MotherOccupation,
			ISNULL(SF.MotherQualification,'') AS MotherQualification,
			ISNULL(SF.MotherContactNo,'') AS MotherContactNo,
			ISNULL(SF.MotherMail,'') AS MotherMail,
			ISNULL(SF.MotherOfficeAddress,'') AS MotherOfficeAddress,
			ISNULL(SF.MotherDesignation,'') AS MotherDesignation,
			ISNULL(SF.MotherOrganization,'') AS MotherOrganization,
			ISNULL(SF.MotherIncome,'') AS MotherIncome,

			ISNULL(SF.RelationshipName,'') AS RelationShip,
			ISNULL(SF.RelativeName,'') AS RelativeName,
			ISNULL(SF.RelativeOccupation,'') AS RelativeOccupation,
			ISNULL(SF.RelativeQualification,'') AS RelativeQualification,
			ISNULL(SF.RelativeContactNo,'') AS RelativeContactNo,
			ISNULL(SF.RelativeMail,'') AS RelativeMail,
			ISNULL(SF.RelativeOfficeAddress,'') AS RelativeOfficeAddress,
			ISNULL(SF.RelativeDesignation,'') AS RelativeDesignation,
			ISNULL(SF.RelativeOrganization,'') AS RelativeOrganization,
			ISNULL(SF.RelativeIncome,'') AS RelativeIncome,
			
			--Health Information
			ISNULL(SA.BloodGroup,'') AS BloodGroup,
			ISNULL(SH.IdentificationMark1,'')+' '+ISNULL(SH.IdentificationMark2,'') as IdentificationMark,
			
			ISNULL(SH.FamilyDoctorName,'') AS FamilyDoctorName,
			ISNULL(SH.FamilyDoctorContactNo,'') AS FamilyDoctorContactNo,
			
			ISNULL(SH.IsPysicalDeformity,0) AS IsPysicalDeformity,
			ISNULL(SH.PysicalDeformityRemark,'') AS PysicalDeformityRemark,
			ISNULL(SH.IsMajorIllness,0) AS IsMajorIllness,
			ISNULL(SH.MajorIllnessRemark,'') As MajorIllnessRemark,
			ISNULL(SH.IsAllergy,0) AS IsAllergy,
			ISNULL(SH.AllergyRemark,'') As AllergyRemark,
			ISNULL(SH.IsPastHistory,0) As IsPastHistory ,
			ISNULL(SH.PastHistoryRemark,'') As PastHistoryRemark,
			--Hostel
			ISNULL(RM.Title,'') AS RoomNo,			
			ISNULL(HM.Title,'') AS Hostel,
			ISNULL(EMW.FirstName,'')+' '+ISNULL(EMW.LastName,'') AS WardenName,
			ISNULL(ECW.PhoneNoCompany,'') As WardenPhoneNo,
			ISNULL(ECW.ExtensionNo,'') AS WardenExtNo,
			ISNULL(ECW.MobileNumber,'') AS WardenMobileNo,
			ISNULL(EMA.FirstName,'')+' '+ISNULL(EMA.LastName,'') AS AssignedRoomBy,	
			ISNULL(ECA.PhoneNoCompany,'') AS AssignedRoomByPhoneNo,
			ISNULL(ECA.ExtensionNo,'') AS AssignedRoomByExtNo,
			ISNULL(ECA.MobileNumber,'') AS AssignedRoomByMobileNo,
			--Notification Details
			ISNULL(SA.ParentEmail,'') AS ParentEmail,
			ISNULL(SA.ParentContactNo,'') As ParentContactNo,
			ISNULL(SA.StudentEmail,'') AS StudentEmail,
			ISNULL(SA.StudentContactNo,'') AS StudentContactNo,

			-- Photos		
	   	    ISNULL(SA.StudentPhoto, CONVERT(VARBINARY(MAX), 0))AS StudentPhoto,
	   	    ISNULL(SA.FatherPhoto, CONVERT(VARBINARY(MAX), 0)) AS FatherPhoto,
	   	    ISNULL(SA.MotherPhoto, CONVERT(VARBINARY(MAX), 0)) AS MotherPhoto,
	   	    ISNULL(SA.RelativePhoto, CONVERT(VARBINARY(MAX), 0)) AS RelativePhoto,
			
		   -- Transport Details
		    A.VehicleName AS VehicleName,
		    A.VehicleRegistrationNumber AS VehicleRegistrationNumber,
		    A.TypeOfVehicle AS TypeOfVehicle,
		    ISNULL(A.BusRoute,'') AS BusRoute,
		    A.DriverName,
		    A.DriverMobileNo,
		    A.ConductorName,
		    A.ConductorMobileNo,
		    ISNULL(A.BusRouteDestination,'') AS BusRouteDestination,		    
		    A.DropVehicleName AS DropVehicleName,
		    A.DropVehicleRegistrationNumber AS DropVehicleRegistrationNumber,
		    A.DropTypeOfVehicle AS DropTypeOfVehicle,
		    ISNULL(A.DropRoute,'') AS DropRoute,
		    A.DropRouteDriverName AS DropRouteDriverName,
		    A.DropRouteDriverMobileNo AS DropRouteDriverMobileNo,
		    A.DropRouteConductorName AS DropRouteConductorName,
		    A.DropRouteConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(A.DropDestination,'') AS DropDestination,
		    
		    --ClassTeacher Details
		    ISNULL(EMT.Id,0) AS TeacherId,
		    EMT.FirstName+' '+EMT.MiddleName+' '+EMT.LastName AS TeacherFullName,
		    EDM.Title AS TeacherDesignation,
		    EPD.Qualification AS TeacherQualification,
			ISNULL(FED.PaidAmount,0) AS FeePaidAmount,
			ISNULL(FED.PendingAmount,0) AS FeePendingAmount,
			ISNULL(FED.PaidAmount,0) + ISNULL(FED.PendingAmount,0) AS FeeTotalAmount,
			(SELECT COUNT(AcademicId) FROM sAttendance.tStudentRegister WHERE AcademicId = @lAcademicId AND IsPresent = 0) AS AbsentCount,
			(SELECT COUNT(AcademicId) FROM sAttendance.tStudentRegister WHERE AcademicId = @lAcademicId AND IsPresent = 1) AS PresentCount,

			--TecherSubjectDivision
			--EM.FirstName + ' ' + EM.LastName AS DivisionTeacherName,
			--SM.Title AS DivisionSubjectName,

			-- Today's Lectures

			ISNULL(STUFF((
			SELECT ',' + OnlineLearningTitle FROM 
			(SELECT OL.Title AS OnlineLearningTitle FROM sAcademic.tOnlineLearning OL INNER JOIN (SELECT OLS.OnlineLearningId FROM sAcademic.tOnlineLearningScope OLS
				WHERE (
				( 
				(OLS.SourceTypeId = 2021 AND OLS.SourceId =SA.OrgId) 
				OR
				(OLS.SourceTypeId = 2017 AND OLS.SourceId =SA.DepartmentId) OR
				(OLS.SourceTypeId = 2016 AND OLS.SourceId =SA.ClassId) OR
				(OLS.SourceTypeId = 2005 AND OLS.SourceId =SA.DivisionId) OR
				(OLS.SourceTypeId = 2003 AND OLS.SourceId =SA.StudentId) OR
				(OLS.SourceTypeId = 2001 AND OLS.SourceId =SA.AcademicId)
				 ))
				) D
				ON D.OnlineLearningId= OL.Id WHERE OL.StartDate >= CAST(sCommon.fGetDate() AS DATE) AND OL.EndDate <= CAST(sCommon.fGetDate() AS DATE)) OL FOR XML PATH('')),1,1,''),'') AS OnlineLearningLectures,

			ISNULL(STUFF((
				SELECT ',' + ExamName + ' (' + CAST([Percentage] AS NVARCHAR(20)) + ')' FROM (
				SELECT AD.Id AS AcademicId,E.[Name] AS ExamName, R.[Percentage] 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=@lAcademicId) OR (@lAcademicId=0))	
					AND IsProcessResult=1 ) E
				FOR XML PATH('')),1,1,''),'') AS ExamPercentage,
				
			(SELECT SUM(Amount) FROM sFee.tDepositAdd WHERE AcademicId = @lAcademicId) AS DepositCreditAmount,
			(SELECT SUM(Amount) FROM sFee.tDepositAdjustment WHERE AcademicId = @lAcademicId) + (SELECT SUM(RefundAmount) FROM sFee.tDepositRefund WHERE AcademicId = @lAcademicId) AS DepositDebitAmount,
			ISNULL(SI.QRCode,0x) AS QRCode,
			CASE WHEN @lSUIdBarcode = 'True' THEN SA.SUId  ELSE SA.Code END AS BarcodeNumber

			FROM 
			sStudent.vStudentAllDetail SA          
           LEFT JOIN sStudent.tStudentHealth SH ON SA.StudentId=SH.StudentId
           LEFT JOIN sStudent.tStudentFamily SF ON SF.StudentId = SA.StudentId           
           LEFT JOIN sActivity.tHouseMaster SM ON SM.ID = SA.HouseId
           LEFT JOIN sHostel.tAssignRoom AR ON AR.SourceId=SA.StudentId AND AR.SourceTypeId=2003  AND ((AR.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sHostel.tRoomMaster RM ON RM.Id=AR.RoomId
           LEFT JOIN sCommon.tPhysicalDisabilityCategoryMaster PDCM ON PDCM.Id = SH.PhysicalDisabilityCategoryId
           LEFT JOIN sHostel.tHostelMaster HM ON HM.Id=RM.HostelId  
		   LEFT JOIN sStudent.tStudentImages SI ON SI.StudentId = SA.StudentId
		   --LEFT JOIN sAcademic.tTeacherSubjectDivision TSD ON TSD.DivisionId = SA.DivisionId
		   --LEFT JOIN sSetup.tSubjectMaster SBM ON SBM.Id = TSD.SubjectId
		   --LEFT JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD.EmployeeId
            LEFT JOIN --HostelDetails
            (
		   SELECT 
		   employeeId, 
		   HostelId,   
		   ROW_NUMBER() OVER (PARTITION BY HostelId ORDER By HostelId ) as ROWNo 		   
		 
		   FROM sHostel.tHostelwarden 
            )  HW ON HW.HostelId=HM.Id AND RowNo = 1           
           LEFT JOIN sHrm.tEmployeeMaster EMW ON HW.EmployeeId=EMW.Id AND  ISNULL(EMW.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeMaster EMA ON RM.AssignedEmployeeId=EMA.Id AND  ISNULL(EMA.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeCommunications ECW ON EMW.Id=ECW.EmployeeId 
           LEFT JOIN sHrm.tEmployeeCommunications ECA ON  EMA.Id=ECA.EmployeeId
           LEFT JOIN -- Transport Details
           ( SElect AR1.SourceId,
           VM.Title AS VehicleName,
		    VM.RegistrationNumber AS VehicleRegistrationNumber,
		    TV.Title AS TypeOfVehicle,
		    ISNULL(BRM.Title,'') AS BusRoute,
		    BRM.DriverName,
		    BRM.DriverMobileNo,
		    BRM.ConductorName,
		    BRM.ConductorMobileNo,
		    ISNULL(BRDM.Title,'') AS BusRouteDestination,
		    VM.Title AS DropVehicleName,
		    VM.RegistrationNumber AS DropVehicleRegistrationNumber,
		    TV1.Title AS DropTypeOfVehicle,
		    ISNULL(BRM1.Title,'') AS DropRoute,
		    BRM1.DriverName AS DropRouteDriverName,
		    BRM1.DriverMobileNo AS DropRouteDriverMobileNo,
		    BRM1.ConductorName AS DropRouteConductorName,
		    BRM1.ConductorMobileNo AS DropRouteConductorMobileNo,
		    ISNULL(BRDM1.Title,'') AS DropDestination
		      FROM
             sTransport.tAssignRoute AR1   
           INNER JOIN sTransport.tBusRouteDestinationMaster BRDM ON BRDM.Id=AR1.PickupDestinationId AND AR1.SourceTypeId=2003
           INNER JOIN sTransport.tBusRouteMaster BRM ON BRM.Id=BRDM.BusRouteId AND ((BRM.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM ON VM.Id=BRM.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV ON TV.Id = VM.VehicleTypeId
           LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM1 ON BRDM1.Id=AR1.DropDestinationId
           LEFT JOIN sTransport.tBusRouteMaster BRM1 ON BRM1.Id=BRDM1.BusRouteId AND ((BRM1.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))
           LEFT JOIN sTransport.tVehicleMaster VM1 ON VM1.Id=BRM1.VehicleId
           LEFT JOIN sTransport.tVehicleTypeMaster TV1 ON TV1.Id = VM1.VehicleTypeId) A ON A.SourceId=SA.StudentId
           LEFT JOIN sSetup.tDivisionMaster DM ON  DM.Id=SA.DivisionId
           LEFT JOIN sHrm.tEmployeeMaster EMT ON EMT.Id=DM.InchargeEmployeeId AND  ISNULL(EMT.IsOtherUser,0) = 0
           LEFT JOIN sHrm.tEmployeeJobDetail EJD ON EJD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeDesignationMaster EDM ON EDM.Id=EJD.EmployeeDesignationId
           LEFT JOIN sHrm.tEmployeePersonalDetail EPD ON EPD.EmployeeId=EMT.Id
           LEFT JOIN sHrm.tEmployeeImages EI ON EI.EmployeeId=EMT.Id
           LEFT JOIN sStudent.tStudentSibling  SS ON SS.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tStudentAdditional  SAD ON SAD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tCollegeDetail  CD ON CD.StudentId=SA.StudentId 
           LEFT JOIN sStudent.tAcademicDetail  ACD ON ACD.AcademicId=SA.AcademicId 
           LEFT JOIN sCommon.tMaritalStatusMaster  MS ON MS.Id=CD.MaritalStatusId
           LEFT JOIN sConfig.fDisplayFieldGet(@rOrgId) AS DF ON DF.OrgId=SA.OrgId
           LEFT JOIN sCommon.tCastCategoryMaster CT ON CT.Id = SA.CastCategoryId
           LEFT JOIN sCommon.tCountryMaster CM ON CM.Id=SA.NationalityId
           INNER JOIN sSetup.tBatchClass BC ON BC.ClassID =  SA.ClassID and BC.BatchId= @rBatchId
           LEFT JOIN sCommunication.tCustomGroupMember CGM ON CGM.SourceId = SA.StudentId AND CGM.SourceTypeId = 2003
           LEFT JOIN sCommunication.tCustomGroup CGG ON CGG.Id = CGM.CustomGroupId
           LEFT JOIN sStudent.tStudentMaster SMM ON SMM.Id = SA.StudentId
           LEFT JOIN sStudent.tStudentGroupMaster SGM ON SGM.Id = SMM.StudentGroupId
           LEFT JOIN sStudent.tStudentOtherGroupMaster SOGM ON SOGM.Id = SMM.StudentOtherGroupId
		   LEFT JOIN sStudent.tStudentAdmission SAM ON SAM.StudentId = SA.StudentId
		   LEFT JOIN -- Fee Details
		   (
				SELECT 
			SUM(ISNULL(R.PaidAmount,0)) AS PaidAmount,
			SUM(ISNULL(FS.Amount,0.00)+ISNULL(FA.VariableAmount,0.00)+ISNULL(FA.AdditionalAmount,0.00) -ISNULL(FA.DiscountAmount,0.00)-ISNULL(FA.NotApplicableAmount,0.00)-ISNULL(R.PaidAmount,0.00)) AS PendingAmount,
			FS.BatchId
			  FROM 
						sFee.tFeeMaster FM
					INNER JOIN 
					(
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId
				 
						FROM sFee.tFeeSetup FS1
			   
							WHERE FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=0
							AND FS1.BatchId = @rBatchId
							UNION ALL
				
						SELECT 
							FS1.FeeId,
							FS1.Id,
							ISNULL(FS1.IsOptional,0)AS IsOptional,
							ISNULL(FS1.IsVariable,0)AS IsVariable,
							ISNULL(FS1.Amount,0)AS Amount,
							ISNULL(FS1.StartDate,'1900-01-01')AS StartDate,
							ISNULL(FS1.EndDate,'1900-01-01')AS EndDate,
							FS1.BatchId,
							ISNULL(FS1.ReceiptBookId,0) AS ReceiptBookId,
							ISNULL(FS1.CollectionGroupId,0) AS CollectionGroupId 
				 
						FROM sFee.tFeeSetup FS1
			 
					INNER JOIN sFee.tFeeOptional FO
						ON FO.FeeSetupId=FS1.Id AND (FO.SourceId=@lAcademicId) AND(FO.SourceTypeId=2001)
						WHERE
						 FS1.BatchId = @rBatchId
						AND	FS1.ClassId=@lClassId AND FS1.AdmissionCategoryId=@lAdmissionCategoryId AND IsOptional=1
					) FS ON FS.FeeId=FM.Id
					LEFT JOIN sFee.tFeeAllocation FA
						ON FA.FeeSetupId=FS.Id AND (FA.SourceId=@lAcademicId) AND(FA.SourceTypeId=2001)
					LEFT JOIN
					(
						SELECT ISNULL(SUM(RD.Amount),0) AS PaidAmount,RD.FeeSetupId
						FROM
						sFee.tReceipt R INNER JOIN sFee.tReceiptDetail RD ON	RD.ReceiptId = R.Id 		
						WHERE						
						 R.SourceId= @lAcademicId
						AND ((R.SourceTypeId = 2001))
						AND R.IsObsolete = 0 
						AND R.BatchId = @rBatchId
						 GROUP BY FeeSetupId
					) R ON R.FeeSetupId = FS.Id	
			WHERE 
				FS.BatchId=@rBatchId
				GROUP BY FS.BatchId
		   ) FED ON FED.BatchId = SA.BatchId			  		  

  WHERE 
			((SA.StudentId=@rStudentId)OR(@rStudentId=0))
			AND((SA.BatchId=@rBatchId) OR(@rBatchId=0))			
			AND ((SA.StudentId=@rStudentId) OR (@rStudentId=0))			
			AND ((SA.OrgGroupBatchId=@rOrgGroupBatchId) OR(@rOrgGroupBatchId=0))			
			AND ((SA.OrgId=@rOrgId) OR (@rOrgId = 0))
	END
	ELSE IF(LOWER(@Tab) = 'studentdetails')
	BEGIN
		exec sStudent.pStudentFullProfileGet @rBatchId=@rBatchId,@rStudentId=@rStudentId,@rOrgGroupBatchId=@rOrgGroupBatchId,@rOrgId=@rOrgId
	END	
	ELSE IF(LOWER(@Tab) = 'feedetails')
	BEGIN
		exec [sFee].[pFeeAllocationViewGet] @rSourceId=@lAcademicId,@rSourceTypeId=2001,@rBatchId=@rBatchId
		
		DECLARE @Receiptgrid NVARCHAR(max)=''
		SELECT  @Receiptgrid = @Receiptgrid + '<tr>		
		<td align="left" scope="col">' + ISNULL(RBM.Title,'') + '</td>
		<td style="color:Black;overflow-wrap:anywhere;"><a style="color: #03afc5 !important;" onclick="FeeReceiptEdit(' + convert(nvarchar,R.ReceiptBookId) + ',' + convert(nvarchar,R.PayTypeId) + ',' + convert(nvarchar,R.ReceiptNumber) + ')">' + convert(varchar,isnull(R.ReceiptNumber,'')) + '</a></td>		
		<td align="left" scope="col">' +  convert(varchar,isnull(R.ReceiptDate,'01/01/0001'),103) + '</td>
		<td align="left" scope="col">' +  ISNULL(PTM.Title,'') + '</td>
		<td align="left" scope="col">' +  isnull(R.ChequeNo,'') + '</td>
		<td align="left" scope="col">' + isnull(R.BankName,'') + '</td>
		<td align="left" scope="col">' +  ISNULL([sFee].[fReceiptFeeDetailGet](R.Id),'') + '</td>
		<td align="left" scope="col">' +  convert(varchar,isnull(R.ReceiptAmount,0)) + '</td>
		<td><input type="button" id="' + convert(varchar,R.Id) + '" value="&#xf02f; Print Fee Receipt" onclick="PrintFeeReceipt(this, ' + convert(varchar,R.Id) + ', ' + convert(varchar,RBM.Id) + ');" class="fas btn btn-report " /></td>
		</tr>'	
			
	  FROM 
				sFee.tReceipt R
			INNER JOIN sStudent.vStudentAcademic SA
				ON SA.AcademicId=R.SourceId AND ((SA.OrgId=@rOrgId) OR (@rOrgId=0))
			INNER JOIN sFinanceCommon.tPayTypeMaster PTM
				ON PTM.Id=R.PayTypeId
			LEFT JOIN sSecurity.tUser U
				ON U.Id=R.CreatedUserId
			INNER JOIN sFee.tReceiptBookMaster RBM 
				ON RBM.Id=R.ReceiptBookId
			
	WHERE 
		R.SourceTypeId = 2001
		AND SA.AcademicId=@lAcademicId		
		ORDER BY R.ReceiptNumber
			
			
	select isnull(@Receiptgrid,'') as Receiptgrid

		--exec [sFee].[pFeeReceiptListViewGet] @rAcademicId=@lAcademicId,@rOrgId=@rOrgId
		exec [sFee].[pFeecancelReceiptListviewGet] @rBatchId=@rBatchId,@rOrgId=@rOrgId,@rAcademicId=@lAcademicId		
		exec [sFee].[pRptFeePendingAllBatchGet] @rOrgGroupBatchId=0,@rOrgId=@rOrgId,@rBatchId=0,@rCode=@lCode,@rUserId=0

		--exec [sFee].[pFeeAllocationViewGet] @rSourceId=@lAcademicId,@rSourceTypeId=2001,@rBatchId=@rBatchId
	END	
	ELSE IF(LOWER(@Tab) = 'attendance')
	BEGIN
		IF(@rAttendanceTypeId = 5)
		BEGIN

		exec [sAttendance].[pSubjectRegisterStudentViewGet] @rAcademicId = @lAcademicId,@rBatchId = @rBatchId, @rAttendanceTypeId = @rAttendanceTypeId		
		END
		ELSE 
		BEGIN
		exec [sAttendance].[pMonthlyRegisterStudentviewGet] @rAttendanceTypeId = @rAttendanceTypeId, @rAcademicId = @lAcademicId,@rBatchId = @rBatchId
		END
	END
	ELSE IF(LOWER(@Tab) = 'assessment')
	BEGIN
		exec [sAssessment].[pExamListGet] @rAcademicId = @lAcademicId, @rBatchId = @rBatchId
	END
	ELSE IF(LOWER(@Tab) = 'certificate')
	BEGIN
		SELECT 'Bonafied' AS CertificateName,CreatedDateTime,Number AS CertificateNumber FROM [sCertificate].[tBonafide] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId
		UNION ALL
		SELECT 'Character' AS CertificateName,CreatedDateTime,Number AS CertificateNumber FROM [sCertificate].[tCharacter] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId		
		UNION ALL
		SELECT 'Leaving' AS CertificateName,CreatedDateTime,LCNumber AS CertificateNumber FROM [sCertificate].[tLeaving] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId
		UNION ALL
		SELECT 'FirstTrial' AS CertificateName,CreatedDateTime,Number AS CertificateNumber FROM [sCertificate].[tFirstTrial] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId		
		UNION ALL
		SELECT 'Transfer' AS CertificateName,CreatedDateTime,Number AS CertificateNumber FROM [sCertificate].[tTransfer] WHERE AcademicId = @lAcademicId AND OrgId = @rOrgId AND BatchId = @rBatchId
	END
	ELSE IF(LOWER(@Tab) = 'deposit')
	BEGIN
		exec sFee.pStudentLedgerGet @rAcademicId=@rStudentId,@rDepositHeadId=@rDepositHeadId,@rCode=@lCode,@rSUId=N'',@rOrgId=@rOrgId
	END
	ELSE IF(LOWER(@Tab) = 'alert')
	BEGIN		
		IF(@rAlertModeId = 3)
		BEGIN
			exec sAlert.pNotificationViewGet @rSourceId = @lAcademicId, @rSourceTypeId = 2001, @rIsFlag = 1
		END
		ELSE
		BEGIN
			exec [sAlert].[pSMSViewGet] @rMobileNumber = @lContactNo,@rEmail = @lEmail, @rOrgId = @rOrgId, @rIsFlag = 1, @rAlertModeId = @rAlertModeId		
		END
	END
	ELSE IF(LOWER(@Tab) = 'library')
	BEGIN
		exec [sLibrary].[pBookLogListViewGet] @rAcademicId = @lAcademicId, @rOrgId = @rOrgId,@rBatchId = @rBatchId
	END
	ELSE IF(LOWER(@Tab) = 'paymentdetails')
	BEGIN
		exec sOp.pPaymentTransactionGet @rId=@lAcademicId,@rFromDate=NULL,@rToDate=@lDate,@rTransactionStatusId=0,@rFunctionalityId=0,
		@rFirstName=NULL,@rOrgGroupId=@lOrgGroupId,@rOrgId=@rOrgId,
		@rBatchId=@rBatchId,@rReceiptBookId=0,@rOSTypeId=0,@rFormNo=0,@rReferenceNo=0,@rPaymentGatewayId=0
	END
	ELSE IF(LOWER(@Tab) = 'onlinelearning')
	BEGIN
	SELECT OL.Title AS OLTitle,  OL.StartTime, OL.EndTime, SM.Title AS [Subject], EM.FirstName + ' ' + Em.LastName AS EmployeeName, DM.Title AS LearningType FROM sAcademic.tOnlineLearningScope OLS
	INNER JOIN sAcademic.tOnlineLearning OL ON OL.Id = OLS.OnlineLearningId
	INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = OL.SubjectId
	INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TeacherEmployeeId
	INNER JOIN sCommon.tDataMaster DM ON DM.Id = OL.LearningTypeId AND DM.DataTypeId = 3
	WHERE (
	( 
	(OLS.SourceTypeId = 2021 AND OLS.SourceId = @rOrgId) 
	OR
	(OLS.SourceTypeId = 2017 AND OLS.SourceId = @lDepartmentId) OR
	(OLS.SourceTypeId = 2016 AND OLS.SourceId = @lClassId) OR
	(OLS.SourceTypeId = 2005 AND OLS.SourceId = @lDivisionId) OR
	(OLS.SourceTypeId = 2003 AND OLS.SourceId = @rStudentId) OR
	(OLS.SourceTypeId = 2001 AND OLS.SourceId = @lAcademicId)
		))

	AND OL.StartDate = CAST(sCommon.fGetDate() AS DATE)

	SELECT
		ISNULL((SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 1 And AcademicId = @lAcademicId),0) AS PresentCount,
		ISNULL((SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 0 And AcademicId = @lAcademicId),0) AS AbsentCount,
		CAST(ISNULL((((SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 1 And AcademicId = @lAcademicId) / 
		(SELECT SUM(AcademicId) FROM sAcademic.tOnlineLearningAttendance WHERE IsPresent = 0 And AcademicId = @lAcademicId)) * 100 ),0) AS DECIMAL(10,2)) AS PresentPercentage
	
	END
	ELSE IF(LOWER(@Tab) = 'charge')
	BEGIN
		exec sFee.pChargeReceiptListGet @rSourceTypeId=0,@rGuestName=N'*',@rSourceCode=@lCode,@rFromDate=NULL,@rToDate=NULL,@rReceiptBookId=0,@rChargeCategoryId=0,@rOrgId=@rOrgId,@rBatchId=0,@rOrgGroupBatchId=@rOrgGroupBatchId,@rFromNo=0,@rToNo=0,@rOrgGroupId=@lOrgGroupId
	END
	ELSE IF(LOWER(@Tab) = 'siblingdetails')
	BEGIN
		exec sStudent.pSiblingLinkListGet @rStudentId=@rStudentId
	END
	ELSE IF (LOWER(@Tab) = 'teachersubject')
	BEGIN
		SELECT DISTINCT SM.Title AS SubjectName,
		(SELECT Stuff (( select ',' + Convert(nvarchar(MAX),EM.FirstName + ' ' + EM.LastName)
			FROM 
			sAcademic.tTeacherSubjectDivision TSD1
			INNER JOIN sHrm.tEmployeeMaster EM ON EM.Id = TSD1.EmployeeId AND EM.StatusId = 7
			WHERE 
			TSD1.SubjectId = TSD.SubjectId AND TSD1.DivisionId = @lDivisionId
			  FOR XML PATH('')  
			 ),1,1,'')) TeacherName

		FROM 
		sAcademic.tTeacherSubjectDivision TSD
		INNER JOIN sSetup.tSubjectMaster SM ON SM.Id = TSD.SubjectId
		WHERE TSD.DivisionId = @lDivisionId
	END
END
GO
PRINT N'Altering [sStudent].[pStudentMasterAdd]...';


GO

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

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

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

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

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

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


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

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

	BEGIN
	DELETE FROM sTransport.tAssignRouteLog WHERE SourceTypeId = @rSourceTypeId AND SourceId = @rSourceId AND OrgGroupBatchId = @rOrgGroupBatchId

	INSERT INTO sTransport.tAssignRouteLog
	(
		SourceTypeId,
		SourceId,
		NewPickupDestinationId,
		NewDropDestinationId,
		StatusId,
		OrgGroupBatchId,
		CreatedUserId,
		CreatedDateTime
	)
	VALUES
	(
		@rSourceTypeId,
		@rSourceId,
		@rNewPickupDestinationId,
		@rNewDropDestinationId,
		@rStatusId,
		@rOrgGroupBatchId ,
		@rCreatedUserId ,
		sCommon.fGetDate()
	)
	END
END
END
GO
PRINT N'Altering [sTransport].[pTransportAdminStudentAdd]...';


GO
ALTER PROCEDURE [sTransport].[pTransportAdminStudentAdd]
	 
	      @rFromOrgGroupBatchId int,
	      @rToOrgGroupBatchId int,
	      @rTransportId int,
		  @rCreatedUserId bigint
	      
AS
SET NOCOUNT ON
BEGIN
	IF NOT EXISTS(
			SELECT 1 FROM  sTransport.tBusRouteMaster  WHERE  OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId )
			BEGIN
			SELECT -105 AS RESULT
			RETURN
	END
		--IF EXISTS (SELECT 1  FROM sTransport.tAssignRoute AR INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=AR.PickupDestinationId
	 --            INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	 --            WHERE BM.OrgGroupBatchId=@rToOrgGroupBatchId AND BM.TransportId=@rTransportId )
		--BEGIN
		--	SELECT -103 AS RESULT
		--	RETURN
		--END


IF((SELECT 	
    (Select ISNULL(COUNT(1),0) from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId  AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId )
	
	FROM sTransport.tAssignRoute AR 
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=Ar.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	INNER JOIN (SELECT StudentId FROM sStudent.vstudentAcademic V WHERE OrgGroupBatchId=@rToOrgGroupBatchId) V ON AR.SourceId = V.StudentId
	WHERE OrgGroupBatchId=@rFromOrgGroupBatchId AND TransportId=@rTransportId 	AND  AR.SourceTypeId=2003 
	 AND V.StudentId NOT IN (SELECT SourceId FROM sTransport.tAssignRoute A  
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=A.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	WHERE SourceTypeId=2003  AND  OrgGroupBatchId=@rToOrgGroupBatchId)
	AND (Select ISNULL(COUNT(1),0) from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId  AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId ) <>0
	UNION		
	SELECT
     (Select ISNULL(COUNT(1),0) from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId  AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId )	
	FROM sTransport.tAssignRoute AR 
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=Ar.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	 INNER JOIN  (SELECT ReferenceSourceId,StudentId FROM sStudent.vstudentAcademic V WHERE OrgGroupBatchId=@rToOrgGroupBatchId) V ON AR.SourceId = V.StudentId
	WHERE OrgGroupBatchId=@rFromOrgGroupBatchId 
	 AND V.StudentId NOT IN (SELECT SourceId FROM sTransport.tAssignRoute A  
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=A.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	WHERE SourceTypeId=2003  AND  OrgGroupBatchId=@rToOrgGroupBatchId)
	AND (Select ISNULL(COUNT(1),0) from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId  AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId )	<>0
	AND TransportId=@rTransportId
	AND  AR.SourceTypeId=2003 )=0)
BEGIN
SELECT -104 AS RESULT
RETURN
END


	BEGIN TRANSACTION
	BEGIN
	INSERT  INTO sTransport.tAssignRoute
	(
	SourceTypeId, SourceId, PickupDestinationId, DropDestinationId
	)
	SELECT 
	 2003,
	 AR.SourceId  ,
     PickupDestinationId =  (Select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId ),
	 DropDestinationId =  (select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where  OldImportBusRouteDestinationId= AR.DropDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId)
	FROM sTransport.tAssignRoute AR 
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=Ar.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	INNER JOIN (SELECT StudentId FROM sStudent.vstudentAcademic V WHERE OrgGroupBatchId=@rToOrgGroupBatchId
			   ) V ON AR.SourceId = V.StudentId
	WHERE OrgGroupBatchId=@rFromOrgGroupBatchId AND TransportId=@rTransportId 	AND  AR.SourceTypeId=2003 
	 AND V.StudentId NOT IN (SELECT SourceId FROM sTransport.tAssignRoute A  
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=A.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	WHERE SourceTypeId=2003  AND  OrgGroupBatchId=@rToOrgGroupBatchId)
	AND (Select ISNULL(COUNT(1),0) from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId  AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId )	<>0

	UNION
		
	SELECT 
	 2003,
	  V.StudentId,
     PickupDestinationId =  (Select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId ),
	 DropDestinationId =  (select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where  OldImportBusRouteDestinationId= AR.DropDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId)
	FROM sTransport.tAssignRoute AR 
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=Ar.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	 INNER JOIN  (SELECT ReferenceSourceId,StudentId FROM sStudent.vstudentAcademic V WHERE OrgGroupBatchId=@rToOrgGroupBatchId 
                  ) V ON AR.SourceId = V.StudentId
	WHERE OrgGroupBatchId=@rFromOrgGroupBatchId 
	 AND V.StudentId NOT IN (SELECT SourceId FROM sTransport.tAssignRoute A  
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=A.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	WHERE SourceTypeId=2003  AND  OrgGroupBatchId=@rToOrgGroupBatchId)
	AND (Select ISNULL(COUNT(1),0) from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId  AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId )	<>0
	AND TransportId=@rTransportId
	AND  AR.SourceTypeId=2003 


	--Add AssignRouteLog
	INSERT INTO sTransport.tAssignRouteLog
	(
		SourceTypeId,
		SourceId,
		NewPickupDestinationId,
		NewDropDestinationId,
		StatusId,
		OrgGroupBatchId,
		CreatedUserId,
		CreatedDateTime
	)
	SELECT 
	 2003,
	 AR.SourceId  ,
     PickupDestinationId =  (Select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId ),
	 DropDestinationId =  (select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where  OldImportBusRouteDestinationId= AR.DropDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId),
	 (CASE WHEN 
	 (Select ISNULL(BD.Id,0)  from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  
	 Where OldImportBusRouteDestinationId = AR.PickupDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId) > 0
	 OR
	 (Select ISNULL(BD.Id,0)  from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  
	 Where OldImportBusRouteDestinationId = AR.DropDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId) > 0
	 THEN 745 ELSE 746 END)AS StatusId,
	 @rToOrgGroupBatchId,
	 @rCreatedUserId,
	 sCommon.fGetDate()
	FROM sTransport.tAssignRoute AR 
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=Ar.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	INNER JOIN (SELECT StudentId FROM sStudent.vstudentAcademic V WHERE OrgGroupBatchId=@rToOrgGroupBatchId
			   ) V ON AR.SourceId = V.StudentId
	WHERE OrgGroupBatchId=@rFromOrgGroupBatchId AND TransportId=@rTransportId 	AND  AR.SourceTypeId=2003 
	 AND V.StudentId NOT IN (SELECT SourceId FROM sTransport.tAssignRoute A  
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=A.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	WHERE SourceTypeId=2003  AND  OrgGroupBatchId=@rToOrgGroupBatchId)
	AND (Select ISNULL(COUNT(1),0) from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId  AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId )	<>0

	UNION
		
	SELECT 
	 2003,
	  V.StudentId,
     PickupDestinationId =  (Select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId ),
	 DropDestinationId =  (select BD.Id from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where  OldImportBusRouteDestinationId= AR.DropDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId),
	 (CASE WHEN 
	 (Select ISNULL(BD.Id,0)  from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  
	 Where OldImportBusRouteDestinationId = AR.PickupDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId) > 0
	 OR
	 (Select ISNULL(BD.Id,0)  from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  
	 Where OldImportBusRouteDestinationId = AR.DropDestinationId AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId) > 0
	 THEN 745 ELSE 746 END)AS StatusId,
	 @rToOrgGroupBatchId,
	 @rCreatedUserId,
	 sCommon.fGetDate()
	FROM sTransport.tAssignRoute AR 
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=Ar.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	 INNER JOIN  (SELECT ReferenceSourceId,StudentId FROM sStudent.vstudentAcademic V WHERE OrgGroupBatchId=@rToOrgGroupBatchId 
                  ) V ON AR.SourceId = V.StudentId
	WHERE OrgGroupBatchId=@rFromOrgGroupBatchId 
	 AND V.StudentId NOT IN (SELECT SourceId FROM sTransport.tAssignRoute A  
	INNER JOIN  sTransport.tBusRouteDestinationMaster  BD ON BD.Id=A.PickupDestinationId
	INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId
	WHERE SourceTypeId=2003  AND  OrgGroupBatchId=@rToOrgGroupBatchId)
	AND (Select ISNULL(COUNT(1),0) from sTransport.tBusRouteDestinationMaster  BD  INNER JOIN  sTransport.tBusRouteMaster  BM ON BM.Id=BD.BusRouteId  Where OldImportBusRouteDestinationId = AR.PickupDestinationId  AND BM.OrgGroupBatchId=@rToOrgGroupBatchId AND TransportId=@rTransportId )	<>0
	AND TransportId=@rTransportId
	AND  AR.SourceTypeId=2003 
	END
  COMMIT TRANSACTION
	
	SELECT 1 AS Result
	

END
GO
PRINT N'Creating [sAssessment].[pMarkEntryRankUpdateOld]...';


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

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


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


Update R Set R.RankNumber = 0 From sAssessment.tResult R 
Inner Join sStudent.tAcademic A ON A.Id = R.AcademicId  
 AND R.ExamId=@rExamId
 AND A.DivisionId = @rDivisionId 
 AND A.BatchId = @rBatchId
 
 
IF(@lIsSkipRankConfigValue=0)
BEGIN
	Update R Set R.RankNumber=A.RankNumber From sAssessment.tResult R
	INNER JOIN
	(Select DENSE_RANK() OVER ( ORDER BY Percentage Desc) AS RankNumber,
	--(Select ROW_NUMBER() OVER(ORDER BY TotalObtain Desc, RS.AcademicId Asc) AS RankNumber,
	--(Select RANK() OVER(ORDER BY TotalObtain Desc, RS.AcademicId Asc) AS RankNumber,
	AcademicId 
	from sAssessment.tResult RS
	INNER JOIN sStudent.tAcademic SA ON SA.Id= RS.AcademicId 
	AND ExamId=@rExamId AND SA.DivisionId=@rDivisionId  AND SA.BatchId = @rBatchId
	AND ResultStatus='PASS' ) A
	ON A.AcademicId = R.AcademicId 
	WHERE R.ExamId = @rExamId
END
ELSE
BEGIN

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


GO
 
CREATE PROCEDURE [sAttendance].[pAttendanceFollowupDetailGet]
	 	 
	 	 @rClassId int=0,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rFollowupDate date,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @rPresentStatus int,
		 @rCode nvarchar(20)=''
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 
	SELECT
	SA.AcademicId, 
	SA.ClassName +'-' + SA.DivisionName AS ClassDivision,
	SA.Code,
	SA.RollNo,
	SA.Name,
	SC.PresentContactNo,
	SC.PermanentContactNo,
	SC.EmergencyContactNo,
	SC.ParentContactNo,
	SC.StudentContactNo,
	--(Select ISNULL(AF.Remark,'') FROM sAttendance.tAttendanceFollowup AF WHERE SA.AcademicId = AF.AcademicId AND AF.AttendanceTypeId = @rAttendanceTypeId AND (AF.FollowupDate=@rFollowupDate))AS Remark
	AF.Remark

	FROM
	sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
	INNER JOIN sAttendance.tStudentRegister SR ON SR.AcademicId=SA.AcademicId 
	--AND (SR.AttendanceTypeId = @rAttendanceTypeId)
	--AND (SR.AttendanceDate = @rFollowupDate)
	LEFT JOIN sAttendance.tAttendanceFollowup AF ON AF.AcademicId = SA.AcademicId AND SR.AttendanceTypeId = AF.AttendanceTypeId AND SR.AttendanceDate  = AF.FollowupDate
	LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
 
	WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
		  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  AND (SA.OrgId = @rOrgId)
		  AND (SA.BatchId = @rBatchId)
		  AND (SA.StatusId NOT IN(2,3))
		  AND SR.IsPresent = @rPresentStatus
		  AND (AD.AdmissionDate <= @rFollowupDate)
		  AND ((SA.Code=@rCode)OR (ISNULL(@rCode,'')=''))
		  AND (SR.AttendanceTypeId = @rAttendanceTypeId)
		  AND (SR.AttendanceDate = @rFollowupDate)
END
GO
PRINT N'Creating [sAttendance].[pAttendanceFollowupListGet]...';


GO

 
CREATE PROCEDURE [sAttendance].[pAttendanceFollowupListGet]
	 	 
	 	 @rClassId int,
	 	 @rDivisionId int,
	 	 @rAttendanceTypeId tinyint,
		 @rFromDate date,
		 @rToDate date,
	 	 @rBatchId int,
	 	 @rOrgId int,
		 @rPresentStatus int,
		 @rCode nvarchar(20)
	 	 
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN 

	SELECT
	SA.AcademicId, 
	SA.ClassName +'-' + SA.DivisionName AS ClassDivision,
	SA.Code,
	SA.RollNo,
	SA.Name,
	SC.PresentContactNo,
	SC.PermanentContactNo,
	SC.EmergencyContactNo,
	SC.ParentContactNo,
	SC.StudentContactNo,
	AF.Remark,
	AF.AttendanceTypeId AS AttendanceTypeId,
	AF.FollowupDate,
	AF.IsPresent
	--(Select ISNULL(AF.Remark,'') FROM sAttendance.tAttendanceFollowup AF WHERE SA.AcademicId = AF.AcademicId AND AF.AttendanceTypeId=1 AND (AF.FollowupDate=@rFollowupDate))AS Remark
	--AF.Remark

	FROM
	sStudent.vStudentAcademic SA
	INNER JOIN sStudent.tStudentAdmission AD ON SA.StudentId = AD.StudentId 
	INNER JOIN sAttendance.tAttendanceFollowup AF ON SA.AcademicId = AF.AcademicId
	LEFT JOIN sStudent.tStudentCommunication SC ON SA.StudentId = SC.StudentId
 
	WHERE 
		  ((SA.ClassId=@rClassId) OR (@rClassId=0))
		  AND ((SA.DivisionId=@rDivisionId) OR (@rDivisionId=0))
		  AND (SA.OrgId = @rOrgId)
		  AND (SA.BatchId = @rBatchId)
		  AND (SA.StatusId NOT IN(2,3))
		  AND ((AF.IsPresent = @rPresentStatus) OR (@rPresentStatus= -1))
		  AND (AF.FollowupDate >= @rFromDate) AND (AF.FollowupDate <= @rToDate)
		  AND ((AF.AttendanceTypeId= @rAttendanceTypeId) OR (@rAttendanceTypeId = 0))
		  AND ((SA.Code=@rCode)OR (ISNULL(@rCode,'')=''))
END
GO
PRINT N'Creating [sAttendance].[pAttendanceFollowupXMLInsert]...';


GO
 
CREATE PROCEDURE [sAttendance].[pAttendanceFollowupXMLInsert]
	
	@rStrXml nvarchar(MAX),
    @rAttendanceTypeId tinyint,
    @rFollowupDate date='',
    @rPresentStatus tinyint,
    @rCreatedUserId bigint
  
		
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
--SET @rStrXml=REPLACE(@rStrXml,'&','AND')
DECLARE @loDoc INT
EXEC sp_xml_preparedocument @loDoc OUTPUT, @rStrXml
BEGIN
	BEGIN TRY
	 BEGIN TRANSACTION 
	  BEGIN
	  
		INSERT INTO sAttendance.tAttendanceFollowup 
			(
				AcademicId,
				AttendanceTypeId,
				FollowupDate,
				IsPresent,
				Remark,
				CreatedUserId,
				CreatedDateTime,
				UpdatedUserId,
				UpdatedDateTime
				
				)
			SELECT	
				
				AcademicId,
				@rAttendanceTypeId,
				@rFollowupDate,
				@rPresentStatus,
				ISNULL(Remark,''),
				@rCreatedUserId,
				sCommon.fGetDate(),
				NULL,
				NULL
				
			FROM OPENXML (@loDoc, '/Table/AttendanceFollowup', 1)
			WITH ( 
					AcademicId bigint,
					Remark nvarchar(500)
					
				)  
			WHERE AcademicId NOT IN (SELECT AcademicId FROM sAttendance.tAttendanceFollowup 
			Where AttendanceTypeId = @rAttendanceTypeId
			AND FollowupDate = @rFollowupDate AND IsPresent = @rPresentStatus)

		UPDATE sAttendance.tAttendanceFollowup 
		SET Remark = A.Remark,
		UpdatedUserId = @rCreatedUserId,
		UpdatedDateTime = sCommon.fGetDate()
		FROM
		(
		 SELECT
			AcademicId,
			Remark
	
		FROM OPENXML (@loDoc, '/Table/AttendanceFollowup', 1)
		WITH
		(
			AcademicId bigint,
			Remark nvarchar(500)
		)) A
		INNER JOIN sAttendance.tAttendanceFollowup AF ON A.AcademicId = AF.AcademicId 
		AND AF.AttendanceTypeId = @rAttendanceTypeId
		AND AF.FollowupDate = @rFollowupDate
		AND AF.IsPresent = @rPresentStatus
		
        SELECT 1 AS Result
	  END
		COMMIT TRANSACTION
		
	END TRY
	
	BEGIN CATCH 
		ROLLBACK TRANSACTION
		SELECT -1 AS Result
	END CATCH	
		
END
GO
PRINT N'Creating [sCommunication].[pAssignmentGetOld]...';


GO

 
CREATE PROCEDURE [sCommunication].[pAssignmentGetOld]
	 @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'Creating [sCommunication].[pAssignmentGetWithScopeOld]...';


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

BEGIN 
	 IF @rIsSearch = 1
		BEGIN
			SET @rTitle = sCommon.fSearchStringGet(@rTitle)
		END
	
	SELECT 
		DISTINCT
			A.Id as AssignmentId,
			A.SubjectId,
			SM.Title as SubjectName,
			A.Title,
			A.Remark,
			A.StartDate,
			A.EndDate,
			U.DisplayTitle as CreatedUserName,
			STUFF((
			SELECT ',' + DM.Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sSetup.tDivisionMaster DM ON CAS.SourceId = DM.Id Where  CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2005 
			FOR XML PATH ('')), 1, 1, '') as StudentSource ,			 
			STUFF((			  
			SELECT ',' + Code FROM [sCommunication].[tAssignmentScope] CAS INNER JOIN sSetup.tDepartmentMaster CM ON CAS.SourceId = CM.Id Where CAS.AssignmentId = A.Id AND CAS.SourceTypeId = 2017			  
			FOR XML PATH ('')), 1, 1, '') as EmployeeSource
		    
  FROM 
            sCommunication.tAssignment A
			INNER JOIN [sCommunication].[tAssignmentScope] CAS on A.Id = CAS.AssignmentId
            INNER JOIN sSecurity.tUser U ON U.Id=A.CreatedUserId
            INNER JOIN sSetup.tSubjectMaster SM ON SM.Id=A.SubjectId
			INNER JOIN [sSetup].[tClassSubject] CS on CS.SubjectId = SM.Id												
			LEFT JOIN [sSetup].[tDivisionMaster] DM on DM.Id = CAS.SourceId and CS.ClassId = Dm.classId 
  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 ((CS.ClassId = @rClassId) OR (@rClassId = 0))
	AND ((DM.Id = @rDivisionId) OR (@rDivisionId = 0))
	AND A.BatchId=@rBatchId
	ORDER BY A.StartDate DESC
END
GO
PRINT N'Creating [sTimetable].[pRptFreeLectureListGet]...';


GO
 

CREATE PROCEDURE [sTimetable].[pRptFreeLectureListGet]
	  @rBatchId int,
	  @rClassID int,
	  @rDivisionId int,
	  @rEmployeeId bigint,
	  @rTimeTableSchemaId int,	
	  @rReportId int,
	  @rOrgId int = 0
	  
	WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON 

BEGIN   
	

CREATE TABLE #Temp (Id int identity, LectureNumber int,TimeTableSchemaId int)
DECLARE @lMaxLecture int = (SELECT MAX(NoOfPeriod) FROM sTimeTable.tTimeSetup WHERE TimeTableSchemaId = @rTimeTableSchemaId)
DECLARE @lCount int = 1

WHILE @lCount <= @lMaxLecture
BEGIN
INSERT INTO #Temp VALUES (@lCount, @rTimeTableSchemaId)

SET @lCount = @lCount + 1
END

--SELECT * FROM #Temp


	SELECT	
		TS.DayId, 
		ISNULL(DM.Title,'') AS DayNames,
		EMP.Code,
		EMP.ID AS EmployeeId,
		EMP.FirstName + ' '  + EMP.LastName AS Employee,
		CASE WHEN ISNULL(TT.LectureNumber,0) = TEM.LectureNumber AND ISNULL(TT.DayId,0) =  TS.DayId THEN ISNULL(TT.Id,0) ELSE 0 END AS TimeTableId,
		CASE WHEN ISNULL(TT.LectureNumber,0) = TEM.LectureNumber AND ISNULL(TT.DayId,0) =  TS.DayId THEN ISNULL(TT.LectureNumber,0) ELSE 0 END AS LectureNumber,
		--ISNULL(TT.LectureNumber,0) AS LectureNumber,
		CASE WHEN ISNULL(TT.LectureNumber,0) = TEM.LectureNumber AND ISNULL(TT.DayId,0) =  TS.DayId THEN ISNULL(TT.DayId,0) ELSE 0 END AS TimeTableDayId,
		--ISNULL(TT.DayId,0) AS TimeTableDayId,		
		TEM.LectureNumber AS Lecture		
	FROM
		sTimetable.tTimeSetup TS
		INNER JOIN sTimetable.tAssignTeacher ASS ON ASS.TimeTableSchemaId = TS.TimeTableSchemaId
		INNER JOIN  sHrm.tEmployeeMaster EMP ON EMP.Id = ASS.EmployeeId 
		LEFT JOIN sTimetable.tTimeTable TT ON TT.EmployeeId = EMP.Id AND TS.TimeTableSchemaId = TT.TimeTableSchemaId AND TS.DayId =TT.DayId
		LEFT JOIN #Temp TEM ON TEM.TimeTableSchemaId = TS.TimeTableSchemaId
		INNER JOIN sCommon.tDayMaster DM ON DM.Id = TS.DayId
	WHERE 
		TS.TimeTableSchemaId = @rTimeTableSchemaId
		AND TS.BatchID =@rBatchId 
		AND EMP.OrgID = @rOrgId AND  ISNULL(EMP.IsOtherUser,0) = 0 
	ORDER BY TT.Id,EMP.Id
    
DROP TABLE #Temp
END
GO
PRINT N'Creating [sTransport].[pAssignRouteLogGet]...';


GO
CREATE PROCEDURE [sTransport].[pAssignRouteLogGet]
	 
	@rStrStudentCode nvarchar(50),
	@rPickupBusRouteId int,
	@rDropBusRouteId int,
	@rNewPickupDestinationId int,
	@rNewDropDestinationId int,
	@rFromLogDate nvarchar(11),
	@rToLogDate nvarchar(11),
	@rOrgGroupBatchId int,
	@rTransportId int
	
	
	
WITH EXECUTE AS CALLER
AS
SET NOCOUNT ON
BEGIN

	SELECT 
	     ARL.AutoId,
		 --CONVERT(varchar(20),ARL.LogDate,103) AS LogDate,
		 FirstName + ' ' + MiddleName + ' ' + LastName AS StudentName,
		 SM.Code,
		 ISNULL(BRDM2.Title,'-') AS PickupPoint,
		 ISNULL(BRDM3.Title,'-') AS DropPoint,
		 ISNULL(BRM2.Title,'-') AS PickUpBusRoute,
		 ISNULL(BRM3.Title,'-') AS DropBusRoute,
		 ARL.CreatedDateTime,
		 StaM.Code AS Status

	FROM 
		 sTransport.tAssignRouteLog ARL
		 INNER JOIN sStudent.tStudentMaster SM ON SM.Id = ARL.SourceId
		 INNER JOIN sCommon.tStatusMaster StaM ON ARL.StatusId = StaM.Id
		 LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM2 ON ((BRDM2.Id = @rNewPickupDestinationId) OR (@rNewPickupDestinationId = 0)) 
			AND (ARL.NewPickupDestinationId=BRDM2.Id)  
		 LEFT JOIN sTransport.tBusRouteMaster BRM2 ON BRM2.Id = BRDM2.BusRouteId AND BRM2.TransportId = @rTransportId AND BRM2.OrgGroupBatchId = @rOrgGroupBatchId
		 LEFT JOIN sTransport.tBusRouteDestinationMaster BRDM3 ON ((BRDM3.Id = @rNewDropDestinationId) OR (@rNewDropDestinationId = 0))
			AND (ARL.NewDropDestinationId=BRDM3.Id) 
		 LEFT JOIN sTransport.tBusRouteMaster BRM3 ON BRM3.Id = BRDM3.BusRouteId AND BRM3.TransportId = @rTransportId AND BRM3.OrgGroupBatchId = @rOrgGroupBatchId
	WHERE 	
		 ((SM.Code IN (SELECT item from sCommon.fnSplit(@rStrStudentCode,','))) OR (@rStrStudentCode = ''))
		 AND ((ARL.NewPickupDestinationId = @rNewPickupDestinationId ) OR (@rNewPickupDestinationId = 0))
		 AND ((ARL.NewDropDestinationId = @rNewDropDestinationId ) OR (@rNewDropDestinationId = 0))
		 AND (Convert(date,ARL.CreatedDateTime) >= Convert(date,@rFromLogDate)) AND (Convert(date,ARL.CreatedDateTime) <=   Convert(date,@rToLogDate))
		 AND ((ARL.OrgGroupBatchId = @rOrgGroupBatchId ) OR (@rOrgGroupBatchId = 0))
		 AND ((BRDM2.BusRouteId = @rPickupBusRouteId) OR (@rPickupBusRouteId = 0)) 
		 AND ((BRDM3.BusRouteId = @rDropBusRouteId) OR (@rDropBusRouteId = 0))
	ORDER BY ARL.CreatedDateTime DESC
END
GO
 
  
 
  
GO
INSERT INTO [sSystem].[tVersionUpdate] ([VersionNumber],[VersionId],[Status],[UpdateScript],[StartDateTime],[EndDateTime],[OrgGroupId])
VALUES('22.05.16',220516,'END','Script',sCommon.fGetDate(),sCommon.fGetDate(),0)
GO